diff --git a/bin/console b/bin/console
index 93e3f51ca2..dad1ccc91e 100755
--- a/bin/console
+++ b/bin/console
@@ -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);
diff --git a/bin/doctrine b/bin/doctrine
index a75824db0f..72fa185e21 100755
--- a/bin/doctrine
+++ b/bin/doctrine
@@ -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();
}
diff --git a/builder.php b/builder.php
index ffcae1f17b..3ad24e17e9 100755
--- a/builder.php
+++ b/builder.php
@@ -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);
diff --git a/check_cs.php b/check_cs.php
index aa00030648..57eb3dc5a8 100755
--- a/check_cs.php
+++ b/check_cs.php
@@ -2,9 +2,9 @@
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(' ', '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);
diff --git a/cleaner.php b/cleaner.php
index c8116865fb..316453070c 100755
--- a/cleaner.php
+++ b/cleaner.php
@@ -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);
diff --git a/launchpadToLocales.php b/launchpadToLocales.php
index 03b694323c..9fa0f2e261 100755
--- a/launchpadToLocales.php
+++ b/launchpadToLocales.php
@@ -2,13 +2,13 @@
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;
diff --git a/lib/Alchemy/Phrasea/Application/Admin.php b/lib/Alchemy/Phrasea/Application/Admin.php
index c35ab30562..258f65547d 100644
--- a/lib/Alchemy/Phrasea/Application/Admin.php
+++ b/lib/Alchemy/Phrasea/Application/Admin.php
@@ -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;
+ });
diff --git a/lib/Alchemy/Phrasea/Application/Api.php b/lib/Alchemy/Phrasea/Application/Api.php
index 4a3b6ad5dd..61f2935cce 100644
--- a/lib/Alchemy/Phrasea/Application/Api.php
+++ b/lib/Alchemy/Phrasea/Application/Api.php
@@ -21,654 +21,612 @@ 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']);
- /**
- * @var API_OAuth2_Token
- */
- $app['token'] = null;
+ /**
+ * @var API_OAuth2_Token
+ */
+ $app['token'] = null;
- /**
- * Api Service
- * @var Closure
- */
- $app['api'] = function () use ($app)
- {
- return new \API_V1_adapter(false, $app["appbox"], $app["Core"]);
- };
+ /**
+ * Api Service
+ * @var Closure
+ */
+ $app['api'] = function () use ($app) {
+ return new \API_V1_adapter(false, $app["appbox"], $app["Core"]);
+ };
- /** *********************************************************
- * oAuth token verification process
- * @ throws \API_V1_exception_unauthorized
- * ********************************************************* */
- $mustBeLogged = function($request) use ($app)
- {
- $session = $app["appbox"]->get_session();
- $oauth2_adapter = new \API_OAuth2_Adapter($app["appbox"]);
- $oauth2_adapter->verifyAccessToken();
+ /** * ********************************************************
+ * oAuth token verification process
+ * @ throws \API_V1_exception_unauthorized
+ * ********************************************************* */
+ $mustBeLogged = function($request) use ($app) {
+ $session = $app["appbox"]->get_session();
+ $oauth2_adapter = new \API_OAuth2_Adapter($app["appbox"]);
+ $oauth2_adapter->verifyAccessToken();
- $user = \User_Adapter::getInstance($oauth2_adapter->get_usr_id(), $app["appbox"]);
- $app['token'] = \API_OAuth2_Token::load_by_oauth_token($app["appbox"], $oauth2_adapter->getToken());
+ $user = \User_Adapter::getInstance($oauth2_adapter->get_usr_id(), $app["appbox"]);
+ $app['token'] = \API_OAuth2_Token::load_by_oauth_token($app["appbox"], $oauth2_adapter->getToken());
- if ($session->is_authenticated())
- {
- return;
- }
+ if ($session->is_authenticated()) {
+ return;
+ }
- if ($oauth2_adapter->has_ses_id())
- {
- try
- {
- $session->restore($user, $oauth2_adapter->get_ses_id());
+ if ($oauth2_adapter->has_ses_id()) {
+ try {
+ $session->restore($user, $oauth2_adapter->get_ses_id());
- return;
+ return;
+ } catch (\Exception $e) {
+
+ }
+ }
+ $auth = new \Session_Authentication_None($user);
+ $session->authenticate($auth);
+ $oauth2_adapter->remember_this_ses_id($session->get_ses_id());
+
+ return;
+ };
+
+
+ /* * ********************************************************
+ * oAUth log process
+ * ******************************************************* */
+
+ $parseRoute = function ($route, Response $response) {
+ $ressource = $general = $aspect = $action = null;
+ $exploded_route = explode('/', \p4string::delFirstSlash(\p4string::delEndSlash($route)));
+ if (sizeof($exploded_route) > 0 && $response->isOk()) {
+ $ressource = $exploded_route[0];
+
+ if (sizeof($exploded_route) == 2 && (int) $exploded_route[1] == 0) {
+ $general = $exploded_route[1];
+ } else {
+ switch ($ressource) {
+ case \API_V1_Log::DATABOXES_RESSOURCE :
+ if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
+ $aspect = $exploded_route[2];
+ break;
+ case \API_V1_Log::RECORDS_RESSOURCE :
+ if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 4) {
+ if ( ! isset($exploded_route[3]))
+ $aspect = "record";
+ elseif (preg_match("/^set/", $exploded_route[3]))
+ $action = $exploded_route[3];
+ else
+ $aspect = $exploded_route[3];
}
- catch (\Exception $e)
- {
-
+ break;
+ case \API_V1_Log::BASKETS_RESSOURCE :
+ if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3) {
+ if (preg_match("/^set/", $exploded_route[2]) || preg_match("/^delete/", $exploded_route[2]))
+ $action = $exploded_route[2];
+ else
+ $aspect = $exploded_route[2];
}
- }
- $auth = new \Session_Authentication_None($user);
- $session->authenticate($auth);
- $oauth2_adapter->remember_this_ses_id($session->get_ses_id());
-
- return;
- };
-
-
- /* *********************************************************
- * oAUth log process
- * ******************************************************* */
-
- $parseRoute = function ($route, Response $response)
- {
- $ressource = $general = $aspect = $action = null;
- $exploded_route = explode('/', \p4string::delFirstSlash(\p4string::delEndSlash($route)));
- if (sizeof($exploded_route) > 0 && $response->isOk())
- {
- $ressource = $exploded_route[0];
-
- if (sizeof($exploded_route) == 2 && (int) $exploded_route[1] == 0)
- {
- $general = $exploded_route[1];
- }
- else
- {
- switch ($ressource)
- {
- case \API_V1_Log::DATABOXES_RESSOURCE :
- if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
- $aspect = $exploded_route[2];
- break;
- case \API_V1_Log::RECORDS_RESSOURCE :
- if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 4)
- {
- if ( ! isset($exploded_route[3]))
- $aspect = "record";
- elseif (preg_match("/^set/", $exploded_route[3]))
- $action = $exploded_route[3];
- else
- $aspect = $exploded_route[3];
- }
- break;
- case \API_V1_Log::BASKETS_RESSOURCE :
- if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
- {
- if (preg_match("/^set/", $exploded_route[2]) || preg_match("/^delete/", $exploded_route[2]))
- $action = $exploded_route[2];
- else
- $aspect = $exploded_route[2];
- }
- break;
- case \API_V1_Log::FEEDS_RESSOURCE :
- if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
- $aspect = $exploded_route[2];
- break;
- }
- }
- }
-
- return array('ressource' => $ressource, 'general' => $general, 'aspect' => $aspect, 'action' => $action);
- };
-
- $app->after(function (Request $request, Response $response) use ($app, $parseRoute)
- {
- $account = $app['token']->get_account();
- $pathInfo = $request->getPathInfo();
- $route = $parseRoute($pathInfo, $response);
- \API_V1_Log::create(
- $app["appbox"]
- , $account
- , $request->getMethod() . " " . $pathInfo
- , $response->getStatusCode()
- , $response->headers->get('content-type')
- , $route['ressource']
- , $route['general']
- , $route['aspect']
- , $route['action']
- );
- });
-
- /**
- * Method Not Allowed Closure
- */
- $bad_request_exception = function()
- {
- throw new \API_V1_exception_badrequest();
- };
-
- /**
- * *******************************************************************
- * Route : /databoxes/list/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- *
- */
- $route = '/databoxes/list/';
- $app->get(
- $route, function() use ($app)
- {
- return $app['api']->get_databoxes($app['request'])->get_response();
+ break;
+ case \API_V1_Log::FEEDS_RESSOURCE :
+ if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3)
+ $aspect = $exploded_route[2];
+ break;
}
- )->middleware($mustBeLogged);
+ }
+ }
- /**
- * *******************************************************************
- *
- * Route /databoxes/DATABOX_ID/collections/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- $route = '/databoxes/{databox_id}/collections/';
- $app->get(
- $route, function($databox_id) use ($app)
- {
- $result = $app['api']->get_databox_collections($app['request'], $databox_id);
+ return array('ressource' => $ressource, 'general' => $general, 'aspect' => $aspect, 'action' => $action);
+ };
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+');
+ $app->after(function (Request $request, Response $response) use ($app, $parseRoute) {
+ $account = $app['token']->get_account();
+ $pathInfo = $request->getPathInfo();
+ $route = $parseRoute($pathInfo, $response);
+ \API_V1_Log::create(
+ $app["appbox"]
+ , $account
+ , $request->getMethod() . " " . $pathInfo
+ , $response->getStatusCode()
+ , $response->headers->get('content-type')
+ , $route['ressource']
+ , $route['general']
+ , $route['aspect']
+ , $route['action']
+ );
+ });
- $app->get('/databoxes/{any_id}/collections/', $bad_request_exception);
+ /**
+ * Method Not Allowed Closure
+ */
+ $bad_request_exception = function() {
+ throw new \API_V1_exception_badrequest();
+ };
+
+ /**
+ * *******************************************************************
+ * Route : /databoxes/list/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ *
+ */
+ $route = '/databoxes/list/';
+ $app->get(
+ $route, function() use ($app) {
+ return $app['api']->get_databoxes($app['request'])->get_response();
+ }
+ )->middleware($mustBeLogged);
+
+ /**
+ * *******************************************************************
+ *
+ * Route /databoxes/DATABOX_ID/collections/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ $route = '/databoxes/{databox_id}/collections/';
+ $app->get(
+ $route, function($databox_id) use ($app) {
+ $result = $app['api']->get_databox_collections($app['request'], $databox_id);
+
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+');
+
+ $app->get('/databoxes/{any_id}/collections/', $bad_request_exception);
- /**
- * *******************************************************************
- * Route /databoxes/DATABOX_ID/status/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- *
- */
- $route = '/databoxes/{databox_id}/status/';
- $app->get(
- $route, function($databox_id) use ($app)
- {
- $result = $app['api']->get_databox_status($app['request'], $databox_id);
+ /**
+ * *******************************************************************
+ * Route /databoxes/DATABOX_ID/status/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ *
+ */
+ $route = '/databoxes/{databox_id}/status/';
+ $app->get(
+ $route, function($databox_id) use ($app) {
+ $result = $app['api']->get_databox_status($app['request'], $databox_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+');
- $app->get('/databoxes/{any_id}/status/', $bad_request_exception);
+ $app->get('/databoxes/{any_id}/status/', $bad_request_exception);
- /**
- * Route /databoxes/DATABOX_ID/metadatas/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- $route = '/databoxes/{databox_id}/metadatas/';
- $app->get(
- $route, function($databox_id) use ($app)
- {
- $result = $app['api']->get_databox_metadatas($app['request'], $databox_id);
+ /**
+ * Route /databoxes/DATABOX_ID/metadatas/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ $route = '/databoxes/{databox_id}/metadatas/';
+ $app->get(
+ $route, function($databox_id) use ($app) {
+ $result = $app['api']->get_databox_metadatas($app['request'], $databox_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+');
- $app->get('/databoxes/{any_id}/metadatas/', $bad_request_exception);
+ $app->get('/databoxes/{any_id}/metadatas/', $bad_request_exception);
- /**
- * Route /databoxes/DATABOX_ID/termsOfUse/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- $route = '/databoxes/{databox_id}/termsOfUse/';
- $app->get(
- $route, function($databox_id) use ($app)
- {
- $result = $app['api']->get_databox_terms($app['request'], $databox_id);
+ /**
+ * Route /databoxes/DATABOX_ID/termsOfUse/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ $route = '/databoxes/{databox_id}/termsOfUse/';
+ $app->get(
+ $route, function($databox_id) use ($app) {
+ $result = $app['api']->get_databox_terms($app['request'], $databox_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+');
- $app->get('/databoxes/{any_id}/termsOfUse/', $bad_request_exception);
+ $app->get('/databoxes/{any_id}/termsOfUse/', $bad_request_exception);
- /**
- * Route : /records/search/FORMAT/
- *
- * Method : GET or POST
- *
- * Parameters :
- * bases[] : array
- * status[] : array
- * fields[] : array
- * record_type : boolean
- * media_type : string
- *
- * Response :
- * Array of record objects
- *
- */
- $route = '/records/search/';
- $app->match(
- $route, function() use ($app)
- {
- $result = $app['api']->search_records($app['request']);
+ /**
+ * Route : /records/search/FORMAT/
+ *
+ * Method : GET or POST
+ *
+ * Parameters :
+ * bases[] : array
+ * status[] : array
+ * fields[] : array
+ * record_type : boolean
+ * media_type : string
+ *
+ * Response :
+ * Array of record objects
+ *
+ */
+ $route = '/records/search/';
+ $app->match(
+ $route, function() use ($app) {
+ $result = $app['api']->search_records($app['request']);
- return $result->get_response();
- }
- )->middleware($mustBeLogged);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged);
- $route = '/records/{databox_id}/{record_id}/caption/';
- $app->get(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->caption_records($app['request'], $databox_id, $record_id);
+ $route = '/records/{databox_id}/{record_id}/caption/';
+ $app->get(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->caption_records($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/caption/', $bad_request_exception);
+ $app->get('/records/{any_id}/{anyother_id}/caption/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/metadatas/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/metadatas/';
- $app->get(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->get_record_metadatas($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/metadatas/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/metadatas/';
+ $app->get(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->get_record_metadatas($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/metadatas/', $bad_request_exception);
+ $app->get('/records/{any_id}/{anyother_id}/metadatas/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/status/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/status/';
- $app->get(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->get_record_status($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/status/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/status/';
+ $app->get(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->get_record_status($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/status/', $bad_request_exception);
+ $app->get('/records/{any_id}/{anyother_id}/status/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/related/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/related/';
- $app->get(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->get_record_related($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/related/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/related/';
+ $app->get(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->get_record_related($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/related/', $bad_request_exception);
+ $app->get('/records/{any_id}/{anyother_id}/related/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/embed/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/embed/';
- $app->get(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->get_record_embed($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/embed/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/embed/';
+ $app->get(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->get_record_embed($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/embed/', $bad_request_exception);
+ $app->get('/records/{any_id}/{anyother_id}/embed/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/setmetadatas/';
- $app->post(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->set_record_metadatas($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/setmetadatas/';
+ $app->post(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->set_record_metadatas($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->post('/records/{any_id}/{anyother_id}/setmetadatas/', $bad_request_exception);
+ $app->post('/records/{any_id}/{anyother_id}/setmetadatas/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setstatus/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/setstatus/';
- $app->post(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->set_record_status($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setstatus/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/setstatus/';
+ $app->post(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->set_record_status($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->post('/records/{any_id}/{anyother_id}/setstatus/', $bad_request_exception);
+ $app->post('/records/{any_id}/{anyother_id}/setstatus/', $bad_request_exception);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setcollection/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- $route = '/records/{databox_id}/{record_id}/setcollection/';
- $app->post(
- $route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->set_record_collection($app['request'], $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setcollection/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ $route = '/records/{databox_id}/{record_id}/setcollection/';
+ $app->post(
+ $route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->set_record_collection($app['request'], $databox_id, $record_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->post('/records/{wrong_databox_id}/{wrong_record_id}/setcollection/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ $app->post('/records/{wrong_databox_id}/{wrong_record_id}/setcollection/', $bad_request_exception);
- $route = '/records/{databox_id}/{record_id}/';
- $app->get($route, function($databox_id, $record_id) use ($app)
- {
- $result = $app['api']->get_record($app['request'], $databox_id, $record_id);
+ $route = '/records/{databox_id}/{record_id}/';
+ $app->get($route, function($databox_id, $record_id) use ($app) {
+ $result = $app['api']->get_record($app['request'], $databox_id, $record_id);
- return $result->get_response();
- })->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
- $app->get('/records/{any_id}/{anyother_id}/', $bad_request_exception);
+ return $result->get_response();
+ })->middleware($mustBeLogged)->assert('databox_id', '\d+')->assert('record_id', '\d+');
+ $app->get('/records/{any_id}/{anyother_id}/', $bad_request_exception);
- /**
- * Route : /baskets/list/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- $route = '/baskets/list/';
- $app->get(
- $route, function() use ($app)
- {
- $result = $app['api']->search_baskets($app['request']);
+ /**
+ * Route : /baskets/list/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ $route = '/baskets/list/';
+ $app->get(
+ $route, function() use ($app) {
+ $result = $app['api']->search_baskets($app['request']);
- return $result->get_response();
- }
- )->middleware($mustBeLogged);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged);
- /**
- * Route : /baskets/add/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- $route = '/baskets/add/';
- $app->post(
- $route, function() use ($app)
- {
- $result = $app['api']->create_basket($app['request']);
+ /**
+ * Route : /baskets/add/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ $route = '/baskets/add/';
+ $app->post(
+ $route, function() use ($app) {
+ $result = $app['api']->create_basket($app['request']);
- return $result->get_response();
- }
- )->middleware($mustBeLogged);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged);
- /**
- * Route : /baskets/BASKET_ID/content/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- $route = '/baskets/{basket_id}/content/';
- $app->get(
- $route, function($basket_id) use ($app)
- {
- $result = $app['api']->get_basket($app['request'], $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/content/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ $route = '/baskets/{basket_id}/content/';
+ $app->get(
+ $route, function($basket_id) use ($app) {
+ $result = $app['api']->get_basket($app['request'], $basket_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('basket_id', '\d+');
- $app->get('/baskets/{wrong_basket_id}/content/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('basket_id', '\d+');
+ $app->get('/baskets/{wrong_basket_id}/content/', $bad_request_exception);
- /**
- * Route : /baskets/BASKET_ID/settitle/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- $route = '/baskets/{basket_id}/setname/';
- $app->post(
- $route, function($basket_id) use ($app)
- {
- $result = $app['api']->set_basket_title($app['request'], $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/settitle/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ $route = '/baskets/{basket_id}/setname/';
+ $app->post(
+ $route, function($basket_id) use ($app) {
+ $result = $app['api']->set_basket_title($app['request'], $basket_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('basket_id', '\d+');
- $app->post('/baskets/{wrong_basket_id}/setname/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('basket_id', '\d+');
+ $app->post('/baskets/{wrong_basket_id}/setname/', $bad_request_exception);
- /**
- * Route : /baskets/BASKET_ID/setdescription/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- $route = '/baskets/{basket_id}/setdescription/';
- $app->post(
- $route, function($basket_id) use ($app)
- {
- $result = $app['api']->set_basket_description($app['request'], $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/setdescription/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ $route = '/baskets/{basket_id}/setdescription/';
+ $app->post(
+ $route, function($basket_id) use ($app) {
+ $result = $app['api']->set_basket_description($app['request'], $basket_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('basket_id', '\d+');
- $app->post('/baskets/{wrong_basket_id}/setdescription/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('basket_id', '\d+');
+ $app->post('/baskets/{wrong_basket_id}/setdescription/', $bad_request_exception);
- /**
- * Route : /baskets/BASKET_ID/delete/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- $route = '/baskets/{basket_id}/delete/';
- $app->post(
- $route, function($basket_id) use ($app)
- {
- $result = $app['api']->delete_basket($app['request'], $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/delete/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ $route = '/baskets/{basket_id}/delete/';
+ $app->post(
+ $route, function($basket_id) use ($app) {
+ $result = $app['api']->delete_basket($app['request'], $basket_id);
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('basket_id', '\d+');
- $app->post('/baskets/{wrong_basket_id}/delete/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('basket_id', '\d+');
+ $app->post('/baskets/{wrong_basket_id}/delete/', $bad_request_exception);
- /**
- * Route : /feeds/list/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
+ /**
+ * Route : /feeds/list/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
// public function search_publications(\Symfony\Component\HttpFoundation\Request $app['request']);
- $route = '/feeds/list/';
- $app->get(
- $route, function() use ($app)
- {
- $result = $app['api']->search_publications($app['request'], $app['Core']->getAuthenticatedUser());
+ $route = '/feeds/list/';
+ $app->get(
+ $route, function() use ($app) {
+ $result = $app['api']->search_publications($app['request'], $app['Core']->getAuthenticatedUser());
- return $result->get_response();
- }
- )->middleware($mustBeLogged);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged);
- /**
- * Route : /feeds/PUBLICATION_ID/content/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * PUBLICATION_ID : required INT
- *
- */
+ /**
+ * Route : /feeds/PUBLICATION_ID/content/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * PUBLICATION_ID : required INT
+ *
+ */
// public function get_publication(\Symfony\Component\HttpFoundation\Request $app['request'], $publication_id);
- $route = '/feeds/{feed_id}/content/';
- $app->get(
- $route, function($feed_id) use ($app)
- {
- $result = $app['api']->get_publication($app['request'], $feed_id, $app['Core']->getAuthenticatedUser());
+ $route = '/feeds/{feed_id}/content/';
+ $app->get(
+ $route, function($feed_id) use ($app) {
+ $result = $app['api']->get_publication($app['request'], $feed_id, $app['Core']->getAuthenticatedUser());
- return $result->get_response();
- }
- )->middleware($mustBeLogged)->assert('feed_id', '\d+');
- $app->get('/feeds/{wrong_feed_id}/content/', $bad_request_exception);
+ return $result->get_response();
+ }
+ )->middleware($mustBeLogged)->assert('feed_id', '\d+');
+ $app->get('/feeds/{wrong_feed_id}/content/', $bad_request_exception);
- /**
- * *******************************************************************
- *
- * Route Errors
- *
- */
- $app->error(function (\Exception $e) use ($app)
- {
+ /**
+ * *******************************************************************
+ *
+ * Route Errors
+ *
+ */
+ $app->error(function (\Exception $e) use ($app) {
- if ($e instanceof \API_V1_exception_methodnotallowed)
- $code = \API_V1_result::ERROR_METHODNOTALLOWED;
- elseif ($e instanceof Exception\MethodNotAllowedHttpException)
- $code = \API_V1_result::ERROR_METHODNOTALLOWED;
- elseif ($e instanceof \API_V1_exception_badrequest)
- $code = \API_V1_result::ERROR_BAD_REQUEST;
- elseif ($e instanceof \API_V1_exception_forbidden)
- $code = \API_V1_result::ERROR_FORBIDDEN;
- elseif ($e instanceof \API_V1_exception_unauthorized)
- $code = \API_V1_result::ERROR_UNAUTHORIZED;
- elseif ($e instanceof \API_V1_exception_internalservererror)
- $code = \API_V1_result::ERROR_INTERNALSERVERERROR;
- elseif ($e instanceof \Exception_NotFound)
- $code = \API_V1_result::ERROR_NOTFOUND;
- elseif ($e instanceof Exception\NotFoundHttpException)
- $code = \API_V1_result::ERROR_NOTFOUND;
- else
- $code = \API_V1_result::ERROR_INTERNALSERVERERROR;
+ if ($e instanceof \API_V1_exception_methodnotallowed)
+ $code = \API_V1_result::ERROR_METHODNOTALLOWED;
+ elseif ($e instanceof Exception\MethodNotAllowedHttpException)
+ $code = \API_V1_result::ERROR_METHODNOTALLOWED;
+ elseif ($e instanceof \API_V1_exception_badrequest)
+ $code = \API_V1_result::ERROR_BAD_REQUEST;
+ elseif ($e instanceof \API_V1_exception_forbidden)
+ $code = \API_V1_result::ERROR_FORBIDDEN;
+ elseif ($e instanceof \API_V1_exception_unauthorized)
+ $code = \API_V1_result::ERROR_UNAUTHORIZED;
+ elseif ($e instanceof \API_V1_exception_internalservererror)
+ $code = \API_V1_result::ERROR_INTERNALSERVERERROR;
+ elseif ($e instanceof \Exception_NotFound)
+ $code = \API_V1_result::ERROR_NOTFOUND;
+ elseif ($e instanceof Exception\NotFoundHttpException)
+ $code = \API_V1_result::ERROR_NOTFOUND;
+ else
+ $code = \API_V1_result::ERROR_INTERNALSERVERERROR;
- $result = $app['api']->get_error_message($app['request'], $code);
+ $result = $app['api']->get_error_message($app['request'], $code);
- return $result->get_response();
- });
+ return $result->get_response();
+ });
////
////
//// /**
@@ -726,5 +684,5 @@ return call_user_func(function()
//// *
//// */
//// public function add_user(\Symfony\Component\HttpFoundation\Request $app['request']);
- return $app;
- });
+ return $app;
+ });
diff --git a/lib/Alchemy/Phrasea/Application/ApiVersion.php b/lib/Alchemy/Phrasea/Application/ApiVersion.php
index c4d223efbe..974fa7d400 100644
--- a/lib/Alchemy/Phrasea/Application/ApiVersion.php
+++ b/lib/Alchemy/Phrasea/Application/ApiVersion.php
@@ -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;
+ });
+
diff --git a/lib/Alchemy/Phrasea/Application/Lightbox.php b/lib/Alchemy/Phrasea/Application/Lightbox.php
index a8ef6f817a..0ef790ae03 100644
--- a/lib/Alchemy/Phrasea/Application/Lightbox.php
+++ b/lib/Alchemy/Phrasea/Application/Lightbox.php
@@ -24,639 +24,594 @@ use Alchemy\Phrasea\Controller\Exception as ControllerException;
* @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();
- $appbox = \appbox::get_instance($app['Core']);
+ $appbox = \appbox::get_instance($app['Core']);
- $app->get('/', function (\Silex\Application $app) use ($appbox)
- {
- \User_Adapter::updateClientInfos((6));
+ $app->get('/', function (\Silex\Application $app) use ($appbox) {
+ \User_Adapter::updateClientInfos((6));
- $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
+ $em = $app['Core']->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
- $current_user = $app['Core']->getAuthenticatedUser();
+ $current_user = $app['Core']->getAuthenticatedUser();
- /* @var $repository \Repositories\BasketRepository */
+ /* @var $repository \Repositories\BasketRepository */
- $basket_collection = array_merge(
- $repository->findActiveByUser($current_user)
- , $repository->findActiveValidationByUser($current_user)
- );
+ $basket_collection = array_merge(
+ $repository->findActiveByUser($current_user)
+ , $repository->findActiveValidationByUser($current_user)
+ );
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
- $browser = \Browser::getInstance();
+ $browser = \Browser::getInstance();
- $template = 'lightbox/index.twig';
- if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
- {
- $template = 'lightbox/IE6/index.twig';
- }
+ $template = 'lightbox/index.twig';
+ if ( ! $browser->isNewGeneration() && ! $browser->isMobile()) {
+ $template = 'lightbox/IE6/index.twig';
+ }
- $output = $twig->render($template, array(
- 'baskets_collection' => $basket_collection,
- 'module_name' => 'Lightbox',
- 'module' => 'lightbox'
- )
- );
- $response = new Response($output);
- $response->setCharset('UTF-8');
+ $output = $twig->render($template, array(
+ 'baskets_collection' => $basket_collection,
+ 'module_name' => 'Lightbox',
+ 'module' => 'lightbox'
+ )
+ );
+ $response = new Response($output);
+ $response->setCharset('UTF-8');
- return $response;
+ return $response;
+ }
+ );
+
+ $app->get('/ajax/NOTE_FORM/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id) use ($appbox) {
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+ $browser = \Browser::getInstance();
+
+ if ( ! $browser->isMobile()) {
+ return new Response('');
+ }
+
+
+ $em = $app['Core']->getEntityManager();
+
+ /* @var $repository \Repositories\BasketElementRepository */
+ $repository = $em->getRepository('\Entities\BasketElement');
+
+ $basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
+
+ $template = 'lightbox/note_form.twig';
+ $output = $twig->render($template, array('basket_element' => $basket_element, 'module_name' => ''));
+
+ return new Response($output);
+ }
+ )->assert('sselcont_id', '\d+');
+
+ $app->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id) {
+ $browser = \Browser::getInstance();
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $em = $app['Core']->getEntityManager();
+
+ /* @var $repository \Repositories\BasketElementRepository */
+ $repository = $em->getRepository('\Entities\BasketElement');
+
+ $BasketElement = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
+
+ if ($browser->isMobile()) {
+ $output = $twig->render('lightbox/basket_element.twig', array(
+ 'basket_element' => $BasketElement,
+ 'module_name' => $BasketElement->getRecord()->get_title()
+ )
+ );
+
+ return new Response($output);
+ } else {
+ $template_options = 'lightbox/sc_options_box.twig';
+ $template_agreement = 'lightbox/agreement_box.twig';
+ $template_selector = 'lightbox/selector_box.twig';
+ $template_note = 'lightbox/sc_note.twig';
+ $template_preview = 'common/preview.html';
+ $template_caption = 'common/caption.html';
+
+ if ( ! $browser->isNewGeneration()) {
+ $template_options = 'lightbox/IE6/sc_options_box.twig';
+ $template_agreement = 'lightbox/IE6/agreement_box.twig';
+ }
+ $appbox = \appbox::get_instance($app['Core']);
+ $usr_id = $appbox->get_session()->get_usr_id();
+
+
+ $Basket = $BasketElement->getBasket();
+
+ $ret = array();
+ $ret['number'] = $BasketElement->getRecord()->get_number();
+ $ret['title'] = $BasketElement->getRecord()->get_title();
+
+ $ret['preview'] = $twig->render($template_preview, array('record' => $BasketElement->getRecord(), 'not_wrapped' => true));
+ $ret['options_html'] = $twig->render($template_options, array('basket_element' => $BasketElement));
+ $ret['agreement_html'] = $twig->render($template_agreement, array('basket' => $Basket, 'basket_element' => $BasketElement));
+ $ret['selector_html'] = $twig->render($template_selector, array('basket_element' => $BasketElement));
+ $ret['note_html'] = $twig->render($template_note, array('basket_element' => $BasketElement));
+ $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $BasketElement->getRecord()));
+
+ $Serializer = $app['Core']['Serializer'];
+
+ return new Response(
+ $Serializer->serialize($ret, 'json')
+ , 200
+ , array('Content-Type' => 'application/json')
+ );
+ }
+ }
+ )->assert('sselcont_id', '\d+');
+
+
+
+
+ $app->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function(\Silex\Application $app, $entry_id, $item_id) {
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $appbox = \appbox::get_instance($app['Core']);
+ $entry = \Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
+ $item = new \Feed_Entry_Item($appbox, $entry, $item_id);
+
+ $browser = \Browser::getInstance();
+
+ if ($browser->isMobile()) {
+ $output = $twig->render('lightbox/feed_element.twig', array(
+ 'feed_element' => $item,
+ 'module_name' => $item->get_record()->get_title()
+ )
+ );
+
+ return new Response($output);
+ } else {
+ $template_options = 'lightbox/feed_options_box.twig';
+ $template_preview = 'common/preview.html';
+ $template_caption = 'common/caption.html';
+
+ if ( ! $browser->isNewGeneration()) {
+ $template_options = 'lightbox/IE6/feed_options_box.twig';
+ }
+ $usr_id = $appbox->get_session()->get_usr_id();
+
+ $ret = array();
+ $ret['number'] = $item->get_record()->get_number();
+ $ret['title'] = $item->get_record()->get_title();
+
+ $ret['preview'] = $twig->render($template_preview, array('record' => $item->get_record(), 'not_wrapped' => true));
+ $ret['options_html'] = $twig->render($template_options, array('feed_element' => $item));
+ $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $item->get_record()));
+
+
+ $ret['agreement_html'] = $ret['selector_html'] = $ret['note_html'] = '';
+
+ $Serializer = $app['Core']['Serializer'];
+
+ return new Response(
+ $Serializer->serialize($ret, 'json')
+ , 200
+ , array('Content-type' => 'application/json')
+ );
+ }
+ }
+ )->assert('entry_id', '\d+')->assert('item_id', '\d+');
+
+ $app->get('/validate/{ssel_id}/', function (\Silex\Application $app, $ssel_id) use ($appbox) {
+
+ \User_Adapter::updateClientInfos((6));
+
+ $browser = \Browser::getInstance();
+
+ $em = $app['Core']->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ /* @var $repository \Repositories\BasketRepository */
+ $basket_collection = $repository->findActiveValidationAndBasketByUser(
+ $app['Core']->getAuthenticatedUser()
+ );
+
+ $basket = $repository->findUserBasket(
+ $ssel_id
+ , $app['Core']->getAuthenticatedUser()
+ , false
+ );
+
+
+ if ($basket->getIsRead() === false) {
+ $basket = $em->merge($basket);
+ $basket->setIsRead(true);
+ $em->flush();
+ }
+
+ if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false) {
+ $basket = $em->merge($basket);
+ $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
+ $em->flush();
+ }
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $template = 'lightbox/validate.twig';
+
+ if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
+ $template = 'lightbox/IE6/validate.twig';
+
+ $response = new Response($twig->render($template, array(
+ 'baskets_collection' => $basket_collection,
+ 'basket' => $basket,
+ 'local_title' => strip_tags($basket->getName()),
+ 'module' => 'lightbox',
+ 'module_name' => _('admin::monitor: module validation')
+ )
+ ));
+ $response->setCharset('UTF-8');
+
+ return $response;
+ }
+ )->assert('ssel_id', '\d+');
+
+ $app->get('/compare/{ssel_id}/', function (\Silex\Application $app, $ssel_id) use ($appbox) {
+
+ \User_Adapter::updateClientInfos((6));
+
+ $browser = \Browser::getInstance();
+
+ $em = $app['Core']->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ /* @var $repository \Repositories\BasketRepository */
+ $basket_collection = $repository->findActiveValidationAndBasketByUser(
+ $app['Core']->getAuthenticatedUser()
+ );
+
+ $basket = $repository->findUserBasket(
+ $ssel_id
+ , $app['Core']->getAuthenticatedUser()
+ , false
+ );
+
+
+ if ($basket->getIsRead() === false) {
+ $basket = $em->merge($basket);
+ $basket->setIsRead(true);
+ $em->flush();
+ }
+
+ if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false) {
+ $basket = $em->merge($basket);
+ $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
+ $em->flush();
+ }
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $template = 'lightbox/validate.twig';
+
+ if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
+ $template = 'lightbox/IE6/validate.twig';
+
+ $response = new Response($twig->render($template, array(
+ 'baskets_collection' => $basket_collection,
+ 'basket' => $basket,
+ 'local_title' => strip_tags($basket->getName()),
+ 'module' => 'lightbox',
+ 'module_name' => _('admin::monitor: module validation')
+ )
+ ));
+ $response->setCharset('UTF-8');
+
+ return $response;
+ }
+ )->assert('ssel_id', '\d+');
+
+
+
+ $app->get('/feeds/entry/{entry_id}/', function (\Silex\Application $app, $entry_id) use ($appbox) {
+
+ \User_Adapter::updateClientInfos((6));
+
+ $browser = \Browser::getInstance();
+
+ $feed_entry = \Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $template = 'lightbox/feed.twig';
+
+ if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
+ $template = 'lightbox/IE6/feed.twig';
+
+ $output = $twig->render($template, array(
+ 'feed_entry' => $feed_entry,
+ 'first_item' => array_shift($feed_entry->get_content()),
+ 'local_title' => $feed_entry->get_title(),
+ 'module' => 'lightbox',
+ 'module_name' => _('admin::monitor: module validation')
+ )
+ );
+ $response = new Response($output, 200);
+ $response->setCharset('UTF-8');
+
+ return $response;
+ }
+ )->assert('entry_id', '\d+');
+
+ $app->get('/ajax/LOAD_REPORT/{ssel_id}/', function(\Silex\Application $app, $ssel_id) {
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $browser = \Browser::getInstance();
+
+ $template = 'lightbox/basket_content_report.twig';
+
+ $em = $app['Core']->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ /* @var $repository \Repositories\BasketRepository */
+ $basket = $repository->findUserBasket(
+ $ssel_id
+ , $app['Core']->getAuthenticatedUser()
+ , false
+ );
+
+ $response = new Response($twig->render($template, array('basket' => $basket)));
+ $response->setCharset('UTF-8');
+
+ return $response;
+ }
+ )->assert('ssel_id', '\d+');
+
+ $app->post('/ajax/SET_NOTE/{sselcont_id}/', function (\Silex\Application $app, $sselcont_id) {
+ $output = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees'));
+
+ $request = $app['request'];
+ $note = $request->get('note');
+
+ if (is_null($note)) {
+ Return new Response('You must provide a note value', 400);
+ }
+
+ $em = $app['Core']->getEntityManager();
+
+ /* @var $repository \Repositories\BasketElementRepository */
+ $repository = $em->getRepository('\Entities\BasketElement');
+
+ $basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
+
+ $validationDatas = $basket_element->getUserValidationDatas($app['Core']->getAuthenticatedUser());
+
+ $validationDatas->setNote($note);
+
+ $em->merge($validationDatas);
+
+ $em->flush();
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+
+ $browser = \Browser::getInstance();
+
+ if ($browser->isMobile()) {
+ $datas = $twig->render('lightbox/sc_note.twig', array('basket_element' => $basket_element));
+
+ $output = array('error' => false, 'datas' => $datas);
+ } else {
+ $template = 'lightbox/sc_note.twig';
+
+ $datas = $twig->render($template, array('basket_element' => $basket_element));
+
+ $output = array('error' => false, 'datas' => $datas);
+ }
+
+ $Serializer = $app['Core']['Serializer'];
+
+ return new Response(
+ $Serializer->serialize($output, 'json')
+ , 200
+ , array('Content-Type' => 'application/json')
+ );
+ }
+ )->assert('sselcont_id', '\d+');
+
+ $app->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id) {
+ $request = $app['request'];
+ $agreement = $request->get('agreement');
+
+ if (is_null($agreement)) {
+ Return new Response('You must provide an agreement value', 400);
+ }
+
+ $agreement = $agreement > 0;
+
+ $releasable = false;
+ try {
+ $ret = array(
+ 'error' => true,
+ 'releasable' => false,
+ 'datas' => _('Erreur lors de la mise a jour des donnes ')
+ );
+
+ $user = $app['Core']->getAuthenticatedUser();
+ $em = $app['Core']->getEntityManager();
+ $repository = $em->getRepository('\Entities\BasketElement');
+
+ /* @var $repository \Repositories\BasketElementRepository */
+ $basket_element = $repository->findUserElement(
+ $sselcont_id
+ , $user
+ );
+ /* @var $basket_element \Entities\BasketElement */
+ $validationDatas = $basket_element->getUserValidationDatas($user);
+
+ if ( ! $basket_element->getBasket()
+ ->getValidation()
+ ->getParticipant($user)->getCanAgree()) {
+ throw new ControllerException('You can not agree on this');
+ }
+
+ $validationDatas->setAgreement($agreement);
+
+ $participant = $basket_element->getBasket()
+ ->getValidation()
+ ->getParticipant($user);
+
+ $em->merge($basket_element);
+
+ $em->flush();
+
+ $releasable = false;
+ if ($participant->isReleasable() === true) {
+ $releasable = _('Do you want to send your report ?');
+ }
+
+ $ret = array(
+ 'error' => false
+ , 'datas' => ''
+ , 'releasable' => $releasable
+ );
+ } catch (ControllerException $e) {
+ $ret['datas'] = $e->getMessage();
+ }
+ $Serializer = $app['Core']['Serializer'];
+
+ return new Response(
+ $Serializer->serialize($ret, 'json')
+ , 200
+ , array('Content-Type' => 'application/json')
+ );
+ }
+ )->assert('sselcont_id', '\d+');
+
+
+ $app->post('/ajax/SET_RELEASE/{ssel_id}/', function(\Silex\Application $app, $ssel_id) use ($appbox) {
+
+ $em = $app['Core']->getEntityManager();
+
+ $user = $app['Core']->getAuthenticatedUser();
+
+ $repository = $em->getRepository('\Entities\Basket');
+
+ $datas = array('error' => true, 'datas' => '');
+
+ try {
+ /* @var $repository \Repositories\BasketRepository */
+ $basket = $repository->findUserBasket(
+ $ssel_id
+ , $user
+ , false
+ );
+
+ if ( ! $basket->getValidation()) {
+ throw new ControllerException('There is no validation session attached to this basket');
+ }
+
+ if ( ! $basket->getValidation()->getParticipant($user)->getCanAgree()) {
+ throw new ControllerException('You have not right to agree');
+ }
+
+ /* @var $basket \Entities\Basket */
+ $participant = $basket->getValidation()->getParticipant($user);
+
+ $appbox = \appbox::get_instance($app['Core']);
+ $evt_mngr = \eventsmanager_broker::getInstance($appbox, $app['Core']);
+
+ $expires = new \DateTime('+10 days');
+ $url = $appbox->get_registry()->get('GV_ServerName')
+ . 'lightbox/index.php?LOG=' . \random::getUrlToken(
+ \random::TYPE_VALIDATE
+ , $basket->getValidation()->getInitiator()->get_id()
+ , $expires
+ , $basket->getId()
+ );
+
+
+ $to = $basket->getValidation()->getInitiator()->get_id();
+ $params = array(
+ 'ssel_id' => $basket->getId(),
+ 'from' => $app['Core']->getAuthenticatedUser()->get_id(),
+ 'url' => $url,
+ 'to' => $to
+ );
+
+
+
+ $evt_mngr->trigger('__VALIDATION_DONE__', $params);
+
+
+ $participant->setIsConfirmed(true);
+
+ $em->merge($participant);
+
+ $em->flush();
+
+ $datas = array('error' => false, 'datas' => _('Envoie avec succes'));
+ } catch (ControllerException $e) {
+ $datas = array('error' => true, 'datas' => $e->getMessage());
+ }
+
+ $Serializer = $app['Core']['Serializer'];
+
+ $response = new Response(
+ $Serializer->serialize($datas, 'json')
+ , 200
+ , array('Content-Type' => 'application/json')
+ );
+
+ $response->setCharset('UTF-8');
+
+ return $response;
+ }
+ )->assert('ssel_id', '\d+');
+
+
+
+ $app->error(function($e) use($app) {
+
+ /* @var $twig \Twig_Environment */
+ $twig = $app['Core']->getTwig();
+ $registry = \registry::get_instance();
+
+ $template = 'lightbox/error.twig';
+
+ if ($registry->get('GV_debug')) {
+ $options = array(
+ 'module' => 'validation',
+ 'module_name' => _('admin::monitor: module validation'),
+ 'error' => sprintf(
+ '%s in %s on line %s '
+ , $e->getMessage()
+ , $e->getFile()
+ , $e->getLine()
+ )
+ );
+ } else {
+ $options = array(
+ 'module' => 'validation',
+ 'module_name' => _('admin::monitor: module validation'),
+ 'error' => ''
+ );
+ }
+ $output = $twig->render($template, $options);
+ $response = new Response($output, 404);
+ $response->setCharset('UTF-8');
+
+ return $response;
+ });
+
+ return $app;
}
- );
-
- $app->get('/ajax/NOTE_FORM/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id) use ($appbox)
- {
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
- $browser = \Browser::getInstance();
-
- if ( ! $browser->isMobile())
- {
- return new Response('');
- }
-
-
- $em = $app['Core']->getEntityManager();
-
- /* @var $repository \Repositories\BasketElementRepository */
- $repository = $em->getRepository('\Entities\BasketElement');
-
- $basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
-
- $template = 'lightbox/note_form.twig';
- $output = $twig->render($template, array('basket_element' => $basket_element, 'module_name' => ''));
-
- return new Response($output);
- }
- )->assert('sselcont_id', '\d+');
-
- $app->get('/ajax/LOAD_BASKET_ELEMENT/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id)
- {
- $browser = \Browser::getInstance();
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $em = $app['Core']->getEntityManager();
-
- /* @var $repository \Repositories\BasketElementRepository */
- $repository = $em->getRepository('\Entities\BasketElement');
-
- $BasketElement = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
-
- if ($browser->isMobile())
- {
- $output = $twig->render('lightbox/basket_element.twig', array(
- 'basket_element' => $BasketElement,
- 'module_name' => $BasketElement->getRecord()->get_title()
- )
- );
-
- return new Response($output);
- }
- else
- {
- $template_options = 'lightbox/sc_options_box.twig';
- $template_agreement = 'lightbox/agreement_box.twig';
- $template_selector = 'lightbox/selector_box.twig';
- $template_note = 'lightbox/sc_note.twig';
- $template_preview = 'common/preview.html';
- $template_caption = 'common/caption.html';
-
- if ( ! $browser->isNewGeneration())
- {
- $template_options = 'lightbox/IE6/sc_options_box.twig';
- $template_agreement = 'lightbox/IE6/agreement_box.twig';
- }
- $appbox = \appbox::get_instance($app['Core']);
- $usr_id = $appbox->get_session()->get_usr_id();
-
-
- $Basket = $BasketElement->getBasket();
-
- $ret = array();
- $ret['number'] = $BasketElement->getRecord()->get_number();
- $ret['title'] = $BasketElement->getRecord()->get_title();
-
- $ret['preview'] = $twig->render($template_preview, array('record' => $BasketElement->getRecord(), 'not_wrapped' => true));
- $ret['options_html'] = $twig->render($template_options, array('basket_element' => $BasketElement));
- $ret['agreement_html'] = $twig->render($template_agreement, array('basket' => $Basket, 'basket_element' => $BasketElement));
- $ret['selector_html'] = $twig->render($template_selector, array('basket_element' => $BasketElement));
- $ret['note_html'] = $twig->render($template_note, array('basket_element' => $BasketElement));
- $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $BasketElement->getRecord()));
-
- $Serializer = $app['Core']['Serializer'];
-
- return new Response(
- $Serializer->serialize($ret, 'json')
- , 200
- , array('Content-Type' => 'application/json')
- );
- }
- }
- )->assert('sselcont_id', '\d+');
-
-
-
-
- $app->get('/ajax/LOAD_FEED_ITEM/{entry_id}/{item_id}/', function(\Silex\Application $app, $entry_id, $item_id)
- {
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $appbox = \appbox::get_instance($app['Core']);
- $entry = \Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
- $item = new \Feed_Entry_Item($appbox, $entry, $item_id);
-
- $browser = \Browser::getInstance();
-
- if ($browser->isMobile())
- {
- $output = $twig->render('lightbox/feed_element.twig', array(
- 'feed_element' => $item,
- 'module_name' => $item->get_record()->get_title()
- )
- );
-
- return new Response($output);
- }
- else
- {
- $template_options = 'lightbox/feed_options_box.twig';
- $template_preview = 'common/preview.html';
- $template_caption = 'common/caption.html';
-
- if ( ! $browser->isNewGeneration())
- {
- $template_options = 'lightbox/IE6/feed_options_box.twig';
- }
- $usr_id = $appbox->get_session()->get_usr_id();
-
- $ret = array();
- $ret['number'] = $item->get_record()->get_number();
- $ret['title'] = $item->get_record()->get_title();
-
- $ret['preview'] = $twig->render($template_preview, array('record' => $item->get_record(), 'not_wrapped' => true));
- $ret['options_html'] = $twig->render($template_options, array('feed_element' => $item));
- $ret['caption'] = $twig->render($template_caption, array('view' => 'preview', 'record' => $item->get_record()));
-
-
- $ret['agreement_html'] = $ret['selector_html'] = $ret['note_html'] = '';
-
- $Serializer = $app['Core']['Serializer'];
-
- return new Response(
- $Serializer->serialize($ret, 'json')
- , 200
- , array('Content-type' => 'application/json')
- );
- }
- }
- )->assert('entry_id', '\d+')->assert('item_id', '\d+');
-
- $app->get('/validate/{ssel_id}/', function (\Silex\Application $app, $ssel_id) use ($appbox)
- {
-
- \User_Adapter::updateClientInfos((6));
-
- $browser = \Browser::getInstance();
-
- $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- /* @var $repository \Repositories\BasketRepository */
- $basket_collection = $repository->findActiveValidationAndBasketByUser(
- $app['Core']->getAuthenticatedUser()
- );
-
- $basket = $repository->findUserBasket(
- $ssel_id
- , $app['Core']->getAuthenticatedUser()
- , false
- );
-
-
- if ($basket->getIsRead() === false)
- {
- $basket = $em->merge($basket);
- $basket->setIsRead(true);
- $em->flush();
- }
-
- if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false)
- {
- $basket = $em->merge($basket);
- $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
- $em->flush();
- }
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $template = 'lightbox/validate.twig';
-
- if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
- $template = 'lightbox/IE6/validate.twig';
-
- $response = new Response($twig->render($template, array(
- 'baskets_collection' => $basket_collection,
- 'basket' => $basket,
- 'local_title' => strip_tags($basket->getName()),
- 'module' => 'lightbox',
- 'module_name' => _('admin::monitor: module validation')
- )
- ));
- $response->setCharset('UTF-8');
-
- return $response;
- }
- )->assert('ssel_id', '\d+');
-
- $app->get('/compare/{ssel_id}/', function (\Silex\Application $app, $ssel_id) use ($appbox)
- {
-
- \User_Adapter::updateClientInfos((6));
-
- $browser = \Browser::getInstance();
-
- $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- /* @var $repository \Repositories\BasketRepository */
- $basket_collection = $repository->findActiveValidationAndBasketByUser(
- $app['Core']->getAuthenticatedUser()
- );
-
- $basket = $repository->findUserBasket(
- $ssel_id
- , $app['Core']->getAuthenticatedUser()
- , false
- );
-
-
- if ($basket->getIsRead() === false)
- {
- $basket = $em->merge($basket);
- $basket->setIsRead(true);
- $em->flush();
- }
-
- if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->getIsAware() === false)
- {
- $basket = $em->merge($basket);
- $basket->getValidation()->getParticipant($app['Core']->getAuthenticatedUser())->setIsAware(true);
- $em->flush();
- }
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $template = 'lightbox/validate.twig';
-
- if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
- $template = 'lightbox/IE6/validate.twig';
-
- $response = new Response($twig->render($template, array(
- 'baskets_collection' => $basket_collection,
- 'basket' => $basket,
- 'local_title' => strip_tags($basket->getName()),
- 'module' => 'lightbox',
- 'module_name' => _('admin::monitor: module validation')
- )
- ));
- $response->setCharset('UTF-8');
-
- return $response;
- }
- )->assert('ssel_id', '\d+');
-
-
-
- $app->get('/feeds/entry/{entry_id}/', function (\Silex\Application $app, $entry_id) use ($appbox)
- {
-
- \User_Adapter::updateClientInfos((6));
-
- $browser = \Browser::getInstance();
-
- $feed_entry = \Feed_Entry_Adapter::load_from_id($appbox, $entry_id);
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $template = 'lightbox/feed.twig';
-
- if ( ! $browser->isNewGeneration() && ! $browser->isMobile())
- $template = 'lightbox/IE6/feed.twig';
-
- $output = $twig->render($template, array(
- 'feed_entry' => $feed_entry,
- 'first_item' => array_shift($feed_entry->get_content()),
- 'local_title' => $feed_entry->get_title(),
- 'module' => 'lightbox',
- 'module_name' => _('admin::monitor: module validation')
- )
- );
- $response = new Response($output, 200);
- $response->setCharset('UTF-8');
-
- return $response;
- }
- )->assert('entry_id', '\d+');
-
- $app->get('/ajax/LOAD_REPORT/{ssel_id}/', function(\Silex\Application $app, $ssel_id)
- {
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $browser = \Browser::getInstance();
-
- $template = 'lightbox/basket_content_report.twig';
-
- $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- /* @var $repository \Repositories\BasketRepository */
- $basket = $repository->findUserBasket(
- $ssel_id
- , $app['Core']->getAuthenticatedUser()
- , false
- );
-
- $response = new Response($twig->render($template, array('basket' => $basket)));
- $response->setCharset('UTF-8');
-
- return $response;
- }
- )->assert('ssel_id', '\d+');
-
- $app->post('/ajax/SET_NOTE/{sselcont_id}/', function (\Silex\Application $app, $sselcont_id)
- {
- $output = array('error' => true, 'datas' => _('Erreur lors de l\'enregistrement des donnees'));
-
- $request = $app['request'];
- $note = $request->get('note');
-
- if (is_null($note))
- {
- Return new Response('You must provide a note value', 400);
- }
-
- $em = $app['Core']->getEntityManager();
-
- /* @var $repository \Repositories\BasketElementRepository */
- $repository = $em->getRepository('\Entities\BasketElement');
-
- $basket_element = $repository->findUserElement($sselcont_id, $app['Core']->getAuthenticatedUser());
-
- $validationDatas = $basket_element->getUserValidationDatas($app['Core']->getAuthenticatedUser());
-
- $validationDatas->setNote($note);
-
- $em->merge($validationDatas);
-
- $em->flush();
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
-
- $browser = \Browser::getInstance();
-
- if ($browser->isMobile())
- {
- $datas = $twig->render('lightbox/sc_note.twig', array('basket_element' => $basket_element));
-
- $output = array('error' => false, 'datas' => $datas);
- }
- else
- {
- $template = 'lightbox/sc_note.twig';
-
- $datas = $twig->render($template, array('basket_element' => $basket_element));
-
- $output = array('error' => false, 'datas' => $datas);
- }
-
- $Serializer = $app['Core']['Serializer'];
-
- return new Response(
- $Serializer->serialize($output, 'json')
- , 200
- , array('Content-Type' => 'application/json')
- );
- }
- )->assert('sselcont_id', '\d+');
-
- $app->post('/ajax/SET_ELEMENT_AGREEMENT/{sselcont_id}/', function(\Silex\Application $app, $sselcont_id)
- {
- $request = $app['request'];
- $agreement = $request->get('agreement');
-
- if (is_null($agreement))
- {
- Return new Response('You must provide an agreement value', 400);
- }
-
- $agreement = $agreement > 0;
-
- $releasable = false;
- try
- {
- $ret = array(
- 'error' => true,
- 'releasable' => false,
- 'datas' => _('Erreur lors de la mise a jour des donnes ')
- );
-
- $user = $app['Core']->getAuthenticatedUser();
- $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\BasketElement');
-
- /* @var $repository \Repositories\BasketElementRepository */
- $basket_element = $repository->findUserElement(
- $sselcont_id
- , $user
- );
- /* @var $basket_element \Entities\BasketElement */
- $validationDatas = $basket_element->getUserValidationDatas($user);
-
- if ( ! $basket_element->getBasket()
- ->getValidation()
- ->getParticipant($user)->getCanAgree())
- {
- throw new ControllerException('You can not agree on this');
- }
-
- $validationDatas->setAgreement($agreement);
-
- $participant = $basket_element->getBasket()
- ->getValidation()
- ->getParticipant($user);
-
- $em->merge($basket_element);
-
- $em->flush();
-
- $releasable = false;
- if ($participant->isReleasable() === true)
- {
- $releasable = _('Do you want to send your report ?');
- }
-
- $ret = array(
- 'error' => false
- , 'datas' => ''
- , 'releasable' => $releasable
- );
- }
- catch (ControllerException $e)
- {
- $ret['datas'] = $e->getMessage();
- }
- $Serializer = $app['Core']['Serializer'];
-
- return new Response(
- $Serializer->serialize($ret, 'json')
- , 200
- , array('Content-Type' => 'application/json')
- );
- }
- )->assert('sselcont_id', '\d+');
-
-
- $app->post('/ajax/SET_RELEASE/{ssel_id}/', function(\Silex\Application $app, $ssel_id) use ($appbox)
- {
-
- $em = $app['Core']->getEntityManager();
-
- $user = $app['Core']->getAuthenticatedUser();
-
- $repository = $em->getRepository('\Entities\Basket');
-
- $datas = array('error' => true, 'datas' => '');
-
- try
- {
- /* @var $repository \Repositories\BasketRepository */
- $basket = $repository->findUserBasket(
- $ssel_id
- , $user
- , false
- );
-
- if ( ! $basket->getValidation())
- {
- throw new ControllerException('There is no validation session attached to this basket');
- }
-
- if ( ! $basket->getValidation()->getParticipant($user)->getCanAgree())
- {
- throw new ControllerException('You have not right to agree');
- }
-
- /* @var $basket \Entities\Basket */
- $participant = $basket->getValidation()->getParticipant($user);
-
- $appbox = \appbox::get_instance($app['Core']);
- $evt_mngr = \eventsmanager_broker::getInstance($appbox, $app['Core']);
-
- $expires = new \DateTime('+10 days');
- $url = $appbox->get_registry()->get('GV_ServerName')
- . 'lightbox/index.php?LOG=' . \random::getUrlToken(
- \random::TYPE_VALIDATE
- , $basket->getValidation()->getInitiator()->get_id()
- , $expires
- , $basket->getId()
- );
-
-
- $to = $basket->getValidation()->getInitiator()->get_id();
- $params = array(
- 'ssel_id' => $basket->getId(),
- 'from' => $app['Core']->getAuthenticatedUser()->get_id(),
- 'url' => $url,
- 'to' => $to
- );
-
-
-
- $evt_mngr->trigger('__VALIDATION_DONE__', $params);
-
-
- $participant->setIsConfirmed(true);
-
- $em->merge($participant);
-
- $em->flush();
-
- $datas = array('error' => false, 'datas' => _('Envoie avec succes'));
- }
- catch (ControllerException $e)
- {
- $datas = array('error' => true, 'datas' => $e->getMessage());
- }
-
- $Serializer = $app['Core']['Serializer'];
-
- $response = new Response(
- $Serializer->serialize($datas, 'json')
- , 200
- , array('Content-Type' => 'application/json')
- );
-
- $response->setCharset('UTF-8');
-
- return $response;
- }
- )->assert('ssel_id', '\d+');
-
-
-
- $app->error(function($e) use($app)
- {
-
- /* @var $twig \Twig_Environment */
- $twig = $app['Core']->getTwig();
- $registry = \registry::get_instance();
-
- $template = 'lightbox/error.twig';
-
- if ($registry->get('GV_debug'))
- {
- $options = array(
- 'module' => 'validation',
- 'module_name' => _('admin::monitor: module validation'),
- 'error' => sprintf(
- '%s in %s on line %s '
- , $e->getMessage()
- , $e->getFile()
- , $e->getLine()
- )
- );
- }
- else
- {
- $options = array(
- 'module' => 'validation',
- 'module_name' => _('admin::monitor: module validation'),
- 'error' => ''
- );
- }
- $output = $twig->render($template, $options);
- $response = new Response($output, 404);
- $response->setCharset('UTF-8');
-
- return $response;
- });
-
- return $app;
- }
);
diff --git a/lib/Alchemy/Phrasea/Application/OAuth2.php b/lib/Alchemy/Phrasea/Application/OAuth2.php
index e1fa9e30a5..f40c738678 100644
--- a/lib/Alchemy/Phrasea/Application/OAuth2.php
+++ b/lib/Alchemy/Phrasea/Application/OAuth2.php
@@ -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;
+ });
diff --git a/lib/Alchemy/Phrasea/Application/Overview.php b/lib/Alchemy/Phrasea/Application/Overview.php
index c614ad6f8b..02e4339407 100644
--- a/lib/Alchemy/Phrasea/Application/Overview.php
+++ b/lib/Alchemy/Phrasea/Application/Overview.php
@@ -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;
+ }
);
diff --git a/lib/Alchemy/Phrasea/Application/Prod.php b/lib/Alchemy/Phrasea/Application/Prod.php
index 8087155a6e..c088fd5268 100644
--- a/lib/Alchemy/Phrasea/Application/Prod.php
+++ b/lib/Alchemy/Phrasea/Application/Prod.php
@@ -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;
- });
diff --git a/lib/Alchemy/Phrasea/Application/Root.php b/lib/Alchemy/Phrasea/Application/Root.php
index 3ce3d7c29d..a06cde0cea 100644
--- a/lib/Alchemy/Phrasea/Application/Root.php
+++ b/lib/Alchemy/Phrasea/Application/Root.php
@@ -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;
+ }
);
diff --git a/lib/Alchemy/Phrasea/Application/Setup.php b/lib/Alchemy/Phrasea/Application/Setup.php
index f5605e6f99..4b87160f29 100644
--- a/lib/Alchemy/Phrasea/Application/Setup.php
+++ b/lib/Alchemy/Phrasea/Application/Setup.php
@@ -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;
- });
diff --git a/lib/Alchemy/Phrasea/Cache/ApcCache.php b/lib/Alchemy/Phrasea/Cache/ApcCache.php
index 33fd6927a9..b02ceec043 100644
--- a/lib/Alchemy/Phrasea/Cache/ApcCache.php
+++ b/lib/Alchemy/Phrasea/Cache/ApcCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Cache/ArrayCache.php b/lib/Alchemy/Phrasea/Cache/ArrayCache.php
index d8ad78c8fd..a8f7a6e4ca 100644
--- a/lib/Alchemy/Phrasea/Cache/ArrayCache.php
+++ b/lib/Alchemy/Phrasea/Cache/ArrayCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Cache/Cache.php b/lib/Alchemy/Phrasea/Cache/Cache.php
index 516072dbba..a2cde4c552 100644
--- a/lib/Alchemy/Phrasea/Cache/Cache.php
+++ b/lib/Alchemy/Phrasea/Cache/Cache.php
@@ -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);
}
diff --git a/lib/Alchemy/Phrasea/Cache/Manager.php b/lib/Alchemy/Phrasea/Cache/Manager.php
index 93f0fa2fc4..5ae45a127a 100644
--- a/lib/Alchemy/Phrasea/Cache/Manager.php
+++ b/lib/Alchemy/Phrasea/Cache/Manager.php
@@ -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);
+ }
}
diff --git a/lib/Alchemy/Phrasea/Cache/MemcacheCache.php b/lib/Alchemy/Phrasea/Cache/MemcacheCache.php
index 7872e3387a..00a6fa9484 100644
--- a/lib/Alchemy/Phrasea/Cache/MemcacheCache.php
+++ b/lib/Alchemy/Phrasea/Cache/MemcacheCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Cache/RedisCache.php b/lib/Alchemy/Phrasea/Cache/RedisCache.php
index 250bc37052..87ea778b05 100644
--- a/lib/Alchemy/Phrasea/Cache/RedisCache.php
+++ b/lib/Alchemy/Phrasea/Cache/RedisCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Cache/XcacheCache.php b/lib/Alchemy/Phrasea/Cache/XcacheCache.php
index 2003704a26..1e959048cd 100644
--- a/lib/Alchemy/Phrasea/Cache/XcacheCache.php
+++ b/lib/Alchemy/Phrasea/Cache/XcacheCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Description.php b/lib/Alchemy/Phrasea/Controller/Admin/Description.php
index 4ba70700dc..35e9229e27 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Description.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Description.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Fields.php b/lib/Alchemy/Phrasea/Controller/Admin/Fields.php
index 5eb5cae355..707ba50026 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Fields.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Fields.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Publications.php b/lib/Alchemy/Phrasea/Controller/Admin/Publications.php
index 17540e6126..afb51c6980 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Publications.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Publications.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Root.php b/lib/Alchemy/Phrasea/Controller/Admin/Root.php
index b08067f561..4bde506853 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Root.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Root.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Subdefs.php b/lib/Alchemy/Phrasea/Controller/Admin/Subdefs.php
index 0a59c55afa..9de2ee89fa 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Subdefs.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Subdefs.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Users.php b/lib/Alchemy/Phrasea/Controller/Admin/Users.php
index 99748cb6ce..139f7efe44 100644
--- a/lib/Alchemy/Phrasea/Controller/Admin/Users.php
+++ b/lib/Alchemy/Phrasea/Controller/Admin/Users.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Exception.php b/lib/Alchemy/Phrasea/Controller/Exception.php
index 4fc86eb317..b1272f4db0 100644
--- a/lib/Alchemy/Phrasea/Controller/Exception.php
+++ b/lib/Alchemy/Phrasea/Controller/Exception.php
@@ -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
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Basket.php b/lib/Alchemy/Phrasea/Controller/Prod/Basket.php
index 8deeae4941..9faa9f7fb6 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/Basket.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/Basket.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php b/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php
index 2ae0074c8f..5824a17a38 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Edit.php b/lib/Alchemy/Phrasea/Controller/Prod/Edit.php
index 171aa30e59..6d6c1dd4cc 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/Edit.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/Edit.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Feed.php b/lib/Alchemy/Phrasea/Controller/Prod/Feed.php
index 312d4f482c..db0340c31e 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/Feed.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/Feed.php
@@ -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' => '
' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
- . '
' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '
+ $output = array(
+ 'texte' => '' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
+ . '
' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '
' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
- . '
' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '
+ $output = array(
+ 'texte' => '' . _('publication::Voici votre fil RSS personnel. Il vous permettra d\'etre tenu au courrant des publications.')
+ . '
' . _('publications::Ne le partagez pas, il est strictement confidentiel') . '
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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php b/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php
index f33328fde4..f9e8d9fde7 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/UserPreferences.php b/lib/Alchemy/Phrasea/Controller/Prod/UserPreferences.php
index d42a0c809c..39200b389c 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/UserPreferences.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/UserPreferences.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php b/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php
index 18d9801fd0..96ee4e9a73 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php
@@ -30,649 +30,568 @@ use Symfony\Component\HttpFoundation\Response,
class UsrLists implements ControllerProviderInterface
{
- public function connect(Application $app)
- {
- $controllers = new ControllerCollection();
+ public function connect(Application $app)
+ {
+ $controllers = new ControllerCollection();
- /**
- * Get all lists
- */
- $controllers->get('/all/', function(Application $app, Request $request)
- {
+ /**
+ * Get all lists
+ */
+ $controllers->get('/all/', function(Application $app, Request $request) {
- $datas = array(
- 'success' => false
- , 'message' => ''
- , 'result' => null
- );
+ $datas = array(
+ 'success' => false
+ , 'message' => ''
+ , 'result' => null
+ );
- $lists = new \Doctrine\Common\Collections\ArrayCollection();
+ $lists = new \Doctrine\Common\Collections\ArrayCollection();
- try
- {
- $em = $app['Core']->getEntityManager();
+ try {
+ $em = $app['Core']->getEntityManager();
- $repository = $em->getRepository('\Entities\UsrList');
+ $repository = $em->getRepository('\Entities\UsrList');
- $lists = $repository->findUserLists($app['Core']->getAuthenticatedUser());
+ $lists = $repository->findUserLists($app['Core']->getAuthenticatedUser());
- $result = array();
+ $result = array();
- foreach ($lists as $list)
- {
- $owners = $entries = array();
+ foreach ($lists as $list) {
+ $owners = $entries = array();
- foreach ($list->getOwners() as $owner)
- {
- $owners[] = array(
- 'usr_id' => $owner->getUser()->get_id(),
- 'display_name' => $owner->getUser()->get_display_name(),
- 'position' => $owner->getUser()->get_position(),
- 'job' => $owner->getUser()->get_job(),
- 'company' => $owner->getUser()->get_company(),
- 'email' => $owner->getUser()->get_email(),
- 'role' => $owner->getRole()
- );
+ foreach ($list->getOwners() as $owner) {
+ $owners[] = array(
+ 'usr_id' => $owner->getUser()->get_id(),
+ 'display_name' => $owner->getUser()->get_display_name(),
+ 'position' => $owner->getUser()->get_position(),
+ 'job' => $owner->getUser()->get_job(),
+ 'company' => $owner->getUser()->get_company(),
+ 'email' => $owner->getUser()->get_email(),
+ 'role' => $owner->getRole()
+ );
+ }
+
+ foreach ($list->getEntries() as $entry) {
+ $entries[] = array(
+ 'usr_id' => $owner->getUser()->get_id(),
+ 'display_name' => $owner->getUser()->get_display_name(),
+ 'position' => $owner->getUser()->get_position(),
+ 'job' => $owner->getUser()->get_job(),
+ 'company' => $owner->getUser()->get_company(),
+ 'email' => $owner->getUser()->get_email(),
+ );
+ }
+
+
+ /* @var $list \Entities\UsrList */
+ $result[] = array(
+ 'name' => $list->getName(),
+ 'created' => $list->getCreated()->format(DATE_ATOM),
+ 'updated' => $list->getUpdated()->format(DATE_ATOM),
+ 'owners' => $owners,
+ 'users' => $entries
+ );
+ }
+
+ $datas = array(
+ 'success' => true
+ , 'message' => ''
+ , 'result' => $result
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ }
+
+ if ($request->getRequestFormat() == 'json') {
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ } else {
+
+ return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/lists-all.html.twig', array('lists' => $lists)));
+ }
}
+ );
- foreach ($list->getEntries() as $entry)
- {
- $entries[] = array(
- 'usr_id' => $owner->getUser()->get_id(),
- 'display_name' => $owner->getUser()->get_display_name(),
- 'position' => $owner->getUser()->get_position(),
- 'job' => $owner->getUser()->get_job(),
- 'company' => $owner->getUser()->get_company(),
- 'email' => $owner->getUser()->get_email(),
- );
+ /**
+ * Creates a list
+ */
+ $controllers->post('/list/', function(Application $app) {
+ $request = $app['request'];
+
+ $list_name = $request->get('name');
+
+ $datas = array(
+ 'success' => false
+ , 'message' => sprintf(_('Unable to create list %s'), $list_name)
+ , 'list_id' => null
+ );
+
+ try {
+ if ( ! $list_name) {
+ throw new ControllerException(_('List name is required'));
+ }
+
+ $em = $app['Core']->getEntityManager();
+
+ $List = new \Entities\UsrList();
+
+ $Owner = new \Entities\UsrListOwner();
+ $Owner->setRole(\Entities\UsrListOwner::ROLE_ADMIN);
+ $Owner->setUser($app['Core']->getAuthenticatedUser());
+ $Owner->setList($List);
+
+ $List->setName($list_name);
+ $List->addUsrListOwner($Owner);
+
+ $em->persist($Owner);
+ $em->persist($List);
+ $em->flush();
+
+ $datas = array(
+ 'success' => true
+ , 'message' => sprintf(_('List %s has been created'), $list_name)
+ , 'list_id' => $List->getId()
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
}
-
-
- /* @var $list \Entities\UsrList */
- $result[] = array(
- 'name' => $list->getName(),
- 'created' => $list->getCreated()->format(DATE_ATOM),
- 'updated' => $list->getUpdated()->format(DATE_ATOM),
- 'owners' => $owners,
- 'users' => $entries
- );
- }
-
- $datas = array(
- 'success' => true
- , 'message' => ''
- , 'result' => $result
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- }
-
- if ($request->getRequestFormat() == 'json')
- {
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- else
- {
-
- return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/lists-all.html.twig', array('lists' => $lists)));
- }
- }
- );
-
- /**
- * Creates a list
- */
- $controllers->post('/list/', function(Application $app)
- {
- $request = $app['request'];
-
- $list_name = $request->get('name');
-
- $datas = array(
- 'success' => false
- , 'message' => sprintf(_('Unable to create list %s'), $list_name)
- , 'list_id' => null
);
- try
- {
- if (!$list_name)
- {
- throw new ControllerException(_('List name is required'));
- }
-
- $em = $app['Core']->getEntityManager();
-
- $List = new \Entities\UsrList();
-
- $Owner = new \Entities\UsrListOwner();
- $Owner->setRole(\Entities\UsrListOwner::ROLE_ADMIN);
- $Owner->setUser($app['Core']->getAuthenticatedUser());
- $Owner->setList($List);
-
- $List->setName($list_name);
- $List->addUsrListOwner($Owner);
-
- $em->persist($Owner);
- $em->persist($List);
- $em->flush();
-
- $datas = array(
- 'success' => true
- , 'message' => sprintf(_('List %s has been created'), $list_name)
- , 'list_id' => $List->getId()
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- }
-
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- );
-
- /**
- * Gets a list
- */
- $controllers->get('/list/{list_id}/', function(Application $app, Request $request, $list_id)
- {
-
- $result = array();
-
- $user = $app['Core']->getAuthenticatedUser();
- $em = $app['Core']->getEntityManager();
-
- $repository = $em->getRepository('\Entities\UsrList');
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
-
- $entries = new \Doctrine\Common\Collections\ArrayCollection();
- $owners = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($list->getOwners() as $owner)
- {
- $owners[] = array(
- 'usr_id' => $owner->getUser()->get_id(),
- 'display_name' => $owner->getUser()->get_display_name(),
- 'position' => $owner->getUser()->get_position(),
- 'job' => $owner->getUser()->get_job(),
- 'company' => $owner->getUser()->get_company(),
- 'email' => $owner->getUser()->get_email(),
- 'role' => $owner->getRole()
- );
- }
-
- foreach ($list->getEntries() as $entry)
- {
- $entries[] = array(
- 'usr_id' => $entry->getUser()->get_id(),
- 'display_name' => $entry->getUser()->get_display_name(),
- 'position' => $entry->getUser()->get_position(),
- 'job' => $entry->getUser()->get_job(),
- 'company' => $entry->getUser()->get_company(),
- 'email' => $entry->getUser()->get_email(),
- );
- }
-
-
- /* @var $list \Entities\UsrList */
- $result = array(
- 'id' => $list->getId(),
- 'name' => $list->getName(),
- 'created' => $list->getCreated()->format(DATE_ATOM),
- 'updated' => $list->getUpdated()->format(DATE_ATOM),
- 'owners' => $owners,
- 'users' => $entries
- );
-
-
- return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/list.html.twig', $result));
- }
- );
-
- /**
- * Update a list
- */
- $controllers->post('/list/{list_id}/update/', function(Application $app, $list_id)
- {
- $request = $app['request'];
-
- $datas = array(
- 'success' => false
- , 'message' => _('Unable to update list')
- );
-
- try
- {
- $list_name = $request->get('name');
-
- if (!$list_name)
- {
- throw new ControllerException(_('List name is required'));
- }
-
- $user = $app['Core']->getAuthenticatedUser();
- $em = $app['Core']->getEntityManager();
-
- $repository = $em->getRepository('\Entities\UsrList');
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
-
- if($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR)
- {
- throw new ControllerException(_('You are not authorized to do this'));
- }
-
- $list->setName($list_name);
-
- $em->flush();
-
- $datas = array(
- 'success' => true
- , 'message' => _('List has been updated')
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- }
-
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+');
-
- /**
- * Delete a list
- */
- $controllers->post('/list/{list_id}/delete/', function(Application $app, $list_id)
- {
- $em = $app['Core']->getEntityManager();
-
- try
- {
- $repository = $em->getRepository('\Entities\UsrList');
-
- $user = $app['Core']->getAuthenticatedUser();
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
-
- if($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN)
- {
- throw new ControllerException(_('You are not authorized to do this'));
- }
-
- $em->remove($list);
- $em->flush();
-
- $datas = array(
- 'success' => true
- , 'message' => sprintf(_('List has been deleted'))
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- $datas = array(
- 'success' => false
- , 'message' => sprintf(_('Unable to delete list'))
- );
- }
-
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+');
-
-
- /**
- * Remove a usr_id from a list
- */
- $controllers->post('/list/{list_id}/remove/{usr_id}/', function(Application $app, $list_id, $usr_id)
- {
- $em = $app['Core']->getEntityManager();
-
- try
- {
- $repository = $em->getRepository('\Entities\UsrList');
-
- $user = $app['Core']->getAuthenticatedUser();
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
- /* @var $list \Entities\UsrList */
-
- if($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR)
- {
- throw new ControllerException(_('You are not authorized to do this'));
- }
-
- $entry_repository = $em->getRepository('\Entities\UsrListEntry');
-
- $user_entry = $entry_repository->findEntryByListAndUsrId($list, $usr_id);
-
- $em->remove($user_entry);
- $em->flush();
-
- $datas = array(
- 'success' => true
- , 'message' => _('Entry removed from list')
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- $datas = array(
- 'success' => false
- , 'message' => _('Unable to remove entry from list ' . $e->getMessage())
- );
- }
-
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+')->assert('entry_id', '\d+');
-
- /**
- * Adds a usr_id to a list
- */
- $controllers->post('/list/{list_id}/add/', function(Application $app, Request $request, $list_id)
- {
- $em = $app['Core']->getEntityManager();
- $user = $app['Core']->getAuthenticatedUser();
-
- try
- {
- if (!is_array($request->get('usr_ids')))
- {
- throw new Controller\Exception('Invalid or missing parameter usr_ids');
- }
-
- $repository = $em->getRepository('\Entities\UsrList');
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
- /* @var $list \Entities\UsrList */
-
- if($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR)
- {
- throw new ControllerException(_('You are not authorized to do this'));
- }
-
- $inserted_usr_ids = array();
-
- foreach ($request->get('usr_ids') as $usr_id)
- {
- $user_entry = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
-
- if ($list->has($user_entry))
- continue;
-
- $entry = new \Entities\UsrListEntry();
- $entry->setUser($user_entry);
- $entry->setList($list);
-
- $list->addUsrListEntry($entry);
-
- $em->persist($entry);
-
- $inserted_usr_ids[] = $user_entry->get_id();
- }
-
- $em->flush();
-
- if (count($inserted_usr_ids) > 1)
- {
- $datas = array(
- 'success' => true
- , 'message' => sprintf(_('%d Users added to list'), count($inserted_usr_ids))
- , 'result' => $inserted_usr_ids
- );
- }
- else
- {
- $datas = array(
- 'success' => true
- , 'message' => sprintf(_('%d User added to list'), count($inserted_usr_ids))
- , 'result' => $inserted_usr_ids
- );
- }
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
-
- $datas = array(
- 'success' => false
- , 'message' => _('Unable to add usr to list')
- );
- }
-
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
-
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+')->assert('usr_id', '\d+');
-
- $controllers->get('/list/{list_id}/share/', function(Application $app, Request $request, $list_id)
- {
-
- $em = $app['Core']->getEntityManager();
- $user = $app['Core']->getAuthenticatedUser();
-
- $list = null;
-
- try
- {
- $repository = $em->getRepository('\Entities\UsrList');
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
- /* @var $list \Entities\UsrList */
-
- if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN)
- {
- $list = null;
- throw new \Exception(_('You are not authorized to do this'));
- }
-
- }
- catch (\Exception $e)
- {
-
- }
-
- return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/List-Share.html.twig', array('list' => $list)));
- })->assert('list_id', '\d+');
-
- /**
- * Share a list to a user with an optionnal role
- */
- $controllers->post('/list/{list_id}/share/{usr_id}/', function(Application $app, $list_id, $usr_id)
- {
- $em = $app['Core']->getEntityManager();
- $user = $app['Core']->getAuthenticatedUser();
-
- $availableRoles = array(
- \Entities\UsrListOwner::ROLE_USER,
- \Entities\UsrListOwner::ROLE_EDITOR,
- \Entities\UsrListOwner::ROLE_ADMIN,
- );
-
- if (!$app['request']->get('role'))
- throw new \Exception_BadRequest('Missing role parameter');
- elseif (!in_array($app['request']->get('role'), $availableRoles))
- throw new \Exception_BadRequest('Role is invalid');
-
- try
- {
- $repository = $em->getRepository('\Entities\UsrList');
-
- $list = $repository->findUserListByUserAndId($user, $list_id);
- /* @var $list \Entities\UsrList */
-
- if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR)
- {
- throw new ControllerException(_('You are not authorized to do this'));
- }
-
- $new_owner = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
-
- if ($list->hasAccess($new_owner))
- {
- if($new_owner->get_id() == $user->get_id())
- {
- throw new ControllerException('You can not downgrade your Admin right');
+ /**
+ * Gets a list
+ */
+ $controllers->get('/list/{list_id}/', function(Application $app, Request $request, $list_id) {
+
+ $result = array();
+
+ $user = $app['Core']->getAuthenticatedUser();
+ $em = $app['Core']->getEntityManager();
+
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+
+ $entries = new \Doctrine\Common\Collections\ArrayCollection();
+ $owners = new \Doctrine\Common\Collections\ArrayCollection();
+
+ foreach ($list->getOwners() as $owner) {
+ $owners[] = array(
+ 'usr_id' => $owner->getUser()->get_id(),
+ 'display_name' => $owner->getUser()->get_display_name(),
+ 'position' => $owner->getUser()->get_position(),
+ 'job' => $owner->getUser()->get_job(),
+ 'company' => $owner->getUser()->get_company(),
+ 'email' => $owner->getUser()->get_email(),
+ 'role' => $owner->getRole()
+ );
+ }
+
+ foreach ($list->getEntries() as $entry) {
+ $entries[] = array(
+ 'usr_id' => $entry->getUser()->get_id(),
+ 'display_name' => $entry->getUser()->get_display_name(),
+ 'position' => $entry->getUser()->get_position(),
+ 'job' => $entry->getUser()->get_job(),
+ 'company' => $entry->getUser()->get_company(),
+ 'email' => $entry->getUser()->get_email(),
+ );
+ }
+
+
+ /* @var $list \Entities\UsrList */
+ $result = array(
+ 'id' => $list->getId(),
+ 'name' => $list->getName(),
+ 'created' => $list->getCreated()->format(DATE_ATOM),
+ 'updated' => $list->getUpdated()->format(DATE_ATOM),
+ 'owners' => $owners,
+ 'users' => $entries
+ );
+
+
+ return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/list.html.twig', $result));
}
+ );
- $owner = $list->getOwner($new_owner);
- }
- else
- {
- $owner = new \Entities\UsrListOwner();
- $owner->setList($list);
- $owner->setUser($new_owner);
+ /**
+ * Update a list
+ */
+ $controllers->post('/list/{list_id}/update/', function(Application $app, $list_id) {
+ $request = $app['request'];
- $list->addUsrListOwner($owner);
+ $datas = array(
+ 'success' => false
+ , 'message' => _('Unable to update list')
+ );
- $em->persist($owner);
- }
+ try {
+ $list_name = $request->get('name');
- $role = $app['request']->get('role');
+ if ( ! $list_name) {
+ throw new ControllerException(_('List name is required'));
+ }
- $owner->setRole($role);
+ $user = $app['Core']->getAuthenticatedUser();
+ $em = $app['Core']->getEntityManager();
- $em->flush();
+ $repository = $em->getRepository('\Entities\UsrList');
- $datas = array(
- 'success' => true
- , 'message' => _('List shared to user')
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
+ $list = $repository->findUserListByUserAndId($user, $list_id);
- $datas = array(
- 'success' => false
- , 'message' => _('Unable to share the list with the usr')
- );
- }
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR) {
+ throw new ControllerException(_('You are not authorized to do this'));
+ }
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+ $list->setName($list_name);
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+')->assert('usr_id', '\d+');
- /**
- * UnShare a list to a user
- */
- $controllers->post('/list/{list_id}/unshare/{usr_id}/', function(Application $app, $list_id, $usr_id)
- {
- $em = $app['Core']->getEntityManager();
- $user = $app['Core']->getAuthenticatedUser();
+ $em->flush();
- try
- {
- $repository = $em->getRepository('\Entities\UsrList');
+ $datas = array(
+ 'success' => true
+ , 'message' => _('List has been updated')
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
- $list = $repository->findUserListByUserAndId($user, $list_id);
- /* @var $list \Entities\UsrList */
+ }
- if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN)
- {
- throw new \Exception(_('You are not authorized to do this'));
- }
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
- $owners_repository = $em->getRepository('\Entities\UsrListOwner');
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+');
- $owner = $owners_repository->findByListAndUsrId($list, $usr_id);
+ /**
+ * Delete a list
+ */
+ $controllers->post('/list/{list_id}/delete/', function(Application $app, $list_id) {
+ $em = $app['Core']->getEntityManager();
- $em->remove($owner);
- $em->flush();
+ try {
+ $repository = $em->getRepository('\Entities\UsrList');
- $datas = array(
- 'success' => true
- , 'message' => _('Owner removed from list')
- );
- }
- catch (ControllerException $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => $e->getMessage()
- );
- }
- catch (\Exception $e)
- {
- $datas = array(
- 'success' => false
- , 'message' => _('Unable to remove usr from list')
- );
- }
+ $user = $app['Core']->getAuthenticatedUser();
- $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+ $list = $repository->findUserListByUserAndId($user, $list_id);
- return new Response($Json, 200, array('Content-Type' => 'application/json'));
- }
- )->assert('list_id', '\d+')->assert('usr_id', '\d+');
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN) {
+ throw new ControllerException(_('You are not authorized to do this'));
+ }
+
+ $em->remove($list);
+ $em->flush();
+
+ $datas = array(
+ 'success' => true
+ , 'message' => sprintf(_('List has been deleted'))
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ $datas = array(
+ 'success' => false
+ , 'message' => sprintf(_('Unable to delete list'))
+ );
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+');
- return $controllers;
- }
+ /**
+ * Remove a usr_id from a list
+ */
+ $controllers->post('/list/{list_id}/remove/{usr_id}/', function(Application $app, $list_id, $usr_id) {
+ $em = $app['Core']->getEntityManager();
+ try {
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $user = $app['Core']->getAuthenticatedUser();
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+ /* @var $list \Entities\UsrList */
+
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR) {
+ throw new ControllerException(_('You are not authorized to do this'));
+ }
+
+ $entry_repository = $em->getRepository('\Entities\UsrListEntry');
+
+ $user_entry = $entry_repository->findEntryByListAndUsrId($list, $usr_id);
+
+ $em->remove($user_entry);
+ $em->flush();
+
+ $datas = array(
+ 'success' => true
+ , 'message' => _('Entry removed from list')
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ $datas = array(
+ 'success' => false
+ , 'message' => _('Unable to remove entry from list ' . $e->getMessage())
+ );
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+')->assert('entry_id', '\d+');
+
+ /**
+ * Adds a usr_id to a list
+ */
+ $controllers->post('/list/{list_id}/add/', function(Application $app, Request $request, $list_id) {
+ $em = $app['Core']->getEntityManager();
+ $user = $app['Core']->getAuthenticatedUser();
+
+ try {
+ if ( ! is_array($request->get('usr_ids'))) {
+ throw new Controller\Exception('Invalid or missing parameter usr_ids');
+ }
+
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+ /* @var $list \Entities\UsrList */
+
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR) {
+ throw new ControllerException(_('You are not authorized to do this'));
+ }
+
+ $inserted_usr_ids = array();
+
+ foreach ($request->get('usr_ids') as $usr_id) {
+ $user_entry = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
+
+ if ($list->has($user_entry))
+ continue;
+
+ $entry = new \Entities\UsrListEntry();
+ $entry->setUser($user_entry);
+ $entry->setList($list);
+
+ $list->addUsrListEntry($entry);
+
+ $em->persist($entry);
+
+ $inserted_usr_ids[] = $user_entry->get_id();
+ }
+
+ $em->flush();
+
+ if (count($inserted_usr_ids) > 1) {
+ $datas = array(
+ 'success' => true
+ , 'message' => sprintf(_('%d Users added to list'), count($inserted_usr_ids))
+ , 'result' => $inserted_usr_ids
+ );
+ } else {
+ $datas = array(
+ 'success' => true
+ , 'message' => sprintf(_('%d User added to list'), count($inserted_usr_ids))
+ , 'result' => $inserted_usr_ids
+ );
+ }
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ $datas = array(
+ 'success' => false
+ , 'message' => _('Unable to add usr to list')
+ );
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+')->assert('usr_id', '\d+');
+
+ $controllers->get('/list/{list_id}/share/', function(Application $app, Request $request, $list_id) {
+
+ $em = $app['Core']->getEntityManager();
+ $user = $app['Core']->getAuthenticatedUser();
+
+ $list = null;
+
+ try {
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+ /* @var $list \Entities\UsrList */
+
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN) {
+ $list = null;
+ throw new \Exception(_('You are not authorized to do this'));
+ }
+ } catch (\Exception $e) {
+
+ }
+
+ return new Response($app['Core']->getTwig()->render('prod/actions/Feedback/List-Share.html.twig', array('list' => $list)));
+ })->assert('list_id', '\d+');
+
+ /**
+ * Share a list to a user with an optionnal role
+ */
+ $controllers->post('/list/{list_id}/share/{usr_id}/', function(Application $app, $list_id, $usr_id) {
+ $em = $app['Core']->getEntityManager();
+ $user = $app['Core']->getAuthenticatedUser();
+
+ $availableRoles = array(
+ \Entities\UsrListOwner::ROLE_USER,
+ \Entities\UsrListOwner::ROLE_EDITOR,
+ \Entities\UsrListOwner::ROLE_ADMIN,
+ );
+
+ if ( ! $app['request']->get('role'))
+ throw new \Exception_BadRequest('Missing role parameter');
+ elseif ( ! in_array($app['request']->get('role'), $availableRoles))
+ throw new \Exception_BadRequest('Role is invalid');
+
+ try {
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+ /* @var $list \Entities\UsrList */
+
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_EDITOR) {
+ throw new ControllerException(_('You are not authorized to do this'));
+ }
+
+ $new_owner = \User_Adapter::getInstance($usr_id, \appbox::get_instance($app['Core']));
+
+ if ($list->hasAccess($new_owner)) {
+ if ($new_owner->get_id() == $user->get_id()) {
+ throw new ControllerException('You can not downgrade your Admin right');
+ }
+
+ $owner = $list->getOwner($new_owner);
+ } else {
+ $owner = new \Entities\UsrListOwner();
+ $owner->setList($list);
+ $owner->setUser($new_owner);
+
+ $list->addUsrListOwner($owner);
+
+ $em->persist($owner);
+ }
+
+ $role = $app['request']->get('role');
+
+ $owner->setRole($role);
+
+ $em->flush();
+
+ $datas = array(
+ 'success' => true
+ , 'message' => _('List shared to user')
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+
+ $datas = array(
+ 'success' => false
+ , 'message' => _('Unable to share the list with the usr')
+ );
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+')->assert('usr_id', '\d+');
+ /**
+ * UnShare a list to a user
+ */
+ $controllers->post('/list/{list_id}/unshare/{usr_id}/', function(Application $app, $list_id, $usr_id) {
+ $em = $app['Core']->getEntityManager();
+ $user = $app['Core']->getAuthenticatedUser();
+
+ try {
+ $repository = $em->getRepository('\Entities\UsrList');
+
+ $list = $repository->findUserListByUserAndId($user, $list_id);
+ /* @var $list \Entities\UsrList */
+
+ if ($list->getOwner($user)->getRole() < \Entities\UsrListOwner::ROLE_ADMIN) {
+ throw new \Exception(_('You are not authorized to do this'));
+ }
+
+ $owners_repository = $em->getRepository('\Entities\UsrListOwner');
+
+ $owner = $owners_repository->findByListAndUsrId($list, $usr_id);
+
+ $em->remove($owner);
+ $em->flush();
+
+ $datas = array(
+ 'success' => true
+ , 'message' => _('Owner removed from list')
+ );
+ } catch (ControllerException $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => $e->getMessage()
+ );
+ } catch (\Exception $e) {
+ $datas = array(
+ 'success' => false
+ , 'message' => _('Unable to remove usr from list')
+ );
+ }
+
+ $Json = $app['Core']['Serializer']->serialize($datas, 'json');
+
+ return new Response($Json, 200, array('Content-Type' => 'application/json'));
+ }
+ )->assert('list_id', '\d+')->assert('usr_id', '\d+');
+
+
+ return $controllers;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Prod/WorkZone.php b/lib/Alchemy/Phrasea/Controller/Prod/WorkZone.php
index b188d77a5f..5a774e8b2b 100644
--- a/lib/Alchemy/Phrasea/Controller/Prod/WorkZone.php
+++ b/lib/Alchemy/Phrasea/Controller/Prod/WorkZone.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php b/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php
index ac89652ca8..6bbbb55351 100644
--- a/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php
+++ b/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Setup/Installer.php b/lib/Alchemy/Phrasea/Controller/Setup/Installer.php
index 7d9562d071..c8948babae 100644
--- a/lib/Alchemy/Phrasea/Controller/Setup/Installer.php
+++ b/lib/Alchemy/Phrasea/Controller/Setup/Installer.php
@@ -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 = "\n\n"
- . str_replace('/phraseanet_indexer', '', $request->get('binary_phraseanet_indexer'))
- . " " . $host . " "
- . $port . " "
- . $appbox_name . ""
- . $user_ab . " "
- . $password . " 25200 "
- . "1 0 "
- . "0 utf8 ";
- }
- 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¬ice=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 = "\n\n"
+ . str_replace('/phraseanet_indexer', '', $request->get('binary_phraseanet_indexer'))
+ . " " . $host . " "
+ . $port . " "
+ . $appbox_name . ""
+ . $user_ab . " "
+ . $password . " 25200 "
+ . "1 0 "
+ . "0 utf8 ";
+ } else {
+ $settings = null;
+ }
+
+ \task_abstract::create($appbox, $class_name, $settings);
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ $redirection = '/admin/?section=taskmanager¬ice=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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Setup/Upgrader.php b/lib/Alchemy/Phrasea/Controller/Setup/Upgrader.php
index 2f019de2c5..816541c7ee 100644
--- a/lib/Alchemy/Phrasea/Controller/Setup/Upgrader.php
+++ b/lib/Alchemy/Phrasea/Controller/Setup/Upgrader.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Utils/ConnectionTest.php b/lib/Alchemy/Phrasea/Controller/Utils/ConnectionTest.php
index 27e52e3d40..5ac66122be 100644
--- a/lib/Alchemy/Phrasea/Controller/Utils/ConnectionTest.php
+++ b/lib/Alchemy/Phrasea/Controller/Utils/ConnectionTest.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Controller/Utils/PathFileTest.php b/lib/Alchemy/Phrasea/Controller/Utils/PathFileTest.php
index f0a5fd6896..43c059619a 100644
--- a/lib/Alchemy/Phrasea/Controller/Utils/PathFileTest.php
+++ b/lib/Alchemy/Phrasea/Controller/Utils/PathFileTest.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core.php b/lib/Alchemy/Phrasea/Core.php
index deb8535581..4c85953e1a 100644
--- a/lib/Alchemy/Phrasea/Core.php
+++ b/lib/Alchemy/Phrasea/Core.php
@@ -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();
}
-
}
diff --git a/lib/Alchemy/Phrasea/Core/Configuration.php b/lib/Alchemy/Phrasea/Core/Configuration.php
index 002ce7593a..3b4d08bbfe 100644
--- a/lib/Alchemy/Phrasea/Core/Configuration.php
+++ b/lib/Alchemy/Phrasea/Core/Configuration.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php b/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php
index 61ca31c428..4b20cf0463 100644
--- a/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php
+++ b/lib/Alchemy/Phrasea/Core/Configuration/ApplicationSpecification.php
@@ -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__ . '/../../../../../');
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Configuration/Specification.php b/lib/Alchemy/Phrasea/Core/Configuration/Specification.php
index 31abc9de5d..6ae56eacca 100644
--- a/lib/Alchemy/Phrasea/Core/Configuration/Specification.php
+++ b/lib/Alchemy/Phrasea/Core/Configuration/Specification.php
@@ -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();
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Builder.php b/lib/Alchemy/Phrasea/Core/Service/Builder.php
index b3f2372af7..0d96d78e1c 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Builder.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Builder.php
@@ -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);
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php
index af531e95d7..9a33193ce1 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Cache/ApcCache.php
@@ -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';
- }
-
-
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php
index 1bdfe6f562..abb233c1be 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Cache/ArrayCache.php
@@ -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';
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php
index a0f2c73cf6..f1a7f2da49 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Cache/MemcacheCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php
index e7eb64429e..0e047abd74 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Cache/RedisCache.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php b/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php
index 3fbea9eab7..153e84d3c1 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Cache/XcacheCache.php
@@ -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';
- }
-
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Monolog.php b/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Monolog.php
index d79bfa1680..e23ba869a3 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Monolog.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Monolog.php
@@ -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';
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php b/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php
index 88960da354..a03b8e5265 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Log/Doctrine/Phpecho.php
@@ -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';
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/FirePHP.php b/lib/Alchemy/Phrasea/Core/Service/Log/FirePHP.php
index 12456141a8..6c9277bdc2 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Log/FirePHP.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Log/FirePHP.php
@@ -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';
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php b/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php
index 69f7029b33..ba249d3906 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Log/Monolog.php
@@ -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');
- }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php b/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php
index 75f98e1b6c..5e1ba2b1f1 100644
--- a/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php
+++ b/lib/Alchemy/Phrasea/Core/Service/Orm/Doctrine.php
@@ -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');
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php b/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php
index 3eb8832869..0da55687f0 100644
--- a/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php
+++ b/lib/Alchemy/Phrasea/Core/Service/ServiceAbstract.php
@@ -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();
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php b/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php
index 50ac477436..67bc611540 100644
--- a/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php
+++ b/lib/Alchemy/Phrasea/Core/Service/ServiceInterface.php
@@ -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();
}
diff --git a/lib/Alchemy/Phrasea/Core/Service/TemplateEngine/Twig.php b/lib/Alchemy/Phrasea/Core/Service/TemplateEngine/Twig.php
index 78cccb4523..8759feecb0 100644
--- a/lib/Alchemy/Phrasea/Core/Service/TemplateEngine/Twig.php
+++ b/lib/Alchemy/Phrasea/Core/Service/TemplateEngine/Twig.php
@@ -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 it’s 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 it’s 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');
+ }
}
diff --git a/lib/Alchemy/Phrasea/Core/Version.php b/lib/Alchemy/Phrasea/Core/Version.php
index 80263eaf1b..85877201d9 100644
--- a/lib/Alchemy/Phrasea/Core/Version.php
+++ b/lib/Alchemy/Phrasea/Core/Version.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Helper.php b/lib/Alchemy/Phrasea/Helper/Helper.php
index d4fecc1093..0e23c84699 100644
--- a/lib/Alchemy/Phrasea/Helper/Helper.php
+++ b/lib/Alchemy/Phrasea/Helper/Helper.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Prod.php b/lib/Alchemy/Phrasea/Helper/Prod.php
index be3cf5fce3..1e42ea00a8 100644
--- a/lib/Alchemy/Phrasea/Helper/Prod.php
+++ b/lib/Alchemy/Phrasea/Helper/Prod.php
@@ -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));
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Bridge.php b/lib/Alchemy/Phrasea/Helper/Record/Bridge.php
index f44c6bc4d7..58a72f6795 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Bridge.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Bridge.php
@@ -23,7 +23,6 @@ use Symfony\Component\HttpFoundation\Request;
*/
class Bridge extends RecordHelper
{
-
- protected $flatten_groupings = true;
+ protected $flatten_groupings = true;
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Edit.php b/lib/Alchemy/Phrasea/Helper/Record/Edit.php
index f156481a47..a4898749fd 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Edit.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Edit.php
@@ -27,575 +27,537 @@ use Alchemy\Phrasea\Core,
*/
class Edit extends RecordHelper
{
+ /**
+ *
+ * @var Array
+ */
+ protected $javascript_fields;
- /**
- *
- * @var Array
- */
- protected $javascript_fields;
+ /**
+ *
+ * @var Array
+ */
+ protected $fields;
- /**
- *
- * @var Array
- */
- protected $fields;
+ /**
+ *
+ * @var Array
+ */
+ protected $javascript_status;
- /**
- *
- * @var Array
- */
- protected $javascript_status;
+ /**
+ *
+ * @var Array
+ */
+ protected $javascript_sugg_values;
- /**
- *
- * @var Array
- */
- protected $javascript_sugg_values;
+ /**
+ *
+ * @var Array
+ */
+ protected $javascript_elements = array();
- /**
- *
- * @var Array
- */
- protected $javascript_elements = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $required_rights = array('canmodifrecord');
- /**
- *
- * @var Array
- */
- protected $required_rights = array('canmodifrecord');
+ /**
+ *
+ * @var boolean
+ */
+ protected $works_on_unique_sbas = true;
- /**
- *
- * @var boolean
- */
- protected $works_on_unique_sbas = true;
+ /**
+ *
+ * @var type
+ */
+ protected $has_thesaurus = false;
- /**
- *
- * @var type
- */
- protected $has_thesaurus = false;
-
- /**
- *
- * @param \Alchemy\Phrasea\Core $core
- * @return Edit
- */
- public function __construct(Core $core, Request $Request)
- {
- parent::__construct($core, $Request);
-
- if ($this->is_single_grouping())
+ /**
+ *
+ * @param \Alchemy\Phrasea\Core $core
+ * @return Edit
+ */
+ public function __construct(Core $core, Request $Request)
{
- $record = array_pop($this->selection->get_elements());
- $children = $record->get_children();
- foreach ($children as $child)
- {
- $this->selection->add_element($child);
- }
- $n = count($children);
- $this->elements_received = $this->selection->get_count() + $n - 1;
- $this->examinate_selection();
- }
- if ($this->is_possible())
- {
- $this->generate_javascript_fields()
- ->generate_javascript_sugg_values()
- ->generate_javascript_status()
- ->generate_javascript_elements();
- }
+ parent::__construct($core, $Request);
- return $this;
- }
-
- public function propose_editing()
- {
- return $this;
- }
-
- public function has_thesaurus()
- {
- return $this->has_thesaurus;
- }
-
- /**
- * Return JSON data for UI
- *
- * @return String
- */
- public function get_javascript_elements_ids()
- {
- return $this->core['Serializer']->serialize(
- array_keys($this->javascript_elements)
- , 'json'
- );
- }
-
- /**
- * Return JSON data for UI
- *
- * @return String
- */
- public function get_javascript_elements()
- {
- return $this->core['Serializer']->serialize(
- array_values($this->javascript_elements)
- , 'json'
- );
- }
-
- /**
- * Return JSON data for UI
- *
- * @return String
- */
- public function get_javascript_sugg_values()
- {
- return $this->core['Serializer']->serialize(
- $this->javascript_sugg_values
- , 'json'
- );
- }
-
- /**
- * Return JSON data for UI
- *
- * @return String
- */
- public function get_javascript_status()
- {
- return $this->core['Serializer']->serialize(
- $this->javascript_status
- , 'json'
- );
- }
-
- /**
- * Return JSON data for UI
- *
- * @return String
- */
- public function get_javascript_fields()
- {
- return $this->core['Serializer']->serialize(
- $this->javascript_fields
- , 'json'
- );
- }
-
- /**
- * Return statusbit informations on database
- *
- * @return Array
- */
- public function get_status()
- {
- return $this->javascript_status;
- }
-
- /**
- * Return fields informations on database
- *
- * @return Array
- */
- public function get_fields()
- {
- return $this->fields;
- }
-
- /**
- * Generate data for JSON UI
- *
- * @return action_edit
- */
- protected function generate_javascript_elements()
- {
- $_lst = array();
- $user = $this->getCore()->getAuthenticatedUser();
-
- $twig = $this->getCore()->getTwig();
-
-
- $databox = \databox::get_instance($this->get_sbas_id());
-
- $databox_fields = array();
- foreach ($databox->get_meta_structure() as $field)
- {
- $databox_fields[$field->get_id()] = array(
- 'dirty' => false,
- 'meta_struct_id' => $field->get_id(),
- 'values' => array()
- );
- }
-
- foreach ($this->selection as $record)
- {
- $indice = $record->get_number();
- $_lst[$indice] = array(
- 'bid' => $record->get_base_id(),
- 'rid' => $record->get_record_id(),
- 'sselcont_id' => null,
- '_selected' => false,
- 'fields' => $databox_fields
- );
-
- $_lst[$indice]['statbits'] = array();
- if ($user->ACL()->has_right_on_base($record->get_base_id(), 'chgstatus'))
- {
- foreach ($this->javascript_status as $n => $s)
- {
- $tmp_val = substr(strrev($record->get_status()), $n, 1);
- $_lst[$indice]['statbits'][$n]['value'] = ($tmp_val == '1') ? '1' : '0';
- $_lst[$indice]['statbits'][$n]['dirty'] = false;
+ if ($this->is_single_grouping()) {
+ $record = array_pop($this->selection->get_elements());
+ $children = $record->get_children();
+ foreach ($children as $child) {
+ $this->selection->add_element($child);
+ }
+ $n = count($children);
+ $this->elements_received = $this->selection->get_count() + $n - 1;
+ $this->examinate_selection();
}
- }
- $_lst[$indice]['originalname'] = '';
-
- $_lst[$indice]['originalname'] = $record->get_original_name();
-
- foreach ($record->get_caption()->get_fields(null, true) as $field)
- {
- $meta_struct_id = $field->get_meta_struct_id();
- if (!isset($this->javascript_fields[$meta_struct_id]))
- {
- continue;
+ if ($this->is_possible()) {
+ $this->generate_javascript_fields()
+ ->generate_javascript_sugg_values()
+ ->generate_javascript_status()
+ ->generate_javascript_elements();
}
- $values = array();
- foreach ($field->get_values() as $value)
- {
- $type = $id = null;
+ return $this;
+ }
- if ($value->getVocabularyType())
- {
- $type = $value->getVocabularyType()->getType();
- $id = $value->getVocabularyId();
- }
+ public function propose_editing()
+ {
+ return $this;
+ }
- $values[$value->getId()] = array(
- 'meta_id' => $value->getId(),
- 'value' => $value->getValue(),
- 'vocabularyId' => $id,
- 'vocabularyType' => $type
- );
- }
+ public function has_thesaurus()
+ {
+ return $this->has_thesaurus;
+ }
- $_lst[$indice]['fields'][$meta_struct_id] = array(
- 'dirty' => false,
- 'meta_struct_id' => $meta_struct_id,
- 'values' => $values
+ /**
+ * Return JSON data for UI
+ *
+ * @return String
+ */
+ public function get_javascript_elements_ids()
+ {
+ return $this->core['Serializer']->serialize(
+ array_keys($this->javascript_elements)
+ , 'json'
);
- }
-
- $_lst[$indice]['subdefs'] = array();
-
- $thumbnail = $record->get_thumbnail();
-
- $_lst[$indice]['subdefs']['thumbnail'] = array(
- 'url' => $thumbnail->get_url()
- , 'w' => $thumbnail->get_width()
- , 'h' => $thumbnail->get_height()
- );
-
- $_lst[$indice]['preview'] = $twig->render('common/preview.html', array('record' => $record));
-
- $_lst[$indice]['type'] = $record->get_type();
}
- $this->javascript_elements = $_lst;
-
- return $this;
- }
-
- /**
- * Generate data for JSON UI
- *
- * @return action_edit
- */
- protected function generate_javascript_sugg_values()
- {
- $done = array();
- $T_sgval = array();
- foreach ($this->selection as $record)
+ /**
+ * Return JSON data for UI
+ *
+ * @return String
+ */
+ public function get_javascript_elements()
{
- /* @var $record record_adapter */
- $base_id = $record->get_base_id();
- $record_id = $record->get_record_id();
- $databox = $record->get_databox();
-
- if (isset($done[$base_id]))
- continue;
-
- $T_sgval['b' . $base_id] = array();
- $collection = \collection::get_from_base_id($base_id);
-
- if ($sxe = simplexml_load_string($collection->get_prefs()))
- {
- $z = $sxe->xpath('/baseprefs/sugestedValues');
-
- if (!$z || !is_array($z))
- continue;
-
- foreach ($z[0] as $ki => $vi) // les champs
- {
-
- $field = $databox->get_meta_structure()->get_element_by_name($ki);
- if (!$field)
- continue; // champ inconnu dans la structure ?
- if (!$vi)
- continue;
-
- $T_sgval['b' . $base_id][$field->get_id()] = array();
- foreach ($vi->value as $oneValue) // les valeurs sug
- {
- $T_sgval['b' . $base_id][$field->get_id()][] =
- (string) $oneValue;
- }
- }
- }
- unset($collection);
- $done[$base_id] = true;
- }
- $this->javascript_sugg_values = $T_sgval;
-
- return $this;
- }
-
- /**
- * Generate data for JSON UI
- *
- * @return action_edit
- */
- protected function generate_javascript_status()
- {
- $_tstatbits = array();
- $user = $this->getCore()->getAuthenticatedUser();
-
- if ($user->ACL()->has_right('changestatus'))
- {
- $status = \databox_status::getDisplayStatus();
- if (isset($status[$this->get_sbas_id()]))
- {
- foreach ($status[$this->get_sbas_id()] as $n => $statbit)
- {
- $_tstatbits[$n] = array();
- $_tstatbits[$n]['label0'] = $statbit['labeloff'];
- $_tstatbits[$n]['label1'] = $statbit['labelon'];
- $_tstatbits[$n]['img_off'] = $statbit['img_off'];
- $_tstatbits[$n]['img_on'] = $statbit['img_on'];
- $_tstatbits[$n]['_value'] = 0;
- }
- }
+ return $this->core['Serializer']->serialize(
+ array_values($this->javascript_elements)
+ , 'json'
+ );
}
- $this->javascript_status = $_tstatbits;
-
- return $this;
- }
-
- /**
- * Generate data for JSON UI
- *
- * @return action_edit
- */
- protected function generate_javascript_fields()
- {
- $_tfields = $fields = array();
-
- $this->has_thesaurus = false;
-
- $databox = \databox::get_instance($this->get_sbas_id());
- $meta_struct = $databox->get_meta_structure();
-
- foreach ($meta_struct as $meta)
+ /**
+ * Return JSON data for UI
+ *
+ * @return String
+ */
+ public function get_javascript_sugg_values()
{
- $fields[] = $meta;
- $this->generate_field($meta);
+ return $this->core['Serializer']->serialize(
+ $this->javascript_sugg_values
+ , 'json'
+ );
}
- $this->fields = $fields;
-
- return $this;
- }
-
- protected function generate_field(\databox_field $meta)
- {
- $i = count($this->javascript_fields);
-
- $source = $meta->get_source();
- $separator = $meta->get_separator();
-
- $datas = array(
- 'meta_struct_id' => $meta->get_id()
- , 'name' => $meta->get_name()
- , '_status' => 0
- , '_value' => ''
- , '_sgval' => array()
- , 'required' => $meta->is_required()
- , 'readonly' => $meta->is_readonly()
- , 'type' => $meta->get_type()
- , 'format' => ''
- , 'explain' => ''
- , 'tbranch' => $meta->get_tbranch()
- , 'maxLength' => $source ? $source->maxlength() : 0
- , 'minLength' => $source ? $source->minLength() : 0
- , 'multi' => $meta->is_multi()
- , 'separator' => $separator
- , 'vocabularyControl' => $meta->getVocabularyControl() ? $meta->getVocabularyControl()->getType() : null
- , 'vocabularyRestricted' => $meta->getVocabularyControl() ? $meta->isVocabularyRestricted() : false
- );
-
- if (trim($meta->get_tbranch()) !== '')
- $this->has_thesaurus = true;
-
- $this->javascript_fields[$meta->get_id()] = $datas;
- }
-
- /**
- * Substitute Head file of groupings and save new Desc
- *
- * @param http_request $request
- * @return action_edit
- */
- public function execute(Request $request)
- {
- $appbox = \appbox::get_instance($this->core);
- if ($request->get('act_option') == 'SAVEGRP' && $request->get('newrepresent'))
+ /**
+ * Return JSON data for UI
+ *
+ * @return String
+ */
+ public function get_javascript_status()
{
- try
- {
- $reg_record = $this->get_grouping_head();
- $reg_sbas_id = $reg_record->get_sbas_id();
-
- $newsubdef_reg = new \record_adapter($reg_sbas_id, $request->get('newrepresent'));
-
- if ($newsubdef_reg->get_type() !== 'image')
- throw new \Exception('A reg image must come from image data');
-
- foreach ($newsubdef_reg->get_subdefs() as $name => $value)
- {
- $pathfile = $value->get_pathfile();
- $system_file = new \system_file($pathfile);
- $reg_record->substitute_subdef($name, $system_file);
- }
- }
- catch (\Exception $e)
- {
-
- }
+ return $this->core['Serializer']->serialize(
+ $this->javascript_status
+ , 'json'
+ );
}
- if (!is_array($request->get('mds')))
+ /**
+ * Return JSON data for UI
+ *
+ * @return String
+ */
+ public function get_javascript_fields()
{
- return $this;
+ return $this->core['Serializer']->serialize(
+ $this->javascript_fields
+ , 'json'
+ );
}
- $sbas_id = (int) $request->get('sbid');
- $databox = \databox::get_instance($sbas_id);
- $meta_struct = $databox->get_meta_structure();
- $write_edit_el = false;
- $date_obj = new \DateTime();
- foreach ($meta_struct->get_elements() as $meta_struct_el)
+ /**
+ * Return statusbit informations on database
+ *
+ * @return Array
+ */
+ public function get_status()
{
- if ($meta_struct_el->get_metadata_namespace() == "PHRASEANET" && $meta_struct_el->get_metadata_tagname() == 'tf-editdate')
- $write_edit_el = $meta_struct_el;
+ return $this->javascript_status;
}
- $elements = $this->selection->get_elements();
-
- foreach ($request->get('mds') as $rec)
+ /**
+ * Return fields informations on database
+ *
+ * @return Array
+ */
+ public function get_fields()
{
- try
- {
- $record = $databox->get_record($rec['record_id']);
- }
- catch (Exception $e)
- {
- continue;
- }
+ return $this->fields;
+ }
+
+ /**
+ * Generate data for JSON UI
+ *
+ * @return action_edit
+ */
+ protected function generate_javascript_elements()
+ {
+ $_lst = array();
+ $user = $this->getCore()->getAuthenticatedUser();
+
+ $twig = $this->getCore()->getTwig();
- $key = $record->get_serialize_key();
+ $databox = \databox::get_instance($this->get_sbas_id());
- if (!array_key_exists($key, $elements))
- continue;
-
- $statbits = $rec['status'];
- $editDirty = $rec['edit'];
-
- if ($editDirty == '0')
- $editDirty = false;
- else
- $editDirty = true;
-
- if (is_array($rec['metadatas']))
- {
- $record->set_metadatas($rec['metadatas']);
- }
-
- /**
- * todo : this should not work
- */
- if ($write_edit_el instanceof \databox_field)
- {
- $fields = $record->get_caption()->get_fields(array($write_edit_el->get_name()), true);
- $field = array_pop($fields);
-
- $meta_id = null;
-
- if ($field && !$field->is_multi())
- {
- $meta_id = array_pop($field->get_values())->getId();
+ $databox_fields = array();
+ foreach ($databox->get_meta_structure() as $field) {
+ $databox_fields[$field->get_id()] = array(
+ 'dirty' => false,
+ 'meta_struct_id' => $field->get_id(),
+ 'values' => array()
+ );
}
- $metas = array(
- array(
- 'meta_struct_id' => $write_edit_el->get_id()
- , 'meta_id' => $meta_id
- , 'value' => $date_obj->format('Y-m-d h:i:s')
- )
+ foreach ($this->selection as $record) {
+ $indice = $record->get_number();
+ $_lst[$indice] = array(
+ 'bid' => $record->get_base_id(),
+ 'rid' => $record->get_record_id(),
+ 'sselcont_id' => null,
+ '_selected' => false,
+ 'fields' => $databox_fields
+ );
+
+ $_lst[$indice]['statbits'] = array();
+ if ($user->ACL()->has_right_on_base($record->get_base_id(), 'chgstatus')) {
+ foreach ($this->javascript_status as $n => $s) {
+ $tmp_val = substr(strrev($record->get_status()), $n, 1);
+ $_lst[$indice]['statbits'][$n]['value'] = ($tmp_val == '1') ? '1' : '0';
+ $_lst[$indice]['statbits'][$n]['dirty'] = false;
+ }
+ }
+ $_lst[$indice]['originalname'] = '';
+
+ $_lst[$indice]['originalname'] = $record->get_original_name();
+
+ foreach ($record->get_caption()->get_fields(null, true) as $field) {
+ $meta_struct_id = $field->get_meta_struct_id();
+ if ( ! isset($this->javascript_fields[$meta_struct_id])) {
+ continue;
+ }
+
+ $values = array();
+ foreach ($field->get_values() as $value) {
+ $type = $id = null;
+
+ if ($value->getVocabularyType()) {
+ $type = $value->getVocabularyType()->getType();
+ $id = $value->getVocabularyId();
+ }
+
+ $values[$value->getId()] = array(
+ 'meta_id' => $value->getId(),
+ 'value' => $value->getValue(),
+ 'vocabularyId' => $id,
+ 'vocabularyType' => $type
+ );
+ }
+
+ $_lst[$indice]['fields'][$meta_struct_id] = array(
+ 'dirty' => false,
+ 'meta_struct_id' => $meta_struct_id,
+ 'values' => $values
+ );
+ }
+
+ $_lst[$indice]['subdefs'] = array();
+
+ $thumbnail = $record->get_thumbnail();
+
+ $_lst[$indice]['subdefs']['thumbnail'] = array(
+ 'url' => $thumbnail->get_url()
+ , 'w' => $thumbnail->get_width()
+ , 'h' => $thumbnail->get_height()
+ );
+
+ $_lst[$indice]['preview'] = $twig->render('common/preview.html', array('record' => $record));
+
+ $_lst[$indice]['type'] = $record->get_type();
+ }
+
+ $this->javascript_elements = $_lst;
+
+ return $this;
+ }
+
+ /**
+ * Generate data for JSON UI
+ *
+ * @return action_edit
+ */
+ protected function generate_javascript_sugg_values()
+ {
+ $done = array();
+ $T_sgval = array();
+ foreach ($this->selection as $record) {
+ /* @var $record record_adapter */
+ $base_id = $record->get_base_id();
+ $record_id = $record->get_record_id();
+ $databox = $record->get_databox();
+
+ if (isset($done[$base_id]))
+ continue;
+
+ $T_sgval['b' . $base_id] = array();
+ $collection = \collection::get_from_base_id($base_id);
+
+ if ($sxe = simplexml_load_string($collection->get_prefs())) {
+ $z = $sxe->xpath('/baseprefs/sugestedValues');
+
+ if ( ! $z || ! is_array($z))
+ continue;
+
+ foreach ($z[0] as $ki => $vi) { // les champs
+
+ $field = $databox->get_meta_structure()->get_element_by_name($ki);
+ if ( ! $field)
+ continue; // champ inconnu dans la structure ?
+ if ( ! $vi)
+ continue;
+
+ $T_sgval['b' . $base_id][$field->get_id()] = array();
+ foreach ($vi->value as $oneValue) { // les valeurs sug
+ $T_sgval['b' . $base_id][$field->get_id()][] =
+ (string) $oneValue;
+ }
+ }
+ }
+ unset($collection);
+ $done[$base_id] = true;
+ }
+ $this->javascript_sugg_values = $T_sgval;
+
+ return $this;
+ }
+
+ /**
+ * Generate data for JSON UI
+ *
+ * @return action_edit
+ */
+ protected function generate_javascript_status()
+ {
+ $_tstatbits = array();
+ $user = $this->getCore()->getAuthenticatedUser();
+
+ if ($user->ACL()->has_right('changestatus')) {
+ $status = \databox_status::getDisplayStatus();
+ if (isset($status[$this->get_sbas_id()])) {
+ foreach ($status[$this->get_sbas_id()] as $n => $statbit) {
+ $_tstatbits[$n] = array();
+ $_tstatbits[$n]['label0'] = $statbit['labeloff'];
+ $_tstatbits[$n]['label1'] = $statbit['labelon'];
+ $_tstatbits[$n]['img_off'] = $statbit['img_off'];
+ $_tstatbits[$n]['img_on'] = $statbit['img_on'];
+ $_tstatbits[$n]['_value'] = 0;
+ }
+ }
+ }
+
+ $this->javascript_status = $_tstatbits;
+
+ return $this;
+ }
+
+ /**
+ * Generate data for JSON UI
+ *
+ * @return action_edit
+ */
+ protected function generate_javascript_fields()
+ {
+ $_tfields = $fields = array();
+
+ $this->has_thesaurus = false;
+
+ $databox = \databox::get_instance($this->get_sbas_id());
+ $meta_struct = $databox->get_meta_structure();
+
+ foreach ($meta_struct as $meta) {
+ $fields[] = $meta;
+ $this->generate_field($meta);
+ }
+
+ $this->fields = $fields;
+
+ return $this;
+ }
+
+ protected function generate_field(\databox_field $meta)
+ {
+ $i = count($this->javascript_fields);
+
+ $source = $meta->get_source();
+ $separator = $meta->get_separator();
+
+ $datas = array(
+ 'meta_struct_id' => $meta->get_id()
+ , 'name' => $meta->get_name()
+ , '_status' => 0
+ , '_value' => ''
+ , '_sgval' => array()
+ , 'required' => $meta->is_required()
+ , 'readonly' => $meta->is_readonly()
+ , 'type' => $meta->get_type()
+ , 'format' => ''
+ , 'explain' => ''
+ , 'tbranch' => $meta->get_tbranch()
+ , 'maxLength' => $source ? $source->maxlength() : 0
+ , 'minLength' => $source ? $source->minLength() : 0
+ , 'multi' => $meta->is_multi()
+ , 'separator' => $separator
+ , 'vocabularyControl' => $meta->getVocabularyControl() ? $meta->getVocabularyControl()->getType() : null
+ , 'vocabularyRestricted' => $meta->getVocabularyControl() ? $meta->isVocabularyRestricted() : false
);
- $record->set_metadatas($metas, true);
- }
+ if (trim($meta->get_tbranch()) !== '')
+ $this->has_thesaurus = true;
- $newstat = $record->get_status();
- $statbits = ltrim($statbits, 'x');
- if (!in_array($statbits, array('', 'null')))
- {
- $mask_and = ltrim(str_replace(
- array('x', '0', '1', 'z'), array('1', 'z', '0', '1'), $statbits), '0');
- if ($mask_and != '')
- $newstat = \databox_status::operation_and_not($newstat, $mask_and);
-
- $mask_or = ltrim(str_replace('x', '0', $statbits), '0');
-
- if ($mask_or != '')
- $newstat = \databox_status::operation_or($newstat, $mask_or);
-
- $record->set_binary_status($newstat);
- }
-
- $collection = \collection::get_from_base_id($record->get_base_id());
- $collection->reset_stamp($record->get_record_id());
-
- $record->write_metas();
-
- if ($statbits != '')
- {
- $appbox->get_session()
- ->get_logger($record->get_databox())
- ->log($record, \Session_Logger::EVENT_STATUS, '', '');
- }
- if ($editDirty)
- {
- $appbox->get_session()
- ->get_logger($record->get_databox())
- ->log($record, \Session_Logger::EVENT_EDIT, '', '');
- }
+ $this->javascript_fields[$meta->get_id()] = $datas;
}
- return $this;
- }
+ /**
+ * Substitute Head file of groupings and save new Desc
+ *
+ * @param http_request $request
+ * @return action_edit
+ */
+ public function execute(Request $request)
+ {
+ $appbox = \appbox::get_instance($this->core);
+ if ($request->get('act_option') == 'SAVEGRP' && $request->get('newrepresent')) {
+ try {
+ $reg_record = $this->get_grouping_head();
+ $reg_sbas_id = $reg_record->get_sbas_id();
+ $newsubdef_reg = new \record_adapter($reg_sbas_id, $request->get('newrepresent'));
+
+ if ($newsubdef_reg->get_type() !== 'image')
+ throw new \Exception('A reg image must come from image data');
+
+ foreach ($newsubdef_reg->get_subdefs() as $name => $value) {
+ $pathfile = $value->get_pathfile();
+ $system_file = new \system_file($pathfile);
+ $reg_record->substitute_subdef($name, $system_file);
+ }
+ } catch (\Exception $e) {
+
+ }
+ }
+
+ if ( ! is_array($request->get('mds'))) {
+ return $this;
+ }
+
+ $sbas_id = (int) $request->get('sbid');
+ $databox = \databox::get_instance($sbas_id);
+ $meta_struct = $databox->get_meta_structure();
+ $write_edit_el = false;
+ $date_obj = new \DateTime();
+ foreach ($meta_struct->get_elements() as $meta_struct_el) {
+ if ($meta_struct_el->get_metadata_namespace() == "PHRASEANET" && $meta_struct_el->get_metadata_tagname() == 'tf-editdate')
+ $write_edit_el = $meta_struct_el;
+ }
+
+ $elements = $this->selection->get_elements();
+
+ foreach ($request->get('mds') as $rec) {
+ try {
+ $record = $databox->get_record($rec['record_id']);
+ } catch (Exception $e) {
+ continue;
+ }
+
+
+ $key = $record->get_serialize_key();
+
+ if ( ! array_key_exists($key, $elements))
+ continue;
+
+ $statbits = $rec['status'];
+ $editDirty = $rec['edit'];
+
+ if ($editDirty == '0')
+ $editDirty = false;
+ else
+ $editDirty = true;
+
+ if (is_array($rec['metadatas'])) {
+ $record->set_metadatas($rec['metadatas']);
+ }
+
+ /**
+ * todo : this should not work
+ */
+ if ($write_edit_el instanceof \databox_field) {
+ $fields = $record->get_caption()->get_fields(array($write_edit_el->get_name()), true);
+ $field = array_pop($fields);
+
+ $meta_id = null;
+
+ if ($field && ! $field->is_multi()) {
+ $meta_id = array_pop($field->get_values())->getId();
+ }
+
+ $metas = array(
+ array(
+ 'meta_struct_id' => $write_edit_el->get_id()
+ , 'meta_id' => $meta_id
+ , 'value' => $date_obj->format('Y-m-d h:i:s')
+ )
+ );
+
+ $record->set_metadatas($metas, true);
+ }
+
+ $newstat = $record->get_status();
+ $statbits = ltrim($statbits, 'x');
+ if ( ! in_array($statbits, array('', 'null'))) {
+ $mask_and = ltrim(str_replace(
+ array('x', '0', '1', 'z'), array('1', 'z', '0', '1'), $statbits), '0');
+ if ($mask_and != '')
+ $newstat = \databox_status::operation_and_not($newstat, $mask_and);
+
+ $mask_or = ltrim(str_replace('x', '0', $statbits), '0');
+
+ if ($mask_or != '')
+ $newstat = \databox_status::operation_or($newstat, $mask_or);
+
+ $record->set_binary_status($newstat);
+ }
+
+ $collection = \collection::get_from_base_id($record->get_base_id());
+ $collection->reset_stamp($record->get_record_id());
+
+ $record->write_metas();
+
+ if ($statbits != '') {
+ $appbox->get_session()
+ ->get_logger($record->get_databox())
+ ->log($record, \Session_Logger::EVENT_STATUS, '', '');
+ }
+ if ($editDirty) {
+ $appbox->get_session()
+ ->get_logger($record->get_databox())
+ ->log($record, \Session_Logger::EVENT_EDIT, '', '');
+ }
+ }
+
+ return $this;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Feed.php b/lib/Alchemy/Phrasea/Helper/Record/Feed.php
index 36c0652528..7c5891cefb 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Feed.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Feed.php
@@ -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;
- }
-
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Helper.php b/lib/Alchemy/Phrasea/Helper/Record/Helper.php
index 704b6de3aa..e5e32e7474 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Helper.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Helper.php
@@ -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
+ */
+ protected $request;
+ protected $flatten_groupings = false;
- /**
- *
- * @var
- */
- 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
- */
- 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
+ */
+ 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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/MoveCollection.php b/lib/Alchemy/Phrasea/Helper/Record/MoveCollection.php
index af558854f2..3fbbead3d6 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/MoveCollection.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/MoveCollection.php
@@ -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;
- }
-
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Printer.php b/lib/Alchemy/Phrasea/Helper/Record/Printer.php
index 8ae7118381..06f67a91e0 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Printer.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Printer.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Push.php b/lib/Alchemy/Phrasea/Helper/Record/Push.php
index 2afca8df86..d27b762d43 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Push.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Push.php
@@ -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');
}
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Tools.php b/lib/Alchemy/Phrasea/Helper/Record/Tools.php
index 18592058cd..ff03bfe08e 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Tools.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Tools.php
@@ -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;
diff --git a/lib/Alchemy/Phrasea/Helper/Record/Tooltip.php b/lib/Alchemy/Phrasea/Helper/Record/Tooltip.php
index 0f595bcab1..06ef6bc919 100644
--- a/lib/Alchemy/Phrasea/Helper/Record/Tooltip.php
+++ b/lib/Alchemy/Phrasea/Helper/Record/Tooltip.php
@@ -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;
diff --git a/lib/Alchemy/Phrasea/Helper/User/Edit.php b/lib/Alchemy/Phrasea/Helper/User/Edit.php
index 972864e942..67078cc0a7 100644
--- a/lib/Alchemy/Phrasea/Helper/User/Edit.php
+++ b/lib/Alchemy/Phrasea/Helper/User/Edit.php
@@ -22,81 +22,77 @@ use Symfony\Component\HttpFoundation\Request;
*/
class Edit extends \Alchemy\Phrasea\Helper\Helper
{
+ /**
+ *
+ * @var array
+ */
+ protected $users = array();
- /**
- *
- * @var array
- */
- protected $users = array();
+ /**
+ *
+ * @var array
+ */
+ protected $users_datas;
- /**
- *
- * @var array
- */
- protected $users_datas;
+ /**
+ *
+ * @var int
+ */
+ protected $base_id;
- /**
- *
- * @var int
- */
- protected $base_id;
-
- public function __construct(Core $core, Request $Request)
- {
- parent::__construct($core, $Request);
-
- $this->users = explode(';', $Request->get('users'));
-
- $users = array();
- foreach ($this->users as $usr_id)
+ public function __construct(Core $core, Request $Request)
{
- $usr_id = (int) $usr_id;
+ parent::__construct($core, $Request);
- if ($usr_id > 0)
- $users[$usr_id] = $usr_id;
+ $this->users = explode(';', $Request->get('users'));
+
+ $users = array();
+ foreach ($this->users as $usr_id) {
+ $usr_id = (int) $usr_id;
+
+ if ($usr_id > 0)
+ $users[$usr_id] = $usr_id;
+ }
+
+ $this->users = $users;
+
+ return $this;
}
- $this->users = $users;
-
- return $this;
- }
-
- public function delete_users()
- {
- $appbox = \appbox::get_instance($this->core);
- foreach ($this->users as $usr_id)
+ public function delete_users()
{
- $user = \User_Adapter::getInstance($usr_id, $appbox);
- $this->delete_user($user);
+ $appbox = \appbox::get_instance($this->core);
+ foreach ($this->users as $usr_id) {
+ $user = \User_Adapter::getInstance($usr_id, $appbox);
+ $this->delete_user($user);
+ }
+
+ return $this;
}
- return $this;
- }
-
- protected function delete_user(\User_Adapter $user)
- {
- $master = $this->getCore()->getAuthenticatedUser();
-
- $list = array_keys($master->ACL()->get_granted_base(array('canadmin')));
-
- $user->ACL()->revoke_access_from_bases($list);
-
- if ($user->ACL()->is_phantom())
+ protected function delete_user(\User_Adapter $user)
{
- $user->delete();
+ $master = $this->getCore()->getAuthenticatedUser();
+
+ $list = array_keys($master->ACL()->get_granted_base(array('canadmin')));
+
+ $user->ACL()->revoke_access_from_bases($list);
+
+ if ($user->ACL()->is_phantom()) {
+ $user->delete();
+ }
+
+ return $this;
}
- return $this;
- }
+ public function get_users_rights()
+ {
+ $user = $this->getCore()->getAuthenticatedUser();
+ $appbox = \appbox::get_instance($this->core);
- public function get_users_rights()
- {
- $user = $this->getCore()->getAuthenticatedUser();
- $appbox = \appbox::get_instance($this->core);
+ $list = array_keys($user->ACL()->get_granted_base(array('canadmin')));
- $list = array_keys($user->ACL()->get_granted_base(array('canadmin')));
-
- $sql = "SELECT
+ $sql = "SELECT
b.sbas_id,
b.base_id,
sum(actif) as actif,
@@ -144,432 +140,396 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
GROUP BY b.base_id
ORDER BY s.ord, s.sbas_id, b.ord, b.base_id ";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $sql = 'SELECT base_id, sum(1) as access FROM basusr
+ $sql = 'SELECT base_id, sum(1) as access FROM basusr
WHERE (usr_id = ' . implode(' OR usr_id = ', $this->users) . ')
AND (base_id = ' . implode(' OR base_id = ', $list) . ')
GROUP BY base_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $access = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $access = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $base_ids = array();
- foreach ($access as $acc)
- {
- $base_ids[$acc['base_id']] = $acc;
- }
- unset($access);
+ $base_ids = array();
+ foreach ($access as $acc) {
+ $base_ids[$acc['base_id']] = $acc;
+ }
+ unset($access);
- foreach ($rs as $k => $row)
- {
- $rs[$k]['access'] = array_key_exists($row['base_id'], $base_ids) ? $base_ids[$row['base_id']]['access'] : '0';
- foreach ($row as $dk => $data)
- {
- if (is_null($data))
- $rs[$k][$dk] = '0';
- }
+ foreach ($rs as $k => $row) {
+ $rs[$k]['access'] = array_key_exists($row['base_id'], $base_ids) ? $base_ids[$row['base_id']]['access'] : '0';
+ foreach ($row as $dk => $data) {
+ if (is_null($data))
+ $rs[$k][$dk] = '0';
+ }
+ }
+
+ $query = new \User_Query($appbox);
+ $templates = $query
+ ->only_templates(true)
+ ->execute()->get_results();
+
+ $this->users_datas = $rs;
+ $out = array(
+ 'datas' => $this->users_datas,
+ 'users' => $this->users,
+ 'users_serial' => implode(';', $this->users),
+ 'base_id' => $this->base_id,
+ 'main_user' => null,
+ 'templates' => $templates
+ );
+
+ if (count($this->users) == 1) {
+ $usr_id = array_pop($this->users);
+ $out['main_user'] = \User_Adapter::getInstance($usr_id, $appbox);
+ }
+
+ return $out;
}
- $query = new \User_Query($appbox);
- $templates = $query
- ->only_templates(true)
- ->execute()->get_results();
-
- $this->users_datas = $rs;
- $out = array(
- 'datas' => $this->users_datas,
- 'users' => $this->users,
- 'users_serial' => implode(';', $this->users),
- 'base_id' => $this->base_id,
- 'main_user' => null,
- 'templates' => $templates
- );
-
- if (count($this->users) == 1)
+ public function get_quotas()
{
- $usr_id = array_pop($this->users);
- $out['main_user'] = \User_Adapter::getInstance($usr_id, $appbox);
- }
+ $this->base_id = (int) $this->request->get('base_id');
- return $out;
- }
-
- public function get_quotas()
- {
- $this->base_id = (int) $this->request->get('base_id');
-
- $sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max
+ $sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
WHERE u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . "
AND bu.base_id = :base_id";
- $conn = \connection::getPDOConnection();
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':base_id' => $this->base_id));
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $conn = \connection::getPDOConnection();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->base_id));
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->users_datas = $rs;
+ $this->users_datas = $rs;
- return array(
- 'datas' => $this->users_datas,
- 'users' => $this->users,
- 'users_serial' => implode(';', $this->users),
- 'base_id' => $this->base_id
- );
- }
+ return array(
+ 'datas' => $this->users_datas,
+ 'users' => $this->users,
+ 'users_serial' => implode(';', $this->users),
+ 'base_id' => $this->base_id
+ );
+ }
- public function get_masks()
- {
- $this->base_id = (int) $this->request->get('base_id');
+ public function get_masks()
+ {
+ $this->base_id = (int) $this->request->get('base_id');
- $sql = "SELECT BIN(mask_and) AS mask_and, BIN(mask_xor) AS mask_xor
+ $sql = "SELECT BIN(mask_and) AS mask_and, BIN(mask_xor) AS mask_xor
FROM basusr
WHERE usr_id IN (" . implode(',', $this->users) . ")
AND base_id = :base_id";
- $conn = \connection::getPDOConnection();
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':base_id' => $this->base_id));
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $conn = \connection::getPDOConnection();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->base_id));
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $msk_and = null;
- $msk_xor = null;
- $tbits_and = array();
- $tbits_xor = array();
+ $msk_and = null;
+ $msk_xor = null;
+ $tbits_and = array();
+ $tbits_xor = array();
- $nrows = 0;
+ $nrows = 0;
- for ($bit = 0; $bit < 64; $bit++)
- $tbits_and[$bit] = $tbits_xor[$bit] = array("nset" => 0);
+ for ($bit = 0; $bit < 64; $bit ++ )
+ $tbits_and[$bit] = $tbits_xor[$bit] = array("nset" => 0);
- foreach ($rs as $row)
- {
- $sta_xor = strrev($row["mask_xor"]);
- for ($bit = 0; $bit < strlen($sta_xor); $bit++)
- $tbits_xor[$bit]["nset"] += substr($sta_xor, $bit, 1) != "0" ? 1 : 0;
+ foreach ($rs as $row) {
+ $sta_xor = strrev($row["mask_xor"]);
+ for ($bit = 0; $bit < strlen($sta_xor); $bit ++ )
+ $tbits_xor[$bit]["nset"] += substr($sta_xor, $bit, 1) != "0" ? 1 : 0;
- $sta_and = strrev($row["mask_and"]);
- for ($bit = 0; $bit < strlen($sta_and); $bit++)
- $tbits_and[$bit]["nset"] += substr($sta_and, $bit, 1) != "0" ? 1 : 0;
+ $sta_and = strrev($row["mask_and"]);
+ for ($bit = 0; $bit < strlen($sta_and); $bit ++ )
+ $tbits_and[$bit]["nset"] += substr($sta_and, $bit, 1) != "0" ? 1 : 0;
- $nrows++;
- }
-
- $tbits_left = array();
- $tbits_right = array();
-
- $sbas_id = \phrasea::sbasFromBas($this->base_id);
- $databox = \databox::get_instance($sbas_id);
- $status = $databox->get_statusbits();
-
- foreach ($status as $bit => $datas)
- {
- $tbits_left[$bit]["nset"] = 0;
- $tbits_left[$bit]["name"] = $datas["labeloff"];
- $tbits_left[$bit]["icon"] = $datas["img_off"];
-
- $tbits_right[$bit]["nset"] = 0;
- $tbits_right[$bit]["name"] = $datas["labelon"];
- $tbits_right[$bit]["icon"] = $datas["img_on"];
- }
-
- $vand_and = $vand_or = $vxor_and = $vxor_or = "0000";
-
- for ($bit = 4; $bit < 64; $bit++)
- {
- if (($tbits_and[$bit]["nset"] != 0 && $tbits_and[$bit]["nset"] != $nrows) || ($tbits_xor[$bit]["nset"] != 0 && $tbits_xor[$bit]["nset"] != $nrows))
- {
- if (isset($tbits_left[$bit]) && isset($tbits_right[$bit]))
- {
- $tbits_left[$bit]["nset"] = 2;
- $tbits_right[$bit]["nset"] = 2;
+ $nrows ++;
}
- $vand_and = "1" . $vand_and;
- $vand_or = "0" . $vand_or;
- $vxor_and = "1" . $vxor_and;
- $vxor_or = "0" . $vxor_or;
- }
- else
- {
- if (isset($tbits_left[$bit]) && isset($tbits_right[$bit]))
- {
- $tbits_left[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == 0) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
- $tbits_right[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == $nrows) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
+
+ $tbits_left = array();
+ $tbits_right = array();
+
+ $sbas_id = \phrasea::sbasFromBas($this->base_id);
+ $databox = \databox::get_instance($sbas_id);
+ $status = $databox->get_statusbits();
+
+ foreach ($status as $bit => $datas) {
+ $tbits_left[$bit]["nset"] = 0;
+ $tbits_left[$bit]["name"] = $datas["labeloff"];
+ $tbits_left[$bit]["icon"] = $datas["img_off"];
+
+ $tbits_right[$bit]["nset"] = 0;
+ $tbits_right[$bit]["name"] = $datas["labelon"];
+ $tbits_right[$bit]["icon"] = $datas["img_on"];
}
- $vand_and = ($tbits_and[$bit]["nset"] == 0 ? "0" : "1") . $vand_and;
- $vand_or = ($tbits_and[$bit]["nset"] == $nrows ? "1" : "0") . $vand_or;
- $vxor_and = ($tbits_xor[$bit]["nset"] == 0 ? "0" : "1") . $vxor_and;
- $vxor_or = ($tbits_xor[$bit]["nset"] == $nrows ? "1" : "0") . $vxor_or;
- }
+
+ $vand_and = $vand_or = $vxor_and = $vxor_or = "0000";
+
+ for ($bit = 4; $bit < 64; $bit ++ ) {
+ if (($tbits_and[$bit]["nset"] != 0 && $tbits_and[$bit]["nset"] != $nrows) || ($tbits_xor[$bit]["nset"] != 0 && $tbits_xor[$bit]["nset"] != $nrows)) {
+ if (isset($tbits_left[$bit]) && isset($tbits_right[$bit])) {
+ $tbits_left[$bit]["nset"] = 2;
+ $tbits_right[$bit]["nset"] = 2;
+ }
+ $vand_and = "1" . $vand_and;
+ $vand_or = "0" . $vand_or;
+ $vxor_and = "1" . $vxor_and;
+ $vxor_or = "0" . $vxor_or;
+ } else {
+ if (isset($tbits_left[$bit]) && isset($tbits_right[$bit])) {
+ $tbits_left[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == 0) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
+ $tbits_right[$bit]["nset"] = (($tbits_and[$bit]["nset"] == $nrows && $tbits_xor[$bit]["nset"] == $nrows) || $tbits_and[$bit]["nset"] == 0 ) ? 1 : 0;
+ }
+ $vand_and = ($tbits_and[$bit]["nset"] == 0 ? "0" : "1") . $vand_and;
+ $vand_or = ($tbits_and[$bit]["nset"] == $nrows ? "1" : "0") . $vand_or;
+ $vxor_and = ($tbits_xor[$bit]["nset"] == 0 ? "0" : "1") . $vxor_and;
+ $vxor_or = ($tbits_xor[$bit]["nset"] == $nrows ? "1" : "0") . $vxor_or;
+ }
+ }
+
+ $this->users_datas = array(
+ 'tbits_left' => $tbits_left,
+ 'tbits_right' => $tbits_right,
+ 'vand_and' => $vand_and,
+ 'vand_or' => $vand_or,
+ 'vxor_and' => $vxor_and,
+ 'vxor_or' => $vxor_or
+ );
+
+ return array(
+ 'datas' => $this->users_datas,
+ 'users' => $this->users,
+ 'users_serial' => implode(';', $this->users),
+ 'base_id' => $this->base_id
+ );
}
- $this->users_datas = array(
- 'tbits_left' => $tbits_left,
- 'tbits_right' => $tbits_right,
- 'vand_and' => $vand_and,
- 'vand_or' => $vand_or,
- 'vxor_and' => $vxor_and,
- 'vxor_or' => $vxor_or
- );
+ public function get_time()
+ {
+ $this->base_id = (int) $this->request->get('base_id');
- return array(
- 'datas' => $this->users_datas,
- 'users' => $this->users,
- 'users_serial' => implode(';', $this->users),
- 'base_id' => $this->base_id
- );
- }
-
- public function get_time()
- {
- $this->base_id = (int) $this->request->get('base_id');
-
- $sql = "SELECT u.usr_id, time_limited, limited_from, limited_to
+ $sql = "SELECT u.usr_id, time_limited, limited_from, limited_to
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
WHERE u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . "
AND bu.base_id = :base_id";
- $conn = \connection::getPDOConnection();
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':base_id' => $this->base_id));
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $conn = \connection::getPDOConnection();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->base_id));
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $time_limited = -1;
- $limited_from = $limited_to = false;
+ $time_limited = -1;
+ $limited_from = $limited_to = false;
- foreach ($rs as $row)
- {
- if ($time_limited < 0)
- $time_limited = $row['time_limited'];
- if ($time_limited < 2 && $row['time_limited'] != $row['time_limited'])
- $time_limited = 2;
+ foreach ($rs as $row) {
+ if ($time_limited < 0)
+ $time_limited = $row['time_limited'];
+ if ($time_limited < 2 && $row['time_limited'] != $row['time_limited'])
+ $time_limited = 2;
- if ($limited_from !== '' && trim($row['limited_from']) != '0000-00-00 00:00:00')
- {
- $limited_from = $limited_from === false ? $row['limited_from'] : (($limited_from == $row['limited_from']) ? $limited_from : '');
- }
- if ($limited_to !== '' && trim($row['limited_to']) != '0000-00-00 00:00:00')
- {
- $limited_to = $limited_to === false ? $row['limited_to'] : (($limited_to == $row['limited_to']) ? $limited_to : '');
- }
- }
-
- if ($limited_from)
- {
- $date_obj_from = new \DateTime($limited_from);
- $limited_from = $date_obj_from->format('Y-m-d');
- }
- if ($limited_to)
- {
- $date_obj_to = new \DateTime($limited_to);
- $limited_to = $date_obj_to->format('Y-m-d');
- }
-
- $datas = array('time_limited' => $time_limited, 'limited_from' => $limited_from, 'limited_to' => $limited_to);
-
- $this->users_datas = $datas;
-
- return array(
- 'datas' => $this->users_datas,
- 'users' => $this->users,
- 'users_serial' => implode(';', $this->users),
- 'base_id' => $this->base_id
- );
- }
-
- public function apply_rights()
- {
- $appbox = \appbox::get_instance($this->core);
- $session = $appbox->get_session();
- $request = \http_request::getInstance();
- $ACL = \User_Adapter::getInstance($session->get_usr_id(), $appbox)->ACL();
- $base_ids = array_keys($ACL->get_granted_base(array('canadmin')));
-
- $update = $create = $delete = $create_sbas = $update_sbas = array();
-
- foreach ($base_ids as $base_id)
- {
- $rights = array(
- 'access',
- 'actif',
- 'canputinalbum',
- 'nowatermark',
- 'candwnldpreview',
- 'candwnldhd',
- 'cancmd',
- 'canaddrecord',
- 'canmodifrecord',
- 'chgstatus',
- 'candeleterecord',
- 'imgtools',
- 'canadmin',
- 'canreport',
- 'canpush',
- 'manage',
- 'modify_struct'
- );
- foreach ($rights as $k => $right)
- {
- if (($right == 'access' && !$ACL->has_access_to_base($base_id))
- || ($right != 'access' && !$ACL->has_right_on_base($base_id, $right)))
- {
- unset($rights[$k]);
- continue;
- }
- $rights[$k] = $right . '_' . $base_id;
- }
- $parm = $request->get_parms_from_serialized_datas($rights, 'values');
-
- foreach ($parm as $p => $v)
- {
- if (trim($v) == '')
- continue;
-
- $serial = explode('_', $p);
- $base_id = array_pop($serial);
-
- $p = implode('_', $serial);
-
- if ($p == 'access')
- {
- if ($v === '1')
- {
- $create_sbas[\phrasea::sbasFromBas($base_id)] = \phrasea::sbasFromBas($base_id);
- $create[] = $base_id;
- }
- else
- $delete[] = $base_id;
- }
- else
- {
- $create_sbas[\phrasea::sbasFromBas($base_id)] = \phrasea::sbasFromBas($base_id);
- $update[$base_id][$p] = $v;
- }
- }
- }
-
- $sbas_ids = $ACL->get_granted_sbas();
-
- foreach ($sbas_ids as $databox)
- {
- $rights = array(
- 'bas_modif_th',
- 'bas_manage',
- 'bas_modify_struct',
- 'bas_chupub'
- );
- foreach ($rights as $k => $right)
- {
- if (!$ACL->has_right_on_sbas($databox->get_sbas_id(), $right))
- {
- unset($rights[$k]);
- continue;
- }
- $rights[$k] = $right . '_' . $databox->get_sbas_id();
- }
-
- $parm = $request->get_parms_from_serialized_datas($rights, 'values');
-
- foreach ($parm as $p => $v)
- {
- if (trim($v) == '')
- continue;
-
- $serial = explode('_', $p);
- $sbas_id = array_pop($serial);
-
- $p = implode('_', $serial);
-
- $update_sbas[$sbas_id][$p] = $v;
- }
- }
-
- foreach ($this->users as $usr_id)
- {
- try
- {
- $appbox->get_connection()->beginTransaction();
-
- $user = \User_Adapter::getInstance($usr_id, $appbox);
- $user->ACL()->revoke_access_from_bases($delete)
- ->give_access_to_base($create)
- ->give_access_to_sbas($create_sbas);
-
- foreach ($update as $base_id => $rights)
- {
- $user->ACL()->update_rights_to_base($base_id, $rights);
+ if ($limited_from !== '' && trim($row['limited_from']) != '0000-00-00 00:00:00') {
+ $limited_from = $limited_from === false ? $row['limited_from'] : (($limited_from == $row['limited_from']) ? $limited_from : '');
+ }
+ if ($limited_to !== '' && trim($row['limited_to']) != '0000-00-00 00:00:00') {
+ $limited_to = $limited_to === false ? $row['limited_to'] : (($limited_to == $row['limited_to']) ? $limited_to : '');
+ }
}
- foreach ($update_sbas as $sbas_id => $rights)
- {
- $user->ACL()->update_rights_to_sbas($sbas_id, $rights);
+ if ($limited_from) {
+ $date_obj_from = new \DateTime($limited_from);
+ $limited_from = $date_obj_from->format('Y-m-d');
+ }
+ if ($limited_to) {
+ $date_obj_to = new \DateTime($limited_to);
+ $limited_to = $date_obj_to->format('Y-m-d');
}
- $appbox->get_connection()->commit();
+ $datas = array('time_limited' => $time_limited, 'limited_from' => $limited_from, 'limited_to' => $limited_to);
- $user->ACL()->revoke_unused_sbas_rights();
+ $this->users_datas = $datas;
- unset($user);
- }
- catch (\Exception $e)
- {
- $appbox->get_connection()->rollBack();
- }
+ return array(
+ 'datas' => $this->users_datas,
+ 'users' => $this->users,
+ 'users_serial' => implode(';', $this->users),
+ 'base_id' => $this->base_id
+ );
}
- return $this;
- }
-
- public function apply_infos()
- {
- if (count($this->users) != 1)
+ public function apply_rights()
{
- return $this;
+ $appbox = \appbox::get_instance($this->core);
+ $session = $appbox->get_session();
+ $request = \http_request::getInstance();
+ $ACL = \User_Adapter::getInstance($session->get_usr_id(), $appbox)->ACL();
+ $base_ids = array_keys($ACL->get_granted_base(array('canadmin')));
+
+ $update = $create = $delete = $create_sbas = $update_sbas = array();
+
+ foreach ($base_ids as $base_id) {
+ $rights = array(
+ 'access',
+ 'actif',
+ 'canputinalbum',
+ 'nowatermark',
+ 'candwnldpreview',
+ 'candwnldhd',
+ 'cancmd',
+ 'canaddrecord',
+ 'canmodifrecord',
+ 'chgstatus',
+ 'candeleterecord',
+ 'imgtools',
+ 'canadmin',
+ 'canreport',
+ 'canpush',
+ 'manage',
+ 'modify_struct'
+ );
+ foreach ($rights as $k => $right) {
+ if (($right == 'access' && ! $ACL->has_access_to_base($base_id))
+ || ($right != 'access' && ! $ACL->has_right_on_base($base_id, $right))) {
+ unset($rights[$k]);
+ continue;
+ }
+ $rights[$k] = $right . '_' . $base_id;
+ }
+ $parm = $request->get_parms_from_serialized_datas($rights, 'values');
+
+ foreach ($parm as $p => $v) {
+ if (trim($v) == '')
+ continue;
+
+ $serial = explode('_', $p);
+ $base_id = array_pop($serial);
+
+ $p = implode('_', $serial);
+
+ if ($p == 'access') {
+ if ($v === '1') {
+ $create_sbas[\phrasea::sbasFromBas($base_id)] = \phrasea::sbasFromBas($base_id);
+ $create[] = $base_id;
+ }
+ else
+ $delete[] = $base_id;
+ }
+ else {
+ $create_sbas[\phrasea::sbasFromBas($base_id)] = \phrasea::sbasFromBas($base_id);
+ $update[$base_id][$p] = $v;
+ }
+ }
+ }
+
+ $sbas_ids = $ACL->get_granted_sbas();
+
+ foreach ($sbas_ids as $databox) {
+ $rights = array(
+ 'bas_modif_th',
+ 'bas_manage',
+ 'bas_modify_struct',
+ 'bas_chupub'
+ );
+ foreach ($rights as $k => $right) {
+ if ( ! $ACL->has_right_on_sbas($databox->get_sbas_id(), $right)) {
+ unset($rights[$k]);
+ continue;
+ }
+ $rights[$k] = $right . '_' . $databox->get_sbas_id();
+ }
+
+ $parm = $request->get_parms_from_serialized_datas($rights, 'values');
+
+ foreach ($parm as $p => $v) {
+ if (trim($v) == '')
+ continue;
+
+ $serial = explode('_', $p);
+ $sbas_id = array_pop($serial);
+
+ $p = implode('_', $serial);
+
+ $update_sbas[$sbas_id][$p] = $v;
+ }
+ }
+
+ foreach ($this->users as $usr_id) {
+ try {
+ $appbox->get_connection()->beginTransaction();
+
+ $user = \User_Adapter::getInstance($usr_id, $appbox);
+ $user->ACL()->revoke_access_from_bases($delete)
+ ->give_access_to_base($create)
+ ->give_access_to_sbas($create_sbas);
+
+ foreach ($update as $base_id => $rights) {
+ $user->ACL()->update_rights_to_base($base_id, $rights);
+ }
+
+ foreach ($update_sbas as $sbas_id => $rights) {
+ $user->ACL()->update_rights_to_sbas($sbas_id, $rights);
+ }
+
+ $appbox->get_connection()->commit();
+
+ $user->ACL()->revoke_unused_sbas_rights();
+
+ unset($user);
+ } catch (\Exception $e) {
+ $appbox->get_connection()->rollBack();
+ }
+ }
+
+ return $this;
}
- $users = $this->users;
-
- $user = \User_adapter::getInstance(array_pop($users), \appbox::get_instance($this->core));
-
- if ($user->is_template() || $user->is_special())
+ public function apply_infos()
{
- return $this;
- }
+ if (count($this->users) != 1) {
+ return $this;
+ }
- $appbox = \appbox::get_instance($this->core);
- $session = $appbox->get_session();
- $request = \http_request::getInstance();
+ $users = $this->users;
- $infos = array(
- 'gender'
- , 'first_name'
- , 'last_name'
- , 'email'
- , 'address'
- , 'zip'
- , 'geonameid'
- , 'function'
- , 'company'
- , 'activite'
- , 'telephone'
- , 'fax'
- );
+ $user = \User_adapter::getInstance(array_pop($users), \appbox::get_instance($this->core));
- $parm = $request->get_parms_from_serialized_datas($infos, 'user_infos');
+ if ($user->is_template() || $user->is_special()) {
+ return $this;
+ }
- if ($parm['email'] && !\mail::validateEmail($parm['email']))
- throw new \Exception_InvalidArgument(_('Email addess is not valid'));
+ $appbox = \appbox::get_instance($this->core);
+ $session = $appbox->get_session();
+ $request = \http_request::getInstance();
- $user->set_firstname($parm['first_name'])
+ $infos = array(
+ 'gender'
+ , 'first_name'
+ , 'last_name'
+ , 'email'
+ , 'address'
+ , 'zip'
+ , 'geonameid'
+ , 'function'
+ , 'company'
+ , 'activite'
+ , 'telephone'
+ , 'fax'
+ );
+
+ $parm = $request->get_parms_from_serialized_datas($infos, 'user_infos');
+
+ if ($parm['email'] && ! \mail::validateEmail($parm['email']))
+ throw new \Exception_InvalidArgument(_('Email addess is not valid'));
+
+ $user->set_firstname($parm['first_name'])
->set_lastname($parm['last_name'])
->set_gender($parm['gender'])
->set_email($parm['email'])
@@ -582,130 +542,117 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
->set_tel($parm['telephone'])
->set_fax($parm['fax']);
- return $this;
- }
-
- public function apply_template()
- {
- $appbox = \appbox::get_instance($this->core);
- $session = $appbox->get_session();
-
- $template = \User_adapter::getInstance($this->request->get('template'), $appbox);
-
- if ($template->get_template_owner()->get_id() != $session->get_usr_id())
- {
- throw new \Exception_Forbidden('You are not the owner of the template');
+ return $this;
}
- $current_user = \User_adapter::getInstance($session->get_usr_id(), $appbox);
-
- $base_ids = array_keys($current_user->ACL()->get_granted_base(array('canadmin')));
-
- foreach ($this->users as $usr_id)
+ public function apply_template()
{
- $user = \User_adapter::getInstance($usr_id, $appbox);
+ $appbox = \appbox::get_instance($this->core);
+ $session = $appbox->get_session();
- if ($user->is_template())
- {
- continue;
- }
+ $template = \User_adapter::getInstance($this->request->get('template'), $appbox);
- $user->ACL()->apply_model($template, $base_ids);
- }
-
- return $this;
- }
-
- public function apply_quotas()
- {
- $this->base_id = (int) $this->request->get('base_id');
-
- foreach ($this->users as $usr_id)
- {
- $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
- if ($this->request->get('quota'))
- $user->ACL()->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes'));
- else
- $user->ACL()->remove_quotas_on_base($this->base_id);
- }
-
- return $this;
- }
-
- public function apply_masks()
- {
- $this->base_id = (int) $this->request->get('base_id');
-
- $vand_and = $this->request->get('vand_and');
- $vand_or = $this->request->get('vand_or');
- $vxor_and = $this->request->get('vxor_and');
- $vxor_or = $this->request->get('vxor_or');
-
- if ($vand_and && $vand_or && $vxor_and && $vxor_or)
- {
- foreach ($this->users as $usr_id)
- {
- $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
-
- $user->ACL()->set_masks_on_base($this->base_id, $vand_and, $vand_or, $vxor_and, $vxor_or);
- }
- }
-
- return $this;
- }
-
- public function apply_time()
- {
- $this->base_id = (int) $this->request->get('base_id');
-
- $dmin = $this->request->get('dmin') ? new \DateTime($this->request->get('dmin')) : null;
- $dmax = $this->request->get('dmax') ? new \DateTime($this->request->get('dmax')) : null;
-
- $activate = !!$this->request->get('limit');
-
- foreach ($this->users as $usr_id)
- {
- $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
-
- $user->ACL()->set_limits($this->base_id, $activate, $dmin, $dmax);
- }
- }
-
- public function resetRights()
- {
- $authUser = $this->core->getAuthenticatedUser();
- $adminACL = $authUser->ACL();
- $base_ids = array_keys($adminACL->get_granted_base(array('canadmin')));
-
- foreach ($this->users as $usr_id)
- {
- $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
- $ACL = $user->ACL();
-
- if ($user->is_template())
- {
- $template = $user;
-
- if ($template->get_template_owner()->get_id() !== $authUser->get_id())
- {
- continue;
- }
- }
-
- foreach ($base_ids as $base_id)
- {
- if (!$ACL->has_access_to_base($base_id))
- {
- continue;
+ if ($template->get_template_owner()->get_id() != $session->get_usr_id()) {
+ throw new \Exception_Forbidden('You are not the owner of the template');
}
- $ACL->set_limits($base_id, false);
- $ACL->set_masks_on_base($base_id, 0, 0, 0, 0);
- $ACL->remove_quotas_on_base($base_id);
- }
- $ACL->revoke_access_from_bases($base_ids);
- $ACL->revoke_unused_sbas_rights();
- }
- }
+ $current_user = \User_adapter::getInstance($session->get_usr_id(), $appbox);
+ $base_ids = array_keys($current_user->ACL()->get_granted_base(array('canadmin')));
+
+ foreach ($this->users as $usr_id) {
+ $user = \User_adapter::getInstance($usr_id, $appbox);
+
+ if ($user->is_template()) {
+ continue;
+ }
+
+ $user->ACL()->apply_model($template, $base_ids);
+ }
+
+ return $this;
+ }
+
+ public function apply_quotas()
+ {
+ $this->base_id = (int) $this->request->get('base_id');
+
+ foreach ($this->users as $usr_id) {
+ $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
+ if ($this->request->get('quota'))
+ $user->ACL()->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes'));
+ else
+ $user->ACL()->remove_quotas_on_base($this->base_id);
+ }
+
+ return $this;
+ }
+
+ public function apply_masks()
+ {
+ $this->base_id = (int) $this->request->get('base_id');
+
+ $vand_and = $this->request->get('vand_and');
+ $vand_or = $this->request->get('vand_or');
+ $vxor_and = $this->request->get('vxor_and');
+ $vxor_or = $this->request->get('vxor_or');
+
+ if ($vand_and && $vand_or && $vxor_and && $vxor_or) {
+ foreach ($this->users as $usr_id) {
+ $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
+
+ $user->ACL()->set_masks_on_base($this->base_id, $vand_and, $vand_or, $vxor_and, $vxor_or);
+ }
+ }
+
+ return $this;
+ }
+
+ public function apply_time()
+ {
+ $this->base_id = (int) $this->request->get('base_id');
+
+ $dmin = $this->request->get('dmin') ? new \DateTime($this->request->get('dmin')) : null;
+ $dmax = $this->request->get('dmax') ? new \DateTime($this->request->get('dmax')) : null;
+
+ $activate = ! ! $this->request->get('limit');
+
+ foreach ($this->users as $usr_id) {
+ $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
+
+ $user->ACL()->set_limits($this->base_id, $activate, $dmin, $dmax);
+ }
+ }
+
+ public function resetRights()
+ {
+ $authUser = $this->core->getAuthenticatedUser();
+ $adminACL = $authUser->ACL();
+ $base_ids = array_keys($adminACL->get_granted_base(array('canadmin')));
+
+ foreach ($this->users as $usr_id) {
+ $user = \User_Adapter::getInstance($usr_id, \appbox::get_instance($this->core));
+ $ACL = $user->ACL();
+
+ if ($user->is_template()) {
+ $template = $user;
+
+ if ($template->get_template_owner()->get_id() !== $authUser->get_id()) {
+ continue;
+ }
+ }
+
+ foreach ($base_ids as $base_id) {
+ if ( ! $ACL->has_access_to_base($base_id)) {
+ continue;
+ }
+
+ $ACL->set_limits($base_id, false);
+ $ACL->set_masks_on_base($base_id, 0, 0, 0, 0);
+ $ACL->remove_quotas_on_base($base_id);
+ }
+ $ACL->revoke_access_from_bases($base_ids);
+ $ACL->revoke_unused_sbas_rights();
+ }
+ }
}
diff --git a/lib/Alchemy/Phrasea/Helper/User/Manage.php b/lib/Alchemy/Phrasea/Helper/User/Manage.php
index 35479a42d4..1f8d9bbba1 100644
--- a/lib/Alchemy/Phrasea/Helper/User/Manage.php
+++ b/lib/Alchemy/Phrasea/Helper/User/Manage.php
@@ -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;
- }
-
}
diff --git a/lib/Alchemy/Phrasea/Helper/WorkZone.php b/lib/Alchemy/Phrasea/Helper/WorkZone.php
index 7274ba674d..3e38f52f84 100644
--- a/lib/Alchemy/Phrasea/Helper/WorkZone.php
+++ b/lib/Alchemy/Phrasea/Helper/WorkZone.php
@@ -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();
+ }
}
diff --git a/lib/Alchemy/Phrasea/Loader/ApcAutoloader.php b/lib/Alchemy/Phrasea/Loader/ApcAutoloader.php
index e4a9f1e9ba..cf35106524 100644
--- a/lib/Alchemy/Phrasea/Loader/ApcAutoloader.php
+++ b/lib/Alchemy/Phrasea/Loader/ApcAutoloader.php
@@ -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');
+ }
}
diff --git a/lib/Alchemy/Phrasea/Loader/Autoloader.php b/lib/Alchemy/Phrasea/Loader/Autoloader.php
index 6a824c8ca7..333446e479 100644
--- a/lib/Alchemy/Phrasea/Loader/Autoloader.php
+++ b/lib/Alchemy/Phrasea/Loader/Autoloader.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Loader/CacheAutoloader.php b/lib/Alchemy/Phrasea/Loader/CacheAutoloader.php
index 458cc603e9..1acec62957 100644
--- a/lib/Alchemy/Phrasea/Loader/CacheAutoloader.php
+++ b/lib/Alchemy/Phrasea/Loader/CacheAutoloader.php
@@ -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;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Loader/LoaderStrategy.php b/lib/Alchemy/Phrasea/Loader/LoaderStrategy.php
index 5741278321..6f488eb859 100644
--- a/lib/Alchemy/Phrasea/Loader/LoaderStrategy.php
+++ b/lib/Alchemy/Phrasea/Loader/LoaderStrategy.php
@@ -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();
}
diff --git a/lib/Alchemy/Phrasea/Loader/XcacheAutoloader.php b/lib/Alchemy/Phrasea/Loader/XcacheAutoloader.php
index 3f0e5dc2d5..b905518143 100644
--- a/lib/Alchemy/Phrasea/Loader/XcacheAutoloader.php
+++ b/lib/Alchemy/Phrasea/Loader/XcacheAutoloader.php
@@ -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';
+ }
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Audio.php b/lib/Alchemy/Phrasea/Media/Subdef/Audio.php
index 0e424aa55f..c675e3e1b2 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Audio.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Audio.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/FlexPaper.php b/lib/Alchemy/Phrasea/Media/Subdef/FlexPaper.php
index 5fa414e5ae..b8bb869b6e 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/FlexPaper.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/FlexPaper.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Gif.php b/lib/Alchemy/Phrasea/Media/Subdef/Gif.php
index 52e54d8e4d..02d9ac0bc8 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Gif.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Gif.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Image.php b/lib/Alchemy/Phrasea/Media/Subdef/Image.php
index 3e7ec534f3..d9847ee409 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Image.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Image.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Boolean.php b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Boolean.php
index 40c064e99c..9673218311 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Boolean.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Boolean.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Enum.php b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Enum.php
index 0738254195..3d555f3fd2 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Enum.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Enum.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/OptionType.php b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/OptionType.php
index 8431216435..a4bf3ae291 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/OptionType.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/OptionType.php
@@ -18,6 +18,8 @@ interface OptionType
const TYPE_BOOLEAN = 'Boolean';
public function getType();
+
public function getName();
+
public function getValue();
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Range.php b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Range.php
index 7af1410bdc..d7ec43b86c 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Range.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/OptionType/Range.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Provider.php b/lib/Alchemy/Phrasea/Media/Subdef/Provider.php
index 20fc453d6c..36996f4a41 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Provider.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Provider.php
@@ -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;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Subdef.php b/lib/Alchemy/Phrasea/Media/Subdef/Subdef.php
index 0a8e7456c3..e44926faec 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Subdef.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Subdef.php
@@ -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();
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Subdef/Video.php b/lib/Alchemy/Phrasea/Media/Subdef/Video.php
index 632be4bbb5..e5c383f44c 100644
--- a/lib/Alchemy/Phrasea/Media/Subdef/Video.php
+++ b/lib/Alchemy/Phrasea/Media/Subdef/Video.php
@@ -13,11 +13,10 @@ namespace Alchemy\Phrasea\Media\Subdef;
class Video extends Audio
{
-
- const OPTION_SIZE = 'size';
+ const OPTION_SIZE = 'size';
const OPTION_FRAMERATE = 'fps';
- const OPTION_VCODEC = 'v_codec';
- const OPTION_GOPSIZE = 'GOPsize';
+ const OPTION_VCODEC = 'v_codec';
+ const OPTION_GOPSIZE = 'GOPsize';
protected $options = array();
@@ -43,8 +42,7 @@ class Video extends Audio
public function getMediaAlchemystSpec()
{
- if ( ! $this->spec)
- {
+ if ( ! $this->spec) {
$this->spec = new \MediaAlchemyst\Specification\Video();
}
@@ -60,5 +58,4 @@ class Video extends Audio
return $this->spec;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Audio.php b/lib/Alchemy/Phrasea/Media/Type/Audio.php
index f1921582fa..85c18eaf70 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Audio.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Audio.php
@@ -18,5 +18,4 @@ class Audio implements Type
{
return self::TYPE_AUDIO;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Document.php b/lib/Alchemy/Phrasea/Media/Type/Document.php
index 3b5b314c52..a61243d898 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Document.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Document.php
@@ -18,5 +18,4 @@ class Document implements Type
{
return self::TYPE_DOCUMENT;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Flash.php b/lib/Alchemy/Phrasea/Media/Type/Flash.php
index d03feb6790..0dc0c81002 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Flash.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Flash.php
@@ -18,5 +18,4 @@ class Flash implements Type
{
return self::TYPE_FLASH;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Image.php b/lib/Alchemy/Phrasea/Media/Type/Image.php
index 703bb8e860..8bcf0a4e66 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Image.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Image.php
@@ -18,5 +18,4 @@ class Image implements Type
{
return self::TYPE_IMAGE;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Type.php b/lib/Alchemy/Phrasea/Media/Type/Type.php
index 08681d717e..67ba02d14f 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Type.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Type.php
@@ -13,13 +13,11 @@ namespace Alchemy\Phrasea\Media\Type;
interface Type
{
-
- const TYPE_AUDIO = 'Audio';
- const TYPE_VIDEO = 'Video';
+ const TYPE_AUDIO = 'Audio';
+ const TYPE_VIDEO = 'Video';
const TYPE_DOCUMENT = 'Document';
- const TYPE_FLASH = 'Flash';
- const TYPE_IMAGE = 'Image';
+ const TYPE_FLASH = 'Flash';
+ const TYPE_IMAGE = 'Image';
public function getType();
-
}
diff --git a/lib/Alchemy/Phrasea/Media/Type/Video.php b/lib/Alchemy/Phrasea/Media/Type/Video.php
index 5fb3eb1e93..589d3b40ba 100644
--- a/lib/Alchemy/Phrasea/Media/Type/Video.php
+++ b/lib/Alchemy/Phrasea/Media/Type/Video.php
@@ -18,5 +18,4 @@ class Video implements Type
{
return self::TYPE_VIDEO;
}
-
}
diff --git a/lib/Alchemy/Phrasea/Out/Module/PDF.php b/lib/Alchemy/Phrasea/Out/Module/PDF.php
index 370c34b4e3..d52002835c 100644
--- a/lib/Alchemy/Phrasea/Out/Module/PDF.php
+++ b/lib/Alchemy/Phrasea/Out/Module/PDF.php
@@ -22,508 +22,463 @@ use \Alchemy\Phrasea\Out\Tool\PhraseaPDF;
*/
class PDF
{
+ protected $records;
+ protected $pdf;
- protected $records;
- protected $pdf;
+ const LAYOUT_PREVIEW = 'preview';
+ const LAYOUT_PREVIEWCAPTION = 'previewCaption';
+ const LAYOUT_PREVIEWCAPTIONTDM = 'previewCaptionTdm';
+ const LAYOUT_THUMBNAILLIST = 'thumbnailList';
+ const LAYOUT_THUMBNAILGRID = 'thumbnailGrid';
- const LAYOUT_PREVIEW = 'preview';
- const LAYOUT_PREVIEWCAPTION = 'previewCaption';
- const LAYOUT_PREVIEWCAPTIONTDM = 'previewCaptionTdm';
- const LAYOUT_THUMBNAILLIST = 'thumbnailList';
- const LAYOUT_THUMBNAILGRID = 'thumbnailGrid';
-
- public function __construct(array $records, $layout)
- {
- $list = array();
-
- foreach ($records as $record)
+ public function __construct(array $records, $layout)
{
- switch ($layout)
- {
- default:
- throw new \Exception('Unknown layout');
- break;
- case self::LAYOUT_PREVIEW:
- case self::LAYOUT_PREVIEWCAPTION:
- case self::LAYOUT_PREVIEWCAPTIONTDM:
- try
- {
- $subdef = $record->get_subdef('preview');
- if (!$subdef->is_physically_present())
- {
- continue;
+ $list = array();
+
+ foreach ($records as $record) {
+ switch ($layout) {
+ default:
+ throw new \Exception('Unknown layout');
+ break;
+ case self::LAYOUT_PREVIEW:
+ case self::LAYOUT_PREVIEWCAPTION:
+ case self::LAYOUT_PREVIEWCAPTIONTDM:
+ try {
+ $subdef = $record->get_subdef('preview');
+ if ( ! $subdef->is_physically_present()) {
+ continue;
+ }
+ if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
+ continue;
+
+ $subdef = $record->get_subdef('thumbnail');
+ if ( ! $subdef->is_physically_present())
+ continue;
+
+ if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
+ continue;
+ } catch (\Exception $e) {
+ continue;
+ }
+ break;
+ case self::LAYOUT_THUMBNAILLIST:
+ case self::LAYOUT_THUMBNAILGRID:
+ try {
+ $subdef = $record->get_subdef('thumbnail');
+ if ( ! $subdef->is_physically_present())
+ continue;
+
+ if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
+ throw new \Exception('Not suitable');
+ } catch (\Exception $e) {
+ continue;
+ }
+ break;
}
- if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
- continue;
- $subdef = $record->get_subdef('thumbnail');
- if (!$subdef->is_physically_present())
- continue;
+ $record->set_number(count($list) + 1);
- if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
- continue;
- }
- catch (\Exception $e)
- {
- continue;
- }
- break;
- case self::LAYOUT_THUMBNAILLIST:
- case self::LAYOUT_THUMBNAILGRID:
- try
- {
- $subdef = $record->get_subdef('thumbnail');
- if (!$subdef->is_physically_present())
- continue;
+ $list[] = $record;
+ }
- if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE)
- throw new \Exception('Not suitable');
- }
- catch (\Exception $e)
- {
- continue;
- }
- break;
- }
+ $this->records = $list;
- $record->set_number(count($list) + 1);
+ $pdf = new PhraseaPDF("P", "mm", "A4", true, 'UTF-8', false);
- $list[] = $record;
+ $pdf->SetAuthor("Phraseanet");
+ $pdf->SetTitle("Phraseanet Print");
+ $pdf->SetDisplayMode("fullpage", "single");
+
+ $this->pdf = $pdf;
+
+ switch ($layout) {
+ case "preview":
+ $this->print_preview(false);
+ break;
+ case "previewCaption":
+ $this->print_preview(false);
+ break;
+ case "previewCaptionTdm":
+ $this->print_preview(true);
+ break;
+ case "thumbnailList":
+ $this->print_thumbnailList();
+ break;
+ case "thumbnailGrid":
+ $this->print_thumbnailGrid();
+ break;
+ }
+
+ return $this;
}
- $this->records = $list;
-
- $pdf = new PhraseaPDF("P", "mm", "A4", true, 'UTF-8', false);
-
- $pdf->SetAuthor("Phraseanet");
- $pdf->SetTitle("Phraseanet Print");
- $pdf->SetDisplayMode("fullpage", "single");
-
- $this->pdf = $pdf;
-
- switch ($layout)
+ public function render()
{
- case "preview":
- $this->print_preview(false);
- break;
- case "previewCaption":
- $this->print_preview(false);
- break;
- case "previewCaptionTdm":
- $this->print_preview(true);
- break;
- case "thumbnailList":
- $this->print_thumbnailList();
- break;
- case "thumbnailGrid":
- $this->print_thumbnailGrid();
- break;
+ $this->pdf->Close();
+
+ return $this->pdf->Output('', 'S');
}
- return $this;
- }
-
- public function render()
- {
- $this->pdf->Close();
-
- return $this->pdf->Output('', 'S');
- }
-
- protected function print_thumbnailGrid($links=false)
- {
- $core = \bootstrap::getCore();
- $appbox = \appbox::get_instance($core);
- $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
-
- $NDiapoW = 3;
- $NDiapoH = 4;
-
- $this->pdf->AddPage();
-
- $oldMargins = $this->pdf->getMargins();
- $tmargin = $oldMargins['top'];
- $lmargin = $oldMargins['left'];
- $bmargin = $oldMargins['bottom'];
- $rmargin = $oldMargins['right'];
-
- $this->pdf->SetLeftMargin($lmargin + 55);
-
- $clientW = $this->pdf->getPageWidth() - $lmargin - $rmargin;
- $clientH = $this->pdf->getPageHeight() - $tmargin - $bmargin;
-
- $DiapoW = floor($clientW / $NDiapoW);
- $DiapoH = floor($clientH / $NDiapoH);
- $TitleH = 5;
- $ImgSize = min($DiapoW, ($DiapoH - $TitleH)) - 5;
-
- $npages = ceil(count($this->records) / ($NDiapoW * $NDiapoH));
-
- $irow = $ipage = 0;
- $icol = -1;
- foreach ($this->records as $rec)
+ protected function print_thumbnailGrid($links = false)
{
- /* @var $rec record_adapter */
- if (++$icol >= $NDiapoW)
- {
- $icol = 0;
- if (++$irow >= $NDiapoH)
- {
- $irow = 0;
- $ipage++;
- $this->pdf->AddPage();
- }
- }
- $fimg = null;
- $himg = 0;
+ $core = \bootstrap::getCore();
+ $appbox = \appbox::get_instance($core);
+ $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
- $subdef = $rec->get_subdef('preview');
+ $NDiapoW = 3;
+ $NDiapoH = 4;
- $fimg = $subdef->get_pathfile();
-
- if (!$user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
- && $subdef->get_type() == \media_subdef::TYPE_IMAGE)
- {
- $fimg = \recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
- }
-
- $wimg = $himg = $ImgSize;
- if ($subdef->get_height() > 0 && $subdef->get_width() > 0)
- {
- if ($subdef->get_width() > $subdef->get_height())
- $himg = $wimg * $subdef->get_height() / $subdef->get_width();
- else
- $wimg = $himg * $subdef->get_width() / $subdef->get_height();
- }
-
- if ($fimg)
- {
- $x = $lmargin + ($icol * $DiapoW);
- $y = $tmargin + ($irow * $DiapoH);
- $this->pdf->SetDrawColor(0);
- $this->pdf->Rect($x, $y, $DiapoW, $DiapoH, "D");
-
- $this->pdf->SetXY($x, $y + 1);
- $this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
- $t = $irow . '-' . $x;
- $t = $rec->get_title();
-
- $this->pdf->MultiCell($DiapoW, $TitleH, $t, '0', 'C', false);
-
- if ($links)
- {
- $lk = $this->pdf->AddLink();
- $this->pdf->SetLink($lk, 0, $npages + $rec->get_number());
- $this->pdf->Image(
- $fimg
- , $x + (($DiapoW - $wimg) / 2)
- , $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
- , $wimg, $himg
- , null, $lk
- );
- }
- else
- {
- $this->pdf->Image($fimg
- , $x + (($DiapoW - $wimg) / 2)
- , $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
- , $wimg, $himg
- );
- }
- }
- }
- $this->pdf->SetLeftMargin($oldMargins['left']);
- }
-
- protected function print_thumbnailList()
- {
- $this->pdf->AddPage();
- $oldMargins = $this->pdf->getMargins();
-
- $tmargin = $oldMargins['top'];
- $lmargin = $oldMargins['left'];
- $bmargin = $oldMargins['bottom'];
- $rmargin = $oldMargins['right'];
-
- $this->pdf->SetLeftMargin($lmargin + 55);
-
- $ndoc = 0;
- $lastpage = $this->pdf->PageNo();
- foreach ($this->records as $rec)
- {
- /* @var $rec record_adapter */
- $subdef = $rec->get_subdef('thumbnail');
-
- $fimg = $subdef->get_pathfile();
- $wimg = $himg = 50;
-
- if ($subdef->get_width() > $subdef->get_height())
- $himg = round($wimg * $subdef->get_height() / $subdef->get_width());
- else
- $wimg = round($himg * $subdef->get_width() / $subdef->get_height());
-
- $himg = 0;
-
- if ($this->pdf->GetY() > $this->pdf->getPageHeight() - (6 + $himg + 20))
$this->pdf->AddPage();
- $title = "record : " . $rec->get_title();
+ $oldMargins = $this->pdf->getMargins();
+ $tmargin = $oldMargins['top'];
+ $lmargin = $oldMargins['left'];
+ $bmargin = $oldMargins['bottom'];
+ $rmargin = $oldMargins['right'];
- $y = $this->pdf->GetY();
+ $this->pdf->SetLeftMargin($lmargin + 55);
- $t = \phrasea::bas_names($rec->get_base_id());
- $this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
- $this->pdf->SetFillColor(220, 220, 220);
- $this->pdf->SetLeftMargin($lmargin);
- $this->pdf->SetRightMargin($rmargin);
- $this->pdf->SetX($lmargin);
- $this->pdf->SetY($y);
+ $clientW = $this->pdf->getPageWidth() - $lmargin - $rmargin;
+ $clientH = $this->pdf->getPageHeight() - $tmargin - $bmargin;
- $this->pdf->out = false;
- $this->pdf->MultiCell(140, 4, $title, "LTR", "L", 1);
- $y2 = $this->pdf->GetY();
- $h = $y2 - $y;
- $this->pdf->out = true;
- $this->pdf->SetX($lmargin);
- $this->pdf->SetY($y);
- $this->pdf->Cell(0, $h, "", "LTR", 1, "R", 1);
- $this->pdf->SetX($lmargin);
- $this->pdf->SetY($y);
- $this->pdf->Cell(0, 4, $t, "", 1, "R");
- $this->pdf->SetX($lmargin);
- $this->pdf->SetY($y);
- $this->pdf->MultiCell(140, 4, $title, "", "L");
- $this->pdf->SetX($lmargin);
- $this->pdf->SetY($y = $y2);
+ $DiapoW = floor($clientW / $NDiapoW);
+ $DiapoH = floor($clientH / $NDiapoH);
+ $TitleH = 5;
+ $ImgSize = min($DiapoW, ($DiapoH - $TitleH)) - 5;
- $this->pdf->SetLeftMargin($lmargin + 55);
- $this->pdf->SetY($y + 2);
+ $npages = ceil(count($this->records) / ($NDiapoW * $NDiapoH));
- if ($fimg)
- {
- $y = $this->pdf->GetY();
- $this->pdf->Image($fimg, $lmargin, $y, $wimg, $himg);
- $this->pdf->SetY($y);
- }
-
- $nf = 0;
- $this->pdf->SetX($lmargin + 55);
- $p0 = $this->pdf->PageNo();
- $y0 = $this->pdf->GetY();
- foreach ($rec->get_caption()->get_fields() as $field)
- {
- /* @var $field caption_field */
-
- $this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
- $this->pdf->Write(5, $field->get_name() . " : ");
-
- $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
- $this->pdf->Write(5, $field->get_serialized_values());
-
- $this->pdf->Write(6, "\n");
- $nf++;
- }
- if ($this->pdf->PageNo() == $p0 && ($this->pdf->GetY() - $y0) < $himg)
- $this->pdf->SetY($y0 + $himg);
- $ndoc++;
- }
- $this->pdf->SetLeftMargin($lmargin);
- }
-
- protected function print_preview($withtdm)
- {
- $core = \bootstrap::getCore();
- $appbox = \appbox::get_instance($core);
- $registry = \registry::get_instance();
- $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
-
- if ($withtdm === true)
- {
- $this->print_thumbnailGrid($this->pdf, $this->records, true);
- }
-
- foreach ($this->records as $krec => $rec)
- {
- /* @var $rec record_adapter */
-
- $this->pdf->AddPage();
-
- if ($withtdm === "CALCPAGES")
- {
- if ($presentationpage)
- $rec->set_number($this->pdf->PageNo() + 1);
- else
- $rec->set_number($this->pdf->PageNo());
- }
- $lmargin = $this->pdf->GetX();
- $tmargin = $this->pdf->GetY();
- $himg = 0;
- $y = 0;
- $miniConv = NULL;
-
- $LEFT__TEXT = "";
- $LEFT__IMG = NULL;
- $RIGHT_TEXT = "";
- $RIGHT_IMG = NULL;
-
- $LEFT__IMG = $registry->get('GV_RootPath') . "config/minilogos/logopdf_"
- . $rec->get_sbas_id() . ".jpg";
-
- if (!is_file($LEFT__IMG))
- {
- $databox = $rec->get_databox();
- $str = $databox->get_sxml_structure();
- $vn = (string) ($str->pdfPrintLogo);
- if (($vn * 1) == 1)
- {
- $LEFT__TEXT = $databox->get_viewname();
- }
- }
-
- $collection = \collection::get_from_base_id($rec->get_base_id());
-
- $vn = "";
- if ($str = simplexml_load_string($collection->get_prefs()))
- $vn = (string) ($str->pdfPrintappear);
-
- if ($vn == "" || $vn == "1")
- {
- $RIGHT_TEXT = \phrasea::bas_names($rec->get_base_id());
- }
- elseif ($vn == "2")
- {
- $RIGHT_IMG = $registry->get('GV_RootPath') . "config/minilogos/" . $rec->get_base_id();
- }
-
- $xtmp = $this->pdf->GetX();
- $ytmp = $this->pdf->GetY();
-
- $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
- $this->pdf->SetFillColor(220, 220, 220);
- $y = $this->pdf->GetY();
- $this->pdf->MultiCell(95, 7, $LEFT__TEXT, "LTB", "L", 1);
- $y2 = $this->pdf->GetY();
- $h = $y2 - $y;
- $this->pdf->SetY($y);
- $this->pdf->SetX(105);
- $this->pdf->Cell(95, $h, $RIGHT_TEXT, "TBR", 1, "R", 1);
-
- if ($LEFT__TEXT == "" && is_file($LEFT__IMG))
- {
- if ($size = @getimagesize($LEFT__IMG))
- {
- $wmm = (int) $size[0] * 25.4 / 72;
- $hmm = (int) $size[1] * 25.4 / 72;
- if ($hmm > 6)
- {
- $coeff = $hmm / 6;
- $wmm = (int) $wmm / $coeff;
- $hmm = (int) $hmm / $coeff;
- }
- $this->pdf->Image($LEFT__IMG, $xtmp + 0.5, $ytmp + 0.5, $wmm, $hmm);
- }
- }
-
- if ($RIGHT_IMG != NULL && is_file($RIGHT_IMG))
- {
- if ($size = @getimagesize($RIGHT_IMG))
- {
-
- if ($size[2] == '1')
- {
- if (!isset($miniConv[$RIGHT_IMG]))
- {
- $tmp_filename = tempnam('minilogos/', 'gif4fpdf');
- $img = imagecreatefromgif($RIGHT_IMG);
- imageinterlace($img, 0);
- imagepng($img, $tmp_filename);
- rename($tmp_filename, $tmp_filename . '.png');
- $miniConv[$RIGHT_IMG] = $tmp_filename . '.png';
- $RIGHT_IMG = $tmp_filename . '.png';
+ $irow = $ipage = 0;
+ $icol = -1;
+ foreach ($this->records as $rec) {
+ /* @var $rec record_adapter */
+ if ( ++ $icol >= $NDiapoW) {
+ $icol = 0;
+ if ( ++ $irow >= $NDiapoH) {
+ $irow = 0;
+ $ipage ++;
+ $this->pdf->AddPage();
+ }
}
+ $fimg = null;
+ $himg = 0;
+
+ $subdef = $rec->get_subdef('preview');
+
+ $fimg = $subdef->get_pathfile();
+
+ if ( ! $user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
+ && $subdef->get_type() == \media_subdef::TYPE_IMAGE) {
+ $fimg = \recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
+ }
+
+ $wimg = $himg = $ImgSize;
+ if ($subdef->get_height() > 0 && $subdef->get_width() > 0) {
+ if ($subdef->get_width() > $subdef->get_height())
+ $himg = $wimg * $subdef->get_height() / $subdef->get_width();
+ else
+ $wimg = $himg * $subdef->get_width() / $subdef->get_height();
+ }
+
+ if ($fimg) {
+ $x = $lmargin + ($icol * $DiapoW);
+ $y = $tmargin + ($irow * $DiapoH);
+ $this->pdf->SetDrawColor(0);
+ $this->pdf->Rect($x, $y, $DiapoW, $DiapoH, "D");
+
+ $this->pdf->SetXY($x, $y + 1);
+ $this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
+ $t = $irow . '-' . $x;
+ $t = $rec->get_title();
+
+ $this->pdf->MultiCell($DiapoW, $TitleH, $t, '0', 'C', false);
+
+ if ($links) {
+ $lk = $this->pdf->AddLink();
+ $this->pdf->SetLink($lk, 0, $npages + $rec->get_number());
+ $this->pdf->Image(
+ $fimg
+ , $x + (($DiapoW - $wimg) / 2)
+ , $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
+ , $wimg, $himg
+ , null, $lk
+ );
+ } else {
+ $this->pdf->Image($fimg
+ , $x + (($DiapoW - $wimg) / 2)
+ , $TitleH + $y + (($DiapoH - $TitleH - $himg) / 2)
+ , $wimg, $himg
+ );
+ }
+ }
+ }
+ $this->pdf->SetLeftMargin($oldMargins['left']);
+ }
+
+ protected function print_thumbnailList()
+ {
+ $this->pdf->AddPage();
+ $oldMargins = $this->pdf->getMargins();
+
+ $tmargin = $oldMargins['top'];
+ $lmargin = $oldMargins['left'];
+ $bmargin = $oldMargins['bottom'];
+ $rmargin = $oldMargins['right'];
+
+ $this->pdf->SetLeftMargin($lmargin + 55);
+
+ $ndoc = 0;
+ $lastpage = $this->pdf->PageNo();
+ foreach ($this->records as $rec) {
+ /* @var $rec record_adapter */
+ $subdef = $rec->get_subdef('thumbnail');
+
+ $fimg = $subdef->get_pathfile();
+ $wimg = $himg = 50;
+
+ if ($subdef->get_width() > $subdef->get_height())
+ $himg = round($wimg * $subdef->get_height() / $subdef->get_width());
else
- $RIGHT_IMG = $miniConv[$RIGHT_IMG];
+ $wimg = round($himg * $subdef->get_width() / $subdef->get_height());
- $wmm = (int) $size[0] * 25.4 / 72;
- $hmm = (int) $size[1] * 25.4 / 72;
- if ($hmm > 6)
- {
- $coeff = $hmm / 6;
- $wmm = (int) $wmm / $coeff;
- $hmm = (int) $hmm / $coeff;
+ $himg = 0;
+
+ if ($this->pdf->GetY() > $this->pdf->getPageHeight() - (6 + $himg + 20))
+ $this->pdf->AddPage();
+
+ $title = "record : " . $rec->get_title();
+
+ $y = $this->pdf->GetY();
+
+ $t = \phrasea::bas_names($rec->get_base_id());
+ $this->pdf->SetFont(PhraseaPDF::FONT, '', 10);
+ $this->pdf->SetFillColor(220, 220, 220);
+ $this->pdf->SetLeftMargin($lmargin);
+ $this->pdf->SetRightMargin($rmargin);
+ $this->pdf->SetX($lmargin);
+ $this->pdf->SetY($y);
+
+ $this->pdf->out = false;
+ $this->pdf->MultiCell(140, 4, $title, "LTR", "L", 1);
+ $y2 = $this->pdf->GetY();
+ $h = $y2 - $y;
+ $this->pdf->out = true;
+ $this->pdf->SetX($lmargin);
+ $this->pdf->SetY($y);
+ $this->pdf->Cell(0, $h, "", "LTR", 1, "R", 1);
+ $this->pdf->SetX($lmargin);
+ $this->pdf->SetY($y);
+ $this->pdf->Cell(0, 4, $t, "", 1, "R");
+ $this->pdf->SetX($lmargin);
+ $this->pdf->SetY($y);
+ $this->pdf->MultiCell(140, 4, $title, "", "L");
+ $this->pdf->SetX($lmargin);
+ $this->pdf->SetY($y = $y2);
+
+ $this->pdf->SetLeftMargin($lmargin + 55);
+ $this->pdf->SetY($y + 2);
+
+ if ($fimg) {
+ $y = $this->pdf->GetY();
+ $this->pdf->Image($fimg, $lmargin, $y, $wimg, $himg);
+ $this->pdf->SetY($y);
}
- $tt = 0;
- if ($hmm < 6)
- $tt = (6 - $hmm) / 2;
- $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5 + $tt);
- }
- else
- {
- $wmm = (int) $size[0] * 25.4 / 72;
- $hmm = (int) $size[1] * 25.4 / 72;
- if ($hmm > 6)
- {
- $coeff = $hmm / 6;
- $wmm = (int) $wmm / $coeff;
- $hmm = (int) $hmm / $coeff;
+
+ $nf = 0;
+ $this->pdf->SetX($lmargin + 55);
+ $p0 = $this->pdf->PageNo();
+ $y0 = $this->pdf->GetY();
+ foreach ($rec->get_caption()->get_fields() as $field) {
+ /* @var $field caption_field */
+
+ $this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
+ $this->pdf->Write(5, $field->get_name() . " : ");
+
+ $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
+ $this->pdf->Write(5, $field->get_serialized_values());
+
+ $this->pdf->Write(6, "\n");
+ $nf ++;
}
- $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5);
- }
+ if ($this->pdf->PageNo() == $p0 && ($this->pdf->GetY() - $y0) < $himg)
+ $this->pdf->SetY($y0 + $himg);
+ $ndoc ++;
}
- }
-
- $y = $this->pdf->GetY() + 3;
-
- $subdef = $rec->get_subdef('preview');
-
- $f = $subdef->get_pathfile();
-
- if (!$user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
- && $subdef->get_type() == \media_subdef::TYPE_IMAGE)
- $f = \recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
-
- $wimg = $himg = 150; // preview dans un carre de 150 mm
- if ($subdef->get_width() > 0 && $subdef->get_height() > 0)
- {
- if ($subdef->get_width() > $subdef->get_height())
- $himg = $wimg * $subdef->get_height() / $subdef->get_width();
- else
- $wimg = $himg * $subdef->get_width() / $subdef->get_height();
- }
- $this->pdf->Image($f, $lmargin, $y, $wimg, $himg);
-
- if ($miniConv != NULL)
- {
- foreach ($miniConv as $oneF)
- unlink($oneF);
- }
- $this->pdf->SetXY($lmargin, $y += ( $himg + 5));
-
- $nf = 0;
- foreach ($rec->get_caption()->get_fields() as $field)
- {
- /* @var $field caption_field */
- if ($nf > 0)
- $this->pdf->Write(6, "\n");
-
- $this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
- $this->pdf->Write(5, $field->get_name() . " : ");
-
- $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
-
- $t = str_replace(
- array("<", ">", "&")
- , array("<", ">", "&")
- , $field->get_serialized_values()
- );
-
- $this->pdf->Write(5, $t);
-
- $nf++;
- }
+ $this->pdf->SetLeftMargin($lmargin);
}
- return;
- }
+ protected function print_preview($withtdm)
+ {
+ $core = \bootstrap::getCore();
+ $appbox = \appbox::get_instance($core);
+ $registry = \registry::get_instance();
+ $user = \User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox);
+ if ($withtdm === true) {
+ $this->print_thumbnailGrid($this->pdf, $this->records, true);
+ }
+
+ foreach ($this->records as $krec => $rec) {
+ /* @var $rec record_adapter */
+
+ $this->pdf->AddPage();
+
+ if ($withtdm === "CALCPAGES") {
+ if ($presentationpage)
+ $rec->set_number($this->pdf->PageNo() + 1);
+ else
+ $rec->set_number($this->pdf->PageNo());
+ }
+ $lmargin = $this->pdf->GetX();
+ $tmargin = $this->pdf->GetY();
+ $himg = 0;
+ $y = 0;
+ $miniConv = NULL;
+
+ $LEFT__TEXT = "";
+ $LEFT__IMG = NULL;
+ $RIGHT_TEXT = "";
+ $RIGHT_IMG = NULL;
+
+ $LEFT__IMG = $registry->get('GV_RootPath') . "config/minilogos/logopdf_"
+ . $rec->get_sbas_id() . ".jpg";
+
+ if ( ! is_file($LEFT__IMG)) {
+ $databox = $rec->get_databox();
+ $str = $databox->get_sxml_structure();
+ $vn = (string) ($str->pdfPrintLogo);
+ if (($vn * 1) == 1) {
+ $LEFT__TEXT = $databox->get_viewname();
+ }
+ }
+
+ $collection = \collection::get_from_base_id($rec->get_base_id());
+
+ $vn = "";
+ if ($str = simplexml_load_string($collection->get_prefs()))
+ $vn = (string) ($str->pdfPrintappear);
+
+ if ($vn == "" || $vn == "1") {
+ $RIGHT_TEXT = \phrasea::bas_names($rec->get_base_id());
+ } elseif ($vn == "2") {
+ $RIGHT_IMG = $registry->get('GV_RootPath') . "config/minilogos/" . $rec->get_base_id();
+ }
+
+ $xtmp = $this->pdf->GetX();
+ $ytmp = $this->pdf->GetY();
+
+ $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
+ $this->pdf->SetFillColor(220, 220, 220);
+ $y = $this->pdf->GetY();
+ $this->pdf->MultiCell(95, 7, $LEFT__TEXT, "LTB", "L", 1);
+ $y2 = $this->pdf->GetY();
+ $h = $y2 - $y;
+ $this->pdf->SetY($y);
+ $this->pdf->SetX(105);
+ $this->pdf->Cell(95, $h, $RIGHT_TEXT, "TBR", 1, "R", 1);
+
+ if ($LEFT__TEXT == "" && is_file($LEFT__IMG)) {
+ if ($size = @getimagesize($LEFT__IMG)) {
+ $wmm = (int) $size[0] * 25.4 / 72;
+ $hmm = (int) $size[1] * 25.4 / 72;
+ if ($hmm > 6) {
+ $coeff = $hmm / 6;
+ $wmm = (int) $wmm / $coeff;
+ $hmm = (int) $hmm / $coeff;
+ }
+ $this->pdf->Image($LEFT__IMG, $xtmp + 0.5, $ytmp + 0.5, $wmm, $hmm);
+ }
+ }
+
+ if ($RIGHT_IMG != NULL && is_file($RIGHT_IMG)) {
+ if ($size = @getimagesize($RIGHT_IMG)) {
+
+ if ($size[2] == '1') {
+ if ( ! isset($miniConv[$RIGHT_IMG])) {
+ $tmp_filename = tempnam('minilogos/', 'gif4fpdf');
+ $img = imagecreatefromgif($RIGHT_IMG);
+ imageinterlace($img, 0);
+ imagepng($img, $tmp_filename);
+ rename($tmp_filename, $tmp_filename . '.png');
+ $miniConv[$RIGHT_IMG] = $tmp_filename . '.png';
+ $RIGHT_IMG = $tmp_filename . '.png';
+ }
+ else
+ $RIGHT_IMG = $miniConv[$RIGHT_IMG];
+
+ $wmm = (int) $size[0] * 25.4 / 72;
+ $hmm = (int) $size[1] * 25.4 / 72;
+ if ($hmm > 6) {
+ $coeff = $hmm / 6;
+ $wmm = (int) $wmm / $coeff;
+ $hmm = (int) $hmm / $coeff;
+ }
+ $tt = 0;
+ if ($hmm < 6)
+ $tt = (6 - $hmm) / 2;
+ $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5 + $tt);
+ }
+ else {
+ $wmm = (int) $size[0] * 25.4 / 72;
+ $hmm = (int) $size[1] * 25.4 / 72;
+ if ($hmm > 6) {
+ $coeff = $hmm / 6;
+ $wmm = (int) $wmm / $coeff;
+ $hmm = (int) $hmm / $coeff;
+ }
+ $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5);
+ }
+ }
+ }
+
+ $y = $this->pdf->GetY() + 3;
+
+ $subdef = $rec->get_subdef('preview');
+
+ $f = $subdef->get_pathfile();
+
+ if ( ! $user->ACL()->has_right_on_base($rec->get_base_id(), "nowatermark")
+ && $subdef->get_type() == \media_subdef::TYPE_IMAGE)
+ $f = \recordutils_image::watermark($rec->get_base_id(), $rec->get_record_id());
+
+ $wimg = $himg = 150; // preview dans un carre de 150 mm
+ if ($subdef->get_width() > 0 && $subdef->get_height() > 0) {
+ if ($subdef->get_width() > $subdef->get_height())
+ $himg = $wimg * $subdef->get_height() / $subdef->get_width();
+ else
+ $wimg = $himg * $subdef->get_width() / $subdef->get_height();
+ }
+ $this->pdf->Image($f, $lmargin, $y, $wimg, $himg);
+
+ if ($miniConv != NULL) {
+ foreach ($miniConv as $oneF)
+ unlink($oneF);
+ }
+ $this->pdf->SetXY($lmargin, $y += ( $himg + 5));
+
+ $nf = 0;
+ foreach ($rec->get_caption()->get_fields() as $field) {
+ /* @var $field caption_field */
+ if ($nf > 0)
+ $this->pdf->Write(6, "\n");
+
+ $this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12);
+ $this->pdf->Write(5, $field->get_name() . " : ");
+
+ $this->pdf->SetFont(PhraseaPDF::FONT, '', 12);
+
+ $t = str_replace(
+ array("<", ">", "&")
+ , array("<", ">", "&")
+ , $field->get_serialized_values()
+ );
+
+ $this->pdf->Write(5, $t);
+
+ $nf ++;
+ }
+ }
+
+ return;
+ }
}
diff --git a/lib/Alchemy/Phrasea/Out/Tool/PhraseaPDF.php b/lib/Alchemy/Phrasea/Out/Tool/PhraseaPDF.php
index d681d42450..3c1e97b450 100644
--- a/lib/Alchemy/Phrasea/Out/Tool/PhraseaPDF.php
+++ b/lib/Alchemy/Phrasea/Out/Tool/PhraseaPDF.php
@@ -19,36 +19,35 @@ namespace Alchemy\Phrasea\Out\Tool;
*/
class PhraseaPDF extends \TCPDF
{
- const FONT = 'freesans';
+ const FONT = 'freesans';
- function Header()
- {
+ function Header()
+ {
- }
+ }
- function Footer()
- {
- $ml = $this->SetLeftMargin(0);
- $mr = $this->SetRightMargin(0);
+ function Footer()
+ {
+ $ml = $this->SetLeftMargin(0);
+ $mr = $this->SetRightMargin(0);
- $this->SetY(-15);
+ $this->SetY(-15);
- $this->SetFont(self::FONT, 'I', 8);
- $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
+ $this->SetFont(self::FONT, 'I', 8);
+ $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
- $this->SetFont(self::FONT, '', 8);
- $w = $this->GetStringWidth('Printed by');
+ $this->SetFont(self::FONT, '', 8);
+ $w = $this->GetStringWidth('Printed by');
- $this->SetFont(self::FONT, 'B', 8);
- $w += $this->GetStringWidth(' Phraseanet');
+ $this->SetFont(self::FONT, 'B', 8);
+ $w += $this->GetStringWidth(' Phraseanet');
- $this->SetXY(-$w - $mr - 5, -15);
+ $this->SetXY(-$w - $mr - 5, -15);
- $this->SetFont(self::FONT, '', 8);
- $this->Write(8, 'Printed by');
-
- $this->SetFont(self::FONT, 'B', 8);
- $this->Write(8, ' Phraseanet');
- }
+ $this->SetFont(self::FONT, '', 8);
+ $this->Write(8, 'Printed by');
+ $this->SetFont(self::FONT, 'B', 8);
+ $this->Write(8, ' Phraseanet');
+ }
}
diff --git a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php
index 4afd32cf25..1d687ee58d 100644
--- a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php
+++ b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php
@@ -22,45 +22,44 @@ namespace Alchemy\Phrasea\Vocabulary\ControlProvider;
interface ControlProviderInterface
{
- /**
- * @return the type of the ControlProvider
- *
- * ControlProvider class should be named like {type}Provider
- * in the ControlProvider namespace
- */
- public static function getType();
+ /**
+ * @return the type of the ControlProvider
+ *
+ * ControlProvider class should be named like {type}Provider
+ * in the ControlProvider namespace
+ */
+ public static function getType();
- /**
- * @return stringa simple i18n word to reprsent this vocabullary
- */
- public static function getName();
+ /**
+ * @return stringa simple i18n word to reprsent this vocabullary
+ */
+ public static function getName();
- /**
- * @return boolean validate an $id in the vocabulary
- */
- public function validate($id);
+ /**
+ * @return boolean validate an $id in the vocabulary
+ */
+ public function validate($id);
- /**
- * @return string returns the value corresponding to an id
- * @throws \Exception if the $id is invalid
- */
- public function getValue($id);
+ /**
+ * @return string returns the value corresponding to an id
+ * @throws \Exception if the $id is invalid
+ */
+ public function getValue($id);
- /**
- * @return mixed returns the actual ressource corresponding to an id
- * @throws \Exception if the $id is invalid
- */
- public function getRessource($id);
-
- /**
- * Find matching Term in the vocabulary repository
- *
- * @param string $query A scalar quaery
- * @param \User_Adapter $for_user The user doing the query
- * @param \databox $on_databox The databox where vocabulary should be requested
- *
- * @return Doctrine\Common\Collections\ArrayCollection
- */
- public function find($query, \User_Adapter $for_user, \databox $on_databox);
+ /**
+ * @return mixed returns the actual ressource corresponding to an id
+ * @throws \Exception if the $id is invalid
+ */
+ public function getRessource($id);
+ /**
+ * Find matching Term in the vocabulary repository
+ *
+ * @param string $query A scalar quaery
+ * @param \User_Adapter $for_user The user doing the query
+ * @param \databox $on_databox The databox where vocabulary should be requested
+ *
+ * @return Doctrine\Common\Collections\ArrayCollection
+ */
+ public function find($query, \User_Adapter $for_user, \databox $on_databox);
}
diff --git a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php
index 8ec4087d9d..791384f7e6 100644
--- a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php
+++ b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php
@@ -23,105 +23,100 @@ use Alchemy\Phrasea\Vocabulary\Term;
class UserProvider implements ControlProviderInterface
{
- /**
- * @return string
- */
- public static function getType()
- {
- return 'User';
- }
-
- /**
- *
- * @return type
- */
- public static function getName()
- {
- return _('Users');
- }
-
- /**
- *
- * @param string $query
- * @param \User_Adapter $for_user
- * @param \databox $on_databox
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function find($query, \User_Adapter $for_user, \databox $on_databox = null)
- {
- $Core = \bootstrap::getCore();
-
- $user_query = new \User_Query(\appbox::get_instance($Core));
-
- $users = $user_query
- ->like(\User_Query::LIKE_EMAIL, $query)
- ->like(\User_Query::LIKE_NAME, $query)
- ->like(\User_Query::LIKE_LOGIN, $query)
- ->like_match(\User_Query::LIKE_MATCH_OR)
- ->include_phantoms(true)
- ->on_bases_where_i_am($for_user->ACL(), array('canadmin'))
- ->limit(0, 50)
- ->execute()->get_results();
-
- $results = new ArrayCollection();
-
- foreach ($users as $user)
+ /**
+ * @return string
+ */
+ public static function getType()
{
- $results->add(
- new Term($user->get_display_name(), '', $this, $user->get_id())
- );
+ return 'User';
}
- return $results;
- }
-
- /**
- *
- * @param mixed $id
- * @return boolean
- */
- public function validate($id)
- {
- $Core = \bootstrap::getCore();
-
- try
+ /**
+ *
+ * @return type
+ */
+ public static function getName()
{
- \User_Adapter::getInstance($id, \appbox::get_instance($Core));
-
- return true;
- }
- catch (\Exception $e)
- {
-
+ return _('Users');
}
- return false;
- }
+ /**
+ *
+ * @param string $query
+ * @param \User_Adapter $for_user
+ * @param \databox $on_databox
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function find($query, \User_Adapter $for_user, \databox $on_databox = null)
+ {
+ $Core = \bootstrap::getCore();
- /**
- *
- * @param mixed $id
- * @return string
- */
- public function getValue($id)
- {
- $Core = \bootstrap::getCore();
+ $user_query = new \User_Query(\appbox::get_instance($Core));
- $user = \User_Adapter::getInstance($id, \appbox::get_instance($Core));
+ $users = $user_query
+ ->like(\User_Query::LIKE_EMAIL, $query)
+ ->like(\User_Query::LIKE_NAME, $query)
+ ->like(\User_Query::LIKE_LOGIN, $query)
+ ->like_match(\User_Query::LIKE_MATCH_OR)
+ ->include_phantoms(true)
+ ->on_bases_where_i_am($for_user->ACL(), array('canadmin'))
+ ->limit(0, 50)
+ ->execute()->get_results();
- return $user->get_display_name();
- }
+ $results = new ArrayCollection();
- /**
- *
- * @param mixed $id
- * @return string
- */
- public function getRessource($id)
- {
- $Core = \bootstrap::getCore();
+ foreach ($users as $user) {
+ $results->add(
+ new Term($user->get_display_name(), '', $this, $user->get_id())
+ );
+ }
- return \User_Adapter::getInstance($id, \appbox::get_instance($Core));
- }
+ return $results;
+ }
+ /**
+ *
+ * @param mixed $id
+ * @return boolean
+ */
+ public function validate($id)
+ {
+ $Core = \bootstrap::getCore();
+
+ try {
+ \User_Adapter::getInstance($id, \appbox::get_instance($Core));
+
+ return true;
+ } catch (\Exception $e) {
+
+ }
+
+ return false;
+ }
+
+ /**
+ *
+ * @param mixed $id
+ * @return string
+ */
+ public function getValue($id)
+ {
+ $Core = \bootstrap::getCore();
+
+ $user = \User_Adapter::getInstance($id, \appbox::get_instance($Core));
+
+ return $user->get_display_name();
+ }
+
+ /**
+ *
+ * @param mixed $id
+ * @return string
+ */
+ public function getRessource($id)
+ {
+ $Core = \bootstrap::getCore();
+
+ return \User_Adapter::getInstance($id, \appbox::get_instance($Core));
+ }
}
diff --git a/lib/Alchemy/Phrasea/Vocabulary/Term.php b/lib/Alchemy/Phrasea/Vocabulary/Term.php
index 6c4b6e65ee..db90c53ac2 100644
--- a/lib/Alchemy/Phrasea/Vocabulary/Term.php
+++ b/lib/Alchemy/Phrasea/Vocabulary/Term.php
@@ -22,94 +22,91 @@ namespace Alchemy\Phrasea\Vocabulary;
*/
class Term
{
+ /**
+ *
+ * @var string
+ */
+ protected $value;
- /**
- *
- * @var string
- */
- protected $value;
+ /**
+ *
+ * @var string
+ */
+ protected $context;
- /**
- *
- * @var string
- */
- protected $context;
+ /**
+ *
+ * @var ControlProviderInterface
+ */
+ protected $type;
- /**
- *
- * @var ControlProviderInterface
- */
- protected $type;
+ /**
+ *
+ * @var mixed
+ */
+ protected $id;
- /**
- *
- * @var mixed
- */
- protected $id;
-
- /**
- * Construct a Term
- *
- * @param string $value the scalar value of the Term
- * @param string $context A string defining the context of the Term
- * @param ControlProviderInterface $type A Vocabulary Controller
- * @param mixed $id The id of the term in the Vocabulary Controller
- *
- * @return \Alchemy\Phrasea\Vocabulary\ControlProvider\Term
- * @throws Exception
- */
- public function __construct($value, $context = null, ControlProvider\ControlProviderInterface $type = null, $id = null)
- {
-
- if (!assert(is_scalar($value)))
+ /**
+ * Construct a Term
+ *
+ * @param string $value the scalar value of the Term
+ * @param string $context A string defining the context of the Term
+ * @param ControlProviderInterface $type A Vocabulary Controller
+ * @param mixed $id The id of the term in the Vocabulary Controller
+ *
+ * @return \Alchemy\Phrasea\Vocabulary\ControlProvider\Term
+ * @throws Exception
+ */
+ public function __construct($value, $context = null, ControlProvider\ControlProviderInterface $type = null, $id = null)
{
- throw new Exception('A Term value should be scalar');
+
+ if ( ! assert(is_scalar($value))) {
+ throw new Exception('A Term value should be scalar');
+ }
+
+ $this->value = $value;
+ $this->context = $context;
+ $this->type = $type;
+ $this->id = $id;
+
+ return $this;
}
- $this->value = $value;
- $this->context = $context;
- $this->type = $type;
- $this->id = $id;
+ /**
+ * Get the scalar value of a term
+ *
+ * @return string
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
- return $this;
- }
+ /**
+ * Get the content of a term
+ *
+ * @return string
+ */
+ public function getContext()
+ {
+ return $this->context;
+ }
- /**
- * Get the scalar value of a term
- *
- * @return string
- */
- public function getValue()
- {
- return $this->value;
- }
-
- /**
- * Get the content of a term
- *
- * @return string
- */
- public function getContext()
- {
- return $this->context;
- }
-
- /**
- *
- * @return ControlProviderInterface
- */
- public function getType()
- {
- return $this->type;
- }
-
- /**
- *
- * @return mixed
- */
- public function getId()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return ControlProviderInterface
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+ /**
+ *
+ * @return mixed
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
}
diff --git a/lib/Doctrine/Entities/Basket.php b/lib/Doctrine/Entities/Basket.php
index 2b4d5a033b..879a5cb77d 100644
--- a/lib/Doctrine/Entities/Basket.php
+++ b/lib/Doctrine/Entities/Basket.php
@@ -22,432 +22,405 @@ require_once __DIR__ . '/../../classes/User/Adapter.class.php';
*/
class Basket
{
+ const ELEMENTSORDER_NAT = 'nat';
+ const ELEMENTSORDER_DESC = 'desc';
+ const ELEMENTSORDER_ASC = 'asc';
- const ELEMENTSORDER_NAT = 'nat';
- const ELEMENTSORDER_DESC = 'desc';
- const ELEMENTSORDER_ASC = 'asc';
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var string $name
+ */
+ protected $name;
- /**
- * @var string $name
- */
- protected $name;
+ /**
+ * @var text $description
+ */
+ protected $description;
- /**
- * @var text $description
- */
- protected $description;
+ /**
+ * @var integer $usr_id
+ */
+ protected $usr_id;
- /**
- * @var integer $usr_id
- */
- protected $usr_id;
+ /**
+ * @var integer $pusher_id
+ */
+ protected $pusher_id;
- /**
- * @var integer $pusher_id
- */
- protected $pusher_id;
+ /**
+ * @var boolean $archived
+ */
+ protected $archived = false;
- /**
- * @var boolean $archived
- */
- protected $archived = false;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var Entities\BasketElement
+ */
+ protected $elements;
- /**
- * @var Entities\BasketElement
- */
- protected $elements;
-
- public function __construct()
- {
- $this->elements = new \Doctrine\Common\Collections\ArrayCollection();
- }
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set name
- *
- * @param string $name
- */
- public function setName($name)
- {
- $this->name = $name;
- }
-
- /**
- * Get name
- *
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Set description
- *
- * @param text $description
- */
- public function setDescription($description)
- {
- $this->description = $description;
- }
-
- /**
- * Get description
- *
- * @return text
- */
- public function getDescription()
- {
- return $this->description;
- }
-
- /**
- * Set usr_id
- *
- * @param integer $usrId
- */
- public function setUsrId($usrId)
- {
- $this->usr_id = $usrId;
- }
-
- /**
- * Get usr_id
- *
- * @return integer
- */
- public function getUsrId()
- {
- return $this->usr_id;
- }
-
- /**
- * Set pusher_id
- *
- * @param integer $pusherId
- */
- public function setPusherId($pusherId)
- {
- $this->pusher_id = $pusherId;
- }
-
- /**
- * Get pusher_id
- *
- * @return integer
- */
- public function getPusherId()
- {
- return $this->pusher_id;
- }
-
- /**
- * Set archived
- *
- * @param boolean $archived
- */
- public function setArchived($archived)
- {
- $this->archived = $archived;
- }
-
- /**
- * Get archived
- *
- * @return boolean
- */
- public function getArchived()
- {
- return $this->archived;
- }
-
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
-
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
-
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
-
- /**
- * Add elements
- *
- * @param Entities\BasketElement $elements
- */
- public function addBasketElement(\Entities\BasketElement $elements)
- {
- $this->elements[] = $elements;
- }
-
- /**
- * Get elements
- *
- * @return Doctrine\Common\Collections\Collection
- */
- public function getElements()
- {
- return $this->elements;
- }
-
- public function getElementsByOrder($ordre)
- {
- if($ordre === self::ELEMENTSORDER_DESC)
+ public function __construct()
{
- $ret = new \Doctrine\Common\Collections\ArrayCollection();
- $elements = $this->elements->toArray();
-
- uasort($elements, 'self::setBEOrderDESC');
-
- foreach($elements as $elem)
- {
- $ret->add($elem);
- }
-
- return $ret;
- }
- elseif($ordre === self::ELEMENTSORDER_ASC)
- {
- $ret = new \Doctrine\Common\Collections\ArrayCollection();
- $elements = $this->elements->toArray();
-
- uasort($elements, 'self::setBEOrderASC');
-
- foreach($elements as $elem)
- {
- $ret->add($elem);
- }
-
- return $ret;
+ $this->elements = new \Doctrine\Common\Collections\ArrayCollection();
}
- return $this->elements;
- }
-
- private static function setBEOrderDESC($element1, $element2)
- {
- $total_el1 = 0;
- $total_el2 = 0;
-
- foreach($element1->getValidationDatas() as $datas)
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- if($datas->getAgreement() !== null)
- {
- $total_el1 += $datas->getAgreement() ? 1 : 0;
- }
- }
- foreach($element2->getValidationDatas() as $datas)
- {
- if($datas->getAgreement() !== null)
- {
- $total_el2 += $datas->getAgreement() ? 1 : 0;
- }
+ return $this->id;
}
- if($total_el1 === $total_el2)
-
- return 0;
-
- return $total_el1 < $total_el2 ? 1 : -1;
- }
-
- private static function setBEOrderASC($element1, $element2)
- {
- $total_el1 = 0;
- $total_el2 = 0;
-
- foreach($element1->getValidationDatas() as $datas)
+ /**
+ * Set name
+ *
+ * @param string $name
+ */
+ public function setName($name)
{
- if($datas->getAgreement() !== null)
- {
- $total_el1 += $datas->getAgreement() ? 0 : 1;
- }
- }
- foreach($element2->getValidationDatas() as $datas)
- {
- if($datas->getAgreement() !== null)
- {
- $total_el2 += $datas->getAgreement() ? 0 : 1;
- }
+ $this->name = $name;
}
- if($total_el1 === $total_el2)
-
- return 0;
-
- return $total_el1 < $total_el2 ? 1 : -1;
- }
-
- public function setPusher(\User_Adapter $user)
- {
- $this->setPusherId($user->get_id());
- }
-
- public function getPusher()
- {
- if ($this->getPusherId())
+ /**
+ * Get name
+ *
+ * @return string
+ */
+ public function getName()
{
- return new \User_Adapter($this->getPusherId(), \appbox::get_instance(\bootstrap::getCore()));
- }
- }
-
- public function setOwner(\User_Adapter $user)
- {
- $this->setUsrId($user->get_id());
- }
-
- public function getOwner()
- {
- if ($this->getUsrId())
- {
- return new \User_Adapter($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
- }
- }
-
- /**
- * @var Entities\ValidationSession
- */
- protected $validation;
-
- /**
- * Set validation
- *
- * @param Entities\ValidationSession $validation
- */
- public function setValidation(\Entities\ValidationSession $validation)
- {
- $this->validation = $validation;
- }
-
- /**
- * Get validation
- *
- * @return Entities\ValidationSession
- */
- public function getValidation()
- {
- return $this->validation;
- }
-
- /**
- * @var boolean $is_read
- */
- protected $is_read = true;
-
- /**
- * Set is_read
- *
- * @param boolean $isRead
- */
- public function setIsRead($isRead)
- {
- $this->is_read = $isRead;
- }
-
- /**
- * Get is_read
- *
- * @return boolean
- */
- public function getIsRead()
- {
- return $this->is_read;
- }
-
- public function hasRecord(\record_adapter $record)
- {
- foreach ($this->getElements() as $basket_element)
- {
- $bask_record = $basket_element->getRecord();
-
- if ($bask_record->get_record_id() == $record->get_record_id()
- && $bask_record->get_sbas_id() == $record->get_sbas_id())
- {
- return true;
- }
+ return $this->name;
}
- return false;
- }
-
- public function getSize()
- {
- $totSize = 0;
-
- foreach ($this->getElements() as $basket_element)
+ /**
+ * Set description
+ *
+ * @param text $description
+ */
+ public function setDescription($description)
{
- try
- {
- $totSize += $basket_element->getRecord()
- ->get_subdef('document')
- ->get_size();
- }
- catch (Exception $e)
- {
-
- }
+ $this->description = $description;
}
- $totSize = round($totSize / (1024 * 1024), 2);
+ /**
+ * Get description
+ *
+ * @return text
+ */
+ public function getDescription()
+ {
+ return $this->description;
+ }
- return $totSize;
- }
+ /**
+ * Set usr_id
+ *
+ * @param integer $usrId
+ */
+ public function setUsrId($usrId)
+ {
+ $this->usr_id = $usrId;
+ }
+ /**
+ * Get usr_id
+ *
+ * @return integer
+ */
+ public function getUsrId()
+ {
+ return $this->usr_id;
+ }
+
+ /**
+ * Set pusher_id
+ *
+ * @param integer $pusherId
+ */
+ public function setPusherId($pusherId)
+ {
+ $this->pusher_id = $pusherId;
+ }
+
+ /**
+ * Get pusher_id
+ *
+ * @return integer
+ */
+ public function getPusherId()
+ {
+ return $this->pusher_id;
+ }
+
+ /**
+ * Set archived
+ *
+ * @param boolean $archived
+ */
+ public function setArchived($archived)
+ {
+ $this->archived = $archived;
+ }
+
+ /**
+ * Get archived
+ *
+ * @return boolean
+ */
+ public function getArchived()
+ {
+ return $this->archived;
+ }
+
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
+
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
+
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
+
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
+
+ /**
+ * Add elements
+ *
+ * @param Entities\BasketElement $elements
+ */
+ public function addBasketElement(\Entities\BasketElement $elements)
+ {
+ $this->elements[] = $elements;
+ }
+
+ /**
+ * Get elements
+ *
+ * @return Doctrine\Common\Collections\Collection
+ */
+ public function getElements()
+ {
+ return $this->elements;
+ }
+
+ public function getElementsByOrder($ordre)
+ {
+ if ($ordre === self::ELEMENTSORDER_DESC) {
+ $ret = new \Doctrine\Common\Collections\ArrayCollection();
+ $elements = $this->elements->toArray();
+
+ uasort($elements, 'self::setBEOrderDESC');
+
+ foreach ($elements as $elem) {
+ $ret->add($elem);
+ }
+
+ return $ret;
+ } elseif ($ordre === self::ELEMENTSORDER_ASC) {
+ $ret = new \Doctrine\Common\Collections\ArrayCollection();
+ $elements = $this->elements->toArray();
+
+ uasort($elements, 'self::setBEOrderASC');
+
+ foreach ($elements as $elem) {
+ $ret->add($elem);
+ }
+
+ return $ret;
+ }
+
+ return $this->elements;
+ }
+
+ private static function setBEOrderDESC($element1, $element2)
+ {
+ $total_el1 = 0;
+ $total_el2 = 0;
+
+ foreach ($element1->getValidationDatas() as $datas) {
+ if ($datas->getAgreement() !== null) {
+ $total_el1 += $datas->getAgreement() ? 1 : 0;
+ }
+ }
+ foreach ($element2->getValidationDatas() as $datas) {
+ if ($datas->getAgreement() !== null) {
+ $total_el2 += $datas->getAgreement() ? 1 : 0;
+ }
+ }
+
+ if ($total_el1 === $total_el2)
+ return 0;
+
+ return $total_el1 < $total_el2 ? 1 : -1;
+ }
+
+ private static function setBEOrderASC($element1, $element2)
+ {
+ $total_el1 = 0;
+ $total_el2 = 0;
+
+ foreach ($element1->getValidationDatas() as $datas) {
+ if ($datas->getAgreement() !== null) {
+ $total_el1 += $datas->getAgreement() ? 0 : 1;
+ }
+ }
+ foreach ($element2->getValidationDatas() as $datas) {
+ if ($datas->getAgreement() !== null) {
+ $total_el2 += $datas->getAgreement() ? 0 : 1;
+ }
+ }
+
+ if ($total_el1 === $total_el2)
+ return 0;
+
+ return $total_el1 < $total_el2 ? 1 : -1;
+ }
+
+ public function setPusher(\User_Adapter $user)
+ {
+ $this->setPusherId($user->get_id());
+ }
+
+ public function getPusher()
+ {
+ if ($this->getPusherId()) {
+ return new \User_Adapter($this->getPusherId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
+ }
+
+ public function setOwner(\User_Adapter $user)
+ {
+ $this->setUsrId($user->get_id());
+ }
+
+ public function getOwner()
+ {
+ if ($this->getUsrId()) {
+ return new \User_Adapter($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
+ }
+ /**
+ * @var Entities\ValidationSession
+ */
+ protected $validation;
+
+ /**
+ * Set validation
+ *
+ * @param Entities\ValidationSession $validation
+ */
+ public function setValidation(\Entities\ValidationSession $validation)
+ {
+ $this->validation = $validation;
+ }
+
+ /**
+ * Get validation
+ *
+ * @return Entities\ValidationSession
+ */
+ public function getValidation()
+ {
+ return $this->validation;
+ }
+ /**
+ * @var boolean $is_read
+ */
+ protected $is_read = true;
+
+ /**
+ * Set is_read
+ *
+ * @param boolean $isRead
+ */
+ public function setIsRead($isRead)
+ {
+ $this->is_read = $isRead;
+ }
+
+ /**
+ * Get is_read
+ *
+ * @return boolean
+ */
+ public function getIsRead()
+ {
+ return $this->is_read;
+ }
+
+ public function hasRecord(\record_adapter $record)
+ {
+ foreach ($this->getElements() as $basket_element) {
+ $bask_record = $basket_element->getRecord();
+
+ if ($bask_record->get_record_id() == $record->get_record_id()
+ && $bask_record->get_sbas_id() == $record->get_sbas_id()) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public function getSize()
+ {
+ $totSize = 0;
+
+ foreach ($this->getElements() as $basket_element) {
+ try {
+ $totSize += $basket_element->getRecord()
+ ->get_subdef('document')
+ ->get_size();
+ } catch (Exception $e) {
+
+ }
+ }
+
+ $totSize = round($totSize / (1024 * 1024), 2);
+
+ return $totSize;
+ }
}
diff --git a/lib/Doctrine/Entities/BasketElement.php b/lib/Doctrine/Entities/BasketElement.php
index 4700d3b837..a7256f8169 100644
--- a/lib/Doctrine/Entities/BasketElement.php
+++ b/lib/Doctrine/Entities/BasketElement.php
@@ -22,234 +22,229 @@ require_once __DIR__ . '/../../classes/record/adapter.class.php';
*/
class BasketElement
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var integer $record_id
+ */
+ protected $record_id;
- /**
- * @var integer $record_id
- */
- protected $record_id;
+ /**
+ * @var integer $sbas_id
+ */
+ protected $sbas_id;
- /**
- * @var integer $sbas_id
- */
- protected $sbas_id;
+ /**
+ * @var integer $ord
+ */
+ protected $ord;
- /**
- * @var integer $ord
- */
- protected $ord;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var Entities\Basket
+ */
+ protected $basket;
- /**
- * @var Entities\Basket
- */
- protected $basket;
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set record_id
- *
- * @param integer $recordId
- */
- public function setRecordId($recordId)
- {
- $this->record_id = $recordId;
- }
-
- /**
- * Get record_id
- *
- * @return integer
- */
- public function getRecordId()
- {
- return $this->record_id;
- }
-
- /**
- * Set sbas_id
- *
- * @param integer $sbasId
- */
- public function setSbasId($sbasId)
- {
- $this->sbas_id = $sbasId;
- }
-
- /**
- * Get sbas_id
- *
- * @return integer
- */
- public function getSbasId()
- {
- return $this->sbas_id;
- }
-
- /**
- * Set ord
- *
- * @param integer $ord
- */
- public function setOrd($ord)
- {
- $this->ord = $ord;
- }
-
- /**
- * Get ord
- *
- * @return integer
- */
- public function getOrd()
- {
- return $this->ord;
- }
-
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
-
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
-
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
-
- /**
- * Set basket
- *
- * @param Entities\Basket $basket
- */
- public function setBasket(\Entities\Basket $basket)
- {
- $this->basket = $basket;
- }
-
- /**
- * Get basket
- *
- * @return Entities\Basket
- */
- public function getBasket()
- {
- return $this->basket;
- }
-
- public function getRecord()
- {
- return new \record_adapter($this->getSbasId(), $this->getRecordId(), $this->getOrd());
- }
-
- public function setRecord(\record_adapter $record)
- {
- $this->setRecordId($record->get_record_id());
- $this->setSbasId($record->get_sbas_id());
- }
-
- public function setLastInBasket()
- {
- $this->setOrd($this->getBasket()->getElements()->count() + 1);
- }
-
- /**
- * @var Entities\ValidationData
- */
- protected $validation_datas;
-
- public function __construct()
- {
- $this->validation_datas = new \Doctrine\Common\Collections\ArrayCollection();
- }
-
- /**
- * Add validation_datas
- *
- * @param Entities\ValidationData $validationDatas
- */
- public function addValidationData(\Entities\ValidationData $validationDatas)
- {
- $this->validation_datas[] = $validationDatas;
- }
-
- /**
- * Get validation_datas
- *
- * @return Doctrine\Common\Collections\Collection
- */
- public function getValidationDatas()
- {
- return $this->validation_datas;
- }
-
- /**
- *
- * @param \User_Adapter $user
- * @return \Entities\ValidationData
- */
- public function getUserValidationDatas(\User_Adapter $user)
- {
- foreach ($this->validation_datas as $validationData)
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- if ($validationData->getParticipant()->getUser()->get_id() == $user->get_id())
- {
- return $validationData;
- }
+ return $this->id;
}
- throw new \Exception('There is no such participant '. $user->get_email());
- }
+ /**
+ * Set record_id
+ *
+ * @param integer $recordId
+ */
+ public function setRecordId($recordId)
+ {
+ $this->record_id = $recordId;
+ }
+ /**
+ * Get record_id
+ *
+ * @return integer
+ */
+ public function getRecordId()
+ {
+ return $this->record_id;
+ }
+
+ /**
+ * Set sbas_id
+ *
+ * @param integer $sbasId
+ */
+ public function setSbasId($sbasId)
+ {
+ $this->sbas_id = $sbasId;
+ }
+
+ /**
+ * Get sbas_id
+ *
+ * @return integer
+ */
+ public function getSbasId()
+ {
+ return $this->sbas_id;
+ }
+
+ /**
+ * Set ord
+ *
+ * @param integer $ord
+ */
+ public function setOrd($ord)
+ {
+ $this->ord = $ord;
+ }
+
+ /**
+ * Get ord
+ *
+ * @return integer
+ */
+ public function getOrd()
+ {
+ return $this->ord;
+ }
+
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
+
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
+
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
+
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
+
+ /**
+ * Set basket
+ *
+ * @param Entities\Basket $basket
+ */
+ public function setBasket(\Entities\Basket $basket)
+ {
+ $this->basket = $basket;
+ }
+
+ /**
+ * Get basket
+ *
+ * @return Entities\Basket
+ */
+ public function getBasket()
+ {
+ return $this->basket;
+ }
+
+ public function getRecord()
+ {
+ return new \record_adapter($this->getSbasId(), $this->getRecordId(), $this->getOrd());
+ }
+
+ public function setRecord(\record_adapter $record)
+ {
+ $this->setRecordId($record->get_record_id());
+ $this->setSbasId($record->get_sbas_id());
+ }
+
+ public function setLastInBasket()
+ {
+ $this->setOrd($this->getBasket()->getElements()->count() + 1);
+ }
+ /**
+ * @var Entities\ValidationData
+ */
+ protected $validation_datas;
+
+ public function __construct()
+ {
+ $this->validation_datas = new \Doctrine\Common\Collections\ArrayCollection();
+ }
+
+ /**
+ * Add validation_datas
+ *
+ * @param Entities\ValidationData $validationDatas
+ */
+ public function addValidationData(\Entities\ValidationData $validationDatas)
+ {
+ $this->validation_datas[] = $validationDatas;
+ }
+
+ /**
+ * Get validation_datas
+ *
+ * @return Doctrine\Common\Collections\Collection
+ */
+ public function getValidationDatas()
+ {
+ return $this->validation_datas;
+ }
+
+ /**
+ *
+ * @param \User_Adapter $user
+ * @return \Entities\ValidationData
+ */
+ public function getUserValidationDatas(\User_Adapter $user)
+ {
+ foreach ($this->validation_datas as $validationData) {
+ if ($validationData->getParticipant()->getUser()->get_id() == $user->get_id()) {
+ return $validationData;
+ }
+ }
+
+ throw new \Exception('There is no such participant ' . $user->get_email());
+ }
}
diff --git a/lib/Doctrine/Entities/StoryWZ.php b/lib/Doctrine/Entities/StoryWZ.php
index 7331f1d396..83c3e72348 100644
--- a/lib/Doctrine/Entities/StoryWZ.php
+++ b/lib/Doctrine/Entities/StoryWZ.php
@@ -24,144 +24,141 @@ require_once __DIR__ . '/../../classes/User/Adapter.class.php';
*/
class StoryWZ
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var integer $sbas_id
+ */
+ protected $sbas_id;
- /**
- * @var integer $sbas_id
- */
- protected $sbas_id;
+ /**
+ * @var integer $record_id
+ */
+ protected $record_id;
- /**
- * @var integer $record_id
- */
- protected $record_id;
+ /**
+ * @var integer $usr_id
+ */
+ protected $usr_id;
- /**
- * @var integer $usr_id
- */
- protected $usr_id;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set sbas_id
- *
- * @param integer $sbasId
- */
- public function setSbasId($sbasId)
- {
- $this->sbas_id = $sbasId;
- }
-
- /**
- * Get sbas_id
- *
- * @return integer
- */
- public function getSbasId()
- {
- return $this->sbas_id;
- }
-
- /**
- * Set record_id
- *
- * @param integer $recordId
- */
- public function setRecordId($recordId)
- {
- $this->record_id = $recordId;
- }
-
- /**
- * Get record_id
- *
- * @return integer
- */
- public function getRecordId()
- {
- return $this->record_id;
- }
-
- /**
- * Set usr_id
- *
- * @param integer $usrId
- */
- public function setUsrId($usrId)
- {
- $this->usr_id = $usrId;
- }
-
- /**
- * Get usr_id
- *
- * @return integer
- */
- public function getUsrId()
- {
- return $this->usr_id;
- }
-
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
-
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- public function setUser(\User_Adapter $user)
- {
- $this->setUsrId($user->get_id());
- }
-
- public function getUser()
- {
- if ($this->getUsrId())
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- return new \User_Adapter($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ return $this->id;
}
- }
- public function getRecord()
- {
- return new \record_adapter($this->getSbasId(), $this->getRecordId());
- }
+ /**
+ * Set sbas_id
+ *
+ * @param integer $sbasId
+ */
+ public function setSbasId($sbasId)
+ {
+ $this->sbas_id = $sbasId;
+ }
- public function setRecord(\record_adapter $record)
- {
- $this->setRecordId($record->get_record_id());
- $this->setSbasId($record->get_sbas_id());
- }
+ /**
+ * Get sbas_id
+ *
+ * @return integer
+ */
+ public function getSbasId()
+ {
+ return $this->sbas_id;
+ }
+ /**
+ * Set record_id
+ *
+ * @param integer $recordId
+ */
+ public function setRecordId($recordId)
+ {
+ $this->record_id = $recordId;
+ }
+
+ /**
+ * Get record_id
+ *
+ * @return integer
+ */
+ public function getRecordId()
+ {
+ return $this->record_id;
+ }
+
+ /**
+ * Set usr_id
+ *
+ * @param integer $usrId
+ */
+ public function setUsrId($usrId)
+ {
+ $this->usr_id = $usrId;
+ }
+
+ /**
+ * Get usr_id
+ *
+ * @return integer
+ */
+ public function getUsrId()
+ {
+ return $this->usr_id;
+ }
+
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
+
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
+
+ public function setUser(\User_Adapter $user)
+ {
+ $this->setUsrId($user->get_id());
+ }
+
+ public function getUser()
+ {
+ if ($this->getUsrId()) {
+ return new \User_Adapter($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
+ }
+
+ public function getRecord()
+ {
+ return new \record_adapter($this->getSbasId(), $this->getRecordId());
+ }
+
+ public function setRecord(\record_adapter $record)
+ {
+ $this->setRecordId($record->get_record_id());
+ $this->setSbasId($record->get_sbas_id());
+ }
}
diff --git a/lib/Doctrine/Entities/UsrList.php b/lib/Doctrine/Entities/UsrList.php
index 9c34627834..b85560bcc8 100644
--- a/lib/Doctrine/Entities/UsrList.php
+++ b/lib/Doctrine/Entities/UsrList.php
@@ -18,198 +18,191 @@ namespace Entities;
*/
class UsrList
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var string $name
+ */
+ protected $name;
- /**
- * @var string $name
- */
- protected $name;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var Entities\UsrListOwner
+ */
+ protected $owners;
- /**
- * @var Entities\UsrListOwner
- */
- protected $owners;
+ /**
+ * @var \Doctrine\Common\Collections\Collection
+ */
+ protected $entries;
- /**
- * @var \Doctrine\Common\Collections\Collection
- */
- protected $entries;
-
- public function __construct()
- {
- $this->owners = new \Doctrine\Common\Collections\ArrayCollection();
- $this->entries = new \Doctrine\Common\Collections\ArrayCollection();
- }
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set name
- *
- * @param string $name
- */
- public function setName($name)
- {
- $this->name = $name;
- }
-
- /**
- * Get name
- *
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
-
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
-
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
-
- /**
- * Add owners
- *
- * @param Entities\UsrListOwner $owners
- */
- public function addUsrListOwner(\Entities\UsrListOwner $owners)
- {
- $this->owners[] = $owners;
- }
-
- /**
- * Get owners
- *
- * @return Doctrine\Common\Collections\Collection
- */
- public function getOwners()
- {
- return $this->owners;
- }
-
- public function hasAccess(\User_Adapter $user)
- {
- foreach ($this->getOwners() as $owner)
+ public function __construct()
{
- if ($owner->getUser()->get_id() == $user->get_id())
- {
- return true;
- }
+ $this->owners = new \Doctrine\Common\Collections\ArrayCollection();
+ $this->entries = new \Doctrine\Common\Collections\ArrayCollection();
}
- return false;
- }
-
- /**
- *
- * @param \User_Adapter $user
- * @return \Entities\UsrListOwner
- */
- public function getOwner(\User_Adapter $user)
- {
- foreach ($this->getOwners() as $owner)
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- if ($owner->getUser()->get_id() == $user->get_id())
- {
- return $owner;
- }
+ return $this->id;
}
- throw new \Exception('This user is not an owner of the list');
- }
+ /**
+ * Set name
+ *
+ * @param string $name
+ */
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- /**
- * Add entry
- *
- * @param Entities\UsrListEntry $entry
- */
- public function addUsrListEntry(\Entities\UsrListEntry $entry)
- {
- $this->entries[] = $entry;
- }
+ /**
+ * Get name
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
- /**
- * Get entries
- *
- * @return \Doctrine\Common\Collections\Collection
- */
- public function getEntries()
- {
- return $this->entries;
- }
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
- /**
- * Return true if one of the entry is related to the given user
- *
- * @param \User_Adapter $user
- * @return boolean
- */
- public function has(\User_Adapter $user)
- {
- return $this->entries->exists(
- function($key, $entry) use ($user)
- {
- return $entry->getUser()->get_id() === $user->get_id();
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
+
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
+
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
+
+ /**
+ * Add owners
+ *
+ * @param Entities\UsrListOwner $owners
+ */
+ public function addUsrListOwner(\Entities\UsrListOwner $owners)
+ {
+ $this->owners[] = $owners;
+ }
+
+ /**
+ * Get owners
+ *
+ * @return Doctrine\Common\Collections\Collection
+ */
+ public function getOwners()
+ {
+ return $this->owners;
+ }
+
+ public function hasAccess(\User_Adapter $user)
+ {
+ foreach ($this->getOwners() as $owner) {
+ if ($owner->getUser()->get_id() == $user->get_id()) {
+ return true;
+ }
}
- );
- }
+ return false;
+ }
+
+ /**
+ *
+ * @param \User_Adapter $user
+ * @return \Entities\UsrListOwner
+ */
+ public function getOwner(\User_Adapter $user)
+ {
+ foreach ($this->getOwners() as $owner) {
+ if ($owner->getUser()->get_id() == $user->get_id()) {
+ return $owner;
+ }
+ }
+
+ throw new \Exception('This user is not an owner of the list');
+ }
+
+ /**
+ * Add entry
+ *
+ * @param Entities\UsrListEntry $entry
+ */
+ public function addUsrListEntry(\Entities\UsrListEntry $entry)
+ {
+ $this->entries[] = $entry;
+ }
+
+ /**
+ * Get entries
+ *
+ * @return \Doctrine\Common\Collections\Collection
+ */
+ public function getEntries()
+ {
+ return $this->entries;
+ }
+
+ /**
+ * Return true if one of the entry is related to the given user
+ *
+ * @param \User_Adapter $user
+ * @return boolean
+ */
+ public function has(\User_Adapter $user)
+ {
+ return $this->entries->exists(
+ function($key, $entry) use ($user) {
+ return $entry->getUser()->get_id() === $user->get_id();
+ }
+ );
+ }
}
diff --git a/lib/Doctrine/Entities/UsrListEntry.php b/lib/Doctrine/Entities/UsrListEntry.php
index 1b1f66c636..26d41fcff5 100644
--- a/lib/Doctrine/Entities/UsrListEntry.php
+++ b/lib/Doctrine/Entities/UsrListEntry.php
@@ -18,129 +18,128 @@ namespace Entities;
*/
class UsrListEntry
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var integer $usr_id
+ */
+ protected $usr_id;
- /**
- * @var integer $usr_id
- */
- protected $usr_id;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var Entities\UsrList
+ */
+ protected $list;
- /**
- * @var Entities\UsrList
- */
- protected $list;
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
+ /**
+ * Set usr_id
+ *
+ * @param integer $usrId
+ */
+ public function setUsrId($usrId)
+ {
+ $this->usr_id = $usrId;
+ }
- /**
- * Set usr_id
- *
- * @param integer $usrId
- */
- public function setUsrId($usrId)
- {
- $this->usr_id = $usrId;
- }
+ /**
+ * Get usr_id
+ *
+ * @return integer
+ */
+ public function getUsrId()
+ {
+ return $this->usr_id;
+ }
- /**
- * Get usr_id
- *
- * @return integer
- */
- public function getUsrId()
- {
- return $this->usr_id;
- }
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
+ /**
+ * Set list
+ *
+ * @param Entities\UsrList $list
+ */
+ public function setList(\Entities\UsrList $list)
+ {
+ $this->list = $list;
+ }
- /**
- * Set list
- *
- * @param Entities\UsrList $list
- */
- public function setList(\Entities\UsrList $list)
- {
- $this->list = $list;
- }
+ /**
+ * Get list
+ *
+ * @return Entities\UsrList
+ */
+ public function getList()
+ {
+ return $this->list;
+ }
- /**
- * Get list
- *
- * @return Entities\UsrList
- */
- public function getList()
- {
- return $this->list;
- }
-
- public function getUser()
- {
- return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
- }
- public function setUser(\User_Adapter $user)
- {
- return $this->setUsrId($user->get_id());
- }
+ public function getUser()
+ {
+ return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
+ public function setUser(\User_Adapter $user)
+ {
+ return $this->setUsrId($user->get_id());
+ }
}
diff --git a/lib/Doctrine/Entities/UsrListOwner.php b/lib/Doctrine/Entities/UsrListOwner.php
index 9abc4f5b8b..8460ffc4dd 100644
--- a/lib/Doctrine/Entities/UsrListOwner.php
+++ b/lib/Doctrine/Entities/UsrListOwner.php
@@ -18,161 +18,160 @@ namespace Entities;
*/
class UsrListOwner
{
- const ROLE_USER = 1;
- const ROLE_EDITOR = 2;
- const ROLE_ADMIN = 3;
+ const ROLE_USER = 1;
+ const ROLE_EDITOR = 2;
+ const ROLE_ADMIN = 3;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $usr_id
- */
- protected $usr_id;
+ /**
+ * @var integer $usr_id
+ */
+ protected $usr_id;
- /**
- * @var string $role
- */
- protected $role;
+ /**
+ * @var string $role
+ */
+ protected $role;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var Entities\UsrList
- */
- protected $list;
+ /**
+ * @var Entities\UsrList
+ */
+ protected $list;
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
- /**
- * Set usr_id
- *
- * @param integer $usrId
- */
- public function setUsrId($usrId)
- {
- $this->usr_id = $usrId;
- }
+ /**
+ * Set usr_id
+ *
+ * @param integer $usrId
+ */
+ public function setUsrId($usrId)
+ {
+ $this->usr_id = $usrId;
+ }
- /**
- * Get usr_id
- *
- * @return integer
- */
- public function getUsrId()
- {
- return $this->usr_id;
- }
+ /**
+ * Get usr_id
+ *
+ * @return integer
+ */
+ public function getUsrId()
+ {
+ return $this->usr_id;
+ }
- /**
- * Set role
- *
- * @param string $role
- */
- public function setRole($role)
- {
- if (!in_array($role, array(self::ROLE_ADMIN, self::ROLE_EDITOR, self::ROLE_USER)))
- throw new \Exception('Unknown role `' . $role . '`');
+ /**
+ * Set role
+ *
+ * @param string $role
+ */
+ public function setRole($role)
+ {
+ if ( ! in_array($role, array(self::ROLE_ADMIN, self::ROLE_EDITOR, self::ROLE_USER)))
+ throw new \Exception('Unknown role `' . $role . '`');
- $this->role = $role;
- }
+ $this->role = $role;
+ }
- /**
- * Get role
- *
- * @return string
- */
- public function getRole()
- {
- return $this->role;
- }
+ /**
+ * Get role
+ *
+ * @return string
+ */
+ public function getRole()
+ {
+ return $this->role;
+ }
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
- /**
- * Set list
- *
- * @param Entities\UsrList $list
- */
- public function setList(\Entities\UsrList $list)
- {
- $this->list = $list;
- }
+ /**
+ * Set list
+ *
+ * @param Entities\UsrList $list
+ */
+ public function setList(\Entities\UsrList $list)
+ {
+ $this->list = $list;
+ }
- /**
- * Get list
- *
- * @return Entities\UsrList
- */
- public function getList()
- {
- return $this->list;
- }
+ /**
+ * Get list
+ *
+ * @return Entities\UsrList
+ */
+ public function getList()
+ {
+ return $this->list;
+ }
- public function setUser(\User_Adapter $user)
- {
- return $this->setUsrId($user->get_id());
- }
-
- public function getUser()
- {
- return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
- }
+ public function setUser(\User_Adapter $user)
+ {
+ return $this->setUsrId($user->get_id());
+ }
+ public function getUser()
+ {
+ return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
}
diff --git a/lib/Doctrine/Entities/ValidationData.php b/lib/Doctrine/Entities/ValidationData.php
index c787f71b6a..588f3e091b 100644
--- a/lib/Doctrine/Entities/ValidationData.php
+++ b/lib/Doctrine/Entities/ValidationData.php
@@ -8,7 +8,9 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+
namespace Entities;
+
/**
*
* @package
@@ -47,7 +49,6 @@ class ValidationData
*/
protected $basket_element;
-
/**
* Get id
*
diff --git a/lib/Doctrine/Entities/ValidationParticipant.php b/lib/Doctrine/Entities/ValidationParticipant.php
index 3fc0c00963..7e4086266d 100644
--- a/lib/Doctrine/Entities/ValidationParticipant.php
+++ b/lib/Doctrine/Entities/ValidationParticipant.php
@@ -19,262 +19,257 @@ namespace Entities;
*/
class ValidationParticipant
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var integer $usr_id
+ */
+ protected $usr_id;
- /**
- * @var integer $usr_id
- */
- protected $usr_id;
+ /**
+ * @var Entities\ValidationSession
+ */
+ protected $session;
- /**
- * @var Entities\ValidationSession
- */
- protected $session;
+ /**
+ * @var datetime $reminded
+ */
+ protected $reminded = null;
- /**
- * @var datetime $reminded
- */
- protected $reminded = null;
+ /**
+ * @var Entities\ValidationData
+ */
+ protected $datas;
- /**
- * @var Entities\ValidationData
- */
- protected $datas;
+ /**
+ * @var boolean $is_confirmed
+ */
+ protected $is_confirmed = false;
- /**
- * @var boolean $is_confirmed
- */
- protected $is_confirmed = false;
+ /**
+ * @var boolean $can_agree
+ */
+ protected $can_agree = false;
- /**
- * @var boolean $can_agree
- */
- protected $can_agree = false;
+ /**
+ * @var boolean $can_see_others
+ */
+ protected $can_see_others = false;
- /**
- * @var boolean $can_see_others
- */
- protected $can_see_others = false;
+ /**
+ * @var boolean $is_aware
+ */
+ protected $is_aware = false;
- /**
- * @var boolean $is_aware
- */
- protected $is_aware = false;
-
- public function __construct()
- {
- $this->datas = new \Doctrine\Common\Collections\ArrayCollection();
- }
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set usr_id
- *
- * @param integer $usrId
- */
- public function setUsrId($usrId)
- {
- $this->usr_id = $usrId;
- }
-
- /**
- * Get usr_id
- *
- * @return integer
- */
- public function getUsrId()
- {
- return $this->usr_id;
- }
-
- /**
- * Add datases
- *
- * @param Entities\ValidationData $datas
- */
- public function addValidationData(\Entities\ValidationData $datas)
- {
- $this->datas[] = $datas;
- }
-
- /**
- * Set session
- *
- * @param Entities\ValidationSession $session
- */
- public function setSession(\Entities\ValidationSession $session)
- {
- $this->session = $session;
- }
-
- /**
- * Get session
- *
- * @return Entities\ValidationSession
- */
- public function getSession()
- {
- return $this->session;
- }
-
- /**
- * Set is_aware
- *
- * @param boolean $isAware
- */
- public function setIsAware($isAware)
- {
- $this->is_aware = $isAware;
- }
-
- /**
- * Get is_aware
- *
- * @return boolean
- */
- public function getIsAware()
- {
- return $this->is_aware;
- }
-
- /**
- *
- * @param \User_Adapter $user
- * @return ValidationParticipant
- */
- public function setUser(\User_Adapter $user)
- {
- $this->usr_id = $user->get_id();
-
- return $this;
- }
-
- public function getUser()
- {
- return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
- }
-
- /**
- * Set reminded
- *
- * @param datetime $reminded
- */
- public function setReminded($reminded)
- {
- $this->reminded = $reminded;
- }
-
- /**
- * Get reminded
- *
- * @return datetime
- */
- public function getReminded()
- {
- return $this->reminded;
- }
-
- /**
- * Get datas
- *
- * @return Doctrine\Common\Collections\Collection
- */
- public function getDatas()
- {
- return $this->datas;
- }
-
- /**
- * Set is_confirmed
- *
- * @param boolean $isConfirmed
- */
- public function setIsConfirmed($isConfirmed)
- {
- $this->is_confirmed = $isConfirmed;
- }
-
- /**
- * Get is_confirmed
- *
- * @return boolean
- */
- public function getIsConfirmed()
- {
- return $this->is_confirmed;
- }
-
- /**
- * Set can_agree
- *
- * @param boolean $canAgree
- */
- public function setCanAgree($canAgree)
- {
- $this->can_agree = $canAgree;
- }
-
- /**
- * Get can_agree
- *
- * @return boolean
- */
- public function getCanAgree()
- {
- return $this->can_agree;
- }
-
- /**
- * Set can_see_others
- *
- * @param boolean $canSeeOthers
- */
- public function setCanSeeOthers($canSeeOthers)
- {
- $this->can_see_others = $canSeeOthers;
- }
-
- /**
- * Get can_see_others
- *
- * @return boolean
- */
- public function getCanSeeOthers()
- {
- return $this->can_see_others;
- }
-
- public function isReleasable()
- {
-
- if ($this->getIsConfirmed())
+ public function __construct()
{
- return false;
+ $this->datas = new \Doctrine\Common\Collections\ArrayCollection();
}
- foreach ($this->getDatas() as $validation_data)
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- /* @var $validation_data \Entities\ValidationData */
- if ($validation_data->getAgreement() === null)
- {
- return false;
- }
+ return $this->id;
}
- return true;
- }
+ /**
+ * Set usr_id
+ *
+ * @param integer $usrId
+ */
+ public function setUsrId($usrId)
+ {
+ $this->usr_id = $usrId;
+ }
+ /**
+ * Get usr_id
+ *
+ * @return integer
+ */
+ public function getUsrId()
+ {
+ return $this->usr_id;
+ }
+
+ /**
+ * Add datases
+ *
+ * @param Entities\ValidationData $datas
+ */
+ public function addValidationData(\Entities\ValidationData $datas)
+ {
+ $this->datas[] = $datas;
+ }
+
+ /**
+ * Set session
+ *
+ * @param Entities\ValidationSession $session
+ */
+ public function setSession(\Entities\ValidationSession $session)
+ {
+ $this->session = $session;
+ }
+
+ /**
+ * Get session
+ *
+ * @return Entities\ValidationSession
+ */
+ public function getSession()
+ {
+ return $this->session;
+ }
+
+ /**
+ * Set is_aware
+ *
+ * @param boolean $isAware
+ */
+ public function setIsAware($isAware)
+ {
+ $this->is_aware = $isAware;
+ }
+
+ /**
+ * Get is_aware
+ *
+ * @return boolean
+ */
+ public function getIsAware()
+ {
+ return $this->is_aware;
+ }
+
+ /**
+ *
+ * @param \User_Adapter $user
+ * @return ValidationParticipant
+ */
+ public function setUser(\User_Adapter $user)
+ {
+ $this->usr_id = $user->get_id();
+
+ return $this;
+ }
+
+ public function getUser()
+ {
+ return \User_Adapter::getInstance($this->getUsrId(), \appbox::get_instance(\bootstrap::getCore()));
+ }
+
+ /**
+ * Set reminded
+ *
+ * @param datetime $reminded
+ */
+ public function setReminded($reminded)
+ {
+ $this->reminded = $reminded;
+ }
+
+ /**
+ * Get reminded
+ *
+ * @return datetime
+ */
+ public function getReminded()
+ {
+ return $this->reminded;
+ }
+
+ /**
+ * Get datas
+ *
+ * @return Doctrine\Common\Collections\Collection
+ */
+ public function getDatas()
+ {
+ return $this->datas;
+ }
+
+ /**
+ * Set is_confirmed
+ *
+ * @param boolean $isConfirmed
+ */
+ public function setIsConfirmed($isConfirmed)
+ {
+ $this->is_confirmed = $isConfirmed;
+ }
+
+ /**
+ * Get is_confirmed
+ *
+ * @return boolean
+ */
+ public function getIsConfirmed()
+ {
+ return $this->is_confirmed;
+ }
+
+ /**
+ * Set can_agree
+ *
+ * @param boolean $canAgree
+ */
+ public function setCanAgree($canAgree)
+ {
+ $this->can_agree = $canAgree;
+ }
+
+ /**
+ * Get can_agree
+ *
+ * @return boolean
+ */
+ public function getCanAgree()
+ {
+ return $this->can_agree;
+ }
+
+ /**
+ * Set can_see_others
+ *
+ * @param boolean $canSeeOthers
+ */
+ public function setCanSeeOthers($canSeeOthers)
+ {
+ $this->can_see_others = $canSeeOthers;
+ }
+
+ /**
+ * Get can_see_others
+ *
+ * @return boolean
+ */
+ public function getCanSeeOthers()
+ {
+ return $this->can_see_others;
+ }
+
+ public function isReleasable()
+ {
+
+ if ($this->getIsConfirmed()) {
+ return false;
+ }
+
+ foreach ($this->getDatas() as $validation_data) {
+ /* @var $validation_data \Entities\ValidationData */
+ if ($validation_data->getAgreement() === null) {
+ return false;
+ }
+ }
+
+ return true;
+ }
}
diff --git a/lib/Doctrine/Entities/ValidationSession.php b/lib/Doctrine/Entities/ValidationSession.php
index 812ba9364f..e1ace6f6e0 100644
--- a/lib/Doctrine/Entities/ValidationSession.php
+++ b/lib/Doctrine/Entities/ValidationSession.php
@@ -19,369 +19,353 @@ namespace Entities;
*/
class ValidationSession
{
+ /**
+ * @var integer $id
+ */
+ protected $id;
- /**
- * @var integer $id
- */
- protected $id;
+ /**
+ * @var string $name
+ */
+ protected $name;
- /**
- * @var string $name
- */
- protected $name;
+ /**
+ * @var text $description
+ */
+ protected $description;
- /**
- * @var text $description
- */
- protected $description;
+ /**
+ * @var boolean $archived
+ */
+ protected $archived;
- /**
- * @var boolean $archived
- */
- protected $archived;
+ /**
+ * @var datetime $created
+ */
+ protected $created;
- /**
- * @var datetime $created
- */
- protected $created;
+ /**
+ * @var datetime $updated
+ */
+ protected $updated;
- /**
- * @var datetime $updated
- */
- protected $updated;
+ /**
+ * @var datetime $expires
+ */
+ protected $expires;
- /**
- * @var datetime $expires
- */
- protected $expires;
+ /**
+ * @var datetime $reminded
+ */
+ protected $reminded;
- /**
- * @var datetime $reminded
- */
- protected $reminded;
+ /**
+ * @var Entities\Basket
+ */
+ protected $basket;
- /**
- * @var Entities\Basket
- */
- protected $basket;
+ /**
+ * @var Entities\ValidationParticipant
+ */
+ protected $participants;
- /**
- * @var Entities\ValidationParticipant
- */
- protected $participants;
-
- public function __construct()
- {
- $this->participants = new \Doctrine\Common\Collections\ArrayCollection();
- }
-
- /**
- * Get id
- *
- * @return integer
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Set name
- *
- * @param string $name
- */
- public function setName($name)
- {
- $this->name = $name;
- }
-
- /**
- * Get name
- *
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Set description
- *
- * @param text $description
- */
- public function setDescription($description)
- {
- $this->description = $description;
- }
-
- /**
- * Get description
- *
- * @return text
- */
- public function getDescription()
- {
- return $this->description;
- }
-
- /**
- * Set archived
- *
- * @param boolean $archived
- */
- public function setArchived($archived)
- {
- $this->archived = $archived;
- }
-
- /**
- * Get archived
- *
- * @return boolean
- */
- public function getArchived()
- {
- return $this->archived;
- }
-
- /**
- * Set created
- *
- * @param datetime $created
- */
- public function setCreated($created)
- {
- $this->created = $created;
- }
-
- /**
- * Get created
- *
- * @return datetime
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Set updated
- *
- * @param datetime $updated
- */
- public function setUpdated($updated)
- {
- $this->updated = $updated;
- }
-
- /**
- * Get updated
- *
- * @return datetime
- */
- public function getUpdated()
- {
- return $this->updated;
- }
-
- /**
- * Set expires
- *
- * @param datetime $expires
- */
- public function setExpires($expires)
- {
- $this->expires = $expires;
- }
-
- /**
- * Get expires
- *
- * @return datetime
- */
- public function getExpires()
- {
- return $this->expires;
- }
-
- /**
- * Set reminded
- *
- * @param datetime $reminded
- */
- public function setReminded($reminded)
- {
- $this->reminded = $reminded;
- }
-
- /**
- * Get reminded
- *
- * @return datetime
- */
- public function getReminded()
- {
- return $this->reminded;
- }
-
- /**
- * Set basket
- *
- * @param Entities\Basket $basket
- */
- public function setBasket(\Entities\Basket $basket)
- {
- $this->basket = $basket;
- }
-
- /**
- * Get basket
- *
- * @return Entities\Basket
- */
- public function getBasket()
- {
- return $this->basket;
- }
-
- /**
- * Add participants
- *
- * @param Entities\ValidationParticipant $participants
- */
- public function addValidationParticipant(\Entities\ValidationParticipant $participants)
- {
- $this->participants[] = $participants;
- }
-
- /**
- * Get participants
- *
- * @return Doctrine\Common\Collections\Collection
- */
- public function getParticipants()
- {
- return $this->participants;
- }
-
- /**
- * Get a participant
- *
- * @return Entities\ValidationParticipant
- */
- public function getParticipant(\User_Adapter $user)
- {
- foreach ($this->getParticipants() as $participant)
+ public function __construct()
{
- if ($participant->getUser()->get_id() == $user->get_id())
- {
- return $participant;
- }
+ $this->participants = new \Doctrine\Common\Collections\ArrayCollection();
}
- throw new \Exception_NotFound('Particpant not found' . $user->get_email());
- }
-
- /**
- * @var integer $initiator
- */
- protected $initiator;
-
- /**
- * @var integer $initiator_id
- */
- protected $initiator_id;
-
- /**
- * Set initiator_id
- *
- * @param integer $initiatorId
- */
- public function setInitiatorId($initiatorId)
- {
- $this->initiator_id = $initiatorId;
- }
-
- /**
- * Get initiator_id
- *
- * @return integer
- */
- public function getInitiatorId()
- {
- return $this->initiator_id;
- }
-
- public function isInitiator(\User_Adapter $user)
- {
- return $this->getInitiatorId() == $user->get_id();
- }
-
- public function setInitiator(\User_Adapter $user)
- {
- $this->initiator_id = $user->get_id();
-
- return;
- }
-
- public function getInitiator()
- {
- if ($this->initiator_id)
+ /**
+ * Get id
+ *
+ * @return integer
+ */
+ public function getId()
{
- return \User_Adapter::getInstance($this->initiator_id, \appbox::get_instance(\bootstrap::getCore()));
- }
- }
-
- public function isFinished()
- {
- if (is_null($this->getExpires()))
- {
- return null;
+ return $this->id;
}
- $date_obj = new \DateTime();
-
- return $date_obj > $this->getExpires();
- }
-
- public function getValidationString(\User_Adapter $user)
- {
-
- if ($this->isInitiator($user))
+ /**
+ * Set name
+ *
+ * @param string $name
+ */
+ public function setName($name)
{
- if ($this->isFinished())
- {
- return sprintf(
+ $this->name = $name;
+ }
+
+ /**
+ * Get name
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * Set description
+ *
+ * @param text $description
+ */
+ public function setDescription($description)
+ {
+ $this->description = $description;
+ }
+
+ /**
+ * Get description
+ *
+ * @return text
+ */
+ public function getDescription()
+ {
+ return $this->description;
+ }
+
+ /**
+ * Set archived
+ *
+ * @param boolean $archived
+ */
+ public function setArchived($archived)
+ {
+ $this->archived = $archived;
+ }
+
+ /**
+ * Get archived
+ *
+ * @return boolean
+ */
+ public function getArchived()
+ {
+ return $this->archived;
+ }
+
+ /**
+ * Set created
+ *
+ * @param datetime $created
+ */
+ public function setCreated($created)
+ {
+ $this->created = $created;
+ }
+
+ /**
+ * Get created
+ *
+ * @return datetime
+ */
+ public function getCreated()
+ {
+ return $this->created;
+ }
+
+ /**
+ * Set updated
+ *
+ * @param datetime $updated
+ */
+ public function setUpdated($updated)
+ {
+ $this->updated = $updated;
+ }
+
+ /**
+ * Get updated
+ *
+ * @return datetime
+ */
+ public function getUpdated()
+ {
+ return $this->updated;
+ }
+
+ /**
+ * Set expires
+ *
+ * @param datetime $expires
+ */
+ public function setExpires($expires)
+ {
+ $this->expires = $expires;
+ }
+
+ /**
+ * Get expires
+ *
+ * @return datetime
+ */
+ public function getExpires()
+ {
+ return $this->expires;
+ }
+
+ /**
+ * Set reminded
+ *
+ * @param datetime $reminded
+ */
+ public function setReminded($reminded)
+ {
+ $this->reminded = $reminded;
+ }
+
+ /**
+ * Get reminded
+ *
+ * @return datetime
+ */
+ public function getReminded()
+ {
+ return $this->reminded;
+ }
+
+ /**
+ * Set basket
+ *
+ * @param Entities\Basket $basket
+ */
+ public function setBasket(\Entities\Basket $basket)
+ {
+ $this->basket = $basket;
+ }
+
+ /**
+ * Get basket
+ *
+ * @return Entities\Basket
+ */
+ public function getBasket()
+ {
+ return $this->basket;
+ }
+
+ /**
+ * Add participants
+ *
+ * @param Entities\ValidationParticipant $participants
+ */
+ public function addValidationParticipant(\Entities\ValidationParticipant $participants)
+ {
+ $this->participants[] = $participants;
+ }
+
+ /**
+ * Get participants
+ *
+ * @return Doctrine\Common\Collections\Collection
+ */
+ public function getParticipants()
+ {
+ return $this->participants;
+ }
+
+ /**
+ * Get a participant
+ *
+ * @return Entities\ValidationParticipant
+ */
+ public function getParticipant(\User_Adapter $user)
+ {
+ foreach ($this->getParticipants() as $participant) {
+ if ($participant->getUser()->get_id() == $user->get_id()) {
+ return $participant;
+ }
+ }
+
+ throw new \Exception_NotFound('Particpant not found' . $user->get_email());
+ }
+ /**
+ * @var integer $initiator
+ */
+ protected $initiator;
+
+ /**
+ * @var integer $initiator_id
+ */
+ protected $initiator_id;
+
+ /**
+ * Set initiator_id
+ *
+ * @param integer $initiatorId
+ */
+ public function setInitiatorId($initiatorId)
+ {
+ $this->initiator_id = $initiatorId;
+ }
+
+ /**
+ * Get initiator_id
+ *
+ * @return integer
+ */
+ public function getInitiatorId()
+ {
+ return $this->initiator_id;
+ }
+
+ public function isInitiator(\User_Adapter $user)
+ {
+ return $this->getInitiatorId() == $user->get_id();
+ }
+
+ public function setInitiator(\User_Adapter $user)
+ {
+ $this->initiator_id = $user->get_id();
+
+ return;
+ }
+
+ public function getInitiator()
+ {
+ if ($this->initiator_id) {
+ return \User_Adapter::getInstance($this->initiator_id, \appbox::get_instance(\bootstrap::getCore()));
+ }
+ }
+
+ public function isFinished()
+ {
+ if (is_null($this->getExpires())) {
+ return null;
+ }
+
+ $date_obj = new \DateTime();
+
+ return $date_obj > $this->getExpires();
+ }
+
+ public function getValidationString(\User_Adapter $user)
+ {
+
+ if ($this->isInitiator($user)) {
+ if ($this->isFinished()) {
+ return sprintf(
_('Vous aviez envoye cette demande a %d utilisateurs')
, (count($this->getParticipants()) - 1)
- );
- }
- else
- {
- return sprintf(
+ );
+ } else {
+ return sprintf(
_('Vous avez envoye cette demande a %d utilisateurs')
, (count($this->getParticipants()) - 1)
- );
- }
- }
- else
- {
- if ($this->getParticipant($user)->getCanSeeOthers())
- {
- return sprintf(
+ );
+ }
+ } else {
+ if ($this->getParticipant($user)->getCanSeeOthers()) {
+ return sprintf(
_('Processus de validation recu de %s et concernant %d utilisateurs')
, $this->getInitiator()->get_display_name()
, (count($this->getParticipants()) - 1));
- }
- else
- {
- return sprintf(
+ } else {
+ return sprintf(
_('Processus de validation recu de %s')
, $this->getInitiator()->get_display_name()
- );
- }
+ );
+ }
+ }
}
- }
-
}
diff --git a/lib/Doctrine/Logger/MonologSQLLogger.php b/lib/Doctrine/Logger/MonologSQLLogger.php
index 7026fd8558..ddf4160319 100644
--- a/lib/Doctrine/Logger/MonologSQLLogger.php
+++ b/lib/Doctrine/Logger/MonologSQLLogger.php
@@ -23,71 +23,64 @@ use Monolog\Handler\StreamHandler;
*/
class MonologSQLLogger implements \Doctrine\DBAL\Logging\SQLLogger
{
- const JSON = 'json';
- const YAML = 'yaml';
- const VDUMP = 'vdump';
+ const JSON = 'json';
+ const YAML = 'yaml';
+ const VDUMP = 'vdump';
- /**
- *
- * @var \Monolog\Logger
- */
- private $logger;
- private $start;
- private $output = array();
- private $outputType;
+ /**
+ *
+ * @var \Monolog\Logger
+ */
+ private $logger;
+ private $start;
+ private $output = array();
+ private $outputType;
- /**
- * Tell which monolog user to use and which format to output
- *
- * @param \Monolog\Logger $logger A monolog logger instance
- * @param type $type the output format
- */
- public function __construct(\Monolog\Logger $logger, $type = self::YAML)
- {
- $this->logger = $logger;
- $this->outputType = $type;
- }
-
- /**
- * {@inheritdoc}
- */
- public function startQuery($sql, array $params = null, array $types = null)
- {
- $this->start = microtime(true);
-
- $this->output["sql"] = $sql;
-
- if ($params)
+ /**
+ * Tell which monolog user to use and which format to output
+ *
+ * @param \Monolog\Logger $logger A monolog logger instance
+ * @param type $type the output format
+ */
+ public function __construct(\Monolog\Logger $logger, $type = self::YAML)
{
- $this->output["params"] = $params;
+ $this->logger = $logger;
+ $this->outputType = $type;
}
- }
- /**
- * {@inheritdoc}
- */
- public function stopQuery()
- {
- $mstime = microtime(true) - $this->start;
-
- $this->output["times"] = $mstime . " seconds";
- if ($this->outputType == self::JSON)
+ /**
+ * {@inheritdoc}
+ */
+ public function startQuery($sql, array $params = null, array $types = null)
{
- $this->log(json_encode($this->output));
- }
- elseif ($this->outputType == self::YAML)
- {
- $this->log(\Symfony\Component\Yaml\Yaml::dump($this->output));
- }
- else
- {
- $this->log(var_export($this->output, true));
- }
- }
+ $this->start = microtime(true);
- protected function log($message)
- {
- $this->logger->debug($message);
- }
+ $this->output["sql"] = $sql;
+ if ($params) {
+ $this->output["params"] = $params;
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function stopQuery()
+ {
+ $mstime = microtime(true) - $this->start;
+
+ $this->output["times"] = $mstime . " seconds";
+ if ($this->outputType == self::JSON) {
+ $this->log(json_encode($this->output));
+ } elseif ($this->outputType == self::YAML) {
+ $this->log(\Symfony\Component\Yaml\Yaml::dump($this->output));
+ } else {
+ $this->log(var_export($this->output, true));
+ }
+ }
+
+ protected function log($message)
+ {
+ $this->logger->debug($message);
+ }
}
diff --git a/lib/Doctrine/Repositories/BasketElementRepository.php b/lib/Doctrine/Repositories/BasketElementRepository.php
index 14bc308191..3efd0fa296 100644
--- a/lib/Doctrine/Repositories/BasketElementRepository.php
+++ b/lib/Doctrine/Repositories/BasketElementRepository.php
@@ -15,9 +15,9 @@ use Entities;
class BasketElementRepository extends EntityRepository
{
- public function findUserElement($element_id, \User_Adapter $user)
- {
- $dql = 'SELECT e
+ public function findUserElement($element_id, \User_Adapter $user)
+ {
+ $dql = 'SELECT e
FROM Entities\BasketElement e
JOIN e.basket b
LEFT JOIN e.validation_datas vd
@@ -26,29 +26,28 @@ class BasketElementRepository extends EntityRepository
WHERE (b.usr_id = :usr_id OR p.usr_id = :same_usr_id)
AND e.id = :element_id';
- $params = array(
- 'usr_id' => $user->get_id(),
- 'same_usr_id' => $user->get_id(),
- 'element_id' => $element_id
- );
+ $params = array(
+ 'usr_id' => $user->get_id(),
+ 'same_usr_id' => $user->get_id(),
+ 'element_id' => $element_id
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- $element = $query->getOneOrNullResult();
+ $element = $query->getOneOrNullResult();
- /* @var $element \Entities\BasketElement */
- if (null === $element)
- {
- throw new \Exception_NotFound(_('Element is not found'));
+ /* @var $element \Entities\BasketElement */
+ if (null === $element) {
+ throw new \Exception_NotFound(_('Element is not found'));
+ }
+
+ return $element;
}
- return $element;
- }
-
- public function findElementsByRecord(\record_adapter $record)
- {
- $dql = 'SELECT e
+ public function findElementsByRecord(\record_adapter $record)
+ {
+ $dql = 'SELECT e
FROM Entities\BasketElement e
JOIN e.basket b
LEFT JOIN b.validation s
@@ -56,26 +55,26 @@ class BasketElementRepository extends EntityRepository
WHERE e.record_id = :record_id
AND e.sbas_id = :sbas_id';
- $params = array(
- 'sbas_id' => $record->get_sbas_id(),
- 'record_id' => $record->get_record_id()
- );
+ $params = array(
+ 'sbas_id' => $record->get_sbas_id(),
+ 'record_id' => $record->get_record_id()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
+ return $query->getResult();
+ }
- /**
- *
- * @param \record_adapter $record
- * @param \User_Adapter $user
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findReceivedElementsByRecord(\record_adapter $record, \User_Adapter $user)
- {
- $dql = 'SELECT e
+ /**
+ *
+ * @param \record_adapter $record
+ * @param \User_Adapter $user
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findReceivedElementsByRecord(\record_adapter $record, \User_Adapter $user)
+ {
+ $dql = 'SELECT e
FROM Entities\BasketElement e
JOIN e.basket b
LEFT JOIN b.validation s
@@ -85,21 +84,21 @@ class BasketElementRepository extends EntityRepository
AND e.record_id = :record_id
AND e.sbas_id = :sbas_id';
- $params = array(
- 'sbas_id' => $record->get_sbas_id(),
- 'record_id' => $record->get_record_id(),
- 'usr_id' => $user->get_id()
- );
+ $params = array(
+ 'sbas_id' => $record->get_sbas_id(),
+ 'record_id' => $record->get_record_id(),
+ 'usr_id' => $user->get_id()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
+ return $query->getResult();
+ }
- public function findReceivedValidationElementsByRecord(\record_adapter $record, \User_Adapter $user)
- {
- $dql = 'SELECT e
+ public function findReceivedValidationElementsByRecord(\record_adapter $record, \User_Adapter $user)
+ {
+ $dql = 'SELECT e
FROM Entities\BasketElement e
JOIN e.basket b
JOIN b.validation v
@@ -108,16 +107,15 @@ class BasketElementRepository extends EntityRepository
AND e.record_id = :record_id
AND e.sbas_id = :sbas_id';
- $params = array(
- 'sbas_id' => $record->get_sbas_id(),
- 'record_id' => $record->get_record_id(),
- 'usr_id' => $user->get_id()
- );
+ $params = array(
+ 'sbas_id' => $record->get_sbas_id(),
+ 'record_id' => $record->get_record_id(),
+ 'usr_id' => $user->get_id()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
-
- return $query->getResult();
- }
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
+ return $query->getResult();
+ }
}
diff --git a/lib/Doctrine/Repositories/BasketRepository.php b/lib/Doctrine/Repositories/BasketRepository.php
index 9408a4dc18..2f62cddb75 100644
--- a/lib/Doctrine/Repositories/BasketRepository.php
+++ b/lib/Doctrine/Repositories/BasketRepository.php
@@ -22,50 +22,46 @@ use Entities;
*/
class BasketRepository extends EntityRepository
{
+ const MYBASKETS = 'my baskets';
+ const RECEIVED = 'received';
+ const VALIDATION_SENT = 'validation_sent';
+ const VALIDATION_DONE = 'validation_done';
- const MYBASKETS = 'my baskets';
- const RECEIVED = 'received';
- const VALIDATION_SENT = 'validation_sent';
- const VALIDATION_DONE = 'validation_done';
-
- /**
- * Returns all basket for a given user that are not marked as archived
- *
- * @param \User_Adapter $user
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findActiveByUser(\User_Adapter $user, $sort = null)
- {
- $dql = 'SELECT b
+ /**
+ * Returns all basket for a given user that are not marked as archived
+ *
+ * @param \User_Adapter $user
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findActiveByUser(\User_Adapter $user, $sort = null)
+ {
+ $dql = 'SELECT b
FROM Entities\Basket b
LEFT JOIN b.elements e
WHERE b.usr_id = :usr_id
AND b.archived = false';
- if ($sort == 'date')
- {
- $dql .= ' ORDER BY b.created DESC';
- }
- elseif ($sort == 'name')
- {
- $dql .= ' ORDER BY b.name ASC';
+ if ($sort == 'date') {
+ $dql .= ' ORDER BY b.created DESC';
+ } elseif ($sort == 'name') {
+ $dql .= ' ORDER BY b.name ASC';
+ }
+
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters(array('usr_id' => $user->get_id()));
+
+ return $query->getResult();
}
- $query = $this->_em->createQuery($dql);
- $query->setParameters(array('usr_id' => $user->get_id()));
-
- return $query->getResult();
- }
-
- /**
- * Returns all unread basket for a given user that are not marked as archived
- *
- * @param \User_Adapter $user
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findUnreadActiveByUser(\User_Adapter $user)
- {
- $dql = 'SELECT b
+ /**
+ * Returns all unread basket for a given user that are not marked as archived
+ *
+ * @param \User_Adapter $user
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findUnreadActiveByUser(\User_Adapter $user)
+ {
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
LEFT JOIN b.validation s
@@ -79,28 +75,28 @@ class BasketRepository extends EntityRepository
)
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())';
- $params = array(
- 'usr_id_owner' => $user->get_id(),
- 'usr_id_ownertwo' => $user->get_id(),
- 'usr_id_participant' => $user->get_id()
- );
+ $params = array(
+ 'usr_id_owner' => $user->get_id(),
+ 'usr_id_ownertwo' => $user->get_id(),
+ 'usr_id_participant' => $user->get_id()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
+ return $query->getResult();
+ }
- /**
- * Returns all baskets that are in validation session not expired and
- * where a specified user is participant (not owner)
- *
- * @param \User_Adapter $user
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findActiveValidationByUser(\User_Adapter $user, $sort = null)
- {
- $dql = 'SELECT b
+ /**
+ * Returns all baskets that are in validation session not expired and
+ * where a specified user is participant (not owner)
+ *
+ * @param \User_Adapter $user
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findActiveValidationByUser(\User_Adapter $user, $sort = null)
+ {
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
JOIN e.validation_datas v
@@ -109,193 +105,180 @@ class BasketRepository extends EntityRepository
WHERE b.usr_id != ?1 AND p.usr_id = ?2
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) ';
- if ($sort == 'date')
- {
- $dql .= ' ORDER BY b.created DESC';
- }
- elseif ($sort == 'name')
- {
- $dql .= ' ORDER BY b.name ASC';
+ if ($sort == 'date') {
+ $dql .= ' ORDER BY b.created DESC';
+ } elseif ($sort == 'name') {
+ $dql .= ' ORDER BY b.name ASC';
+ }
+
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters(array(1 => $user->get_id(), 2 => $user->get_id()));
+
+ return $query->getResult();
}
- $query = $this->_em->createQuery($dql);
- $query->setParameters(array(1 => $user->get_id(), 2 => $user->get_id()));
-
- return $query->getResult();
- }
-
- /**
- * Find a basket specified by his basket_id and his owner
- *
- * @throws \Exception_NotFound
- * @throws \Exception_Forbidden
- * @param type $basket_id
- * @param \User_Adapter $user
- * @return \Entities\Basket
- */
- public function findUserBasket($basket_id, \User_Adapter $user, $requireOwner)
- {
- $dql = 'SELECT b
+ /**
+ * Find a basket specified by his basket_id and his owner
+ *
+ * @throws \Exception_NotFound
+ * @throws \Exception_Forbidden
+ * @param type $basket_id
+ * @param \User_Adapter $user
+ * @return \Entities\Basket
+ */
+ public function findUserBasket($basket_id, \User_Adapter $user, $requireOwner)
+ {
+ $dql = 'SELECT b
FROM Entities\Basket b
LEFT JOIN b.elements e
WHERE b.id = :basket_id';
- $query = $this->_em->createQuery($dql);
- $query->setParameters(array('basket_id' => $basket_id));
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters(array('basket_id' => $basket_id));
- $basket = $query->getOneOrNullResult();
+ $basket = $query->getOneOrNullResult();
- /* @var $basket \Entities\Basket */
- if (null === $basket)
- {
- throw new \Exception_NotFound(_('Basket is not found'));
+ /* @var $basket \Entities\Basket */
+ if (null === $basket) {
+ throw new \Exception_NotFound(_('Basket is not found'));
+ }
+
+ if ($basket->getOwner()->get_id() != $user->get_id()) {
+ $participant = false;
+
+ if ($basket->getValidation() && ! $requireOwner) {
+ try {
+ $basket->getValidation()->getParticipant($user);
+ $participant = true;
+ } catch (\Exception $e) {
+
+ }
+ }
+ if ( ! $participant) {
+ throw new \Exception_Forbidden(_('You have not access to this basket'));
+ }
+ }
+
+ return $basket;
}
- if ($basket->getOwner()->get_id() != $user->get_id())
+ public function findContainingRecordForUser(\record_adapter $record, \User_Adapter $user)
{
- $participant = false;
- if ($basket->getValidation() && ! $requireOwner)
- {
- try
- {
- $basket->getValidation()->getParticipant($user);
- $participant = true;
- }
- catch (\Exception $e)
- {
-
- }
- }
- if ( ! $participant)
- {
- throw new \Exception_Forbidden(_('You have not access to this basket'));
- }
- }
-
- return $basket;
- }
-
- public function findContainingRecordForUser(\record_adapter $record, \User_Adapter $user)
- {
-
- $dql = 'SELECT b
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
WHERE e.record_id = :record_id AND e.sbas_id = e.sbas_id
AND b.usr_id = :usr_id';
- $params = array(
- 'record_id' => $record->get_record_id(),
- 'usr_id' => $user->get_id()
- );
+ $params = array(
+ 'record_id' => $record->get_record_id(),
+ 'usr_id' => $user->get_id()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
+ return $query->getResult();
+ }
- public function findWorkzoneBasket(\User_Adapter $user, $query, $year, $type, $offset, $perPage)
- {
- $params = array();
-
- switch ($type)
+ public function findWorkzoneBasket(\User_Adapter $user, $query, $year, $type, $offset, $perPage)
{
- case self::RECEIVED:
- $dql = 'SELECT b
+ $params = array();
+
+ switch ($type) {
+ case self::RECEIVED:
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
WHERE b.usr_id = :usr_id AND b.pusher_id IS NOT NULL';
- $params = array(
- 'usr_id' => $user->get_id()
- );
- break;
- case self::VALIDATION_DONE:
- $dql = 'SELECT b
+ $params = array(
+ 'usr_id' => $user->get_id()
+ );
+ break;
+ case self::VALIDATION_DONE:
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
JOIN b.validation s
JOIN s.participants p
WHERE b.usr_id != ?1 AND p.usr_id = ?2';
- $params = array(
- 1 => $user->get_id()
- , 2 => $user->get_id()
- );
- break;
- case self::VALIDATION_SENT:
- $dql = 'SELECT b
+ $params = array(
+ 1 => $user->get_id()
+ , 2 => $user->get_id()
+ );
+ break;
+ case self::VALIDATION_SENT:
+ $dql = 'SELECT b
FROM Entities\Basket b
JOIN b.elements e
JOIN b.validation v
WHERE b.usr_id = :usr_id';
- $params = array(
- 'usr_id' => $user->get_id()
- );
- break;
- default:
- $dql = 'SELECT b
+ $params = array(
+ 'usr_id' => $user->get_id()
+ );
+ break;
+ default:
+ $dql = 'SELECT b
FROM Entities\Basket b
LEFT JOIN b.elements e
LEFT JOIN b.validation s
LEFT JOIN s.participants p
WHERE (b.usr_id = :usr_id OR p.usr_id = :validating_usr_id)';
- $params = array(
- 'usr_id' => $user->get_id(),
- 'validating_usr_id' => $user->get_id()
- );
- break;
- case self::MYBASKETS:
- $dql = 'SELECT b
+ $params = array(
+ 'usr_id' => $user->get_id(),
+ 'validating_usr_id' => $user->get_id()
+ );
+ break;
+ case self::MYBASKETS:
+ $dql = 'SELECT b
FROM Entities\Basket b
LEFT JOIN b.elements e
LEFT JOIN b.validation s
LEFT JOIN s.participants p
WHERE (b.usr_id = :usr_id)';
- $params = array(
- 'usr_id' => $user->get_id()
- );
- break;
+ $params = array(
+ 'usr_id' => $user->get_id()
+ );
+ break;
+ }
+
+ if (ctype_digit($year) && strlen($year) == 4) {
+ $dql .= ' AND b.created >= :min_date AND b.created <= :max_date ';
+
+ $params['min_date'] = sprintf('%d-01-01 00:00:00', $year);
+ $params['max_date'] = sprintf('%d-12-31 23:59:59', $year);
+ }
+
+ if (trim($query) !== '') {
+ $dql .= ' AND (b.name LIKE :name OR b.description LIKE :description) ';
+
+ $params['name'] = '%' . $query . '%';
+ $params['description'] = '%' . $query . '%';
+ }
+
+ $dql .= ' ORDER BY b.id DESC';
+
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params)
+ ->setFirstResult($offset)
+ ->setMaxResults($perPage);
+
+ $paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query, true);
+
+ return $paginator;
}
- if (ctype_digit($year) && strlen($year) == 4)
+ /**
+ * Return all actives validation where current user is involved and user basket
+ *
+ * @param \User_Adapter $user
+ * @param type $sort
+ * @return Array
+ */
+ public function findActiveValidationAndBasketByUser(\User_Adapter $user, $sort = null)
{
- $dql .= ' AND b.created >= :min_date AND b.created <= :max_date ';
-
- $params['min_date'] = sprintf('%d-01-01 00:00:00', $year);
- $params['max_date'] = sprintf('%d-12-31 23:59:59', $year);
- }
-
- if (trim($query) !== '')
- {
- $dql .= ' AND (b.name LIKE :name OR b.description LIKE :description) ';
-
- $params['name'] = '%' . $query . '%';
- $params['description'] = '%' . $query . '%';
- }
-
- $dql .= ' ORDER BY b.id DESC';
-
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params)
- ->setFirstResult($offset)
- ->setMaxResults($perPage);
-
- $paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query, true);
-
- return $paginator;
- }
-
- /**
- * Return all actives validation where current user is involved and user basket
- *
- * @param \User_Adapter $user
- * @param type $sort
- * @return Array
- */
- public function findActiveValidationAndBasketByUser(\User_Adapter $user, $sort = null)
- {
- $dql = 'SELECT b
+ $dql = 'SELECT b
FROM Entities\Basket b
LEFT JOIN b.elements e
LEFT JOIN b.validation s
@@ -305,19 +288,15 @@ class BasketRepository extends EntityRepository
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())
)';
- if ($sort == 'date')
- {
- $dql .= ' ORDER BY b.created DESC';
+ if ($sort == 'date') {
+ $dql .= ' ORDER BY b.created DESC';
+ } elseif ($sort == 'name') {
+ $dql .= ' ORDER BY b.name ASC';
+ }
+
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters(array('usr_id' => $user->get_id()));
+
+ return $query->getResult();
}
- elseif ($sort == 'name')
- {
- $dql .= ' ORDER BY b.name ASC';
- }
-
- $query = $this->_em->createQuery($dql);
- $query->setParameters(array('usr_id' => $user->get_id()));
-
- return $query->getResult();
- }
-
}
diff --git a/lib/Doctrine/Repositories/StoryWZRepository.php b/lib/Doctrine/Repositories/StoryWZRepository.php
index 8b1db19628..763dc57fe3 100644
--- a/lib/Doctrine/Repositories/StoryWZRepository.php
+++ b/lib/Doctrine/Repositories/StoryWZRepository.php
@@ -13,116 +13,94 @@ use Doctrine\ORM\EntityRepository;
class StoryWZRepository extends EntityRepository
{
- public function findByUser(\User_Adapter $user, $sort)
- {
- $dql = 'SELECT s FROM Entities\StoryWZ s WHERE s.usr_id = :usr_id ';
-
- if ($sort == 'date')
+ public function findByUser(\User_Adapter $user, $sort)
{
- $dql .= ' ORDER BY s.created DESC';
+ $dql = 'SELECT s FROM Entities\StoryWZ s WHERE s.usr_id = :usr_id ';
+
+ if ($sort == 'date') {
+ $dql .= ' ORDER BY s.created DESC';
+ }
+
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters(array('usr_id' => $user->get_id()));
+
+ $stories = $query->getResult();
+
+ foreach ($stories as $key => $story) {
+ try {
+ $story->getRecord()->get_title();
+ } catch (\Exception_Record_AdapterNotFound $e) {
+ $this->getEntityManager()->remove($story);
+ unset($stories[$key]);
+ }
+ }
+
+ $this->getEntityManager()->flush();
+
+ if ($sort == 'name') {
+ $sortedStories = array();
+ foreach ($stories as $story) {
+ $sortedStories[] = $story->getRecord()->get_title();
+ }
+
+ uasort($sortedStories, function($a, $b) {
+ if ($a == $b) {
+ return 0;
+ }
+
+ return ($a < $b) ? -1 : 1;
+ });
+
+ foreach ($sortedStories as $idStory => $titleStory) {
+ $sortedStories[$idStory] = $stories[$idStory];
+ }
+ }
+
+ return $stories;
}
- $query = $this->_em->createQuery($dql);
- $query->setParameters(array('usr_id' => $user->get_id()));
-
- $stories = $query->getResult();
-
- foreach ($stories as $key => $story)
+ public function findByUserAndId(\User_Adapter $user, $id)
{
- try
- {
- $story->getRecord()->get_title();
- }
- catch (\Exception_Record_AdapterNotFound $e)
- {
- $this->getEntityManager()->remove($story);
- unset($stories[$key]);
- }
+ $story = $this->find($id);
+
+ if ($story) {
+ try {
+ $story->getRecord()->get_title();
+ } catch (\Exception_Record_AdapterNotFound $e) {
+ $this->getEntityManager()->remove($story);
+ throw new \Exception_NotFound('Story not found');
+ }
+
+ if ($story->getUser()->get_id() !== $user->get_id()) {
+ throw new \Exception_Forbidden('You have not access to ths story');
+ }
+ } else {
+ throw new \Exception_NotFound('Story not found');
+ }
+
+ return $story;
}
- $this->getEntityManager()->flush();
-
- if ($sort == 'name')
+ public function findUserStory(\User_Adapter $user, \record_adapter $Story)
{
- $sortedStories = array();
- foreach ($stories as $story)
- {
- $sortedStories[] = $story->getRecord()->get_title();
- }
-
- uasort($sortedStories, function($a, $b)
- {
- if ($a == $b)
- {
- return 0;
- }
-
- return ($a < $b) ? -1 : 1;
- });
-
- foreach ($sortedStories as $idStory => $titleStory)
- {
- $sortedStories[$idStory] = $stories[$idStory];
- }
- }
-
- return $stories;
- }
-
- public function findByUserAndId(\User_Adapter $user, $id)
- {
- $story = $this->find($id);
-
- if ($story)
- {
- try
- {
- $story->getRecord()->get_title();
- }
- catch (\Exception_Record_AdapterNotFound $e)
- {
- $this->getEntityManager()->remove($story);
- throw new \Exception_NotFound('Story not found');
- }
-
- if ($story->getUser()->get_id() !== $user->get_id())
- {
- throw new \Exception_Forbidden('You have not access to ths story');
- }
- }
- else
- {
- throw new \Exception_NotFound('Story not found');
- }
-
- return $story;
- }
-
- public function findUserStory(\User_Adapter $user, \record_adapter $Story)
- {
- $story = $this->findOneBy(
+ $story = $this->findOneBy(
array(
- 'usr_id' => $user->get_id(),
- 'sbas_id' => $Story->get_sbas_id(),
+ 'usr_id' => $user->get_id(),
+ 'sbas_id' => $Story->get_sbas_id(),
'record_id' => $Story->get_record_id(),
)
- );
+ );
- if ($story)
- {
- try
- {
- $record = $story->getRecord();
- }
- catch (\Exception_Record_AdapterNotFound $e)
- {
- $this->getEntityManager()->remove($story);
- $this->getEntityManager()->flush();
- $story = null;
- }
+ if ($story) {
+ try {
+ $record = $story->getRecord();
+ } catch (\Exception_Record_AdapterNotFound $e) {
+ $this->getEntityManager()->remove($story);
+ $this->getEntityManager()->flush();
+ $story = null;
+ }
+ }
+
+ return $story;
}
-
- return $story;
- }
-
}
diff --git a/lib/Doctrine/Repositories/UsrListEntryRepository.php b/lib/Doctrine/Repositories/UsrListEntryRepository.php
index dab4b9a254..2f30b2a09f 100644
--- a/lib/Doctrine/Repositories/UsrListEntryRepository.php
+++ b/lib/Doctrine/Repositories/UsrListEntryRepository.php
@@ -13,68 +13,64 @@ use Doctrine\ORM\EntityRepository;
class UsrListEntryRepository extends EntityRepository
{
- /**
- * Get all lists entries matching a given User
- *
- * @param \User_Adapter $user
- * @param type $like
- */
- public function findUserList(\User_Adapter $user)
- {
- $dql = 'SELECT e FROM Entities\UsrListEntry e
+ /**
+ * Get all lists entries matching a given User
+ *
+ * @param \User_Adapter $user
+ * @param type $like
+ */
+ public function findUserList(\User_Adapter $user)
+ {
+ $dql = 'SELECT e FROM Entities\UsrListEntry e
WHERE e.usr_id = :usr_id';
- $params = array(
- 'usr_id' => $user->get_id(),
- );
+ $params = array(
+ 'usr_id' => $user->get_id(),
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
-
- public function findEntryByListAndEntryId(\Entities\UsrList $list, $entry_id)
- {
- $entry = $this->find($entry_id);
-
- if(!$entry)
- {
- throw new \Exception_NotFound('Entry not found');
+ return $query->getResult();
}
- /* @var $entry \Entities\UsrListEntry */
- if($entry->getList()->getId() != $list->getId())
+ public function findEntryByListAndEntryId(\Entities\UsrList $list, $entry_id)
{
- throw new \Exception_Forbidden('Entry mismatch list');
+ $entry = $this->find($entry_id);
+
+ if ( ! $entry) {
+ throw new \Exception_NotFound('Entry not found');
+ }
+
+ /* @var $entry \Entities\UsrListEntry */
+ if ($entry->getList()->getId() != $list->getId()) {
+ throw new \Exception_Forbidden('Entry mismatch list');
+ }
+
+ return $entry;
}
- return $entry;
- }
-
-
- public function findEntryByListAndUsrId(\Entities\UsrList $list, $usr_id)
- {
- $dql = 'SELECT e FROM Entities\UsrListEntry e
+ public function findEntryByListAndUsrId(\Entities\UsrList $list, $usr_id)
+ {
+ $dql = 'SELECT e FROM Entities\UsrListEntry e
JOIN e.list l
WHERE e.usr_id = :usr_id AND l.id = :list_id';
- $params = array(
- 'usr_id' => $usr_id,
- 'list_id' => $list->getId(),
- );
+ $params = array(
+ 'usr_id' => $usr_id,
+ 'list_id' => $list->getId(),
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- $entry = $query->getResult();
+ $entry = $query->getResult();
- if(!$entry)
- {
- throw new \Exception_NotFound('Entry not found');
+ if ( ! $entry) {
+ throw new \Exception_NotFound('Entry not found');
+ }
+
+ return $query->getSingleResult();
}
-
- return $query->getSingleResult();
- }
}
diff --git a/lib/Doctrine/Repositories/UsrListOwnerRepository.php b/lib/Doctrine/Repositories/UsrListOwnerRepository.php
index 789204c841..03356280ca 100644
--- a/lib/Doctrine/Repositories/UsrListOwnerRepository.php
+++ b/lib/Doctrine/Repositories/UsrListOwnerRepository.php
@@ -13,61 +13,57 @@ use Doctrine\ORM\EntityRepository;
class UsrListOwnerRepository extends EntityRepository
{
- /**
- *
- *
- * @param \Entities\UsrList $list
- * @param type $owner_id
- * @return \Entities\UsrList
- */
- public function findByListAndOwner(\Entities\UsrList $list, $owner_id)
- {
- $owner = $this->find($owner_id);
-
- /* @var $owner \Entities\UsrListOwner */
- if (null === $owner)
+ /**
+ *
+ *
+ * @param \Entities\UsrList $list
+ * @param type $owner_id
+ * @return \Entities\UsrList
+ */
+ public function findByListAndOwner(\Entities\UsrList $list, $owner_id)
{
- throw new \Exception_NotFound(_('Owner is not found'));
+ $owner = $this->find($owner_id);
+
+ /* @var $owner \Entities\UsrListOwner */
+ if (null === $owner) {
+ throw new \Exception_NotFound(_('Owner is not found'));
+ }
+
+ if ( ! $owner->getList()->getid() != $list->getId()) {
+ throw new \Exception_Forbidden(_('Owner and list mismatch'));
+ }
+
+ return $owner;
}
- if (!$owner->getList()->getid() != $list->getId())
+ /**
+ *
+ *
+ * @param \Entities\UsrList $list
+ * @param type $usr_id
+ * @return \Entities\UsrList
+ */
+ public function findByListAndUsrId(\Entities\UsrList $list, $usr_id)
{
- throw new \Exception_Forbidden(_('Owner and list mismatch'));
- }
-
- return $owner;
- }
-
- /**
- *
- *
- * @param \Entities\UsrList $list
- * @param type $usr_id
- * @return \Entities\UsrList
- */
- public function findByListAndUsrId(\Entities\UsrList $list, $usr_id)
- {
- $dql = 'SELECT o FROM Entities\UsrListOwner o
+ $dql = 'SELECT o FROM Entities\UsrListOwner o
JOIN o.list l
WHERE l.id = :list_id AND o.usr_id = :usr_id';
- $params = array(
- 'usr_id' => $usr_id,
- 'list_id' => $list->getId()
- );
+ $params = array(
+ 'usr_id' => $usr_id,
+ 'list_id' => $list->getId()
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- $owner = $query->getSingleResult();
+ $owner = $query->getSingleResult();
- /* @var $owner \Entities\UsrListOwner */
- if (null === $owner)
- {
- throw new \Exception_NotFound(_('Owner is not found'));
+ /* @var $owner \Entities\UsrListOwner */
+ if (null === $owner) {
+ throw new \Exception_NotFound(_('Owner is not found'));
+ }
+
+ return $owner;
}
-
- return $owner;
- }
-
}
diff --git a/lib/Doctrine/Repositories/UsrListRepository.php b/lib/Doctrine/Repositories/UsrListRepository.php
index a4f83dbd63..e4630859e1 100644
--- a/lib/Doctrine/Repositories/UsrListRepository.php
+++ b/lib/Doctrine/Repositories/UsrListRepository.php
@@ -12,75 +12,73 @@ use Doctrine\ORM\EntityRepository;
*/
class UsrListRepository extends EntityRepository
{
- /**
- * Get all lists readable for a given User
- *
- * @param \User_Adapter $user
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findUserLists(\User_Adapter $user)
- {
- $dql = 'SELECT l FROM Entities\UsrList l
+
+ /**
+ * Get all lists readable for a given User
+ *
+ * @param \User_Adapter $user
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findUserLists(\User_Adapter $user)
+ {
+ $dql = 'SELECT l FROM Entities\UsrList l
JOIN l.owners o
WHERE o.usr_id = :usr_id';
- $params = array(
- 'usr_id' => $user->get_id(),
- );
+ $params = array(
+ 'usr_id' => $user->get_id(),
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
- return $query->getResult();
- }
-
- /**
- *
- * @param \User_Adapter $user
- * @param type $list_id
- * @return \Entities\UsrList
- */
- public function findUserListByUserAndId(\User_Adapter $user, $list_id)
- {
- $list = $this->find($list_id);
-
- /* @var $basket \Entities\UsrList */
- if (null === $list)
- {
- throw new \Exception_NotFound(_('List is not found'));
+ return $query->getResult();
}
- if (!$list->hasAccess($user))
+ /**
+ *
+ * @param \User_Adapter $user
+ * @param type $list_id
+ * @return \Entities\UsrList
+ */
+ public function findUserListByUserAndId(\User_Adapter $user, $list_id)
{
- throw new \Exception_Forbidden(_('You have not access to this list'));
+ $list = $this->find($list_id);
+
+ /* @var $basket \Entities\UsrList */
+ if (null === $list) {
+ throw new \Exception_NotFound(_('List is not found'));
+ }
+
+ if ( ! $list->hasAccess($user)) {
+ throw new \Exception_Forbidden(_('You have not access to this list'));
+ }
+
+ return $list;
}
- return $list;
- }
-
- /**
- * Search for a UsrList like '' with a given value, for a user
- *
- * @param \User_Adapter $user
- * @param type $name
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function findUserListLike(\User_Adapter $user, $name)
- {
- $dql = 'SELECT l FROM Entities\UsrList l
+ /**
+ * Search for a UsrList like '' with a given value, for a user
+ *
+ * @param \User_Adapter $user
+ * @param type $name
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function findUserListLike(\User_Adapter $user, $name)
+ {
+ $dql = 'SELECT l FROM Entities\UsrList l
JOIN l.owners o
WHERE o.usr_id = :usr_id AND l.name LIKE :name';
- $params = array(
- 'usr_id' => $user->get_id(),
- 'name' => $name.'%'
- );
+ $params = array(
+ 'usr_id' => $user->get_id(),
+ 'name' => $name . '%'
+ );
- $query = $this->_em->createQuery($dql);
- $query->setParameters($params);
-
- return $query->getResult();
- }
+ $query = $this->_em->createQuery($dql);
+ $query->setParameters($params);
+ return $query->getResult();
+ }
}
diff --git a/lib/Doctrine/Types/Binary.php b/lib/Doctrine/Types/Binary.php
index 17debee9b4..ceb553174c 100644
--- a/lib/Doctrine/Types/Binary.php
+++ b/lib/Doctrine/Types/Binary.php
@@ -23,16 +23,15 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
class Binary extends Type
{
- const BINARY = 'binary';
+ const BINARY = 'binary';
- public function getName()
- {
- return static::BINARY;
- }
-
- public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
- {
- return $platform->getDoctrineTypeMapping('BINARY');
- }
+ public function getName()
+ {
+ return static::BINARY;
+ }
+ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
+ {
+ return $platform->getDoctrineTypeMapping('BINARY');
+ }
}
diff --git a/lib/Doctrine/Types/Blob.php b/lib/Doctrine/Types/Blob.php
index 9f6ead26d5..80edab0092 100644
--- a/lib/Doctrine/Types/Blob.php
+++ b/lib/Doctrine/Types/Blob.php
@@ -23,16 +23,15 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
class Blob extends Type
{
- const BLOB = 'blob';
+ const BLOB = 'blob';
- public function getName()
- {
- return static::BLOB;
- }
-
- public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
- {
- return $platform->getDoctrineTypeMapping('BLOB');
- }
+ public function getName()
+ {
+ return static::BLOB;
+ }
+ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
+ {
+ return $platform->getDoctrineTypeMapping('BLOB');
+ }
}
diff --git a/lib/Doctrine/Types/Enum.php b/lib/Doctrine/Types/Enum.php
index 6c9a51d4d9..53e02a2b9d 100644
--- a/lib/Doctrine/Types/Enum.php
+++ b/lib/Doctrine/Types/Enum.php
@@ -23,16 +23,15 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
class Enum extends Type
{
- const ENUM = 'enum';
+ const ENUM = 'enum';
- public function getName()
- {
- return static::ENUM;
- }
-
- public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
- {
- return $platform->getDoctrineTypeMapping('ENUM');
- }
+ public function getName()
+ {
+ return static::ENUM;
+ }
+ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
+ {
+ return $platform->getDoctrineTypeMapping('ENUM');
+ }
}
diff --git a/lib/Doctrine/Types/LongBlob.php b/lib/Doctrine/Types/LongBlob.php
index 6ac39ddb01..8b5a717898 100644
--- a/lib/Doctrine/Types/LongBlob.php
+++ b/lib/Doctrine/Types/LongBlob.php
@@ -23,16 +23,15 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
class LongBlob extends Type
{
- const LONGBLOB = 'longblob';
+ const LONGBLOB = 'longblob';
- public function getName()
- {
- return static::LONGBLOB;
- }
-
- public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
- {
- return $platform->getDoctrineTypeMapping('LONGBLOB');
- }
+ public function getName()
+ {
+ return static::LONGBLOB;
+ }
+ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
+ {
+ return $platform->getDoctrineTypeMapping('LONGBLOB');
+ }
}
diff --git a/lib/Doctrine/Types/VarBinary.php b/lib/Doctrine/Types/VarBinary.php
index b8796064ad..fbb7ba30eb 100644
--- a/lib/Doctrine/Types/VarBinary.php
+++ b/lib/Doctrine/Types/VarBinary.php
@@ -23,16 +23,15 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
class VarBinary extends Type
{
- const VARBINARY = 'varbinary';
+ const VARBINARY = 'varbinary';
- public function getName()
- {
- return static::VARBINARY;
- }
-
- public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
- {
- return $platform->getDoctrineTypeMapping('VARBINARY');
- }
+ public function getName()
+ {
+ return static::VARBINARY;
+ }
+ public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
+ {
+ return $platform->getDoctrineTypeMapping('VARBINARY');
+ }
}
diff --git a/lib/classes/ACL.class.php b/lib/classes/ACL.class.php
index 403ab425d5..c14b37c804 100644
--- a/lib/classes/ACL.class.php
+++ b/lib/classes/ACL.class.php
@@ -17,1217 +17,1133 @@
*/
class ACL implements cache_cacheableInterface
{
+ /**
+ *
+ * @var user
+ */
+ protected $user;
- /**
- *
- * @var user
- */
- protected $user;
+ /**
+ *
+ * @var Array
+ */
+ protected $_rights_sbas;
- /**
- *
- * @var Array
- */
- protected $_rights_sbas;
+ /**
+ *
+ * @var Array
+ */
+ protected $_rights_bas;
- /**
- *
- * @var Array
- */
- protected $_rights_bas;
+ /**
+ *
+ * @var Array
+ */
+ protected $_rights_records_document;
- /**
- *
- * @var Array
- */
- protected $_rights_records_document;
+ /**
+ *
+ * @var Array
+ */
+ protected $_rights_records_preview;
- /**
- *
- * @var Array
- */
- protected $_rights_records_preview;
+ /**
+ *
+ * @var Array
+ */
+ protected $_limited;
- /**
- *
- * @var Array
- */
- protected $_limited;
+ /**
+ *
+ * @var Array
+ */
+ protected $_global_rights = array(
+ 'taskmanager' => false,
+ 'manageusers' => false,
+ 'order' => false,
+ 'report' => false,
+ 'push' => false,
+ 'addrecord' => false,
+ 'modifyrecord' => false,
+ 'changestatus' => false,
+ 'doctools' => false,
+ 'deleterecord' => false,
+ 'addtoalbum' => false,
+ 'coll_modify_struct' => false,
+ 'coll_manage' => false,
+ 'order_master' => false,
+ 'bas_modif_th' => false,
+ 'bas_modify_struct' => false,
+ 'bas_manage' => false,
+ 'bas_chupub' => false,
+ 'candwnldpreview' => true,
+ 'candwnldhd' => true
+ );
- /**
- *
- * @var Array
- */
- protected $_global_rights = array(
- 'taskmanager' => false,
- 'manageusers' => false,
- 'order' => false,
- 'report' => false,
- 'push' => false,
- 'addrecord' => false,
- 'modifyrecord' => false,
- 'changestatus' => false,
- 'doctools' => false,
- 'deleterecord' => false,
- 'addtoalbum' => false,
- 'coll_modify_struct' => false,
- 'coll_manage' => false,
- 'order_master' => false,
- 'bas_modif_th' => false,
- 'bas_modify_struct' => false,
- 'bas_manage' => false,
- 'bas_chupub' => false,
- 'candwnldpreview' => true,
- 'candwnldhd' => true
- );
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ const CACHE_RIGHTS_BAS = 'rights_bas';
+ const CACHE_LIMITS_BAS = 'limits_bas';
+ const CACHE_RIGHTS_SBAS = 'rights_sbas';
+ const CACHE_RIGHTS_RECORDS = 'rights_records';
+ const CACHE_GLOBAL_RIGHTS = 'global_rights';
+ const GRANT_ACTION_PUSH = 'push';
+ const GRANT_ACTION_VALIDATE = 'validate';
- const CACHE_RIGHTS_BAS = 'rights_bas';
- const CACHE_LIMITS_BAS = 'limits_bas';
- const CACHE_RIGHTS_SBAS = 'rights_sbas';
- const CACHE_RIGHTS_RECORDS = 'rights_records';
- const CACHE_GLOBAL_RIGHTS = 'global_rights';
+ /**
+ * Constructor
+ *
+ * @param User_Interface $user
+ * @return ACL
+ */
+ public function __construct(User_Interface $user, appbox &$appbox)
+ {
+ $this->user = $user;
+ $this->appbox = $appbox;
- const GRANT_ACTION_PUSH = 'push';
- const GRANT_ACTION_VALIDATE = 'validate';
+ return $this;
+ }
- /**
- * Constructor
- *
- * @param User_Interface $user
- * @return ACL
- */
- public function __construct(User_Interface $user, appbox &$appbox)
- {
- $this->user = $user;
- $this->appbox = $appbox;
+ /**
+ * Check if a hd grant has been received for a record
+ *
+ * @param record_Interface $record
+ * @return boolean
+ */
+ public function has_hd_grant(record_Interface $record)
+ {
- return $this;
- }
+ $this->load_hd_grant();
- /**
- * Check if a hd grant has been received for a record
- *
- * @param record_Interface $record
- * @return boolean
- */
- public function has_hd_grant(record_Interface $record)
- {
+ $key = $record->get_serialize_key();
- $this->load_hd_grant();
+ if (array_key_exists($key, $this->_rights_records_document))
+ return true;
- $key = $record->get_serialize_key();
+ return false;
+ }
- if (array_key_exists($key, $this->_rights_records_document))
-
- return true;
-
- return false;
- }
-
- public function grant_hd_on(record_adapter $record, User_Adapter $pusher, $action)
- {
- $sql = 'REPLACE INTO records_rights
+ public function grant_hd_on(record_adapter $record, User_Adapter $pusher, $action)
+ {
+ $sql = 'REPLACE INTO records_rights
(id, usr_id, sbas_id, record_id, document, `case`, pusher_usr_id)
VALUES
(null, :usr_id, :sbas_id, :record_id, 1, :case, :pusher)';
- $params = array(
- ':usr_id' => $this->user->get_id()
- , ':sbas_id' => $record->get_sbas_id()
- , ':record_id' => $record->get_record_id()
- , ':case' => $action
- , ':pusher' => $pusher->get_id()
- );
+ $params = array(
+ ':usr_id' => $this->user->get_id()
+ , ':sbas_id' => $record->get_sbas_id()
+ , ':record_id' => $record->get_record_id()
+ , ':case' => $action
+ , ':pusher' => $pusher->get_id()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->delete_data_from_cache(self::CACHE_RIGHTS_RECORDS);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_RECORDS);
- return $this;
- }
+ return $this;
+ }
- public function grant_preview_on(record_adapter $record, User_Adapter $pusher, $action)
- {
- $sql = 'REPLACE INTO records_rights
+ public function grant_preview_on(record_adapter $record, User_Adapter $pusher, $action)
+ {
+ $sql = 'REPLACE INTO records_rights
(id, usr_id, sbas_id, record_id, preview, `case`, pusher_usr_id)
VALUES
(null, :usr_id, :sbas_id, :record_id, 1, :case, :pusher)';
- $params = array(
- ':usr_id' => $this->user->get_id()
- , ':sbas_id' => $record->get_sbas_id()
- , ':record_id' => $record->get_record_id()
- , ':case' => $action
- , ':pusher' => $pusher->get_id()
- );
+ $params = array(
+ ':usr_id' => $this->user->get_id()
+ , ':sbas_id' => $record->get_sbas_id()
+ , ':record_id' => $record->get_record_id()
+ , ':case' => $action
+ , ':pusher' => $pusher->get_id()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->delete_data_from_cache(self::CACHE_RIGHTS_RECORDS);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_RECORDS);
- return $this;
- }
-
- /**
- * Check if a hd grant has been received for a record
- *
- * @param record_Interface $record
- * @return boolean
- */
- public function has_preview_grant(record_Interface $record)
- {
-
- $this->load_hd_grant();
-
- $key = $record->get_serialize_key();
-
- if (array_key_exists($key, $this->_rights_records_preview))
-
- return true;
-
- return false;
- }
-
- public function has_access_to_subdef(record_Interface $record, $subdef_name)
- {
- try
- {
- $subdef_class = $record->get_databox()->get_subdef_structure()
- ->get_subdef($record->get_type(), $subdef_name)
- ->get_class();
+ return $this;
}
- catch (Exception $e)
- {
- return false;
- }
- $granted = false;
-
- if ($subdef_class == databox_subdef::CLASS_THUMBNAIL)
- {
- $granted = true;
- }
- elseif ($subdef_class == databox_subdef::CLASS_PREVIEW && $this->has_right_on_base($record->get_base_id(), 'candwnldpreview'))
- {
- $granted = true;
- }
- elseif ($subdef_class == databox_subdef::CLASS_PREVIEW && $this->has_preview_grant($record))
- {
- $granted = true;
- }
- elseif ($subdef_class == databox_subdef::CLASS_DOCUMENT && $this->has_right_on_base($record->get_base_id(), 'candwnldhd'))
- {
- $granted = true;
- }
- elseif ($subdef_class == databox_subdef::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record))
- {
- $granted = true;
- }
-
- return $granted;
- }
-
- /**
- * Apply a template on user
- *
- * @param User_Interface $template_user
- * @param array $base_ids
- * @return ACL
- */
- public function apply_model(User_Interface $template_user, Array $base_ids)
- {
- if (count($base_ids) == 0)
-
- return $this;
-
- $sbas_ids = array();
-
- foreach ($base_ids as $base_id)
- {
- $sbas_ids[] = phrasea::sbasFromBas($base_id);
- }
-
- $sbas_ids = array_unique($sbas_ids);
-
- $sbas_rights = array('bas_manage', 'bas_modify_struct', 'bas_modif_th', 'bas_chupub');
-
- $sbas_to_acces = array();
- $rights_to_give = array();
-
- foreach ($template_user->ACL()->get_granted_sbas() as $databox)
- {
- $sbas_id = $databox->get_sbas_id();
-
- if (!in_array($sbas_id, $sbas_ids))
- continue;
-
-
- if (!$this->has_access_to_sbas($sbas_id))
- {
- $sbas_to_acces[] = $sbas_id;
- }
-
- foreach ($sbas_rights as $right)
- {
- if ($template_user->ACL()->has_right_on_sbas($sbas_id, $right))
- {
- $rights_to_give[$sbas_id][$right] = '1';
- }
- }
- }
-
- $this->give_access_to_sbas($sbas_to_acces);
-
- foreach ($rights_to_give as $sbas_id => $rights)
- {
- $this->update_rights_to_sbas($sbas_id, $rights);
- }
-
- $bas_rights = array('canputinalbum', 'candwnldhd'
- , 'candwnldpreview', 'cancmd'
- , 'canadmin', 'actif', 'canreport', 'canpush'
- , 'canaddrecord', 'canmodifrecord', 'candeleterecord'
- , 'chgstatus', 'imgtools'
- , 'manage', 'modify_struct'
- , 'nowatermark', 'order_master'
- );
-
- $bas_to_acces = $masks_to_give = $rights_to_give = array();
/**
- * map masks (and+xor) of template to masks to apply to user on base
- * (and_and, and_or, xor_and, xor_or)
+ * Check if a hd grant has been received for a record
+ *
+ * @param record_Interface $record
+ * @return boolean
*/
- $sbmap = array(
- '00' => array('aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'),
- '01' => array('aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'),
- '10' => array('aa' => '1', 'ao' => '1', 'xa' => '0', 'xo' => '0'),
- '11' => array('aa' => '1', 'ao' => '1', 'xa' => '1', 'xo' => '1')
- );
-
- foreach ($template_user->ACL()->get_granted_base() as $collection)
+ public function has_preview_grant(record_Interface $record)
{
- $base_id = $collection->get_base_id();
- if (!in_array($base_id, $base_ids))
- continue;
+ $this->load_hd_grant();
- if (!$this->has_access_to_base($base_id))
- {
- $bas_to_acces[] = $base_id;
- }
+ $key = $record->get_serialize_key();
- foreach ($bas_rights as $right)
- {
- if ($template_user->ACL()->has_right_on_base($base_id, $right))
- {
- $rights_to_give[$base_id][$right] = '1';
+ if (array_key_exists($key, $this->_rights_records_preview))
+ return true;
+
+ return false;
+ }
+
+ public function has_access_to_subdef(record_Interface $record, $subdef_name)
+ {
+ try {
+ $subdef_class = $record->get_databox()->get_subdef_structure()
+ ->get_subdef($record->get_type(), $subdef_name)
+ ->get_class();
+ } catch (Exception $e) {
+ return false;
}
- }
+ $granted = false;
- $mask_and = $template_user->ACL()->get_mask_and($base_id);
- $mask_xor = $template_user->ACL()->get_mask_xor($base_id);
-
- $mask_and = ctype_digit($mask_and) ? $mask_and : '0';
- $mask_xor = ctype_digit($mask_xor) ? $mask_xor : '0';
-
-
- /**
- * apply sb is substractive
- */
- $mand = substr(
- str_repeat('0', 64)
- . databox_status::dec2bin($mask_and)
- , -64
- );
- $mxor = substr(
- str_repeat('0', 64)
- . databox_status::dec2bin($mask_xor)
- , -64
- );
- $m = array('aa' => '', 'ao' => '', 'xa' => '', 'xo' => '');
- for ($i = 0; $i < 64; $i++)
- {
- $ax = $mand[$i] . $mxor[$i];
-
- foreach ($m as $k => $v)
- {
- $m[$k] .= $sbmap[$ax][$k];
+ if ($subdef_class == databox_subdef::CLASS_THUMBNAIL) {
+ $granted = true;
+ } elseif ($subdef_class == databox_subdef::CLASS_PREVIEW && $this->has_right_on_base($record->get_base_id(), 'candwnldpreview')) {
+ $granted = true;
+ } elseif ($subdef_class == databox_subdef::CLASS_PREVIEW && $this->has_preview_grant($record)) {
+ $granted = true;
+ } elseif ($subdef_class == databox_subdef::CLASS_DOCUMENT && $this->has_right_on_base($record->get_base_id(), 'candwnldhd')) {
+ $granted = true;
+ } elseif ($subdef_class == databox_subdef::CLASS_DOCUMENT && $user->ACL()->has_hd_grant($record)) {
+ $granted = true;
}
- }
- $masks_to_give[$base_id] = array(
- 'aa' => $m['aa']
- , 'ao' => $m['ao']
- , 'xa' => $m['xa']
- , 'xo' => $m['xo']
- );
+ return $granted;
}
- $this->give_access_to_base($bas_to_acces);
-
- foreach ($masks_to_give as $base_id => $mask)
+ /**
+ * Apply a template on user
+ *
+ * @param User_Interface $template_user
+ * @param array $base_ids
+ * @return ACL
+ */
+ public function apply_model(User_Interface $template_user, Array $base_ids)
{
- $this->set_masks_on_base($base_id, $mask['aa'], $mask['ao'], $mask['xa'], $mask['xo']);
- }
+ if (count($base_ids) == 0)
+ return $this;
- foreach ($rights_to_give as $base_id => $rights)
- {
- $this->update_rights_to_base($base_id, $rights);
- }
+ $sbas_ids = array();
- $this->user->set_last_template($template_user);
-
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_phantom()
- {
- return count($this->get_granted_base()) === 0;
- }
-
- /**
- *
- * @param int $base_id
- * @param string $right
- * @return boolean
- */
- public function has_right_on_base($base_id, $right)
- {
- $this->load_rights_bas();
-
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- if ($this->is_limited($base_id))
- {
- return false;
- }
-
- if (!isset($this->_rights_bas[$base_id][$right]))
- throw new Exception('right ' . $right . ' does not exists');
-
- return ($this->_rights_bas[$base_id][$right] === true);
- }
-
- /**
- *
- * @param $option
- * @return
- */
- public function get_cache_key($option = null)
- {
- return '_ACL_' . $this->user->get_id() . ($option ? '_' . $option : '');
- }
-
- /**
- *
- * @param $option
- * @return
- */
- public function delete_data_from_cache($option = null)
- {
- switch ($option)
- {
- case self::CACHE_GLOBAL_RIGHTS:
- $this->_global_rights = null;
- break;
- case self::CACHE_RIGHTS_BAS:
- case self::CACHE_LIMITS_BAS:
- $this->_rights_bas = null;
- $this->_limited = null;
- break;
- case self::CACHE_RIGHTS_RECORDS:
- $this->_rights_records_document = null;
- $this->_rights_records_preview = null;
- break;
- case self::CACHE_RIGHTS_SBAS:
- $this->_rights_sbas = null;
- break;
- default:
- break;
- }
-
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
-
- /**
- *
- * @param $option
- * @return
- */
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
-
- /**
- *
- * @param $value
- * @param $option
- * @param $duration
- * @return
- */
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
-
- /**
- * Return true if user is restricted in download on the collection
- *
- * @param int $base_id
- * @return boolean
- */
- public function is_restricted_download($base_id)
- {
- $this->load_rights_bas();
-
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- return $this->_rights_bas[$base_id]['restrict_dwnld'];
- }
-
- /**
- * Return the number of remaining downloads on the collection
- *
- * @param int $base_id
- * @return int
- */
- public function remaining_download($base_id)
- {
- $this->load_rights_bas();
-
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- return (int) $this->_rights_bas[$base_id]['remain_dwnld'];
- }
-
- /**
- * Remove n download from the remainings
- *
- * @param int $base_id
- * @param int $n
- * @return ACL
- */
- public function remove_remaining($base_id, $n = 1)
- {
- $this->load_rights_bas();
-
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- $this->_rights_bas[$base_id]['remain_dwnld'] =
- $this->_rights_bas[$base_id]['remain_dwnld'] - (int) $n;
- $v = $this->_rights_bas[$base_id]['remain_dwnld'];
- $this->_rights_bas[$base_id]['remain_dwnld'] =
- $this->_rights_bas[$base_id]['remain_dwnld'] < 0 ? 0 : $v;
-
- return $this;
- }
-
- /**
- * Check if the user has the right, at least on one collection
- *
- * @param string $right
- * @return boolean
- */
- public function has_right($right)
- {
- $this->load_global_rights();
-
- if (!isset($this->_global_rights[$right]))
- throw new Exception('This right does not exists');
-
- return $this->_global_rights[$right];
- }
-
- /**
- * Check if the user has the required right on a database
- *
- * @param $sbas_id
- * @param $right
- * @return
- */
- public function has_right_on_sbas($sbas_id, $right)
- {
- $this->load_rights_sbas();
-
- if (!isset($this->_rights_sbas[$sbas_id]))
-
- return false;
-
- if (!isset($this->_rights_sbas[$sbas_id][$right]))
- throw new Exception('This right does not exists');
-
- if ($this->_rights_sbas[$sbas_id][$right] === true)
-
- return true;
-
- return false;
- }
-
- /**
- * Retrieve mask AND for user on specified base_id
- *
- * @param int $base_id
- * @return string
- */
- public function get_mask_and($base_id)
- {
- $this->load_rights_bas();
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- return $this->_rights_bas[$base_id]['mask_and'];
- }
-
- /**
- * Retrieve mask XOR for user on specified base_id
- *
- * @param int $base_id
- * @return string
- */
- public function get_mask_xor($base_id)
- {
- $this->load_rights_bas();
- if (!$this->has_access_to_base($base_id))
-
- return false;
-
- return $this->_rights_bas[$base_id]['mask_xor'];
- }
-
- /**
- * Return true if access to base_id is granted
- *
- * @param int $base_id
- * @return boolean
- */
- public function has_access_to_base($base_id)
- {
- $this->load_rights_bas();
-
- return (isset($this->_rights_bas[$base_id]) &&
- $this->_rights_bas[$base_id]['actif'] === true);
- }
-
- /**
- * Return true if access to sbas_id is granted
- *
- * @param int $sbas_id
- * @return boolean
- */
- public function has_access_to_sbas($sbas_id)
- {
- $this->load_rights_sbas();
-
- return (isset($this->_rights_sbas[$sbas_id]));
- }
-
- /**
- * Return an array of base_id which are granted, with
- * optionnal filter by rights
- *
- * @param Array $rights
- * @return Array
- */
- public function get_granted_base(Array $rights = array(), array $sbas_ids = null)
- {
- $this->load_rights_bas();
- $ret = array();
-
- foreach($this->appbox->get_databoxes() as $databox)
- {
- if ($sbas_ids && !in_array($databox->get_sbas_id(), $sbas_ids))
- {
- continue;
- }
-
- foreach ($databox->get_collections() as $collection)
- {
- $continue = false;
-
- if(!array_key_exists($collection->get_base_id(), $this->_rights_bas))
- continue;
-
- $base_id = $collection->get_base_id();
- $datas = $this->_rights_bas[$base_id];
-
- foreach ($rights as $right)
- {
- if (!$this->has_right_on_base($base_id, $right))
- {
- $continue = true;
- break;
- }
+ foreach ($base_ids as $base_id) {
+ $sbas_ids[] = phrasea::sbasFromBas($base_id);
}
- if ($continue || $this->is_limited($base_id))
- continue;
- try
- {
- $ret[$base_id] = collection::get_from_base_id($base_id);
+ $sbas_ids = array_unique($sbas_ids);
+
+ $sbas_rights = array('bas_manage', 'bas_modify_struct', 'bas_modif_th', 'bas_chupub');
+
+ $sbas_to_acces = array();
+ $rights_to_give = array();
+
+ foreach ($template_user->ACL()->get_granted_sbas() as $databox) {
+ $sbas_id = $databox->get_sbas_id();
+
+ if ( ! in_array($sbas_id, $sbas_ids))
+ continue;
+
+
+ if ( ! $this->has_access_to_sbas($sbas_id)) {
+ $sbas_to_acces[] = $sbas_id;
+ }
+
+ foreach ($sbas_rights as $right) {
+ if ($template_user->ACL()->has_right_on_sbas($sbas_id, $right)) {
+ $rights_to_give[$sbas_id][$right] = '1';
+ }
+ }
}
- catch (Exception $e)
- {
+
+ $this->give_access_to_sbas($sbas_to_acces);
+
+ foreach ($rights_to_give as $sbas_id => $rights) {
+ $this->update_rights_to_sbas($sbas_id, $rights);
+ }
+
+ $bas_rights = array('canputinalbum', 'candwnldhd'
+ , 'candwnldpreview', 'cancmd'
+ , 'canadmin', 'actif', 'canreport', 'canpush'
+ , 'canaddrecord', 'canmodifrecord', 'candeleterecord'
+ , 'chgstatus', 'imgtools'
+ , 'manage', 'modify_struct'
+ , 'nowatermark', 'order_master'
+ );
+
+ $bas_to_acces = $masks_to_give = $rights_to_give = array();
+
+ /**
+ * map masks (and+xor) of template to masks to apply to user on base
+ * (and_and, and_or, xor_and, xor_or)
+ */
+ $sbmap = array(
+ '00' => array('aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'),
+ '01' => array('aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'),
+ '10' => array('aa' => '1', 'ao' => '1', 'xa' => '0', 'xo' => '0'),
+ '11' => array('aa' => '1', 'ao' => '1', 'xa' => '1', 'xo' => '1')
+ );
+
+ foreach ($template_user->ACL()->get_granted_base() as $collection) {
+ $base_id = $collection->get_base_id();
+
+ if ( ! in_array($base_id, $base_ids))
+ continue;
+
+ if ( ! $this->has_access_to_base($base_id)) {
+ $bas_to_acces[] = $base_id;
+ }
+
+ foreach ($bas_rights as $right) {
+ if ($template_user->ACL()->has_right_on_base($base_id, $right)) {
+ $rights_to_give[$base_id][$right] = '1';
+ }
+ }
+
+ $mask_and = $template_user->ACL()->get_mask_and($base_id);
+ $mask_xor = $template_user->ACL()->get_mask_xor($base_id);
+
+ $mask_and = ctype_digit($mask_and) ? $mask_and : '0';
+ $mask_xor = ctype_digit($mask_xor) ? $mask_xor : '0';
+
+
+ /**
+ * apply sb is substractive
+ */
+ $mand = substr(
+ str_repeat('0', 64)
+ . databox_status::dec2bin($mask_and)
+ , -64
+ );
+ $mxor = substr(
+ str_repeat('0', 64)
+ . databox_status::dec2bin($mask_xor)
+ , -64
+ );
+ $m = array('aa' => '', 'ao' => '', 'xa' => '', 'xo' => '');
+ for ($i = 0; $i < 64; $i ++ ) {
+ $ax = $mand[$i] . $mxor[$i];
+
+ foreach ($m as $k => $v) {
+ $m[$k] .= $sbmap[$ax][$k];
+ }
+ }
+
+ $masks_to_give[$base_id] = array(
+ 'aa' => $m['aa']
+ , 'ao' => $m['ao']
+ , 'xa' => $m['xa']
+ , 'xo' => $m['xo']
+ );
+ }
+
+ $this->give_access_to_base($bas_to_acces);
+
+ foreach ($masks_to_give as $base_id => $mask) {
+ $this->set_masks_on_base($base_id, $mask['aa'], $mask['ao'], $mask['xa'], $mask['xo']);
+ }
+
+ foreach ($rights_to_give as $base_id => $rights) {
+ $this->update_rights_to_base($base_id, $rights);
+ }
+
+ $this->user->set_last_template($template_user);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_phantom()
+ {
+ return count($this->get_granted_base()) === 0;
+ }
+
+ /**
+ *
+ * @param int $base_id
+ * @param string $right
+ * @return boolean
+ */
+ public function has_right_on_base($base_id, $right)
+ {
+ $this->load_rights_bas();
+
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ if ($this->is_limited($base_id)) {
+ return false;
+ }
+
+ if ( ! isset($this->_rights_bas[$base_id][$right]))
+ throw new Exception('right ' . $right . ' does not exists');
+
+ return ($this->_rights_bas[$base_id][$right] === true);
+ }
+
+ /**
+ *
+ * @param $option
+ * @return
+ */
+ public function get_cache_key($option = null)
+ {
+ return '_ACL_' . $this->user->get_id() . ($option ? '_' . $option : '');
+ }
+
+ /**
+ *
+ * @param $option
+ * @return
+ */
+ public function delete_data_from_cache($option = null)
+ {
+ switch ($option) {
+ case self::CACHE_GLOBAL_RIGHTS:
+ $this->_global_rights = null;
+ break;
+ case self::CACHE_RIGHTS_BAS:
+ case self::CACHE_LIMITS_BAS:
+ $this->_rights_bas = null;
+ $this->_limited = null;
+ break;
+ case self::CACHE_RIGHTS_RECORDS:
+ $this->_rights_records_document = null;
+ $this->_rights_records_preview = null;
+ break;
+ case self::CACHE_RIGHTS_SBAS:
+ $this->_rights_sbas = null;
+ break;
+ default:
+ break;
+ }
+
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
+
+ /**
+ *
+ * @param $option
+ * @return
+ */
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
+
+ /**
+ *
+ * @param $value
+ * @param $option
+ * @param $duration
+ * @return
+ */
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+
+ /**
+ * Return true if user is restricted in download on the collection
+ *
+ * @param int $base_id
+ * @return boolean
+ */
+ public function is_restricted_download($base_id)
+ {
+ $this->load_rights_bas();
+
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ return $this->_rights_bas[$base_id]['restrict_dwnld'];
+ }
+
+ /**
+ * Return the number of remaining downloads on the collection
+ *
+ * @param int $base_id
+ * @return int
+ */
+ public function remaining_download($base_id)
+ {
+ $this->load_rights_bas();
+
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ return (int) $this->_rights_bas[$base_id]['remain_dwnld'];
+ }
+
+ /**
+ * Remove n download from the remainings
+ *
+ * @param int $base_id
+ * @param int $n
+ * @return ACL
+ */
+ public function remove_remaining($base_id, $n = 1)
+ {
+ $this->load_rights_bas();
+
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ $this->_rights_bas[$base_id]['remain_dwnld'] =
+ $this->_rights_bas[$base_id]['remain_dwnld'] - (int) $n;
+ $v = $this->_rights_bas[$base_id]['remain_dwnld'];
+ $this->_rights_bas[$base_id]['remain_dwnld'] =
+ $this->_rights_bas[$base_id]['remain_dwnld'] < 0 ? 0 : $v;
+
+ return $this;
+ }
+
+ /**
+ * Check if the user has the right, at least on one collection
+ *
+ * @param string $right
+ * @return boolean
+ */
+ public function has_right($right)
+ {
+ $this->load_global_rights();
+
+ if ( ! isset($this->_global_rights[$right]))
+ throw new Exception('This right does not exists');
+
+ return $this->_global_rights[$right];
+ }
+
+ /**
+ * Check if the user has the required right on a database
+ *
+ * @param $sbas_id
+ * @param $right
+ * @return
+ */
+ public function has_right_on_sbas($sbas_id, $right)
+ {
+ $this->load_rights_sbas();
+
+ if ( ! isset($this->_rights_sbas[$sbas_id]))
+ return false;
+
+ if ( ! isset($this->_rights_sbas[$sbas_id][$right]))
+ throw new Exception('This right does not exists');
+
+ if ($this->_rights_sbas[$sbas_id][$right] === true)
+ return true;
+
+ return false;
+ }
+
+ /**
+ * Retrieve mask AND for user on specified base_id
+ *
+ * @param int $base_id
+ * @return string
+ */
+ public function get_mask_and($base_id)
+ {
+ $this->load_rights_bas();
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ return $this->_rights_bas[$base_id]['mask_and'];
+ }
+
+ /**
+ * Retrieve mask XOR for user on specified base_id
+ *
+ * @param int $base_id
+ * @return string
+ */
+ public function get_mask_xor($base_id)
+ {
+ $this->load_rights_bas();
+ if ( ! $this->has_access_to_base($base_id))
+ return false;
+
+ return $this->_rights_bas[$base_id]['mask_xor'];
+ }
+
+ /**
+ * Return true if access to base_id is granted
+ *
+ * @param int $base_id
+ * @return boolean
+ */
+ public function has_access_to_base($base_id)
+ {
+ $this->load_rights_bas();
+
+ return (isset($this->_rights_bas[$base_id]) &&
+ $this->_rights_bas[$base_id]['actif'] === true);
+ }
+
+ /**
+ * Return true if access to sbas_id is granted
+ *
+ * @param int $sbas_id
+ * @return boolean
+ */
+ public function has_access_to_sbas($sbas_id)
+ {
+ $this->load_rights_sbas();
+
+ return (isset($this->_rights_sbas[$sbas_id]));
+ }
+
+ /**
+ * Return an array of base_id which are granted, with
+ * optionnal filter by rights
+ *
+ * @param Array $rights
+ * @return Array
+ */
+ public function get_granted_base(Array $rights = array(), array $sbas_ids = null)
+ {
+ $this->load_rights_bas();
+ $ret = array();
+
+ foreach ($this->appbox->get_databoxes() as $databox) {
+ if ($sbas_ids && ! in_array($databox->get_sbas_id(), $sbas_ids)) {
+ continue;
+ }
+
+ foreach ($databox->get_collections() as $collection) {
+ $continue = false;
+
+ if ( ! array_key_exists($collection->get_base_id(), $this->_rights_bas))
+ continue;
+
+ $base_id = $collection->get_base_id();
+ $datas = $this->_rights_bas[$base_id];
+
+ foreach ($rights as $right) {
+ if ( ! $this->has_right_on_base($base_id, $right)) {
+ $continue = true;
+ break;
+ }
+ }
+ if ($continue || $this->is_limited($base_id))
+ continue;
+
+ try {
+ $ret[$base_id] = collection::get_from_base_id($base_id);
+ } catch (Exception $e) {
+
+ }
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Return an array of sbas_id which are granted, with
+ * optionnal filter by rights
+ *
+ * @param Array $rights
+ * @return Array
+ */
+ public function get_granted_sbas($rights = array())
+ {
+ if (is_string($rights))
+ $rights = array($rights);
+
+ assert(is_array($rights));
+
+ $this->load_rights_sbas();
+
+ $ret = array();
+
+ foreach ($this->_rights_sbas as $sbas_id => $datas) {
+ $continue = false;
+
+ foreach ($rights as $right) {
+ if ( ! $this->has_right_on_sbas($sbas_id, $right)) {
+ $continue = true;
+ break;
+ }
+ }
+ if ($continue)
+ continue;
+
+ try {
+ $ret[$sbas_id] = databox::get_instance((int) $sbas_id);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Load if needed the elements which have a HD grant
+ *
+ * @return Array
+ */
+ protected function load_hd_grant()
+ {
+
+ if ($this->_rights_records_preview)
+ return $this;
+
+ try {
+ $tmp_rights = $this->get_data_from_cache(self::CACHE_RIGHTS_RECORDS);
+ $this->_rights_records_preview = $tmp_rights['preview'];
+ $this->_rights_records_document = $tmp_rights['document'];
+
+ return $this;
+ } catch (Exception $e) {
}
- }
- }
-
- return $ret;
- }
-
- /**
- * Return an array of sbas_id which are granted, with
- * optionnal filter by rights
- *
- * @param Array $rights
- * @return Array
- */
- public function get_granted_sbas($rights = array())
- {
- if (is_string($rights))
- $rights = array($rights);
-
- assert(is_array($rights));
-
- $this->load_rights_sbas();
-
- $ret = array();
-
- foreach ($this->_rights_sbas as $sbas_id => $datas)
- {
- $continue = false;
-
- foreach ($rights as $right)
- {
- if (!$this->has_right_on_sbas($sbas_id, $right))
- {
- $continue = true;
- break;
- }
- }
- if ($continue)
- continue;
-
- try
- {
- $ret[$sbas_id] = databox::get_instance((int) $sbas_id);
- }
- catch (Exception $e)
- {
-
- }
- }
-
- return $ret;
- }
-
- /**
- * Load if needed the elements which have a HD grant
- *
- * @return Array
- */
- protected function load_hd_grant()
- {
-
- if ($this->_rights_records_preview)
-
- return $this;
-
- try
- {
- $tmp_rights = $this->get_data_from_cache(self::CACHE_RIGHTS_RECORDS);
- $this->_rights_records_preview = $tmp_rights['preview'];
- $this->_rights_records_document = $tmp_rights['document'];
-
- return $this;
- }
- catch (Exception $e)
- {
-
- }
- $sql = 'SELECT sbas_id, record_id, preview, document
+ $sql = 'SELECT sbas_id, record_id, preview, document
FROM records_rights WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
- $this->_rights_records_preview = array();
- $this->_rights_records_document = array();
+ $this->_rights_records_preview = array();
+ $this->_rights_records_document = array();
- foreach ($rs as $row)
- {
- $currentid = $row["sbas_id"] . "_" . $row["record_id"];
- if ($row['document'] == '1')
- $this->_rights_records_document[$currentid] = $currentid;
- $this->_rights_records_preview[$currentid] = $currentid;
+ foreach ($rs as $row) {
+ $currentid = $row["sbas_id"] . "_" . $row["record_id"];
+ if ($row['document'] == '1')
+ $this->_rights_records_document[$currentid] = $currentid;
+ $this->_rights_records_preview[$currentid] = $currentid;
+ }
+
+ $datas = array(
+ 'preview' => $this->_rights_records_preview
+ , 'document' => $this->_rights_records_document
+ );
+
+ $this->set_data_to_cache($datas, self::CACHE_RIGHTS_RECORDS);
+
+ return $this;
}
- $datas = array(
- 'preview' => $this->_rights_records_preview
- , 'document' => $this->_rights_records_document
- );
-
- $this->set_data_to_cache($datas, self::CACHE_RIGHTS_RECORDS);
-
- return $this;
- }
-
- /**
- * Loads rights of specified user for all sbas
- *
- * @return ACL
- */
- protected function load_rights_sbas()
- {
-
- if ($this->_rights_sbas && $this->_global_rights)
-
- return $this;
-
- try
- {
- $this->_rights_sbas = $this->get_data_from_cache(self::CACHE_RIGHTS_SBAS);
- $this->_global_rights = $this->get_data_from_cache(self::CACHE_GLOBAL_RIGHTS);
-
- return $this;
- }
- catch (Exception $e)
+ /**
+ * Loads rights of specified user for all sbas
+ *
+ * @return ACL
+ */
+ protected function load_rights_sbas()
{
- }
+ if ($this->_rights_sbas && $this->_global_rights)
+ return $this;
- $sql = 'SELECT sbasusr.* FROM sbasusr, sbas
+ try {
+ $this->_rights_sbas = $this->get_data_from_cache(self::CACHE_RIGHTS_SBAS);
+ $this->_global_rights = $this->get_data_from_cache(self::CACHE_GLOBAL_RIGHTS);
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT sbasusr.* FROM sbasusr, sbas
WHERE usr_id= :usr_id
AND sbas.sbas_id = sbasusr.sbas_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->_rights_sbas = array();
+ $this->_rights_sbas = array();
- $this->_global_rights['bas_modif_th'] = false;
- $this->_global_rights['bas_modify_struct'] = false;
- $this->_global_rights['bas_manage'] = false;
- $this->_global_rights['bas_chupub'] = false;
+ $this->_global_rights['bas_modif_th'] = false;
+ $this->_global_rights['bas_modify_struct'] = false;
+ $this->_global_rights['bas_manage'] = false;
+ $this->_global_rights['bas_chupub'] = false;
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
- if ($row['bas_modif_th'] == '1')
- $this->_global_rights['bas_modif_th'] = true;
- if ($row['bas_modify_struct'] == '1')
- $this->_global_rights['bas_modify_struct'] = true;
- if ($row['bas_manage'] == '1')
- $this->_global_rights['bas_manage'] = true;
- if ($row['bas_chupub'] == '1')
- $this->_global_rights['bas_chupub'] = true;
+ if ($row['bas_modif_th'] == '1')
+ $this->_global_rights['bas_modif_th'] = true;
+ if ($row['bas_modify_struct'] == '1')
+ $this->_global_rights['bas_modify_struct'] = true;
+ if ($row['bas_manage'] == '1')
+ $this->_global_rights['bas_manage'] = true;
+ if ($row['bas_chupub'] == '1')
+ $this->_global_rights['bas_chupub'] = true;
- $this->_rights_sbas[$row['sbas_id']]['bas_modify_struct'] = ($row['bas_modify_struct'] == '1');
- $this->_rights_sbas[$row['sbas_id']]['bas_manage'] = ($row['bas_manage'] == '1');
- $this->_rights_sbas[$row['sbas_id']]['bas_chupub'] = ($row['bas_chupub'] == '1');
- $this->_rights_sbas[$row['sbas_id']]['bas_modif_th'] = ($row['bas_modif_th'] == '1');
- }
- $this->set_data_to_cache($this->_rights_sbas, self::CACHE_RIGHTS_SBAS);
- $this->set_data_to_cache($this->_global_rights, self::CACHE_GLOBAL_RIGHTS);
-
- return $this;
- }
-
- /**
- * Loads rights of specified user for all bas
- *
- * @return ACL
- */
- protected function load_rights_bas()
- {
- if ($this->_rights_bas && $this->_global_rights && is_array($this->_limited))
-
- return $this;
-
- try
- {
- $this->_rights_bas = $this->get_data_from_cache(self::CACHE_RIGHTS_BAS);
- $this->_global_rights = $this->get_data_from_cache(self::CACHE_GLOBAL_RIGHTS);
- $this->_limited = $this->get_data_from_cache(self::CACHE_LIMITS_BAS);
-
- return $this;
- }
- catch (Exception $e)
- {
+ $this->_rights_sbas[$row['sbas_id']]['bas_modify_struct'] = ($row['bas_modify_struct'] == '1');
+ $this->_rights_sbas[$row['sbas_id']]['bas_manage'] = ($row['bas_manage'] == '1');
+ $this->_rights_sbas[$row['sbas_id']]['bas_chupub'] = ($row['bas_chupub'] == '1');
+ $this->_rights_sbas[$row['sbas_id']]['bas_modif_th'] = ($row['bas_modif_th'] == '1');
+ }
+ $this->set_data_to_cache($this->_rights_sbas, self::CACHE_RIGHTS_SBAS);
+ $this->set_data_to_cache($this->_global_rights, self::CACHE_GLOBAL_RIGHTS);
+ return $this;
}
- $sql = 'SELECT u.* FROM basusr u, bas b, sbas s
+ /**
+ * Loads rights of specified user for all bas
+ *
+ * @return ACL
+ */
+ protected function load_rights_bas()
+ {
+ if ($this->_rights_bas && $this->_global_rights && is_array($this->_limited))
+ return $this;
+
+ try {
+ $this->_rights_bas = $this->get_data_from_cache(self::CACHE_RIGHTS_BAS);
+ $this->_global_rights = $this->get_data_from_cache(self::CACHE_GLOBAL_RIGHTS);
+ $this->_limited = $this->get_data_from_cache(self::CACHE_LIMITS_BAS);
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT u.* FROM basusr u, bas b, sbas s
WHERE usr_id= :usr_id
AND b.base_id = u.base_id
AND b.sbas_id = s.sbas_id
AND s.sbas_id = b.sbas_id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->_rights_bas = $this->_limited = array();
+ $this->_rights_bas = $this->_limited = array();
- $this->_global_rights['manageusers'] = false;
- $this->_global_rights['coll_manage'] = false;
- $this->_global_rights['coll_modify_struct'] = false;
- $this->_global_rights['order'] = false;
- $this->_global_rights['push'] = false;
- $this->_global_rights['addrecord'] = false;
- $this->_global_rights['modifyrecord'] = false;
- $this->_global_rights['changestatus'] = false;
- $this->_global_rights['doctools'] = false;
- $this->_global_rights['deleterecord'] = false;
- $this->_global_rights['addtoalbum'] = false;
- $this->_global_rights['report'] = false;
- $this->_global_rights['candwnldpreview'] = false;
- $this->_global_rights['candwnldhd'] = false;
- $this->_global_rights['order_master'] = false;
+ $this->_global_rights['manageusers'] = false;
+ $this->_global_rights['coll_manage'] = false;
+ $this->_global_rights['coll_modify_struct'] = false;
+ $this->_global_rights['order'] = false;
+ $this->_global_rights['push'] = false;
+ $this->_global_rights['addrecord'] = false;
+ $this->_global_rights['modifyrecord'] = false;
+ $this->_global_rights['changestatus'] = false;
+ $this->_global_rights['doctools'] = false;
+ $this->_global_rights['deleterecord'] = false;
+ $this->_global_rights['addtoalbum'] = false;
+ $this->_global_rights['report'] = false;
+ $this->_global_rights['candwnldpreview'] = false;
+ $this->_global_rights['candwnldhd'] = false;
+ $this->_global_rights['order_master'] = false;
- foreach ($rs as $row)
- {
- $this->_rights_bas[$row['base_id']]['actif'] = ($row['actif'] == '1');
+ foreach ($rs as $row) {
+ $this->_rights_bas[$row['base_id']]['actif'] = ($row['actif'] == '1');
- if ($row['canadmin'] == '1')
- $this->_global_rights['manageusers'] = true;
- if ($row['manage'] == '1')
- $this->_global_rights['coll_manage'] = true;
- if ($row['modify_struct'] == '1')
- $this->_global_rights['coll_modify_struct'] = true;
- if ($row['cancmd'] == '1')
- $this->_global_rights['order'] = true;
- if ($row['canpush'] == '1')
- $this->_global_rights['push'] = true;
- if ($row['canaddrecord'] == '1')
- $this->_global_rights['addrecord'] = true;
- if ($row['canmodifrecord'] == '1')
- $this->_global_rights['modifyrecord'] = true;
- if ($row['chgstatus'] == '1')
- $this->_global_rights['changestatus'] = true;
- if ($row['imgtools'] == '1')
- $this->_global_rights['doctools'] = true;
- if ($row['candeleterecord'] == '1')
- $this->_global_rights['deleterecord'] = true;
- if ($row['canputinalbum'] == '1')
- $this->_global_rights['addtoalbum'] = true;
- if ($row['canreport'] == '1')
- $this->_global_rights['report'] = true;
- if ($row['candwnldpreview'] == '1')
- $this->_global_rights['candwnldpreview'] = true;
- if ($row['candwnldhd'] == '1')
- $this->_global_rights['candwnldhd'] = true;
- if ($row['order_master'] == '1')
- $this->_global_rights['order_master'] = true;
+ if ($row['canadmin'] == '1')
+ $this->_global_rights['manageusers'] = true;
+ if ($row['manage'] == '1')
+ $this->_global_rights['coll_manage'] = true;
+ if ($row['modify_struct'] == '1')
+ $this->_global_rights['coll_modify_struct'] = true;
+ if ($row['cancmd'] == '1')
+ $this->_global_rights['order'] = true;
+ if ($row['canpush'] == '1')
+ $this->_global_rights['push'] = true;
+ if ($row['canaddrecord'] == '1')
+ $this->_global_rights['addrecord'] = true;
+ if ($row['canmodifrecord'] == '1')
+ $this->_global_rights['modifyrecord'] = true;
+ if ($row['chgstatus'] == '1')
+ $this->_global_rights['changestatus'] = true;
+ if ($row['imgtools'] == '1')
+ $this->_global_rights['doctools'] = true;
+ if ($row['candeleterecord'] == '1')
+ $this->_global_rights['deleterecord'] = true;
+ if ($row['canputinalbum'] == '1')
+ $this->_global_rights['addtoalbum'] = true;
+ if ($row['canreport'] == '1')
+ $this->_global_rights['report'] = true;
+ if ($row['candwnldpreview'] == '1')
+ $this->_global_rights['candwnldpreview'] = true;
+ if ($row['candwnldhd'] == '1')
+ $this->_global_rights['candwnldhd'] = true;
+ if ($row['order_master'] == '1')
+ $this->_global_rights['order_master'] = true;
- $row['limited_from'] = $row['limited_from'] == '0000-00-00 00:00:00' ? '' : trim($row['limited_from']);
- $row['limited_to'] = $row['limited_to'] == '0000-00-00 00:00:00' ? '' : trim($row['limited_to']);
+ $row['limited_from'] = $row['limited_from'] == '0000-00-00 00:00:00' ? '' : trim($row['limited_from']);
+ $row['limited_to'] = $row['limited_to'] == '0000-00-00 00:00:00' ? '' : trim($row['limited_to']);
- if ($row['time_limited'] == '1'
- && ($row['limited_from'] !== '' || $row['limited_to'] !== ''))
- {
- $this->_limited[$row['base_id']] = array(
- 'dmin' => $row['limited_from'] ? new DateTime($row['limited_from']) : null
- , 'dmax' => $row['limited_to'] ? new DateTime($row['limited_to']) : null
- );
- }
+ if ($row['time_limited'] == '1'
+ && ($row['limited_from'] !== '' || $row['limited_to'] !== '')) {
+ $this->_limited[$row['base_id']] = array(
+ 'dmin' => $row['limited_from'] ? new DateTime($row['limited_from']) : null
+ , 'dmax' => $row['limited_to'] ? new DateTime($row['limited_to']) : null
+ );
+ }
- $this->_rights_bas[$row['base_id']]['imgtools']
- = $row['imgtools'] == '1';
+ $this->_rights_bas[$row['base_id']]['imgtools']
+ = $row['imgtools'] == '1';
- $this->_rights_bas[$row['base_id']]['chgstatus']
- = $row['chgstatus'] == '1';
- $this->_rights_bas[$row['base_id']]['cancmd']
- = $row['cancmd'] == '1';
- $this->_rights_bas[$row['base_id']]['canaddrecord']
- = $row['canaddrecord'] == '1';
- $this->_rights_bas[$row['base_id']]['canpush']
- = $row['canpush'] == '1';
- $this->_rights_bas[$row['base_id']]['candeleterecord']
- = $row['candeleterecord'] == '1';
- $this->_rights_bas[$row['base_id']]['canadmin']
- = $row['canadmin'] == '1';
- $this->_rights_bas[$row['base_id']]['chgstatus']
- = $row['chgstatus'] == '1';
- $this->_rights_bas[$row['base_id']]['candwnldpreview']
- = $row['candwnldpreview'] == '1';
- $this->_rights_bas[$row['base_id']]['candwnldhd']
- = $row['candwnldhd'] == '1';
- $this->_rights_bas[$row['base_id']]['nowatermark']
- = $row['nowatermark'] == '1';
- $this->_rights_bas[$row['base_id']]['restrict_dwnld']
- = $row['restrict_dwnld'] == '1';
- $this->_rights_bas[$row['base_id']]['remain_dwnld']
- = (int) $row['remain_dwnld'];
- $this->_rights_bas[$row['base_id']]['canmodifrecord']
- = $row['canmodifrecord'] == '1';
- $this->_rights_bas[$row['base_id']]['canputinalbum']
- = $row['canputinalbum'] == '1';
- $this->_rights_bas[$row['base_id']]['canreport']
- = $row['canreport'] == '1';
- $this->_rights_bas[$row['base_id']]['mask_and']
- = $row['mask_and'];
- $this->_rights_bas[$row['base_id']]['mask_xor']
- = $row['mask_xor'];
- $this->_rights_bas[$row['base_id']]['modify_struct']
- = $row['modify_struct'] == '1';
- $this->_rights_bas[$row['base_id']]['manage']
- = $row['manage'] == '1';
- $this->_rights_bas[$row['base_id']]['order_master']
- = $row['order_master'] == '1';
+ $this->_rights_bas[$row['base_id']]['chgstatus']
+ = $row['chgstatus'] == '1';
+ $this->_rights_bas[$row['base_id']]['cancmd']
+ = $row['cancmd'] == '1';
+ $this->_rights_bas[$row['base_id']]['canaddrecord']
+ = $row['canaddrecord'] == '1';
+ $this->_rights_bas[$row['base_id']]['canpush']
+ = $row['canpush'] == '1';
+ $this->_rights_bas[$row['base_id']]['candeleterecord']
+ = $row['candeleterecord'] == '1';
+ $this->_rights_bas[$row['base_id']]['canadmin']
+ = $row['canadmin'] == '1';
+ $this->_rights_bas[$row['base_id']]['chgstatus']
+ = $row['chgstatus'] == '1';
+ $this->_rights_bas[$row['base_id']]['candwnldpreview']
+ = $row['candwnldpreview'] == '1';
+ $this->_rights_bas[$row['base_id']]['candwnldhd']
+ = $row['candwnldhd'] == '1';
+ $this->_rights_bas[$row['base_id']]['nowatermark']
+ = $row['nowatermark'] == '1';
+ $this->_rights_bas[$row['base_id']]['restrict_dwnld']
+ = $row['restrict_dwnld'] == '1';
+ $this->_rights_bas[$row['base_id']]['remain_dwnld']
+ = (int) $row['remain_dwnld'];
+ $this->_rights_bas[$row['base_id']]['canmodifrecord']
+ = $row['canmodifrecord'] == '1';
+ $this->_rights_bas[$row['base_id']]['canputinalbum']
+ = $row['canputinalbum'] == '1';
+ $this->_rights_bas[$row['base_id']]['canreport']
+ = $row['canreport'] == '1';
+ $this->_rights_bas[$row['base_id']]['mask_and']
+ = $row['mask_and'];
+ $this->_rights_bas[$row['base_id']]['mask_xor']
+ = $row['mask_xor'];
+ $this->_rights_bas[$row['base_id']]['modify_struct']
+ = $row['modify_struct'] == '1';
+ $this->_rights_bas[$row['base_id']]['manage']
+ = $row['manage'] == '1';
+ $this->_rights_bas[$row['base_id']]['order_master']
+ = $row['order_master'] == '1';
+ }
+
+ $this->set_data_to_cache($this->_global_rights, self::CACHE_GLOBAL_RIGHTS);
+ $this->set_data_to_cache($this->_rights_bas, self::CACHE_RIGHTS_BAS);
+ $this->set_data_to_cache($this->_limited, self::CACHE_LIMITS_BAS);
+
+ return $this;
}
- $this->set_data_to_cache($this->_global_rights, self::CACHE_GLOBAL_RIGHTS);
- $this->set_data_to_cache($this->_rights_bas, self::CACHE_RIGHTS_BAS);
- $this->set_data_to_cache($this->_limited, self::CACHE_LIMITS_BAS);
-
- return $this;
- }
-
- /**
- * Loads global rights for user
- *
- * @return ACL
- */
- protected function load_global_rights()
- {
- $this->load_rights_bas();
- $this->load_rights_sbas();
- $this->_global_rights['taskmanager'] = $this->user->is_admin();
-
- return $this;
- }
-
- /**
- * Return whether or not the acces to the specified module is OK
- *
- * @param String $module_name
- * @return boolean
- */
- public function has_access_to_module($module_name)
- {
- switch ($module_name)
+ /**
+ * Loads global rights for user
+ *
+ * @return ACL
+ */
+ protected function load_global_rights()
{
- case 'admin':
- return (
- ($this->has_right('bas_modify_struct') ||
- $this->has_right('coll_modify_struct') ||
- $this->has_right('bas_manage') ||
- $this->has_right('coll_manage') ||
- $this->has_right('manageusers') ||
- $this->user->is_admin()) );
- break;
- case 'thesaurus':
- return ($this->has_right('bas_modif_th') === true );
- break;
- case 'upload':
- return ($this->has_right('addrecord') === true);
- break;
- case 'report':
- return ($this->has_right('report') === true);
- break;
- default:
- break;
+ $this->load_rights_bas();
+ $this->load_rights_sbas();
+ $this->_global_rights['taskmanager'] = $this->user->is_admin();
+
+ return $this;
}
- return true;
- }
-
- /**
- *
- * @param array $base_ids
- * @return ACL
- */
- public function revoke_access_from_bases(Array $base_ids)
- {
- $sql_del = 'DELETE FROM basusr WHERE base_id = :base_id AND usr_id = :usr_id';
- $stmt_del = $this->appbox->get_connection()->prepare($sql_del);
-
- $usr_id = $this->user->get_id();
-
- foreach ($base_ids as $base_id)
+ /**
+ * Return whether or not the acces to the specified module is OK
+ *
+ * @param String $module_name
+ * @return boolean
+ */
+ public function has_access_to_module($module_name)
{
- if (!$stmt_del->execute(array(':base_id' => $base_id, ':usr_id' => $usr_id)))
- {
- throw new Exception('Error while deleteing some rights');
- }
+ switch ($module_name) {
+ case 'admin':
+ return (
+ ($this->has_right('bas_modify_struct') ||
+ $this->has_right('coll_modify_struct') ||
+ $this->has_right('bas_manage') ||
+ $this->has_right('coll_manage') ||
+ $this->has_right('manageusers') ||
+ $this->user->is_admin()) );
+ break;
+ case 'thesaurus':
+ return ($this->has_right('bas_modif_th') === true );
+ break;
+ case 'upload':
+ return ($this->has_right('addrecord') === true);
+ break;
+ case 'report':
+ return ($this->has_right('report') === true);
+ break;
+ default:
+ break;
+ }
+
+ return true;
}
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- return $this;
- }
+ /**
+ *
+ * @param array $base_ids
+ * @return ACL
+ */
+ public function revoke_access_from_bases(Array $base_ids)
+ {
+ $sql_del = 'DELETE FROM basusr WHERE base_id = :base_id AND usr_id = :usr_id';
+ $stmt_del = $this->appbox->get_connection()->prepare($sql_del);
- /**
- *
- * @param array $base_ids
- * @return ACL
- */
- public function give_access_to_base(Array $base_ids)
- {
- $sql_ins = 'INSERT INTO basusr (id, base_id, usr_id, actif)
+ $usr_id = $this->user->get_id();
+
+ foreach ($base_ids as $base_id) {
+ if ( ! $stmt_del->execute(array(':base_id' => $base_id, ':usr_id' => $usr_id))) {
+ throw new Exception('Error while deleteing some rights');
+ }
+ }
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param array $base_ids
+ * @return ACL
+ */
+ public function give_access_to_base(Array $base_ids)
+ {
+ $sql_ins = 'INSERT INTO basusr (id, base_id, usr_id, actif)
VALUES (null, :base_id, :usr_id, "1")';
- $stmt_ins = $this->appbox->get_connection()->prepare($sql_ins);
- $usr_id = $this->user->get_id();
- $to_update = array();
- $this->load_rights_bas();
+ $stmt_ins = $this->appbox->get_connection()->prepare($sql_ins);
+ $usr_id = $this->user->get_id();
+ $to_update = array();
+ $this->load_rights_bas();
- foreach ($base_ids as $base_id)
- {
- if (!isset($this->_rights_bas[$base_id]))
- {
- $stmt_ins->execute(array(':base_id' => $base_id, ':usr_id' => $usr_id));
- }
- elseif ($this->_rights_bas[$base_id]['actif'] === false)
- {
- $to_update[] = $base_id;
- }
- }
- $stmt_ins->closeCursor();
+ foreach ($base_ids as $base_id) {
+ if ( ! isset($this->_rights_bas[$base_id])) {
+ $stmt_ins->execute(array(':base_id' => $base_id, ':usr_id' => $usr_id));
+ } elseif ($this->_rights_bas[$base_id]['actif'] === false) {
+ $to_update[] = $base_id;
+ }
+ }
+ $stmt_ins->closeCursor();
- $sql_upd = 'UPDATE basusr SET actif="1"
+ $sql_upd = 'UPDATE basusr SET actif="1"
WHERE usr_id = :usr_id AND base_id = :base_id';
- $stmt_upd = $this->appbox->get_connection()->prepare($sql_upd);
- foreach ($to_update as $base_id)
- {
- $stmt_upd->execute(array(':usr_id' => $usr_id, ':base_id' => $base_id));
- }
- $stmt_upd->closeCursor();
+ $stmt_upd = $this->appbox->get_connection()->prepare($sql_upd);
+ foreach ($to_update as $base_id) {
+ $stmt_upd->execute(array(':usr_id' => $usr_id, ':base_id' => $base_id));
+ }
+ $stmt_upd->closeCursor();
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- $this->inject_rights();
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+ $this->inject_rights();
- return $this;
- }
-
- /**
- *
- * @param array $sbas_ids
- * @return ACL
- */
- public function give_access_to_sbas(Array $sbas_ids)
- {
- $sql_ins = 'INSERT INTO sbasusr (sbasusr_id, sbas_id, usr_id) VALUES (null, :sbas_id, :usr_id)';
- $stmt_ins = $this->appbox->get_connection()->prepare($sql_ins);
-
- $usr_id = $this->user->get_id();
-
- foreach ($sbas_ids as $sbas_id)
- {
- if (!$this->has_access_to_sbas($sbas_id))
- $stmt_ins->execute(array(':sbas_id' => $sbas_id, ':usr_id' => $usr_id));
- }
- $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
-
- return $this;
- }
-
- /**
- * @todo Create special toggle 'actif' / not a right like others
- * => nested loops when updating right to actif on an inactif account
- *
- * @param $base_id
- * @param $rights
- * @return ACL
- */
- public function update_rights_to_base($base_id, $rights)
- {
-
- if (!$this->has_access_to_base($base_id) && (!isset($rights['actif']) || $rights['actif'] == '1'))
- {
- $this->give_access_to_base(array($base_id));
+ return $this;
}
- $sql_up = "UPDATE basusr SET ";
-
- $sql_args = $params = array();
- foreach ($rights as $right => $v)
+ /**
+ *
+ * @param array $sbas_ids
+ * @return ACL
+ */
+ public function give_access_to_sbas(Array $sbas_ids)
{
- $sql_args[] = " " . $right . " = :" . $right;
- switch ($right)
- {
- default:
- $params[':' . $right] = $v ? '1' : '0';
- break;
- case 'mask_and':
- case 'mask_xor':
- $params[':' . $right] = $v;
- break;
- }
+ $sql_ins = 'INSERT INTO sbasusr (sbasusr_id, sbas_id, usr_id) VALUES (null, :sbas_id, :usr_id)';
+ $stmt_ins = $this->appbox->get_connection()->prepare($sql_ins);
+
+ $usr_id = $this->user->get_id();
+
+ foreach ($sbas_ids as $sbas_id) {
+ if ( ! $this->has_access_to_sbas($sbas_id))
+ $stmt_ins->execute(array(':sbas_id' => $sbas_id, ':usr_id' => $usr_id));
+ }
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
+
+ return $this;
}
- if (count($sql_args) == 0)
+ /**
+ * @todo Create special toggle 'actif' / not a right like others
+ * => nested loops when updating right to actif on an inactif account
+ *
+ * @param $base_id
+ * @param $rights
+ * @return ACL
+ */
+ public function update_rights_to_base($base_id, $rights)
{
- return $this;
- }
- $usr_id = $this->user->get_id();
+ if ( ! $this->has_access_to_base($base_id) && ( ! isset($rights['actif']) || $rights['actif'] == '1')) {
+ $this->give_access_to_base(array($base_id));
+ }
- $sql_up .= implode(', ', $sql_args) . ' WHERE base_id = :base_id
+ $sql_up = "UPDATE basusr SET ";
+
+ $sql_args = $params = array();
+ foreach ($rights as $right => $v) {
+ $sql_args[] = " " . $right . " = :" . $right;
+ switch ($right) {
+ default:
+ $params[':' . $right] = $v ? '1' : '0';
+ break;
+ case 'mask_and':
+ case 'mask_xor':
+ $params[':' . $right] = $v;
+ break;
+ }
+ }
+
+ if (count($sql_args) == 0) {
+ return $this;
+ }
+
+ $usr_id = $this->user->get_id();
+
+ $sql_up .= implode(', ', $sql_args) . ' WHERE base_id = :base_id
AND usr_id = :usr_id';
- $params = array_merge(
- $params
- , array(':base_id' => $base_id, ':usr_id' => $usr_id)
- );
+ $params = array_merge(
+ $params
+ , array(':base_id' => $base_id, ':usr_id' => $usr_id)
+ );
- $stmt_up = $this->appbox->get_connection()->prepare($sql_up);
- $stmt_up->execute($params);
- $stmt_up->closeCursor();
+ $stmt_up = $this->appbox->get_connection()->prepare($sql_up);
+ $stmt_up->execute($params);
+ $stmt_up->closeCursor();
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return ACL
- */
- public function revoke_unused_sbas_rights()
- {
- $sql = 'DELETE FROM sbasusr
+ /**
+ *
+ * @return ACL
+ */
+ public function revoke_unused_sbas_rights()
+ {
+ $sql = 'DELETE FROM sbasusr
WHERE usr_id = :usr_id_1
AND sbas_id NOT IN
(SELECT distinct sbas_id FROM basusr bu, bas b WHERE usr_id = :usr_id_2 AND b.base_id = bu.base_id)';
- $usr_id = $this->user->get_id();
- $params = array(':usr_id_1' => $usr_id, ':usr_id_2' => $usr_id);
+ $usr_id = $this->user->get_id();
+ $params = array(':usr_id_1' => $usr_id, ':usr_id_2' => $usr_id);
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
// $sql = 'DELETE FROM sbasusr
// WHERE sbas_id NOT IN
@@ -1237,351 +1153,335 @@ class ACL implements cache_cacheableInterface
// $stmt->execute();
// $stmt->closeCursor();
- $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
- return $this;
- }
-
- /**
- *
- * @param $sbas_id
- * @param $rights
- * @return ACL
- */
- public function update_rights_to_sbas($sbas_id, $rights)
- {
- if (!$this->has_access_to_sbas($sbas_id))
- $this->give_access_to_sbas(array($sbas_id));
-
- $sql_up = "UPDATE sbasusr SET ";
-
- $sql_args = array();
- $usr_id = $this->user->get_id();
- $params = array(':sbas_id' => $sbas_id, ':usr_id' => $usr_id);
-
- foreach ($rights as $right => $v)
- {
- $sql_args[] = " " . $right . " = :" . $right;
- $params[':' . $right] = $v ? '1' : '0';
+ return $this;
}
- if (count($sql_args) == 0)
+ /**
+ *
+ * @param $sbas_id
+ * @param $rights
+ * @return ACL
+ */
+ public function update_rights_to_sbas($sbas_id, $rights)
{
- return $this;
- }
+ if ( ! $this->has_access_to_sbas($sbas_id))
+ $this->give_access_to_sbas(array($sbas_id));
- $sql_up .= implode(', ', $sql_args) . '
+ $sql_up = "UPDATE sbasusr SET ";
+
+ $sql_args = array();
+ $usr_id = $this->user->get_id();
+ $params = array(':sbas_id' => $sbas_id, ':usr_id' => $usr_id);
+
+ foreach ($rights as $right => $v) {
+ $sql_args[] = " " . $right . " = :" . $right;
+ $params[':' . $right] = $v ? '1' : '0';
+ }
+
+ if (count($sql_args) == 0) {
+ return $this;
+ }
+
+ $sql_up .= implode(', ', $sql_args) . '
WHERE sbas_id = :sbas_id AND usr_id = :usr_id';
- $stmt_up = $this->appbox->get_connection()->prepare($sql_up);
+ $stmt_up = $this->appbox->get_connection()->prepare($sql_up);
- if (!$stmt_up->execute($params))
- {
- throw new Exception('Error while updating some rights');
+ if ( ! $stmt_up->execute($params)) {
+ throw new Exception('Error while updating some rights');
+ }
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
+
+ return $this;
}
- $this->delete_data_from_cache(self::CACHE_RIGHTS_SBAS);
- return $this;
- }
-
- /**
- *
- * @param $base_id
- * @return ACL
- */
- public function remove_quotas_on_base($base_id)
- {
- $sql = 'UPDATE basusr
+ /**
+ *
+ * @param $base_id
+ * @return ACL
+ */
+ public function remove_quotas_on_base($base_id)
+ {
+ $sql = 'UPDATE basusr
SET remain_dwnld = 0, restrict_dwnld = 0, month_dwnld_max = 0
WHERE usr_id = :usr_id AND base_id = :base_id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id(), ':base_id' => $base_id));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id(), ':base_id' => $base_id));
+ $stmt->closeCursor();
- unset($stmt);
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+ unset($stmt);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- return $this;
- }
+ return $this;
+ }
- public function update_download_restrictions()
- {
- $sql = 'UPDATE basusr SET remain_dwnld = month_dwnld_max
+ public function update_download_restrictions()
+ {
+ $sql = 'UPDATE basusr SET remain_dwnld = month_dwnld_max
WHERE actif = 1
AND usr_id = :usr_id
AND MONTH(lastconn) != MONTH(NOW()) AND restrict_dwnld = 1';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $stmt->closeCursor();
- $sql = "UPDATE basusr SET lastconn=now()
+ $sql = "UPDATE basusr SET lastconn=now()
WHERE usr_id = :usr_id AND actif = 1";
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $stmt->closeCursor();
- unset($stmt);
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+ unset($stmt);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param $base_id
- * @param $droits
- * @param $restes
- * @return ACL
- */
- public function set_quotas_on_base($base_id, $droits, $restes)
- {
- $sql = 'UPDATE basusr
+ /**
+ *
+ * @param $base_id
+ * @param $droits
+ * @param $restes
+ * @return ACL
+ */
+ public function set_quotas_on_base($base_id, $droits, $restes)
+ {
+ $sql = 'UPDATE basusr
SET remain_dwnld = :restes, restrict_dwnld = 1, month_dwnld_max = :droits
WHERE usr_id = :usr_id AND base_id = :base_id ';
- $params = array(
- ':usr_id' => $this->user->get_id(),
- ':base_id' => $base_id,
- ':restes' => $restes,
- ':droits' => $droits
- );
+ $params = array(
+ ':usr_id' => $this->user->get_id(),
+ ':base_id' => $base_id,
+ ':restes' => $restes,
+ ':droits' => $droits
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- unset($stmt);
- $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
+ unset($stmt);
+ $this->delete_data_from_cache(self::CACHE_RIGHTS_BAS);
- return $this;
- }
+ return $this;
+ }
- public function duplicate_right_from_bas($base_id_from, $base_id_dest)
- {
- $sql = 'SELECT * FROM basusr
+ public function duplicate_right_from_bas($base_id_from, $base_id_dest)
+ {
+ $sql = 'SELECT * FROM basusr
WHERE base_id = :base_from AND usr_id = :usr_id';
- $params = array(
- ':base_from' => $base_id_from,
- ':usr_id' => $this->user->get_id()
- );
+ $params = array(
+ ':base_from' => $base_id_from,
+ ':usr_id' => $this->user->get_id()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
+ if ( ! $row)
+ return $this;
- return $this;
+ $this->give_access_to_base(array($base_id_dest));
- $this->give_access_to_base(array($base_id_dest));
+ $rights = array();
+ if ($row['canputinalbum'])
+ $rights['canputinalbum'] = true;
+ if ($row['candwnldhd'])
+ $rights['candwnldhd'] = true;
+ if ($row['candwnldpreview'])
+ $rights['candwnldpreview'] = true;
+ if ($row['cancmd'])
+ $rights['cancmd'] = true;
+ if ($row['canadmin'])
+ $rights['canadmin'] = true;
+ if ($row['canreport'])
+ $rights['canreport'] = true;
+ if ($row['canpush'])
+ $rights['canpush'] = true;
+ if ($row['nowatermark'])
+ $rights['nowatermark'] = true;
+ if ($row['canaddrecord'])
+ $rights['canaddrecord'] = true;
+ if ($row['canmodifrecord'])
+ $rights['canmodifrecord'] = true;
+ if ($row['candeleterecord'])
+ $rights['candeleterecord'] = true;
+ if ($row['chgstatus'])
+ $rights['chgstatus'] = true;
+ if ($row['imgtools'])
+ $rights['imgtools'] = true;
+ if ($row['manage'])
+ $rights['manage'] = true;
+ if ($row['modify_struct'])
+ $rights['modify_struct'] = true;
- $rights = array();
- if ($row['canputinalbum'])
- $rights['canputinalbum'] = true;
- if ($row['candwnldhd'])
- $rights['candwnldhd'] = true;
- if ($row['candwnldpreview'])
- $rights['candwnldpreview'] = true;
- if ($row['cancmd'])
- $rights['cancmd'] = true;
- if ($row['canadmin'])
- $rights['canadmin'] = true;
- if ($row['canreport'])
- $rights['canreport'] = true;
- if ($row['canpush'])
- $rights['canpush'] = true;
- if ($row['nowatermark'])
- $rights['nowatermark'] = true;
- if ($row['canaddrecord'])
- $rights['canaddrecord'] = true;
- if ($row['canmodifrecord'])
- $rights['canmodifrecord'] = true;
- if ($row['candeleterecord'])
- $rights['candeleterecord'] = true;
- if ($row['chgstatus'])
- $rights['chgstatus'] = true;
- if ($row['imgtools'])
- $rights['imgtools'] = true;
- if ($row['manage'])
- $rights['manage'] = true;
- if ($row['modify_struct'])
- $rights['modify_struct'] = true;
+ $this->update_rights_to_base($base_id_dest, $rights);
- $this->update_rights_to_base($base_id_dest, $rights);
-
- return $this;
- }
-
- public function inject_rights()
- {
- $this->update_download_restrictions();
-
- foreach ($this->get_granted_sbas() as $databox)
- {
- $this->inject_rights_sbas($databox);
+ return $this;
}
- return $this;
- }
+ public function inject_rights()
+ {
+ $this->update_download_restrictions();
- protected function inject_rights_sbas(databox $databox)
- {
- $this->delete_injected_rights_sbas($databox);
+ foreach ($this->get_granted_sbas() as $databox) {
+ $this->inject_rights_sbas($databox);
+ }
- $sql = "INSERT INTO collusr
+ return $this;
+ }
+
+ protected function inject_rights_sbas(databox $databox)
+ {
+ $this->delete_injected_rights_sbas($databox);
+
+ $sql = "INSERT INTO collusr
(site, usr_id, coll_id, mask_and, mask_xor, ord)
VALUES (:site_id, :usr_id, :coll_id, :mask_and, :mask_xor, :ord)";
- $stmt = $databox->get_connection()->prepare($sql);
- $iord = 0;
+ $stmt = $databox->get_connection()->prepare($sql);
+ $iord = 0;
- foreach ($this->get_granted_base(array(), array($databox->get_sbas_id())) as $collection)
- {
- $stmt->execute(array(
- ':site_id' => $this->appbox->get_registry()->get('GV_sit'),
- ':usr_id' => $this->user->get_id(),
- ':coll_id' => $collection->get_coll_id(),
- ':mask_and' => $this->get_mask_and($collection->get_base_id()),
- ':mask_xor' => $this->get_mask_xor($collection->get_base_id()),
- ':ord' => $iord++
- ));
+ foreach ($this->get_granted_base(array(), array($databox->get_sbas_id())) as $collection) {
+ $stmt->execute(array(
+ ':site_id' => $this->appbox->get_registry()->get('GV_sit'),
+ ':usr_id' => $this->user->get_id(),
+ ':coll_id' => $collection->get_coll_id(),
+ ':mask_and' => $this->get_mask_and($collection->get_base_id()),
+ ':mask_xor' => $this->get_mask_xor($collection->get_base_id()),
+ ':ord' => $iord ++
+ ));
+ }
+
+ $stmt->closeCursor();
+
+ return $this;
}
- $stmt->closeCursor();
-
- return $this;
- }
-
- public function delete_injected_rights()
- {
- foreach ($this->get_granted_sbas() as $databox)
+ public function delete_injected_rights()
{
- $this->delete_injected_rights_sbas($databox);
+ foreach ($this->get_granted_sbas() as $databox) {
+ $this->delete_injected_rights_sbas($databox);
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function delete_injected_rights_sbas(databox $databox)
- {
- $sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site';
- $params = array(
- ':usr_id' => $this->user->get_id()
- , ':site' => $this->appbox->get_registry()->get('GV_sit')
- );
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
-
- return $this;
- }
-
- public function set_masks_on_base($base_id, $and_and, $and_or, $xor_and, $xor_or)
- {
- $vhex = array();
- $datas = array(
- 'and_and' => $and_and,
- 'and_or' => $and_or,
- 'xor_and' => $xor_and,
- 'xor_or' => $xor_or
- );
-
- foreach ($datas as $name => $f)
+ public function delete_injected_rights_sbas(databox $databox)
{
- $vhex[$name] = "0x";
- while (strlen($datas[$name]) < 64)
- $datas[$name] = "0" . $datas[$name];
- }
- foreach ($datas as $name => $f)
- {
- while (strlen($datas[$name]) > 0)
- {
- $valtmp = substr($datas[$name], 0, 4);
- $datas[$name] = substr($datas[$name], 4);
- $vhex[$name] .= dechex(bindec($valtmp));
- }
+ $sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site';
+ $params = array(
+ ':usr_id' => $this->user->get_id()
+ , ':site' => $this->appbox->get_registry()->get('GV_sit')
+ );
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ return $this;
}
- $sql = "UPDATE basusr
+ public function set_masks_on_base($base_id, $and_and, $and_or, $xor_and, $xor_or)
+ {
+ $vhex = array();
+ $datas = array(
+ 'and_and' => $and_and,
+ 'and_or' => $and_or,
+ 'xor_and' => $xor_and,
+ 'xor_or' => $xor_or
+ );
+
+ foreach ($datas as $name => $f) {
+ $vhex[$name] = "0x";
+ while (strlen($datas[$name]) < 64)
+ $datas[$name] = "0" . $datas[$name];
+ }
+ foreach ($datas as $name => $f) {
+ while (strlen($datas[$name]) > 0) {
+ $valtmp = substr($datas[$name], 0, 4);
+ $datas[$name] = substr($datas[$name], 4);
+ $vhex[$name] .= dechex(bindec($valtmp));
+ }
+ }
+
+ $sql = "UPDATE basusr
SET mask_and=((mask_and & " . $vhex['and_and'] . ") | " . $vhex['and_or'] . ")
,mask_xor=((mask_xor & " . $vhex['xor_and'] . ") | " . $vhex['xor_or'] . ")
WHERE usr_id = :usr_id and base_id = :base_id";
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $base_id, ':usr_id' => $this->user->get_id()));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $base_id, ':usr_id' => $this->user->get_id()));
+ $stmt->closeCursor();
- unset($stmt);
+ unset($stmt);
- return $this;
- }
-
- public function is_limited($base_id)
- {
- $this->load_rights_bas();
-
- $datetime = new DateTime();
-
- if (!isset($this->_limited[$base_id]))
- {
- return false;
+ return $this;
}
- $lim_min = $this->_limited[$base_id]['dmin'] && $this->_limited[$base_id]['dmin'] > $datetime;
-
- $lim_max = $this->_limited[$base_id]['dmax'] && $this->_limited[$base_id]['dmax'] < $datetime;
-
- return $lim_max || $lim_min;
- }
-
- public function get_limits($base_id)
- {
- $this->load_rights_bas();
- if (!isset($this->_limited[$base_id]))
-
- return null;
- return ($this->_limited[$base_id]);
- }
-
- public function set_limits($base_id, $limit, DateTime $limit_from = null, DateTime $limit_to = null)
- {
- if ($limit)
+ public function is_limited($base_id)
{
- $sql = 'UPDATE basusr
+ $this->load_rights_bas();
+
+ $datetime = new DateTime();
+
+ if ( ! isset($this->_limited[$base_id])) {
+ return false;
+ }
+
+ $lim_min = $this->_limited[$base_id]['dmin'] && $this->_limited[$base_id]['dmin'] > $datetime;
+
+ $lim_max = $this->_limited[$base_id]['dmax'] && $this->_limited[$base_id]['dmax'] < $datetime;
+
+ return $lim_max || $lim_min;
+ }
+
+ public function get_limits($base_id)
+ {
+ $this->load_rights_bas();
+ if ( ! isset($this->_limited[$base_id]))
+ return null;
+ return ($this->_limited[$base_id]);
+ }
+
+ public function set_limits($base_id, $limit, DateTime $limit_from = null, DateTime $limit_to = null)
+ {
+ if ($limit) {
+ $sql = 'UPDATE basusr
SET time_limited = 1
, limited_from = :limited_from
, limited_to = :limited_to
WHERE base_id = :base_id AND usr_id = :usr_id';
- }
- else
- {
- $sql = 'UPDATE basusr
+ } else {
+ $sql = 'UPDATE basusr
SET time_limited = 0
, limited_from = :limited_from
, limited_to = :limited_to
WHERE base_id = :base_id AND usr_id = :usr_id';
+ }
+
+ $params = array(
+ ':usr_id' => $this->user->get_id()
+ , ':base_id' => $base_id
+ , 'limited_from' => ($limit_from ? $limit_from->format(DATE_ISO8601) : null)
+ , 'limited_to' => ($limit_to ? $limit_to->format(DATE_ISO8601) : null)
+ );
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+
+ $stmt->execute($params);
+
+ $stmt->closeCursor();
+
+ $this->delete_data_from_cache(self::CACHE_LIMITS_BAS);
+
+ return $this;
}
-
- $params = array(
- ':usr_id' => $this->user->get_id()
- , ':base_id' => $base_id
- , 'limited_from' => ($limit_from ? $limit_from->format(DATE_ISO8601) : null)
- , 'limited_to' => ($limit_to ? $limit_to->format(DATE_ISO8601) : null)
- );
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
-
- $stmt->execute($params);
-
- $stmt->closeCursor();
-
- $this->delete_data_from_cache(self::CACHE_LIMITS_BAS);
-
- return $this;
- }
-
}
diff --git a/lib/classes/API/OAuth2/Account.class.php b/lib/classes/API/OAuth2/Account.class.php
index 758593ffc7..3f4f56095b 100644
--- a/lib/classes/API/OAuth2/Account.class.php
+++ b/lib/classes/API/OAuth2/Account.class.php
@@ -21,278 +21,270 @@
*/
class API_OAuth2_Account
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @var API_OAuth2_Application
+ */
+ protected $application;
- /**
- *
- * @var API_OAuth2_Application
- */
- protected $application;
+ /**
+ *
+ * @var int
+ */
+ protected $application_id;
- /**
- *
- * @var int
- */
- protected $application_id;
+ /**
+ *
+ * @var string
+ */
+ protected $api_version;
- /**
- *
- * @var string
- */
- protected $api_version;
+ /**
+ *
+ * @var boolean
+ */
+ protected $revoked;
- /**
- *
- * @var boolean
- */
- protected $revoked;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
+ /**
+ *
+ * @var string
+ */
+ protected $token;
- /**
- *
- * @var string
- */
- protected $token;
-
- /**
- * Constructor
- *
- * @param appbox $appbox
- * @param int $account_id
- * @return API_OAuth2_Account
- */
- public function __construct(appbox &$appbox, $account_id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $account_id;
- $sql = 'SELECT api_account_id, usr_id, api_version, revoked
+ /**
+ * Constructor
+ *
+ * @param appbox $appbox
+ * @param int $account_id
+ * @return API_OAuth2_Account
+ */
+ public function __construct(appbox &$appbox, $account_id)
+ {
+ $this->appbox = $appbox;
+ $this->id = (int) $account_id;
+ $sql = 'SELECT api_account_id, usr_id, api_version, revoked
, application_id, created
FROM api_accounts
WHERE api_account_id = :api_account_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':api_account_id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':api_account_id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->application_id = (int) $row['application_id'];
- $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ $this->application_id = (int) $row['application_id'];
+ $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
- $this->api_version = $row['api_version'];
- $this->revoked = !!$row['revoked'];
- $this->created_on = new DateTime($row['created']);
+ $this->api_version = $row['api_version'];
+ $this->revoked = ! ! $row['revoked'];
+ $this->created_on = new DateTime($row['created']);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- /**
- *
- * @return string
- */
- public function get_api_version()
- {
- return $this->api_version;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_api_version()
+ {
+ return $this->api_version;
+ }
- /**
- *
- * @return boolean
- */
- public function is_revoked()
- {
- return $this->revoked;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_revoked()
+ {
+ return $this->revoked;
+ }
- /**
- *
- * @param boolean $boolean
- * @return API_OAuth2_Account
- */
- public function set_revoked($boolean)
- {
- $this->revoked = !!$boolean;
+ /**
+ *
+ * @param boolean $boolean
+ * @return API_OAuth2_Account
+ */
+ public function set_revoked($boolean)
+ {
+ $this->revoked = ! ! $boolean;
- $sql = 'UPDATE api_accounts SET revoked = :revoked
+ $sql = 'UPDATE api_accounts SET revoked = :revoked
WHERE api_account_id = :account_id';
- $params = array(
- ':revoked' => ($boolean ? '1' : '0')
- , 'account_id' => $this->id
- );
+ $params = array(
+ ':revoked' => ($boolean ? '1' : '0')
+ , 'account_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
-
- /**
- *
- * @return API_OAuth2_Token
- */
- public function get_token()
- {
- if (!$this->token)
- {
- try
- {
- $this->token = new API_OAuth2_Token($this->appbox, $this);
- }
- catch (Exception_NotFound $e)
- {
- $this->token = API_OAuth2_Token::create($this->appbox, $this);
- }
+ return $this;
}
- return $this->token;
- }
-
- /**
- *
- * @return API_OAuth2_Application
- */
- public function get_application()
- {
- if (!$this->application)
- $this->application = new API_OAuth2_Application($this->appbox, $this->application_id);
-
- return $this->application;
- }
-
- /**
- *
- * @return void
- */
- public function delete()
- {
- $this->get_token()->delete();
-
- foreach(API_OAuth2_AuthCode::load_codes_by_account($this->appbox, $this) as $code)
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
{
- $code->delete();
- }
- foreach(API_OAuth2_RefreshToken::load_by_account($this->appbox, $this) as $token)
- {
- $token->delete();
+ return $this->created_on;
}
- $sql = 'DELETE FROM api_accounts WHERE api_account_id = :account_id';
+ /**
+ *
+ * @return API_OAuth2_Token
+ */
+ public function get_token()
+ {
+ if ( ! $this->token) {
+ try {
+ $this->token = new API_OAuth2_Token($this->appbox, $this);
+ } catch (Exception_NotFound $e) {
+ $this->token = API_OAuth2_Token::create($this->appbox, $this);
+ }
+ }
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array('account_id' => $this->id));
- $stmt->closeCursor();
+ return $this->token;
+ }
- return;
- }
+ /**
+ *
+ * @return API_OAuth2_Application
+ */
+ public function get_application()
+ {
+ if ( ! $this->application)
+ $this->application = new API_OAuth2_Application($this->appbox, $this->application_id);
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param API_OAuth2_Application $application
- * @return API_OAuth2_Account
- */
- public static function create(appbox &$appbox, User_Adapter $user, API_OAuth2_Application $application)
- {
- $sql = 'INSERT INTO api_accounts
+ return $this->application;
+ }
+
+ /**
+ *
+ * @return void
+ */
+ public function delete()
+ {
+ $this->get_token()->delete();
+
+ foreach (API_OAuth2_AuthCode::load_codes_by_account($this->appbox, $this) as $code) {
+ $code->delete();
+ }
+ foreach (API_OAuth2_RefreshToken::load_by_account($this->appbox, $this) as $token) {
+ $token->delete();
+ }
+
+ $sql = 'DELETE FROM api_accounts WHERE api_account_id = :account_id';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array('account_id' => $this->id));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param API_OAuth2_Application $application
+ * @return API_OAuth2_Account
+ */
+ public static function create(appbox &$appbox, User_Adapter $user, API_OAuth2_Application $application)
+ {
+ $sql = 'INSERT INTO api_accounts
(api_account_id, usr_id, revoked, api_version, application_id, created)
VALUES (null, :usr_id, :revoked, :api_version, :application_id, :created)';
- $datetime = new Datetime();
- $params = array(
- ':usr_id' => $user->get_id()
- , ':application_id' => $application->get_id()
- , ':api_version' => API_OAuth2_Adapter::API_VERSION
- , ':revoked' => 0
- , ':created' => $datetime->format("Y-m-d H:i:s")
- );
+ $datetime = new Datetime();
+ $params = array(
+ ':usr_id' => $user->get_id()
+ , ':application_id' => $application->get_id()
+ , ':api_version' => API_OAuth2_Adapter::API_VERSION
+ , ':revoked' => 0
+ , ':created' => $datetime->format("Y-m-d H:i:s")
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $account_id = $appbox->get_connection()->lastInsertId();
+ $account_id = $appbox->get_connection()->lastInsertId();
- return new self($appbox, $account_id);
- }
+ return new self($appbox, $account_id);
+ }
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Application $application
- * @param User_Adapter $user
- * @return API_OAuth2_Account
- */
- public static function load_with_user(appbox &$appbox, API_OAuth2_Application $application, User_Adapter $user)
- {
- $sql = 'SELECT api_account_id FROM api_accounts
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Application $application
+ * @param User_Adapter $user
+ * @return API_OAuth2_Account
+ */
+ public static function load_with_user(appbox &$appbox, API_OAuth2_Application $application, User_Adapter $user)
+ {
+ $sql = 'SELECT api_account_id FROM api_accounts
WHERE usr_id = :usr_id AND application_id = :application_id';
- $params = array(
- ":usr_id" => $user->get_id(),
- ":application_id" => $application->get_id()
- );
+ $params = array(
+ ":usr_id" => $user->get_id(),
+ ":application_id" => $application->get_id()
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_NotFound();
-
- return new self($appbox, $row['api_account_id']);
- }
+ if ( ! $row)
+ throw new Exception_NotFound();
+ return new self($appbox, $row['api_account_id']);
+ }
}
diff --git a/lib/classes/API/OAuth2/Adapter.class.php b/lib/classes/API/OAuth2/Adapter.class.php
index ed83012e10..7d2798ff9b 100644
--- a/lib/classes/API/OAuth2/Adapter.class.php
+++ b/lib/classes/API/OAuth2/Adapter.class.php
@@ -22,841 +22,798 @@
*/
class API_OAuth2_Adapter extends OAuth2
{
- /**
- * Version
- */
- const API_VERSION = "1.0";
-
- /**
- *
- * @var API_OAuth2_Application
- */
- protected $client;
-
- /**
- *
- * @var appbox
- */
- protected $appbox;
-
- /**
- * request parameter
- * @var array
- */
- protected $params;
-
- /**
- *
- * @var array
- */
- protected $token_type = array("bearer" => "Bearer");
-
- /**
- * @var array
- */
- protected $authentication_scheme = array("authorization", "uri", "body");
-
- /**
- *
- * do we enable expiration on access_token
- * @param boolean
- */
- protected $enable_expire = false;
-
- /**
- *
- * @var string
- */
- protected $session_id;
-
- /**
- *
- * @var string
- */
- protected $usr_id_requested;
-
- /**
- * access token of current request
- * @var string
- */
- protected $token;
-
- /**
- *
- * @param appbox $appbox
- * @return API_OAuth2_Adapter
- */
- public function __construct(appbox $appbox)
- {
- parent::__construct();
- $this->params = array();
- $this->appbox = $appbox;
-
- return $this;
- }
-
- /**
- *
- * @return array
- */
- public function getParams()
- {
- return $this->params;
- }
-
- /**
- *
- * @return API_OAuth2_Application
- */
- public function getClient()
- {
- return $this->client;
- }
-
- /**
- *
- * @param array $params
- * @return API_OAuth2_Adapter
- */
- public function setParams(array $params)
- {
- $this->params = $params;
-
- return $this;
- }
-
- public function getToken()
- {
- return $this->token;
- }
- /**
- *
- * @param API_OAuth2_Application $client
- */
- public function setClient(API_OAuth2_Application $client)
- {
- $this->client = $client;
-
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function has_ses_id()
- {
- return $this->session_id !== null;
- }
-
- /**
- *
- * @return int
- */
- public function get_ses_id()
- {
- return $this->session_id;
- }
-
- /**
- *
- * @return int
- */
- public function get_usr_id()
- {
- return $this->usr_id;
- }
-
- /**
- *
- * @param string $secret
- * @param string $nonce
- * @return string
- */
- protected static function crypt_secret($secret, $nonce)
- {
- $registry = registry::get_instance();
-
- return hash_hmac('sha512', $secret . $nonce, $registry->get('GV_sit'));
- }
-
- /**
- *
- * Implements OAuth2::checkClientCredentials().
- *
- * @param string $client_id
- * @param string $client_secret
- * @return boolean
- */
- protected function checkClientCredentials($client_id, $client_secret = NULL)
- {
- try
- {
- $application = API_OAuth2_Application::load_from_client_id($this->appbox, $client_id);
-
- if ($client_secret === NULL)
-
- return true;
-
- $crypted = $this->crypt_secret($client_secret, $application->get_nonce());
-
- return ($result["client_secret"] === $crypted);
- }
- catch (Exception $e)
- {
-
- }
-
- return false;
- }
-
- /**
- *
- * Implements OAuth2::getRedirectUri().
- *
- * @param string $client_id
- * @return string
- */
- protected function getRedirectUri($client_id)
- {
- $application = API_OAuth2_Application::load_from_client_id($this->appbox, $client_id);
-
- return $application->get_redirect_uri();
- }
-
- /**
- *
- * Implements OAuth2::getAccessToken().
- *
- * @param string $oauth_token
- * @return array
- */
- protected function getAccessToken($oauth_token)
- {
- $result = null;
- try
- {
- $token = API_OAuth2_Token::load_by_oauth_token($this->appbox, $oauth_token);
- $result = array(
- 'scope' => $token->get_scope()
- , 'expires' => $token->get_expires()
- , 'client_id' => $token->get_account()->get_application()->get_client_id()
- , 'session_id' => $token->get_session_id()
- , 'revoked' => ($token->get_account()->is_revoked() ? '1' : '0')
- , 'usr_id' => $token->get_account()->get_user()->get_id()
- , 'oauth_token' => $token->get_value()
- );
- }
- catch (Exception $e)
- {
-
- }
-
- return $result;
- }
-
- /**
- * Implements OAuth2::setAccessToken().
- */
-
- /**
- *
- * @param type $oauth_token
- * @param type $account_id
- * @param type $expires
- * @param string $scope
- * @return API_OAuth2_Adapter
- */
- protected function setAccessToken($oauth_token, $account_id, $expires, $scope = NULL)
- {
- $account = new API_OAuth2_Account($this->appbox, $account_id);
- $token = API_OAuth2_Token::create($this->appbox, $account, $scope);
- $token->set_value($oauth_token)->set_expires($expires);
-
- return $this;
- }
-
- /**
- *
- * Overrides OAuth2::getSupportedGrantTypes().
- *
- * @return array
- */
- protected function getSupportedGrantTypes()
- {
- return array(
- OAUTH2_GRANT_TYPE_AUTH_CODE,
- OAUTH2_GRANT_TYPE_USER_CREDENTIALS
- );
- }
-
- /**
- *
- * Overrides OAuth2::getSupportedScopes().
- *
- * @return array
- */
- protected function getSupportedScopes()
- {
- return array();
- }
-
- /**
- *
- * Overrides OAuth2::getAuthCode().
- *
- * @return array
- */
- protected function getAuthCode($code)
- {
- try
- {
- $code = new API_OAuth2_AuthCode($this->appbox, $code);
-
- return array(
- 'redirect_uri' => $code->get_redirect_uri()
- , 'client_id' => $code->get_account()->get_application()->get_client_id()
- , 'expires' => $code->get_expires()
- , 'account_id' => $code->get_account()->get_id()
- );
- }
- catch (Exception $e)
- {
-
- }
-
- return null;
- }
-
- /**
- *
- * Overrides OAuth2::setAuthCode().
- *
- * @param string $code
- * @param int $account_id
- * @param string $redirect_uri
- * @param string $expires
- * @param string $scope
- * @return API_OAuth2_Adapter
- */
- protected function setAuthCode($code, $account_id, $redirect_uri, $expires, $scope = NULL)
- {
- $account = new API_OAuth2_Account($this->appbox, $account_id);
- $code = API_OAuth2_AuthCode::create($this->appbox, $account, $code, $expires);
- $code->set_redirect_uri($redirect_uri)->set_scope($scope);
-
- return $this;
- }
-
- /**
- * Overrides OAuth2::setRefreshToken().
- */
- protected function setRefreshToken($refresh_token, $account_id, $expires, $scope = NULL)
- {
- $account = new API_OAuth2_Account($this->appbox, $account_id);
- API_OAuth2_RefreshToken::create($this->appbox, $account, $expires, $refresh_token, $scope);
-
- return $this;
- }
-
- /**
- * Overrides OAuth2::getRefreshToken().
- */
- protected function getRefreshToken($refresh_token)
- {
- try
- {
- $token = new API_OAuth2_RefreshToken($this->appbox, $refresh_token);
-
- return array(
- 'token' => $token->get_value()
- , 'expires' => $token->get_expires()->format('U')
- , 'client_id' => $token->get_account()->get_application()->get_client_id()
- );
- }
- catch (Exception $e)
- {
-
- }
-
- return null;
- }
-
- /**
- * Overrides OAuth2::unsetRefreshToken().
- */
- protected function unsetRefreshToken($refresh_token)
- {
- $token = new API_OAuth2_RefreshToken($this->appbox, $refresh_token);
- $token->delete();
-
- return $this;
- }
-
- /**
- *
- * @param Symfony\Component\HttpFoundation\Request $request
- * @return array
- */
- public function getAuthorizationRequestParameters(Symfony\Component\HttpFoundation\Request $request)
- {
-
- $datas = array(
- 'response_type' => $request->get('response_type', false)
- , 'client_id' => $request->get('client_id', false)
- , 'redirect_uri' => $request->get('redirect_uri', false)
- );
-
-
- $scope = $request->get('scope', false);
- $state = $request->get('state', false);
-
- if ($state)
- {
- $datas["state"] = $state;
- }
-
- if ($scope)
- {
- $datas["scope"] = $scope;
- }
-
- $filters = array(
- "client_id" => array(
- "filter" => FILTER_VALIDATE_REGEXP
- , "options" => array("regexp" => OAUTH2_CLIENT_ID_REGEXP)
- , "flags" => FILTER_REQUIRE_SCALAR
- )
- , "response_type" => array(
- "filter" => FILTER_VALIDATE_REGEXP
- , "options" => array("regexp" => OAUTH2_AUTH_RESPONSE_TYPE_REGEXP)
- , "flags" => FILTER_REQUIRE_SCALAR
- )
- , "redirect_uri" => array("filter" => FILTER_SANITIZE_URL)
- , "state" => array("flags" => FILTER_REQUIRE_SCALAR)
- , "scope" => array("flags" => FILTER_REQUIRE_SCALAR)
- );
-
-
- $input = filter_var_array($datas, $filters);
+ /**
+ * Version
+ */
+ const API_VERSION = "1.0";
/**
- * check for valid client_id
- * check for valid redirect_uri
+ *
+ * @var API_OAuth2_Application
*/
- if ( ! $input["client_id"])
+ protected $client;
+
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
+
+ /**
+ * request parameter
+ * @var array
+ */
+ protected $params;
+
+ /**
+ *
+ * @var array
+ */
+ protected $token_type = array("bearer" => "Bearer");
+
+ /**
+ * @var array
+ */
+ protected $authentication_scheme = array("authorization", "uri", "body");
+
+ /**
+ *
+ * do we enable expiration on access_token
+ * @param boolean
+ */
+ protected $enable_expire = false;
+
+ /**
+ *
+ * @var string
+ */
+ protected $session_id;
+
+ /**
+ *
+ * @var string
+ */
+ protected $usr_id_requested;
+
+ /**
+ * access token of current request
+ * @var string
+ */
+ protected $token;
+
+ /**
+ *
+ * @param appbox $appbox
+ * @return API_OAuth2_Adapter
+ */
+ public function __construct(appbox $appbox)
{
- if ($input["redirect_uri"])
- $this->errorDoRedirectUriCallback(
- $input["redirect_uri"], OAUTH2_ERROR_INVALID_CLIENT, NULL, NULL, $input["state"]
+ parent::__construct();
+ $this->params = array();
+ $this->appbox = $appbox;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ public function getParams()
+ {
+ return $this->params;
+ }
+
+ /**
+ *
+ * @return API_OAuth2_Application
+ */
+ public function getClient()
+ {
+ return $this->client;
+ }
+
+ /**
+ *
+ * @param array $params
+ * @return API_OAuth2_Adapter
+ */
+ public function setParams(array $params)
+ {
+ $this->params = $params;
+
+ return $this;
+ }
+
+ public function getToken()
+ {
+ return $this->token;
+ }
+
+ /**
+ *
+ * @param API_OAuth2_Application $client
+ */
+ public function setClient(API_OAuth2_Application $client)
+ {
+ $this->client = $client;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function has_ses_id()
+ {
+ return $this->session_id !== null;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_ses_id()
+ {
+ return $this->session_id;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_usr_id()
+ {
+ return $this->usr_id;
+ }
+
+ /**
+ *
+ * @param string $secret
+ * @param string $nonce
+ * @return string
+ */
+ protected static function crypt_secret($secret, $nonce)
+ {
+ $registry = registry::get_instance();
+
+ return hash_hmac('sha512', $secret . $nonce, $registry->get('GV_sit'));
+ }
+
+ /**
+ *
+ * Implements OAuth2::checkClientCredentials().
+ *
+ * @param string $client_id
+ * @param string $client_secret
+ * @return boolean
+ */
+ protected function checkClientCredentials($client_id, $client_secret = NULL)
+ {
+ try {
+ $application = API_OAuth2_Application::load_from_client_id($this->appbox, $client_id);
+
+ if ($client_secret === NULL)
+ return true;
+
+ $crypted = $this->crypt_secret($client_secret, $application->get_nonce());
+
+ return ($result["client_secret"] === $crypted);
+ } catch (Exception $e) {
+
+ }
+
+ return false;
+ }
+
+ /**
+ *
+ * Implements OAuth2::getRedirectUri().
+ *
+ * @param string $client_id
+ * @return string
+ */
+ protected function getRedirectUri($client_id)
+ {
+ $application = API_OAuth2_Application::load_from_client_id($this->appbox, $client_id);
+
+ return $application->get_redirect_uri();
+ }
+
+ /**
+ *
+ * Implements OAuth2::getAccessToken().
+ *
+ * @param string $oauth_token
+ * @return array
+ */
+ protected function getAccessToken($oauth_token)
+ {
+ $result = null;
+ try {
+ $token = API_OAuth2_Token::load_by_oauth_token($this->appbox, $oauth_token);
+ $result = array(
+ 'scope' => $token->get_scope()
+ , 'expires' => $token->get_expires()
+ , 'client_id' => $token->get_account()->get_application()->get_client_id()
+ , 'session_id' => $token->get_session_id()
+ , 'revoked' => ($token->get_account()->is_revoked() ? '1' : '0')
+ , 'usr_id' => $token->get_account()->get_user()->get_id()
+ , 'oauth_token' => $token->get_value()
+ );
+ } catch (Exception $e) {
+
+ }
+
+ return $result;
+ }
+ /**
+ * Implements OAuth2::setAccessToken().
+ */
+
+ /**
+ *
+ * @param type $oauth_token
+ * @param type $account_id
+ * @param type $expires
+ * @param string $scope
+ * @return API_OAuth2_Adapter
+ */
+ protected function setAccessToken($oauth_token, $account_id, $expires, $scope = NULL)
+ {
+ $account = new API_OAuth2_Account($this->appbox, $account_id);
+ $token = API_OAuth2_Token::create($this->appbox, $account, $scope);
+ $token->set_value($oauth_token)->set_expires($expires);
+
+ return $this;
+ }
+
+ /**
+ *
+ * Overrides OAuth2::getSupportedGrantTypes().
+ *
+ * @return array
+ */
+ protected function getSupportedGrantTypes()
+ {
+ return array(
+ OAUTH2_GRANT_TYPE_AUTH_CODE,
+ OAUTH2_GRANT_TYPE_USER_CREDENTIALS
);
- // We don't have a good URI to use
- $this->errorJsonResponse(OAUTH2_HTTP_FOUND, OAUTH2_ERROR_INVALID_CLIENT);
}
/**
- * redirect_uri is not required if already established via other channels
- * check an existing redirect URI against the one supplied
+ *
+ * Overrides OAuth2::getSupportedScopes().
+ *
+ * @return array
*/
- $redirect_uri = $this->getRedirectUri($input["client_id"]);
+ protected function getSupportedScopes()
+ {
+ return array();
+ }
/**
- * At least one of: existing redirect URI or input redirect URI must be specified
+ *
+ * Overrides OAuth2::getAuthCode().
+ *
+ * @return array
*/
- if ( ! $redirect_uri && ! $input["redirect_uri"])
- $this->errorJsonResponse(
- OAUTH2_HTTP_FOUND, OAUTH2_ERROR_INVALID_REQUEST);
+ protected function getAuthCode($code)
+ {
+ try {
+ $code = new API_OAuth2_AuthCode($this->appbox, $code);
+ return array(
+ 'redirect_uri' => $code->get_redirect_uri()
+ , 'client_id' => $code->get_account()->get_application()->get_client_id()
+ , 'expires' => $code->get_expires()
+ , 'account_id' => $code->get_account()->get_id()
+ );
+ } catch (Exception $e) {
+
+ }
+
+ return null;
+ }
/**
- * getRedirectUri() should return FALSE if the given client ID is invalid
- * this probably saves us from making a separate db call, and simplifies the method set
+ *
+ * Overrides OAuth2::setAuthCode().
+ *
+ * @param string $code
+ * @param int $account_id
+ * @param string $redirect_uri
+ * @param string $expires
+ * @param string $scope
+ * @return API_OAuth2_Adapter
*/
- if ($redirect_uri === FALSE)
- $this->errorDoRedirectUriCallback(
- $input["redirect_uri"], OAUTH2_ERROR_INVALID_CLIENT, NULL, NULL, $input["state"]);
+ protected function setAuthCode($code, $account_id, $redirect_uri, $expires, $scope = NULL)
+ {
+ $account = new API_OAuth2_Account($this->appbox, $account_id);
+ $code = API_OAuth2_AuthCode::create($this->appbox, $account, $code, $expires);
+ $code->set_redirect_uri($redirect_uri)->set_scope($scope);
+
+ return $this;
+ }
/**
- * If there's an existing uri and one from input, verify that they match
+ * Overrides OAuth2::setRefreshToken().
*/
- if ($redirect_uri && $input["redirect_uri"])
+ protected function setRefreshToken($refresh_token, $account_id, $expires, $scope = NULL)
{
- /**
- * Ensure that the input uri starts with the stored uri
- */
- $compare = strcasecmp(
- substr(
- $input["redirect_uri"], 0, strlen($redirect_uri)
- ), $redirect_uri);
- if ($compare !== 0)
- $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_REDIRECT_URI_MISMATCH, NULL, NULL, $input["state"]);
- }
- elseif ($redirect_uri)
- {
- /**
- * They did not provide a uri from input, so use the stored one
- */
- $input["redirect_uri"] = $redirect_uri;
- }
+ $account = new API_OAuth2_Account($this->appbox, $account_id);
+ API_OAuth2_RefreshToken::create($this->appbox, $account, $expires, $refresh_token, $scope);
+ return $this;
+ }
/**
- * Check response_type
+ * Overrides OAuth2::getRefreshToken().
*/
- if ( ! $input["response_type"])
+ protected function getRefreshToken($refresh_token)
{
- $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_INVALID_REQUEST, 'Invalid response type.', NULL, $input["state"]);
- }
+ try {
+ $token = new API_OAuth2_RefreshToken($this->appbox, $refresh_token);
+ return array(
+ 'token' => $token->get_value()
+ , 'expires' => $token->get_expires()->format('U')
+ , 'client_id' => $token->get_account()->get_application()->get_client_id()
+ );
+ } catch (Exception $e) {
+
+ }
+
+ return null;
+ }
/**
- * Check requested auth response type against the list of supported types
+ * Overrides OAuth2::unsetRefreshToken().
*/
- if (array_search($input["response_type"], $this->getSupportedAuthResponseTypes()) === FALSE)
- $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_UNSUPPORTED_RESPONSE_TYPE, NULL, NULL, $input["state"]);
+ protected function unsetRefreshToken($refresh_token)
+ {
+ $token = new API_OAuth2_RefreshToken($this->appbox, $refresh_token);
+ $token->delete();
+ return $this;
+ }
/**
- * Restrict clients to certain authorization response types
+ *
+ * @param Symfony\Component\HttpFoundation\Request $request
+ * @return array
*/
- if ($this->checkRestrictedAuthResponseType($input["client_id"], $input["response_type"]) === FALSE)
- $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_UNAUTHORIZED_CLIENT, NULL, NULL, $input["state"]);
+ public function getAuthorizationRequestParameters(Symfony\Component\HttpFoundation\Request $request)
+ {
+ $datas = array(
+ 'response_type' => $request->get('response_type', false)
+ , 'client_id' => $request->get('client_id', false)
+ , 'redirect_uri' => $request->get('redirect_uri', false)
+ );
+
+
+ $scope = $request->get('scope', false);
+ $state = $request->get('state', false);
+
+ if ($state) {
+ $datas["state"] = $state;
+ }
+
+ if ($scope) {
+ $datas["scope"] = $scope;
+ }
+
+ $filters = array(
+ "client_id" => array(
+ "filter" => FILTER_VALIDATE_REGEXP
+ , "options" => array("regexp" => OAUTH2_CLIENT_ID_REGEXP)
+ , "flags" => FILTER_REQUIRE_SCALAR
+ )
+ , "response_type" => array(
+ "filter" => FILTER_VALIDATE_REGEXP
+ , "options" => array("regexp" => OAUTH2_AUTH_RESPONSE_TYPE_REGEXP)
+ , "flags" => FILTER_REQUIRE_SCALAR
+ )
+ , "redirect_uri" => array("filter" => FILTER_SANITIZE_URL)
+ , "state" => array("flags" => FILTER_REQUIRE_SCALAR)
+ , "scope" => array("flags" => FILTER_REQUIRE_SCALAR)
+ );
+
+
+ $input = filter_var_array($datas, $filters);
+
+ /**
+ * check for valid client_id
+ * check for valid redirect_uri
+ */
+ if ( ! $input["client_id"]) {
+ if ($input["redirect_uri"])
+ $this->errorDoRedirectUriCallback(
+ $input["redirect_uri"], OAUTH2_ERROR_INVALID_CLIENT, NULL, NULL, $input["state"]
+ );
+ // We don't have a good URI to use
+ $this->errorJsonResponse(OAUTH2_HTTP_FOUND, OAUTH2_ERROR_INVALID_CLIENT);
+ }
+
+ /**
+ * redirect_uri is not required if already established via other channels
+ * check an existing redirect URI against the one supplied
+ */
+ $redirect_uri = $this->getRedirectUri($input["client_id"]);
+
+ /**
+ * At least one of: existing redirect URI or input redirect URI must be specified
+ */
+ if ( ! $redirect_uri && ! $input["redirect_uri"])
+ $this->errorJsonResponse(
+ OAUTH2_HTTP_FOUND, OAUTH2_ERROR_INVALID_REQUEST);
+
+
+ /**
+ * getRedirectUri() should return FALSE if the given client ID is invalid
+ * this probably saves us from making a separate db call, and simplifies the method set
+ */
+ if ($redirect_uri === FALSE)
+ $this->errorDoRedirectUriCallback(
+ $input["redirect_uri"], OAUTH2_ERROR_INVALID_CLIENT, NULL, NULL, $input["state"]);
+
+ /**
+ * If there's an existing uri and one from input, verify that they match
+ */
+ if ($redirect_uri && $input["redirect_uri"]) {
+ /**
+ * Ensure that the input uri starts with the stored uri
+ */
+ $compare = strcasecmp(
+ substr(
+ $input["redirect_uri"], 0, strlen($redirect_uri)
+ ), $redirect_uri);
+ if ($compare !== 0)
+ $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_REDIRECT_URI_MISMATCH, NULL, NULL, $input["state"]);
+ }
+ elseif ($redirect_uri) {
+ /**
+ * They did not provide a uri from input, so use the stored one
+ */
+ $input["redirect_uri"] = $redirect_uri;
+ }
+
+
+ /**
+ * Check response_type
+ */
+ if ( ! $input["response_type"]) {
+ $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_INVALID_REQUEST, 'Invalid response type.', NULL, $input["state"]);
+ }
+
+
+ /**
+ * Check requested auth response type against the list of supported types
+ */
+ if (array_search($input["response_type"], $this->getSupportedAuthResponseTypes()) === FALSE)
+ $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_UNSUPPORTED_RESPONSE_TYPE, NULL, NULL, $input["state"]);
+
+
+ /**
+ * Restrict clients to certain authorization response types
+ */
+ if ($this->checkRestrictedAuthResponseType($input["client_id"], $input["response_type"]) === FALSE)
+ $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_UNAUTHORIZED_CLIENT, NULL, NULL, $input["state"]);
+
+
+ /**
+ * Validate that the requested scope is supported
+ */
+ if ($input["scope"] && ! $this->checkScope($input["scope"], $this->getSupportedScopes()))
+ $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_INVALID_SCOPE, NULL, NULL, $input["state"]);
+
+ /**
+ * at this point all params are ok
+ */
+ $this->params = $input;
+
+ return $input;
+ }
/**
- * Validate that the requested scope is supported
+ *
+ * @param usr_id $usr_id
+ * @return API_OAuth2_Account
*/
- if ($input["scope"] && ! $this->checkScope($input["scope"], $this->getSupportedScopes()))
- $this->errorDoRedirectUriCallback($input["redirect_uri"], OAUTH2_ERROR_INVALID_SCOPE, NULL, NULL, $input["state"]);
+ public function updateAccount($usr_id)
+ {
+ if ($this->client === null)
+ throw new logicalException("Client property must be set before update an account");
+
+ try {
+ $user = User_Adapter::getInstance($usr_id, $this->appbox);
+ $account = API_OAuth2_Account::load_with_user($this->appbox, $this->client, $user);
+ } catch (Exception $e) {
+ $account = $this->createAccount($usr_id);
+ }
+
+ return $account;
+ }
/**
- * at this point all params are ok
+ *
+ * @param int $usr_id
+ * @return API_OAuth2_Account
*/
- $this->params = $input;
-
- return $input;
- }
-
-
-
- /**
- *
- * @param usr_id $usr_id
- * @return API_OAuth2_Account
- */
- public function updateAccount($usr_id)
- {
- if ($this->client === null)
- throw new logicalException("Client property must be set before update an account");
-
- try
+ private function createAccount($usr_id)
{
- $user = User_Adapter::getInstance($usr_id, $this->appbox);
- $account = API_OAuth2_Account::load_with_user($this->appbox, $this->client, $user);
- }
- catch (Exception $e)
- {
- $account = $this->createAccount($usr_id);
+ $user = User_Adapter::getInstance($usr_id, $this->appbox);
+
+ return API_OAuth2_Account::create($this->appbox, $user, $this->client);
}
- return $account;
- }
-
- /**
- *
- * @param int $usr_id
- * @return API_OAuth2_Account
- */
- private function createAccount($usr_id)
- {
- $user = User_Adapter::getInstance($usr_id, $this->appbox);
-
- return API_OAuth2_Account::create($this->appbox, $user, $this->client);
- }
-
- /**
- *
- * @param $is_authorized
- * @param array $params
- * @return string
- */
- public function finishNativeClientAuthorization($is_authorized, $params = array())
- {
- $result = array();
- $params += array(
- 'scope' => NULL,
- 'state' => NULL,
- );
- extract($params);
-
- if ($state !== NULL)
- $result["query"]["state"] = $state;
-
- if ($is_authorized === FALSE)
+ /**
+ *
+ * @param $is_authorized
+ * @param array $params
+ * @return string
+ */
+ public function finishNativeClientAuthorization($is_authorized, $params = array())
{
- $result["error"] = OAUTH2_ERROR_USER_DENIED;
- }
- else
- {
- if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_AUTH_CODE)
- $result["code"] = $this->createAuthCode($account_id, $redirect_uri, $scope);
+ $result = array();
+ $params += array(
+ 'scope' => NULL,
+ 'state' => NULL,
+ );
+ extract($params);
- if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_ACCESS_TOKEN)
- $result["error"] = OAUTH2_ERROR_UNSUPPORTED_RESPONSE_TYPE;
+ if ($state !== NULL)
+ $result["query"]["state"] = $state;
+
+ if ($is_authorized === FALSE) {
+ $result["error"] = OAUTH2_ERROR_USER_DENIED;
+ } else {
+ if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_AUTH_CODE)
+ $result["code"] = $this->createAuthCode($account_id, $redirect_uri, $scope);
+
+ if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_ACCESS_TOKEN)
+ $result["error"] = OAUTH2_ERROR_UNSUPPORTED_RESPONSE_TYPE;
+ }
+
+ return $result;
}
- return $result;
- }
-
- /**
- *
- * @param $redirect_uri
- * @return
- */
- public function isNativeApp($redirect_uri)
- {
- return $redirect_uri === API_OAuth2_Application::NATIVE_APP_REDIRECT_URI;
- }
-
- public function remember_this_ses_id($ses_id)
- {
- try
+ /**
+ *
+ * @param $redirect_uri
+ * @return
+ */
+ public function isNativeApp($redirect_uri)
{
- $token = API_OAuth2_Token::load_by_oauth_token($this->appbox, $this->token);
- $token->set_session_id($ses_id);
-
- return true;
- }
- catch (Exception $e)
- {
-
+ return $redirect_uri === API_OAuth2_Application::NATIVE_APP_REDIRECT_URI;
}
- return false;
- }
-
- public function verifyAccessToken($scope = NULL, $exit_not_present = TRUE, $exit_invalid = TRUE, $exit_expired = TRUE, $exit_scope = TRUE, $realm = NULL)
- {
- $token_param = $this->getAccessTokenParams();
-
-
- if ($token_param === FALSE) // Access token was not provided
-
- return $exit_not_present ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_BAD_REQUEST, $realm, OAUTH2_ERROR_INVALID_REQUEST, 'The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.', NULL, $scope) : FALSE;
- // Get the stored token data (from the implementing subclass)
- $token = $this->getAccessToken($token_param);
-
- if ($token === NULL)
-
- return $exit_invalid ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_INVALID_TOKEN, 'The access token provided is invalid.', NULL, $scope) : FALSE;
-
- if (isset($token['revoked']) && $token['revoked'])
+ public function remember_this_ses_id($ses_id)
{
- return $exit_invalid ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_INVALID_TOKEN, 'End user has revoked access to his personal datas for your application.', NULL, $scope) : FALSE;
+ try {
+ $token = API_OAuth2_Token::load_by_oauth_token($this->appbox, $this->token);
+ $token->set_session_id($ses_id);
+
+ return true;
+ } catch (Exception $e) {
+
+ }
+
+ return false;
}
- if ($this->enable_expire)
+ public function verifyAccessToken($scope = NULL, $exit_not_present = TRUE, $exit_invalid = TRUE, $exit_expired = TRUE, $exit_scope = TRUE, $realm = NULL)
{
- // Check token expiration (I'm leaving this check separated, later we'll fill in better error messages)
- if (isset($token["expires"]) && time() > $token["expires"])
+ $token_param = $this->getAccessTokenParams();
- return $exit_expired ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_EXPIRED_TOKEN, 'The access token provided has expired.', NULL, $scope) : FALSE;
- }
- // Check scope, if provided
- // If token doesn't have a scope, it's NULL/empty, or it's insufficient, then throw an error
- if ($scope && ( ! isset($token["scope"]) || ! $token["scope"] || ! $this->checkScope($scope, $token["scope"])))
- return $exit_scope ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_FORBIDDEN, $realm, OAUTH2_ERROR_INSUFFICIENT_SCOPE, 'The request requires higher privileges than provided by the access token.', NULL, $scope) : FALSE;
+ if ($token_param === FALSE) // Access token was not provided
+ return $exit_not_present ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_BAD_REQUEST, $realm, OAUTH2_ERROR_INVALID_REQUEST, 'The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.', NULL, $scope) : FALSE;
+ // Get the stored token data (from the implementing subclass)
+ $token = $this->getAccessToken($token_param);
- //save token's linked ses_id
- $this->session_id = $token['session_id'];
- $this->usr_id = $token['usr_id'];
- $this->token = $token['oauth_token'];
+ if ($token === NULL)
+ return $exit_invalid ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_INVALID_TOKEN, 'The access token provided is invalid.', NULL, $scope) : FALSE;
- return TRUE;
- }
+ if (isset($token['revoked']) && $token['revoked']) {
+ return $exit_invalid ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_INVALID_TOKEN, 'End user has revoked access to his personal datas for your application.', NULL, $scope) : FALSE;
+ }
- public function finishClientAuthorization($is_authorized, $params = array())
- {
- $params += array(
- 'scope' => NULL,
- 'state' => NULL,
- );
- extract($params);
+ if ($this->enable_expire) {
+ // Check token expiration (I'm leaving this check separated, later we'll fill in better error messages)
+ if (isset($token["expires"]) && time() > $token["expires"])
+ return $exit_expired ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_UNAUTHORIZED, $realm, OAUTH2_ERROR_EXPIRED_TOKEN, 'The access token provided has expired.', NULL, $scope) : FALSE;
+ }
+ // Check scope, if provided
+ // If token doesn't have a scope, it's NULL/empty, or it's insufficient, then throw an error
+ if ($scope && ( ! isset($token["scope"]) || ! $token["scope"] || ! $this->checkScope($scope, $token["scope"])))
+ return $exit_scope ? $this->errorWWWAuthenticateResponseHeader(OAUTH2_HTTP_FORBIDDEN, $realm, OAUTH2_ERROR_INSUFFICIENT_SCOPE, 'The request requires higher privileges than provided by the access token.', NULL, $scope) : FALSE;
- if ($state !== NULL)
- $result["query"]["state"] = $state;
- if ($is_authorized === FALSE)
- $result["query"]["error"] = OAUTH2_ERROR_USER_DENIED;
- else
- {
- if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_AUTH_CODE || $response_type == OAUTH2_AUTH_RESPONSE_TYPE_CODE_AND_TOKEN)
- $result["query"]["code"] = $this->createAuthCode($account_id, $redirect_uri, $scope);
+ //save token's linked ses_id
+ $this->session_id = $token['session_id'];
+ $this->usr_id = $token['usr_id'];
+ $this->token = $token['oauth_token'];
- if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_ACCESS_TOKEN || $response_type == OAUTH2_AUTH_RESPONSE_TYPE_CODE_AND_TOKEN)
- $result["fragment"] = $this->createAccessToken($account_id, $scope);
- }
- $this->doRedirectUriCallback($redirect_uri, $result);
- }
-
- /**
- *
- */
- public function grantAccessToken()
- {
- $filters = array(
- "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => OAUTH2_GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
- "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
- "code" => array("flags" => FILTER_REQUIRE_SCALAR),
- "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
- "username" => array("flags" => FILTER_REQUIRE_SCALAR),
- "password" => array("flags" => FILTER_REQUIRE_SCALAR),
- "assertion_type" => array("flags" => FILTER_REQUIRE_SCALAR),
- "assertion" => array("flags" => FILTER_REQUIRE_SCALAR),
- "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
- );
-
- $input = filter_input_array(INPUT_POST, $filters);
-
- // Grant Type must be specified.
- if ( ! $input["grant_type"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
-
- // Make sure we've implemented the requested grant type
- if ( ! in_array($input["grant_type"], $this->getSupportedGrantTypes()))
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_UNSUPPORTED_GRANT_TYPE);
-
- // Authorize the client
- $client = $this->getClientCredentials();
-
- if ($this->checkClientCredentials($client[0], $client[1]) === FALSE)
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_CLIENT);
-
- if ( ! $this->checkRestrictedGrantType($client[0], $input["grant_type"]))
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_UNAUTHORIZED_CLIENT);
-
- // Do the granting
- switch ($input["grant_type"])
- {
- case OAUTH2_GRANT_TYPE_AUTH_CODE:
- if ( ! $input["code"] || ! $input["redirect_uri"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
- $stored = $this->getAuthCode($input["code"]);
-
- // Ensure that the input uri starts with the stored uri
- if ($stored === NULL || (strcasecmp(substr($input["redirect_uri"], 0, strlen($stored["redirect_uri"])), $stored["redirect_uri"]) !== 0) || $client[0] != $stored["client_id"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
-
- if ($stored["expires"] < time())
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_EXPIRED_TOKEN);
- break;
- case OAUTH2_GRANT_TYPE_USER_CREDENTIALS:
- if ( ! $input["username"] || ! $input["password"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
-
- $stored = $this->checkUserCredentials($client[0], $input["username"], $input["password"]);
-
- if ($stored === FALSE)
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT, 'Unknow user');
-
- break;
- case OAUTH2_GRANT_TYPE_ASSERTION:
- if ( ! $input["assertion_type"] || ! $input["assertion"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
-
- $stored = $this->checkAssertion($client[0], $input["assertion_type"], $input["assertion"]);
-
- if ($stored === FALSE)
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
-
- break;
- case OAUTH2_GRANT_TYPE_REFRESH_TOKEN:
- if ( ! $input["refresh_token"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
-
- $stored = $this->getRefreshToken($input["refresh_token"]);
-
- if ($stored === NULL || $client[0] != $stored["client_id"])
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
-
- if ($stored["expires"] < time())
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_EXPIRED_TOKEN);
-
- // store the refresh token locally so we can delete it when a new refresh token is generated
- $this->setVariable('_old_refresh_token', $stored["token"]);
-
- break;
- case OAUTH2_GRANT_TYPE_NONE:
- $stored = $this->checkNoneAccess($client[0]);
-
- if ($stored === FALSE)
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
+ return TRUE;
}
- // Check scope, if provided
- if ($input["scope"] && ( ! is_array($stored) || ! isset($stored["scope"]) || ! $this->checkScope($input["scope"], $stored["scope"])))
- $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_SCOPE);
-
- if ( ! $input["scope"])
- $input["scope"] = NULL;
-
- $token = $this->createAccessToken($stored['account_id'], $input["scope"]);
- $this->sendJsonHeaders();
-
- echo json_encode($token);
-
- return;
- }
-
- protected function createAccessToken($account_id, $scope = NULL)
- {
- $token = array(
- "access_token" => $this->genAccessToken(),
- "scope" => $scope
- );
-
- if ($this->enable_expire)
- $token['expires_in'] = $this->getVariable('access_token_lifetime', OAUTH2_DEFAULT_ACCESS_TOKEN_LIFETIME);
-
- $this->setAccessToken($token["access_token"], $account_id, time() + $this->getVariable('access_token_lifetime', OAUTH2_DEFAULT_ACCESS_TOKEN_LIFETIME), $scope);
-
- // Issue a refresh token also, if we support them
- if (in_array(OAUTH2_GRANT_TYPE_REFRESH_TOKEN, $this->getSupportedGrantTypes()))
+ public function finishClientAuthorization($is_authorized, $params = array())
{
- $token["refresh_token"] = $this->genAccessToken();
- $this->setRefreshToken($token["refresh_token"], $account_id, time() + $this->getVariable('refresh_token_lifetime', OAUTH2_DEFAULT_REFRESH_TOKEN_LIFETIME), $scope);
- // If we've granted a new refresh token, expire the old one
- if ($this->getVariable('_old_refresh_token'))
- $this->unsetRefreshToken($this->getVariable('_old_refresh_token'));
+ $params += array(
+ 'scope' => NULL,
+ 'state' => NULL,
+ );
+ extract($params);
+
+ if ($state !== NULL)
+ $result["query"]["state"] = $state;
+ if ($is_authorized === FALSE)
+ $result["query"]["error"] = OAUTH2_ERROR_USER_DENIED;
+ else {
+ if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_AUTH_CODE || $response_type == OAUTH2_AUTH_RESPONSE_TYPE_CODE_AND_TOKEN)
+ $result["query"]["code"] = $this->createAuthCode($account_id, $redirect_uri, $scope);
+
+ if ($response_type == OAUTH2_AUTH_RESPONSE_TYPE_ACCESS_TOKEN || $response_type == OAUTH2_AUTH_RESPONSE_TYPE_CODE_AND_TOKEN)
+ $result["fragment"] = $this->createAccessToken($account_id, $scope);
+ }
+ $this->doRedirectUriCallback($redirect_uri, $result);
}
- return $token;
- }
-
- protected function checkUserCredentials($client_id, $username, $password)
- {
- try
+ /**
+ *
+ */
+ public function grantAccessToken()
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
+ $filters = array(
+ "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => OAUTH2_GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
+ "scope" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "code" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
+ "username" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "password" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "assertion_type" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "assertion" => array("flags" => FILTER_REQUIRE_SCALAR),
+ "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
+ );
- $application = API_OAuth2_Application::load_from_client_id($appbox, $client_id);
+ $input = filter_input_array(INPUT_POST, $filters);
- $auth = new \Session_Authentication_Native($appbox, $username, $password);
+ // Grant Type must be specified.
+ if ( ! $input["grant_type"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
- $auth->challenge_password();
+ // Make sure we've implemented the requested grant type
+ if ( ! in_array($input["grant_type"], $this->getSupportedGrantTypes()))
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_UNSUPPORTED_GRANT_TYPE);
- $account = API_OAuth2_Account::load_with_user($appbox, $application, $auth->get_user());
+ // Authorize the client
+ $client = $this->getClientCredentials();
- return array(
- 'redirect_uri' => $application->get_redirect_uri()
- , 'client_id' => $application->get_client_id()
- , 'account_id' => $account->get_id()
- );
+ if ($this->checkClientCredentials($client[0], $client[1]) === FALSE)
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_CLIENT);
+
+ if ( ! $this->checkRestrictedGrantType($client[0], $input["grant_type"]))
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_UNAUTHORIZED_CLIENT);
+
+ // Do the granting
+ switch ($input["grant_type"]) {
+ case OAUTH2_GRANT_TYPE_AUTH_CODE:
+ if ( ! $input["code"] || ! $input["redirect_uri"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
+ $stored = $this->getAuthCode($input["code"]);
+
+ // Ensure that the input uri starts with the stored uri
+ if ($stored === NULL || (strcasecmp(substr($input["redirect_uri"], 0, strlen($stored["redirect_uri"])), $stored["redirect_uri"]) !== 0) || $client[0] != $stored["client_id"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
+
+ if ($stored["expires"] < time())
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_EXPIRED_TOKEN);
+ break;
+ case OAUTH2_GRANT_TYPE_USER_CREDENTIALS:
+ if ( ! $input["username"] || ! $input["password"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
+
+ $stored = $this->checkUserCredentials($client[0], $input["username"], $input["password"]);
+
+ if ($stored === FALSE)
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT, 'Unknow user');
+
+ break;
+ case OAUTH2_GRANT_TYPE_ASSERTION:
+ if ( ! $input["assertion_type"] || ! $input["assertion"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
+
+ $stored = $this->checkAssertion($client[0], $input["assertion_type"], $input["assertion"]);
+
+ if ($stored === FALSE)
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
+
+ break;
+ case OAUTH2_GRANT_TYPE_REFRESH_TOKEN:
+ if ( ! $input["refresh_token"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
+
+ $stored = $this->getRefreshToken($input["refresh_token"]);
+
+ if ($stored === NULL || $client[0] != $stored["client_id"])
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_GRANT);
+
+ if ($stored["expires"] < time())
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_EXPIRED_TOKEN);
+
+ // store the refresh token locally so we can delete it when a new refresh token is generated
+ $this->setVariable('_old_refresh_token', $stored["token"]);
+
+ break;
+ case OAUTH2_GRANT_TYPE_NONE:
+ $stored = $this->checkNoneAccess($client[0]);
+
+ if ($stored === FALSE)
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_REQUEST);
+ }
+
+ // Check scope, if provided
+ if ($input["scope"] && ( ! is_array($stored) || ! isset($stored["scope"]) || ! $this->checkScope($input["scope"], $stored["scope"])))
+ $this->errorJsonResponse(OAUTH2_HTTP_BAD_REQUEST, OAUTH2_ERROR_INVALID_SCOPE);
+
+ if ( ! $input["scope"])
+ $input["scope"] = NULL;
+
+ $token = $this->createAccessToken($stored['account_id'], $input["scope"]);
+ $this->sendJsonHeaders();
+
+ echo json_encode($token);
+
+ return;
}
- catch (\Exception $e)
+
+ protected function createAccessToken($account_id, $scope = NULL)
{
- return false;
- }
- }
+ $token = array(
+ "access_token" => $this->genAccessToken(),
+ "scope" => $scope
+ );
+ if ($this->enable_expire)
+ $token['expires_in'] = $this->getVariable('access_token_lifetime', OAUTH2_DEFAULT_ACCESS_TOKEN_LIFETIME);
+
+ $this->setAccessToken($token["access_token"], $account_id, time() + $this->getVariable('access_token_lifetime', OAUTH2_DEFAULT_ACCESS_TOKEN_LIFETIME), $scope);
+
+ // Issue a refresh token also, if we support them
+ if (in_array(OAUTH2_GRANT_TYPE_REFRESH_TOKEN, $this->getSupportedGrantTypes())) {
+ $token["refresh_token"] = $this->genAccessToken();
+ $this->setRefreshToken($token["refresh_token"], $account_id, time() + $this->getVariable('refresh_token_lifetime', OAUTH2_DEFAULT_REFRESH_TOKEN_LIFETIME), $scope);
+ // If we've granted a new refresh token, expire the old one
+ if ($this->getVariable('_old_refresh_token'))
+ $this->unsetRefreshToken($this->getVariable('_old_refresh_token'));
+ }
+
+ return $token;
+ }
+
+ protected function checkUserCredentials($client_id, $username, $password)
+ {
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+
+ $application = API_OAuth2_Application::load_from_client_id($appbox, $client_id);
+
+ $auth = new \Session_Authentication_Native($appbox, $username, $password);
+
+ $auth->challenge_password();
+
+ $account = API_OAuth2_Account::load_with_user($appbox, $application, $auth->get_user());
+
+ return array(
+ 'redirect_uri' => $application->get_redirect_uri()
+ , 'client_id' => $application->get_client_id()
+ , 'account_id' => $account->get_id()
+ );
+ } catch (\Exception $e) {
+ return false;
+ }
+ }
}
diff --git a/lib/classes/API/OAuth2/Application.class.php b/lib/classes/API/OAuth2/Application.class.php
index 43cf5041c2..198ac3a55f 100644
--- a/lib/classes/API/OAuth2/Application.class.php
+++ b/lib/classes/API/OAuth2/Application.class.php
@@ -21,629 +21,622 @@
*/
class API_OAuth2_Application
{
- /**
- * constant for desktop application
- */
- const DESKTOP_TYPE = 'desktop';
- /**
- * constant for web application
- */
- const WEB_TYPE = 'web';
- /**
- * Uniform Resource Name
- */
- const NATIVE_APP_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
+ /**
+ * constant for desktop application
+ */
+ const DESKTOP_TYPE = 'desktop';
+ /**
+ * constant for web application
+ */
+ const WEB_TYPE = 'web';
+ /**
+ * Uniform Resource Name
+ */
+ const NATIVE_APP_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var User_Adapter
- */
- protected $creator;
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $creator;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $name;
+ /**
+ *
+ * @var string
+ */
+ protected $name;
- /**
- *
- * @var string
- */
- protected $nonce;
+ /**
+ *
+ * @var string
+ */
+ protected $nonce;
- /**
- *
- * @var string
- */
- protected $description;
+ /**
+ *
+ * @var string
+ */
+ protected $description;
- /**
- *
- * @var string
- */
- protected $website;
+ /**
+ *
+ * @var string
+ */
+ protected $website;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $last_modified;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $last_modified;
- /**
- *
- * @var string
- */
- protected $client_id;
+ /**
+ *
+ * @var string
+ */
+ protected $client_id;
- /**
- *
- * @var string
- */
- protected $client_secret;
+ /**
+ *
+ * @var string
+ */
+ protected $client_secret;
- /**
- *
- * @var string
- */
- protected $redirect_uri;
+ /**
+ *
+ * @var string
+ */
+ protected $redirect_uri;
- /**
- *
- * @param appbox $appbox
- * @param int $application_id
- * @return API_OAuth2_Application
- */
- public function __construct(appbox &$appbox, $application_id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $application_id;
+ /**
+ *
+ * @param appbox $appbox
+ * @param int $application_id
+ * @return API_OAuth2_Application
+ */
+ public function __construct(appbox &$appbox, $application_id)
+ {
+ $this->appbox = $appbox;
+ $this->id = (int) $application_id;
- $sql = 'SELECT application_id, creator, type, name, description, website
+ $sql = 'SELECT application_id, creator, type, name, description, website
, created_on, last_modified, client_id, client_secret, nonce
, redirect_uri
FROM api_applications
WHERE application_id = :application_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':application_id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':application_id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->creator = User_Adapter::getInstance($row['creator'], $this->appbox);
- $this->type = $row['type'];
- $this->name = $row['name'];
- $this->description = $row['description'];
- $this->website = $row['website'];
- $this->created_on = new DateTime($row['created_on']);
- $this->last_modified = new DateTime($row['last_modified']);
- $this->client_id = $row['client_id'];
- $this->client_secret = $row['client_secret'];
- $this->redirect_uri = $row['redirect_uri'];
- $this->nonce = $row['nonce'];
+ $this->creator = User_Adapter::getInstance($row['creator'], $this->appbox);
+ $this->type = $row['type'];
+ $this->name = $row['name'];
+ $this->description = $row['description'];
+ $this->website = $row['website'];
+ $this->created_on = new DateTime($row['created_on']);
+ $this->last_modified = new DateTime($row['last_modified']);
+ $this->client_id = $row['client_id'];
+ $this->client_secret = $row['client_secret'];
+ $this->redirect_uri = $row['redirect_uri'];
+ $this->nonce = $row['nonce'];
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_creator()
- {
- return $this->creator;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_creator()
+ {
+ return $this->creator;
+ }
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @return string
- */
- public function get_nonce()
- {
- return $this->nonce;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_nonce()
+ {
+ return $this->nonce;
+ }
- /**
- *
- * @param string $type
- * @return API_OAuth2_Application
- */
- public function set_type($type)
- {
- if (!in_array($type, array(self::DESKTOP_TYPE, self::WEB_TYPE)))
- throw new Exception_InvalidArgument();
+ /**
+ *
+ * @param string $type
+ * @return API_OAuth2_Application
+ */
+ public function set_type($type)
+ {
+ if ( ! in_array($type, array(self::DESKTOP_TYPE, self::WEB_TYPE)))
+ throw new Exception_InvalidArgument();
- $this->type = $type;
+ $this->type = $type;
- if ($this->type == self::DESKTOP_TYPE)
- $this->set_redirect_uri(self::NATIVE_APP_REDIRECT_URI);
+ if ($this->type == self::DESKTOP_TYPE)
+ $this->set_redirect_uri(self::NATIVE_APP_REDIRECT_URI);
- $sql = 'UPDATE api_applications SET type = :type, last_modified = NOW()
+ $sql = 'UPDATE api_applications SET type = :type, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':type' => $this->type
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':type' => $this->type
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
- /**
- *
- * @param string $name
- * @return API_OAuth2_Application
- */
- public function set_name($name)
- {
- $this->name = $name;
+ /**
+ *
+ * @param string $name
+ * @return API_OAuth2_Application
+ */
+ public function set_name($name)
+ {
+ $this->name = $name;
- $sql = 'UPDATE api_applications SET name = :name, last_modified = NOW()
+ $sql = 'UPDATE api_applications SET name = :name, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':name' => $this->name
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':name' => $this->name
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return $this->description;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return $this->description;
+ }
- /**
- *
- * @param string $description
- * @return API_OAuth2_Application
- */
- public function set_description($description)
- {
- $this->description = $description;
+ /**
+ *
+ * @param string $description
+ * @return API_OAuth2_Application
+ */
+ public function set_description($description)
+ {
+ $this->description = $description;
- $sql = 'UPDATE api_applications
+ $sql = 'UPDATE api_applications
SET description = :description, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':description' => $this->description
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':description' => $this->description
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_website()
- {
- return $this->website;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_website()
+ {
+ return $this->website;
+ }
- /**
- *
- * @param string $website
- * @return API_OAuth2_Application
- */
- public function set_website($website)
- {
- $this->website = $website;
+ /**
+ *
+ * @param string $website
+ * @return API_OAuth2_Application
+ */
+ public function set_website($website)
+ {
+ $this->website = $website;
- $sql = 'UPDATE api_applications
+ $sql = 'UPDATE api_applications
SET website = :website, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':website' => $this->website
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':website' => $this->website
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_last_modified()
- {
- return $this->last_modified;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_last_modified()
+ {
+ return $this->last_modified;
+ }
- /**
- *
- * @return int
- */
- public function get_client_id()
- {
- return $this->client_id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_client_id()
+ {
+ return $this->client_id;
+ }
- /**
- *
- * @param int $client_id
- * @return API_OAuth2_Application
- */
- public function set_client_id($client_id)
- {
- $this->client_id = $client_id;
+ /**
+ *
+ * @param int $client_id
+ * @return API_OAuth2_Application
+ */
+ public function set_client_id($client_id)
+ {
+ $this->client_id = $client_id;
- $sql = 'UPDATE api_applications
+ $sql = 'UPDATE api_applications
SET client_id = :client_id, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':client_id' => $this->client_id
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':client_id' => $this->client_id
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_client_secret()
- {
- return $this->client_secret;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_client_secret()
+ {
+ return $this->client_secret;
+ }
- /**
- *
- * @param string $client_secret
- * @return API_OAuth2_Application
- */
- public function set_client_secret($client_secret)
- {
- $this->client_secret = $client_secret;
+ /**
+ *
+ * @param string $client_secret
+ * @return API_OAuth2_Application
+ */
+ public function set_client_secret($client_secret)
+ {
+ $this->client_secret = $client_secret;
- $sql = 'UPDATE api_applications
+ $sql = 'UPDATE api_applications
SET client_secret = :client_secret, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':client_secret' => $this->client_secret
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':client_secret' => $this->client_secret
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_redirect_uri()
- {
- return $this->redirect_uri;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_redirect_uri()
+ {
+ return $this->redirect_uri;
+ }
- /**
- *
- * @param string $redirect_uri
- * @return API_OAuth2_Application
- */
- public function set_redirect_uri($redirect_uri)
- {
- $this->redirect_uri = $redirect_uri;
- $sql = 'UPDATE api_applications
+ /**
+ *
+ * @param string $redirect_uri
+ * @return API_OAuth2_Application
+ */
+ public function set_redirect_uri($redirect_uri)
+ {
+ $this->redirect_uri = $redirect_uri;
+ $sql = 'UPDATE api_applications
SET redirect_uri = :redirect_uri, last_modified = NOW()
WHERE application_id = :application_id';
- $params = array(
- ':redirect_uri' => $this->redirect_uri
- , ':application_id' => $this->id
- );
+ $params = array(
+ ':redirect_uri' => $this->redirect_uri
+ , ':application_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param User_Adapter $user
- * @return API_OAuth2_Account
- */
- public function get_user_account(user_adapter $user)
- {
- $sql = 'SELECT api_account_id FROM api_accounts
+ /**
+ *
+ * @param User_Adapter $user
+ * @return API_OAuth2_Account
+ */
+ public function get_user_account(user_adapter $user)
+ {
+ $sql = 'SELECT api_account_id FROM api_accounts
WHERE usr_id = :usr_id AND application_id = :id';
- $params = array(
- ':usr_id' => $user->get_id()
- , ':id' => $this->id
- );
+ $params = array(
+ ':usr_id' => $user->get_id()
+ , ':id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_NotFound();
+ if ( ! $row)
+ throw new Exception_NotFound();
- return new API_OAuth2_Account($this->appbox, $row['api_account_id']);
- }
-
- /**
- *
- * @return void
- */
- public function delete()
- {
- foreach ($this->get_related_accounts() as $account)
- {
- $account->delete();
+ return new API_OAuth2_Account($this->appbox, $row['api_account_id']);
}
- $sql = 'DELETE FROM api_applications
- WHERE application_id = :application_id';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':application_id' => $this->get_id()));
- $stmt->closeCursor();
-
- return;
- }
-
- /**
- *
- * @return array
- */
- protected function get_related_accounts()
- {
- $sql = 'SELECT api_account_id FROM api_accounts
- WHERE application_id = :application_id';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':application_id' => $this->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $accounts = array();
-
- foreach ($rs as $row)
+ /**
+ *
+ * @return void
+ */
+ public function delete()
{
- $accounts[] = new API_OAuth2_Account($this->appbox, $row['api_account_id']);
+ foreach ($this->get_related_accounts() as $account) {
+ $account->delete();
+ }
+
+ $sql = 'DELETE FROM api_applications
+ WHERE application_id = :application_id';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':application_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ return;
}
- return $accounts;
- }
+ /**
+ *
+ * @return array
+ */
+ protected function get_related_accounts()
+ {
+ $sql = 'SELECT api_account_id FROM api_accounts
+ WHERE application_id = :application_id';
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param type $name
- * @return API_OAuth2_Application
- */
- public static function create(appbox &$appbox, User_Adapter $user, $name)
- {
- $sql = 'INSERT INTO api_applications
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':application_id' => $this->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $accounts = array();
+
+ foreach ($rs as $row) {
+ $accounts[] = new API_OAuth2_Account($this->appbox, $row['api_account_id']);
+ }
+
+ return $accounts;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param type $name
+ * @return API_OAuth2_Application
+ */
+ public static function create(appbox &$appbox, User_Adapter $user, $name)
+ {
+ $sql = 'INSERT INTO api_applications
(application_id, creator, created_on, name
, last_modified, nonce, client_id, client_secret)
VALUES (null, :usr_id, NOW(), :name, NOW()
, :nonce, :client_id, :client_secret)';
- $nonce = random::generatePassword(6);
- $client_secret = API_OAuth2_Token::generate_token();
- $client_token = API_OAuth2_Token::generate_token();
+ $nonce = random::generatePassword(6);
+ $client_secret = API_OAuth2_Token::generate_token();
+ $client_token = API_OAuth2_Token::generate_token();
- $params = array(
- ':usr_id' => $user->get_id(),
- ':name' => $name,
- ':client_id' => $client_token,
- ':client_secret' => $client_secret,
- ':nonce' => $nonce,
- );
+ $params = array(
+ ':usr_id' => $user->get_id(),
+ ':name' => $name,
+ ':client_id' => $client_token,
+ ':client_secret' => $client_secret,
+ ':nonce' => $nonce,
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $application_id = $appbox->get_connection()->lastInsertId();
+ $application_id = $appbox->get_connection()->lastInsertId();
- $application = new self($appbox, $application_id);
- $account = API_OAuth2_Account::create($appbox, $user, $application);
+ $application = new self($appbox, $application_id);
+ $account = API_OAuth2_Account::create($appbox, $user, $application);
- return $application;
- }
+ return $application;
+ }
- /**
- *
- * @param appbox $appbox
- * @param type $client_id
- * @return API_OAuth2_Application
- */
- public static function load_from_client_id(appbox &$appbox, $client_id)
- {
- $sql = 'SELECT application_id FROM api_applications
+ /**
+ *
+ * @param appbox $appbox
+ * @param type $client_id
+ * @return API_OAuth2_Application
+ */
+ public static function load_from_client_id(appbox &$appbox, $client_id)
+ {
+ $sql = 'SELECT application_id FROM api_applications
WHERE client_id = :client_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':client_id' => $client_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':client_id' => $client_id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_NotFound();
+ if ( ! $row)
+ throw new Exception_NotFound();
- return new self($appbox, $row['application_id']);
- }
+ return new self($appbox, $row['application_id']);
+ }
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @return array
- */
- public static function load_dev_app_by_user(appbox &$appbox, User_Adapter $user)
- {
- $sql = 'SELECT a.application_id
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @return array
+ */
+ public static function load_dev_app_by_user(appbox &$appbox, User_Adapter $user)
+ {
+ $sql = 'SELECT a.application_id
FROM api_applications a, api_accounts b
WHERE a.creator = :usr_id AND a.application_id = b.application_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $apps = array();
- foreach ($rs as $row)
- {
- $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ $apps = array();
+ foreach ($rs as $row) {
+ $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ }
+
+ return $apps;
}
- return $apps;
- }
+ /**
+ *
+ * @param appbox $appbox
+ * @param user_adapter $user
+ * @return API_OAuth2_Application
+ */
+ public static function load_app_by_user(appbox $appbox, user_adapter $user)
+ {
- /**
- *
- * @param appbox $appbox
- * @param user_adapter $user
- * @return API_OAuth2_Application
- */
- public static function load_app_by_user(appbox $appbox, user_adapter $user)
- {
-
- $usr_id = $user->get_id();
- $sql = 'SELECT a.application_id
+ $usr_id = $user->get_id();
+ $sql = 'SELECT a.application_id
FROM api_accounts a, api_applications c
WHERE usr_id = :usr_id AND c.application_id = a.application_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $apps = array();
- foreach ($rs as $row)
- {
- $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ $apps = array();
+ foreach ($rs as $row) {
+ $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ }
+
+ return $apps;
}
- return $apps;
- }
+ public static function load_authorized_app_by_user(appbox $appbox, user_adapter $user)
+ {
-
- public static function load_authorized_app_by_user(appbox $appbox, user_adapter $user)
- {
-
- $usr_id = $user->get_id();
- $sql = '
+ $usr_id = $user->get_id();
+ $sql = '
SELECT a.application_id
FROM api_accounts a, api_applications c
WHERE usr_id = :usr_id AND c.application_id = a.application_id
AND revoked = 0';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $apps = array();
- foreach ($rs as $row)
- {
- $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ $apps = array();
+ foreach ($rs as $row) {
+ $apps[] = new API_OAuth2_Application($appbox, $row['application_id']);
+ }
+
+ return $apps;
}
-
- return $apps;
- }
-
}
diff --git a/lib/classes/API/OAuth2/AuthCode.class.php b/lib/classes/API/OAuth2/AuthCode.class.php
index 014a0759cf..32a4d1c6f7 100644
--- a/lib/classes/API/OAuth2/AuthCode.class.php
+++ b/lib/classes/API/OAuth2/AuthCode.class.php
@@ -21,170 +21,167 @@
*/
class API_OAuth2_AuthCode
{
+ protected $appbox;
+ protected $code;
+ protected $account;
+ protected $account_id;
+ protected $redirect_uri;
+ protected $expires;
+ protected $scope;
- protected $appbox;
- protected $code;
- protected $account;
- protected $account_id;
- protected $redirect_uri;
- protected $expires;
- protected $scope;
-
- public function __construct(appbox &$appbox, $code)
- {
- $this->appbox = $appbox;
- $this->code = $code;
- $sql = 'SELECT code, api_account_id, redirect_uri, UNIX_TIMESTAMP(expires) AS expires, scope
+ public function __construct(appbox &$appbox, $code)
+ {
+ $this->appbox = $appbox;
+ $this->code = $code;
+ $sql = 'SELECT code, api_account_id, redirect_uri, UNIX_TIMESTAMP(expires) AS expires, scope
FROM api_oauth_codes WHERE code = :code';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':code' => $this->code));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':code' => $this->code));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_NotFound();
+ if ( ! $row)
+ throw new Exception_NotFound();
- $this->account_id = (int) $row['api_account_id'];
- $this->redirect_uri = $row['redirect_uri'];
- $this->expires = $row['expires'];
- $this->scope = $row['scope'];
+ $this->account_id = (int) $row['api_account_id'];
+ $this->redirect_uri = $row['redirect_uri'];
+ $this->expires = $row['expires'];
+ $this->scope = $row['scope'];
- return $this;
- }
-
- public function get_code()
- {
- return $this->code;
- }
-
- /**
- *
- * @return API_OAuth2_Account
- */
- public function get_account()
- {
- if (!$this->account)
- $this->account = new API_OAuth2_Account($this->appbox, $this->account_id);
-
- return $this->account;
- }
-
- public function get_redirect_uri()
- {
- return $this->redirect_uri;
- }
-
- public function set_redirect_uri($redirect_uri)
- {
- $sql = 'UPDATE api_oauth_codes SET redirect_uri = :redirect_uri
- WHERE code = :code';
-
- $params = array(':redirect_uri' => $redirect_uri, ':code' => $this->code);
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
-
- $this->redirect_uri = $redirect_uri;
-
- return $this;
- }
-
- /**
- *
- * @return int
- */
- public function get_expires()
- {
- return $this->expires;
- }
-
- public function get_scope()
- {
- return $this->scope;
- }
-
- public function set_scope($scope)
- {
- $sql = 'UPDATE api_oauth_codes SET scope = :scope
- WHERE code = :code';
-
- $params = array(':scope' => $scope, ':code' => $this->code);
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
-
- $this->scope = $scope;
-
- return $this;
- }
-
- public function delete()
- {
- $sql = 'DELETE FROM api_oauth_codes WHERE code = :code';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':code' => $this->code));
- $stmt->closeCursor();
-
- return;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @return array
- */
- public static function load_codes_by_account(appbox &$appbox, API_OAuth2_Account $account)
- {
- $sql = 'SELECT code FROM api_oauth_codes
- WHERE api_account_id = :account_id';
-
- $stmt = $appbox->get_connection()->prepare($sql);
-
- $params = array(":account_id" => $account->get_id());
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $codes = array();
-
- foreach ($rs as $row)
- {
- $codes[] = new API_OAuth2_AuthCode($appbox, $row['code']);
+ return $this;
}
- return $codes;
- }
+ public function get_code()
+ {
+ return $this->code;
+ }
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @param type $code
- * @param int $expires
- * @return API_OAuth2_AuthCode
- */
- public static function create(appbox &$appbox, API_OAuth2_Account $account, $code, $expires)
- {
+ /**
+ *
+ * @return API_OAuth2_Account
+ */
+ public function get_account()
+ {
+ if ( ! $this->account)
+ $this->account = new API_OAuth2_Account($this->appbox, $this->account_id);
- $sql = 'INSERT INTO api_oauth_codes (code, api_account_id, expires)
+ return $this->account;
+ }
+
+ public function get_redirect_uri()
+ {
+ return $this->redirect_uri;
+ }
+
+ public function set_redirect_uri($redirect_uri)
+ {
+ $sql = 'UPDATE api_oauth_codes SET redirect_uri = :redirect_uri
+ WHERE code = :code';
+
+ $params = array(':redirect_uri' => $redirect_uri, ':code' => $this->code);
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $this->redirect_uri = $redirect_uri;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_expires()
+ {
+ return $this->expires;
+ }
+
+ public function get_scope()
+ {
+ return $this->scope;
+ }
+
+ public function set_scope($scope)
+ {
+ $sql = 'UPDATE api_oauth_codes SET scope = :scope
+ WHERE code = :code';
+
+ $params = array(':scope' => $scope, ':code' => $this->code);
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $this->scope = $scope;
+
+ return $this;
+ }
+
+ public function delete()
+ {
+ $sql = 'DELETE FROM api_oauth_codes WHERE code = :code';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':code' => $this->code));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @return array
+ */
+ public static function load_codes_by_account(appbox &$appbox, API_OAuth2_Account $account)
+ {
+ $sql = 'SELECT code FROM api_oauth_codes
+ WHERE api_account_id = :account_id';
+
+ $stmt = $appbox->get_connection()->prepare($sql);
+
+ $params = array(":account_id" => $account->get_id());
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $codes = array();
+
+ foreach ($rs as $row) {
+ $codes[] = new API_OAuth2_AuthCode($appbox, $row['code']);
+ }
+
+ return $codes;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @param type $code
+ * @param int $expires
+ * @return API_OAuth2_AuthCode
+ */
+ public static function create(appbox &$appbox, API_OAuth2_Account $account, $code, $expires)
+ {
+
+ $sql = 'INSERT INTO api_oauth_codes (code, api_account_id, expires)
VALUES (:code, :account_id, FROM_UNIXTIME(:expires))';
- $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt = $appbox->get_connection()->prepare($sql);
- $params = array(
- ":code" => $code,
- ":account_id" => $account->get_id(),
- ":expires" => $expires
- );
- $stmt->execute($params);
- $stmt->closeCursor();
-
- return new self($appbox, $code);
- }
+ $params = array(
+ ":code" => $code,
+ ":account_id" => $account->get_id(),
+ ":expires" => $expires
+ );
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ return new self($appbox, $code);
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Exception.class.php b/lib/classes/API/OAuth2/Exception/Exception.class.php
index f05781de7c..d1948712a9 100644
--- a/lib/classes/API/OAuth2/Exception/Exception.class.php
+++ b/lib/classes/API/OAuth2/Exception/Exception.class.php
@@ -22,160 +22,158 @@
*/
class API_OAuth2_Exception_Exception extends Exception implements API_OAuth2_Exception_Interface
{
+ /**
+ *
+ * @var int
+ */
+ protected $http_code;
- /**
- *
- * @var int
- */
- protected $http_code;
+ /**
+ *
+ * @var string
+ */
+ protected $error;
- /**
- *
- * @var string
- */
- protected $error;
+ /**
+ *
+ * @var string
+ */
+ protected $error_description;
- /**
- *
- * @var string
- */
- protected $error_description;
+ /**
+ *
+ * @var string
+ */
+ protected $error_uri;
- /**
- *
- * @var string
- */
- protected $error_uri;
+ /**
+ *
+ * @var string
+ */
+ protected $scope;
- /**
- *
- * @var string
- */
- protected $scope;
+ /**
+ *
+ * @param int $http_code
+ * @param string $error
+ * @param string $error_description
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function __construct($http_code, $error, $error_description = null, $scope = null, $error_uri = null)
+ {
+ $this->error = $error;
+ $this->error_description = $error_description;
+ $this->scope = $scope;
+ $this->error_uri = $error_uri;
+ parent::__construct();
- /**
- *
- * @param int $http_code
- * @param string $error
- * @param string $error_description
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_Exception
- */
- public function __construct($http_code, $error, $error_description = null, $scope = null, $error_uri = null)
- {
- $this->error = $error;
- $this->error_description = $error_description;
- $this->scope = $scope;
- $this->error_uri = $error_uri;
- parent::__construct();
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function getHttp_code()
+ {
+ return $this->http_code;
+ }
- /**
- *
- * @return int
- */
- public function getHttp_code()
- {
- return $this->http_code;
- }
+ /**
+ *
+ * @param int $http_code
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function setHttp_code($http_code)
+ {
+ $this->http_code = $http_code;
- /**
- *
- * @param int $http_code
- * @return API_OAuth2_Exception_Exception
- */
- public function setHttp_code($http_code)
- {
- $this->http_code = $http_code;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function getError()
+ {
+ return $this->error;
+ }
- /**
- *
- * @return string
- */
- public function getError()
- {
- return $this->error;
- }
+ /**
+ *
+ * @param string $scope
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function setError($error)
+ {
+ $this->error = $error;
- /**
- *
- * @param string $scope
- * @return API_OAuth2_Exception_Exception
- */
- public function setError($error)
- {
- $this->error = $error;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function getError_description()
+ {
+ return $this->error_description;
+ }
- /**
- *
- * @return string
- */
- public function getError_description()
- {
- return $this->error_description;
- }
+ /**
+ *
+ * @param string $scope
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function setError_description($error_description)
+ {
+ $this->error_description = $error_description;
- /**
- *
- * @param string $scope
- * @return API_OAuth2_Exception_Exception
- */
- public function setError_description($error_description)
- {
- $this->error_description = $error_description;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function getError_uri()
+ {
+ return $this->error_uri;
+ }
- /**
- *
- * @return string
- */
- public function getError_uri()
- {
- return $this->error_uri;
- }
+ /**
+ *
+ * @param string $scope
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function setError_uri($error_uri)
+ {
+ $this->error_uri = $error_uri;
- /**
- *
- * @param string $scope
- * @return API_OAuth2_Exception_Exception
- */
- public function setError_uri($error_uri)
- {
- $this->error_uri = $error_uri;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function getScope()
+ {
+ return $this->scope;
+ }
- /**
- *
- * @return string
- */
- public function getScope()
- {
- return $this->scope;
- }
-
- /**
- *
- * @param string $scope
- * @return API_OAuth2_Exception_Exception
- */
- public function setScope($scope)
- {
- $this->scope = $scope;
-
- return $this;
- }
+ /**
+ *
+ * @param string $scope
+ * @return API_OAuth2_Exception_Exception
+ */
+ public function setScope($scope)
+ {
+ $this->scope = $scope;
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Interface.class.php b/lib/classes/API/OAuth2/Exception/Interface.class.php
index 875df825e0..515229931e 100644
--- a/lib/classes/API/OAuth2/Exception/Interface.class.php
+++ b/lib/classes/API/OAuth2/Exception/Interface.class.php
@@ -23,11 +23,11 @@
interface API_OAuth2_Exception_Interface
{
- public function getError();
+ public function getError();
- public function getHttp_code();
+ public function getHttp_code();
- public function getError_description();
+ public function getError_description();
- public function getError_uri();
+ public function getError_uri();
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect.class.php b/lib/classes/API/OAuth2/Exception/Redirect.class.php
index 20817eced1..8f71bf60cd 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect.class.php
@@ -22,81 +22,81 @@
*/
class API_OAuth2_Exception_Redirect extends API_OAuth2_Exception_Exception
{
+ /**
+ *
+ * @var int
+ */
+ protected $http_code = 302;
- /**
- *
- * @var int
- */
- protected $http_code = 302;
- /**
- *
- * @var string
- */
- protected $state;
- /**
- *
- * @var string
- */
- protected $redirect_uri;
+ /**
+ *
+ * @var string
+ */
+ protected $state;
- /**
- *
- * @param string $redirect_uri
- * @param string $error
- * @param string $error_description
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect
- */
- public function __construct($redirect_uri, $error, $error_description = null, $state = null, $error_uri = null)
- {
- $this->redirect_uri = $redirect_uri;
- $this->state = $state;
- parent::__construct($this->http_code, $error, $error_description, $error_uri);
+ /**
+ *
+ * @var string
+ */
+ protected $redirect_uri;
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $error
+ * @param string $error_description
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect
+ */
+ public function __construct($redirect_uri, $error, $error_description = null, $state = null, $error_uri = null)
+ {
+ $this->redirect_uri = $redirect_uri;
+ $this->state = $state;
+ parent::__construct($this->http_code, $error, $error_description, $error_uri);
- /**
- *
- * @return string
- */
- public function getState()
- {
- return $this->state;
- }
+ return $this;
+ }
- /**
- *
- * @param string $redirect_uri
- * @return API_OAuth2_Exception_Redirect
- */
- public function setState($state)
- {
- $this->state = $state;
+ /**
+ *
+ * @return string
+ */
+ public function getState()
+ {
+ return $this->state;
+ }
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @return API_OAuth2_Exception_Redirect
+ */
+ public function setState($state)
+ {
+ $this->state = $state;
- /**
- *
- * @return string
- */
- public function getRedirect_uri()
- {
- return $this->redirect_uri;
- }
+ return $this;
+ }
- /**
- *
- * @param string $redirect_uri
- * @return API_OAuth2_Exception_Redirect
- */
- public function setRedirect_uri($redirect_uri)
- {
- $this->redirect_uri = $redirect_uri;
+ /**
+ *
+ * @return string
+ */
+ public function getRedirect_uri()
+ {
+ return $this->redirect_uri;
+ }
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @return API_OAuth2_Exception_Redirect
+ */
+ public function setRedirect_uri($redirect_uri)
+ {
+ $this->redirect_uri = $redirect_uri;
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/AccessDenied.class.php b/lib/classes/API/OAuth2/Exception/Redirect/AccessDenied.class.php
index 54947de0e5..0c2ac17288 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/AccessDenied.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/AccessDenied.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_AccessDenied extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'access_denied';
- /**
- *
- * @var string
- */
- protected $error = 'access_denied';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = " The resource owner or authorization server denied the request.";
- /**
- *
- * @var string
- */
- protected $error_description = " The resource owner or authorization server denied the request.";
-
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_AccessDenied
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
-
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_AccessDenied
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/InvalidClient.class.php b/lib/classes/API/OAuth2/Exception/Redirect/InvalidClient.class.php
index eaf680ed03..aecee8af01 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/InvalidClient.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/InvalidClient.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_InvalidClient extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_Client';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_Client';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The Client id is not valid.";
- /**
- *
- * @var string
- */
- protected $error_description = "The Client id is not valid.";
-
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_InvalidClient
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
-
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_InvalidClient
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/InvalidRequest.class.php b/lib/classes/API/OAuth2/Exception/Redirect/InvalidRequest.class.php
index 51117dea05..2adf7e6f6f 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/InvalidRequest.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/InvalidRequest.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_InvalidRequest extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_request';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_request';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
- /**
- *
- * @var string
- */
- protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
-
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_InvalidRequest
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
-
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_InvalidRequest
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/InvalidScope.class.php b/lib/classes/API/OAuth2/Exception/Redirect/InvalidScope.class.php
index 1879694032..c921d75d1d 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/InvalidScope.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/InvalidScope.class.php
@@ -22,60 +22,58 @@
*/
class API_OAuth2_Exception_Redirect_InvalidScope extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_scope';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_scope';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The requested scope is invalid, unknown, or malformed.";
- /**
- *
- * @var string
- */
- protected $error_description = "The requested scope is invalid, unknown, or malformed.";
+ /**
+ *
+ * @var string
+ */
+ protected $scope;
- /**
- *
- * @var string
- */
- protected $scope;
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $scope
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_InvalidScope
+ */
+ public function __construct($redirect_uri, $scope, $state = null, $error_uri = null)
+ {
+ $this->scope = $scope;
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
- /**
- *
- * @param string $redirect_uri
- * @param string $scope
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_InvalidScope
- */
- public function __construct($redirect_uri, $scope, $state = null, $error_uri = null)
- {
- $this->scope = $scope;
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ public function getScope()
+ {
+ return $this->scope;
+ }
- /**
- *
- * @var string
- */
- public function getScope()
- {
- return $this->scope;
- }
-
- /**
- *
- * @param string $scope
- * @return API_OAuth2_Exception_Redirect_InvalidScope
- */
- public function setScope($scope)
- {
- $this->scope = $scope;
-
- return $this;
- }
+ /**
+ *
+ * @param string $scope
+ * @return API_OAuth2_Exception_Redirect_InvalidScope
+ */
+ public function setScope($scope)
+ {
+ $this->scope = $scope;
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/ServerError.class.php b/lib/classes/API/OAuth2/Exception/Redirect/ServerError.class.php
index 8c393331a2..c7247c2fb7 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/ServerError.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/ServerError.class.php
@@ -22,29 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_ServerError extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'server_error';
- /**
- *
- * @var string
- */
- protected $error = 'server_error';
- /**
- *
- * @var string
- */
- protected $error_description = "The authorization server encountered an unexpected condition which prevented it from fulfilling the request.";
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The authorization server encountered an unexpected condition which prevented it from fulfilling the request.";
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_ServerError
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_ServerError
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
- return $this;
- }
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/TemporaryUnavailable.class.php b/lib/classes/API/OAuth2/Exception/Redirect/TemporaryUnavailable.class.php
index c5eff49170..dda4d8b8a4 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/TemporaryUnavailable.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/TemporaryUnavailable.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_Unauthorized extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'temporarily_unavailable';
- /**
- *
- * @var string
- */
- protected $error = 'temporarily_unavailable';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.";
- /**
- *
- * @var string
- */
- protected $error_description = "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.";
-
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_Unauthorized
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
-
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_Unauthorized
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/UnauthorizedClient.class.php b/lib/classes/API/OAuth2/Exception/Redirect/UnauthorizedClient.class.php
index 5f3ab97620..a829fb64c2 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/UnauthorizedClient.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/UnauthorizedClient.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_Redirect_UnauthorizedClient extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'unauthorized_client';
- /**
- *
- * @var string
- */
- protected $error = 'unauthorized_client';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The client is not authorized to request an authorization code using this method.";
- /**
- *
- * @var string
- */
- protected $error_description = "The client is not authorized to request an authorization code using this method.";
-
- /**
- *
- * @param string $redirect_uri
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_UnauthorizedClient
- */
- public function __construct($redirect_uri, $state = null, $error_uri = null)
- {
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
-
- return $this;
- }
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_UnauthorizedClient
+ */
+ public function __construct($redirect_uri, $state = null, $error_uri = null)
+ {
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/Redirect/UnsupportedResponseType.class.php b/lib/classes/API/OAuth2/Exception/Redirect/UnsupportedResponseType.class.php
index 62c7da1481..41d4911a9d 100644
--- a/lib/classes/API/OAuth2/Exception/Redirect/UnsupportedResponseType.class.php
+++ b/lib/classes/API/OAuth2/Exception/Redirect/UnsupportedResponseType.class.php
@@ -22,60 +22,58 @@
*/
class API_OAuth2_Exception_Redirect_UnsupportedResponseType extends API_OAuth2_Exception_Redirect
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'unsupported_response_type';
- /**
- *
- * @var string
- */
- protected $error = 'unsupported_response_type';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The authorization server does not support obtaining an authorization code using this method.";
- /**
- *
- * @var string
- */
- protected $error_description = "The authorization server does not support obtaining an authorization code using this method.";
+ /**
+ *
+ * @var string
+ */
+ protected $method;
- /**
- *
- * @var string
- */
- protected $method;
+ /**
+ *
+ * @param string $redirect_uri
+ * @param string $method
+ * @param string $state
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_Redirect_UnsupportedResponseType
+ */
+ public function __construct($redirect_uri, $method, $state = null, $error_uri = null)
+ {
+ $this->method = $method;
+ parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
- /**
- *
- * @param string $redirect_uri
- * @param string $method
- * @param string $state
- * @param string $error_uri
- * @return API_OAuth2_Exception_Redirect_UnsupportedResponseType
- */
- public function __construct($redirect_uri, $method, $state = null, $error_uri = null)
- {
- $this->method = $method;
- parent::__construct($redirect_uri, $this->error, $this->error_description, $state, $error_uri);
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ public function getMethod()
+ {
+ return $this->method;
+ }
- /**
- *
- * @var string
- */
- public function getMethod()
- {
- return $this->method;
- }
-
- /**
- *
- * @param string $method
- * @return API_OAuth2_Exception_Redirect_UnsupportedResponseType
- */
- public function setMethod($method)
- {
- $this->method = $method;
-
- return $this;
- }
+ /**
+ *
+ * @param string $method
+ * @return API_OAuth2_Exception_Redirect_UnsupportedResponseType
+ */
+ public function setMethod($method)
+ {
+ $this->method = $method;
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate.class.php
index f4d3ccb04f..d0614a3aea 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate.class.php
@@ -22,58 +22,56 @@
*/
class API_OAuth2_Exception_WWWAuthenticate extends API_OAuth2_Exception_Exception
{
+ /**
+ *
+ * @var string
+ */
+ protected $realm;
- /**
- *
- * @var string
- */
- protected $realm;
+ /**
+ *
+ * @var string
+ */
+ protected $scope;
- /**
- *
- * @var string
- */
- protected $scope;
+ /**
+ *
+ * @param int $http_code
+ * @param string $realm
+ * @param string $error
+ * @param string $error_description
+ * @param string $error_uri
+ * @param string $scope
+ * @return API_OAuth2_Exception_WWWAuthenticate
+ */
+ public function __construct($http_code, $realm, $error, $error_description = null, $error_uri = null, $scope = null)
+ {
+ $this->realm = $realm;
+ $this->scope = $scope;
- /**
- *
- * @param int $http_code
- * @param string $realm
- * @param string $error
- * @param string $error_description
- * @param string $error_uri
- * @param string $scope
- * @return API_OAuth2_Exception_WWWAuthenticate
- */
- public function __construct($http_code, $realm, $error, $error_description = null, $error_uri = null, $scope = null)
- {
- $this->realm = $realm;
- $this->scope = $scope;
+ parent::__construct($http_code, $error, $error_description, $error_uri);
- parent::__construct($http_code, $error, $error_description, $error_uri);
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function getRealm()
+ {
+ return $this->realm;
+ }
- /**
- *
- * @return string
- */
- public function getRealm()
- {
- return $this->realm;
- }
-
- /**
- *
- * @param string $realm
- * @return API_OAuth2_Exception_WWWAuthenticate
- */
- public function setRealm($realm)
- {
- $this->realm = $realm;
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @return API_OAuth2_Exception_WWWAuthenticate
+ */
+ public function setRealm($realm)
+ {
+ $this->realm = $realm;
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/ExpiredToken.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/ExpiredToken.php
index bc2a983e9f..be245a69e4 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/ExpiredToken.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/ExpiredToken.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_ExpiredToken extends API_OAuth2_Exception_WWWAuthenticate_Type_Unauthorized
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'expired_token';
- /**
- *
- * @var string
- */
- protected $error = 'expired_token';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The access token provided has expired.";
- /**
- *
- * @var string
- */
- protected $error_description = "The access token provided has expired.";
-
- /**
- *
- * @param string $realm
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_WWWAuthenticate_ExpiredToken
- */
- public function __construct($realm, $scope = null, $error_uri = null)
- {
- parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_WWWAuthenticate_ExpiredToken
+ */
+ public function __construct($realm, $scope = null, $error_uri = null)
+ {
+ parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InsufficientScope.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InsufficientScope.php
index 1c2f67aebf..4038f4571f 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InsufficientScope.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InsufficientScope.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_InsufficientScope extends API_OAuth2_Exception_WWWAuthenticate_Type_Forbidden
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'insufficient_scope';
- /**
- *
- * @var string
- */
- protected $error = 'insufficient_scope';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The request requires higher privileges than provided by the access token.";
- /**
- *
- * @var string
- */
- protected $error_description = "The request requires higher privileges than provided by the access token.";
-
- /**
- *
- * @param string $realm
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_WWWAuthenticate_InsufficientScope
- */
- public function __construct($realm, $scope = null, $error_uri = null)
- {
- parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_WWWAuthenticate_InsufficientScope
+ */
+ public function __construct($realm, $scope = null, $error_uri = null)
+ {
+ parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidClient.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidClient.class.php
index d63aec8c20..3c55cca8e3 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidClient.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidClient.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_InvalidClient extends API_OAuth2_Exception_WWWAuthenticate_Type_BadRequest
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_request';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_request';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
- /**
- *
- * @var string
- */
- protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
-
- /**
- *
- * @param string $realm
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_WWWAuthenticate_InvalidClient
- */
- public function __construct($realm, $scope = null, $error_uri = null)
- {
- parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_WWWAuthenticate_InvalidClient
+ */
+ public function __construct($realm, $scope = null, $error_uri = null)
+ {
+ parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidRequest.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidRequest.class.php
index 39078a427f..15d1118681 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidRequest.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidRequest.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_InvalidRequest extends API_OAuth2_Exception_WWWAuthenticate_Type_BadRequest
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_request';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_request';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
- /**
- *
- * @var string
- */
- protected $error_description = "The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.";
-
- /**
- *
- * @param string $realm
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_WWWAuthenticate_InvalidRequest
- */
- public function __construct($realm, $scope = null, $error_uri = null)
- {
- parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_WWWAuthenticate_InvalidRequest
+ */
+ public function __construct($realm, $scope = null, $error_uri = null)
+ {
+ parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidToken.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidToken.class.php
index e57ec112b0..877aaaa996 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidToken.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/InvalidToken.class.php
@@ -22,31 +22,29 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_InvalidToken extends API_OAuth2_Exception_WWWAuthenticate_Type_Unauthorized
{
+ /**
+ *
+ * @var string
+ */
+ protected $error = 'invalid_token';
- /**
- *
- * @var string
- */
- protected $error = 'invalid_token';
+ /**
+ *
+ * @var string
+ */
+ protected $error_description = "The access token provided is invalid.";
- /**
- *
- * @var string
- */
- protected $error_description = "The access token provided is invalid.";
-
- /**
- *
- * @param string $realm
- * @param string $scope
- * @param string $error_uri
- * @return API_OAuth2_Exception_WWWAuthenticate_InvalidToken
- */
- public function __construct($realm, $scope = null, $error_uri = null)
- {
- parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $scope
+ * @param string $error_uri
+ * @return API_OAuth2_Exception_WWWAuthenticate_InvalidToken
+ */
+ public function __construct($realm, $scope = null, $error_uri = null)
+ {
+ parent::__construct($realm, $this->error, $this->error_description, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/BadRequest.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/BadRequest.class.php
index 915a9eadcd..d7238d4d39 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/BadRequest.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/BadRequest.class.php
@@ -22,27 +22,25 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_Type_BadRequest extends API_OAuth2_Exception_WWWAuthenticate
{
+ /**
+ *
+ * @var int
+ */
+ protected $http_code = 400;
- /**
- *
- * @var int
- */
- protected $http_code = 400;
-
- /**
- *
- * @param string $realm
- * @param string $error
- * @param string $error_description
- * @param string $error_uri
- * @param string $scope
- * @return API_OAuth2_Exception_WWWAuthenticate_Type_BadRequest
- */
- public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
- {
- parent::__construct($this->http_code, $realm, $error, $error_description = null, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $error
+ * @param string $error_description
+ * @param string $error_uri
+ * @param string $scope
+ * @return API_OAuth2_Exception_WWWAuthenticate_Type_BadRequest
+ */
+ public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
+ {
+ parent::__construct($this->http_code, $realm, $error, $error_description = null, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Forbidden.class.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Forbidden.class.php
index 5960c38e90..4af07a58fa 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Forbidden.class.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Forbidden.class.php
@@ -23,21 +23,20 @@
class API_OAuth2_Exception_WWWAuthenticate_Type_Forbidden extends API_OAuth2_Exception_WWWAuthenticate
{
- /**
- *
- * @param string $realm
- * @param string $error
- * @param string $error_description
- * @param string $error_uri
- * @param string $scope
- * @return API_OAuth2_Exception_WWWAuthenticate_Type_Forbidden
- */
- public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
- {
- parent::__construct($realm, $error, $error_description = null, $error_uri, $scope);
- $this->setHttp_code(403);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $error
+ * @param string $error_description
+ * @param string $error_uri
+ * @param string $scope
+ * @return API_OAuth2_Exception_WWWAuthenticate_Type_Forbidden
+ */
+ public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
+ {
+ parent::__construct($realm, $error, $error_description = null, $error_uri, $scope);
+ $this->setHttp_code(403);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Unauthorized.php b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Unauthorized.php
index 5e94d07471..6b322909a2 100644
--- a/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Unauthorized.php
+++ b/lib/classes/API/OAuth2/Exception/WWWAuthenticate/Type/Unauthorized.php
@@ -22,27 +22,25 @@
*/
class API_OAuth2_Exception_WWWAuthenticate_Type_Unauthorized extends API_OAuth2_Exception_WWWAuthenticate
{
+ /**
+ *
+ * @var string
+ */
+ protected $http_code = 401;
- /**
- *
- * @var string
- */
- protected $http_code = 401;
-
- /**
- *
- * @param string $realm
- * @param string $error
- * @param string $error_description
- * @param string $error_uri
- * @param string $scope
- * @return API_OAuth2_Exception_WWWAuthenticate_Type_Unauthorized
- */
- public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
- {
- parent::__construct($this->http_code, $realm, $error, $error_description = null, $error_uri, $scope);
-
- return $this;
- }
+ /**
+ *
+ * @param string $realm
+ * @param string $error
+ * @param string $error_description
+ * @param string $error_uri
+ * @param string $scope
+ * @return API_OAuth2_Exception_WWWAuthenticate_Type_Unauthorized
+ */
+ public function __construct($realm, $error, $error_description = null, $error_uri = null, $scope = null)
+ {
+ parent::__construct($this->http_code, $realm, $error, $error_description = null, $error_uri, $scope);
+ return $this;
+ }
}
diff --git a/lib/classes/API/OAuth2/Form/DevAppDesktop.class.php b/lib/classes/API/OAuth2/Form/DevAppDesktop.class.php
index 175eea6e4b..590efd6603 100644
--- a/lib/classes/API/OAuth2/Form/DevAppDesktop.class.php
+++ b/lib/classes/API/OAuth2/Form/DevAppDesktop.class.php
@@ -26,134 +26,132 @@ use Symfony\Component\Validator\Constraints;
class API_OAuth2_Form_DevAppDesktop
{
-
- /**
- *
- * @var string
- */
- public $name;
-
- /**
- *
- * @var string
- */
- public $description;
-
- /**
- *
- * @var string
- */
- public $website;
-
- /**
- *
- * @var string
- */
- public $callback;
-
- /**
- *
- * @var string
- */
- public $type;
- public $scheme_website;
- public $urlwebsite;
-
- /**
- *
- * @param Request $request
- * @return API_OAuth2_Form_DevApp
- */
- public function __construct(Request $request)
- {
- $this->name = $request->get('name', '');
- $this->description = $request->get('description', '');
- $this->scheme_website = $request->get('scheme-website', 'http://');
- $this->website = $request->get('website', '');
- $this->callback = API_OAuth2_Application::NATIVE_APP_REDIRECT_URI;
- $this->type = API_OAuth2_Application::DESKTOP_TYPE;
-
- $this->urlwebsite = $this->scheme_website . $this->website;
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- *
- * @return string
- */
- public function getDescription()
- {
- return $this->description;
- }
-
- /**
- *
- * @return string
- */
- public function getWebsite()
- {
- return $this->website;
- }
-
- /**
- *
- * @return string
- */
- public function getCallback()
- {
- return $this->callback;
- }
-
- /**
- *
- * @return string
- */
- public function getType()
- {
- return $this->type;
- }
-
- public function getSchemeWebsite()
- {
- return $this->scheme_website;
- }
-
- public function getUrlwebsite()
- {
- return $this->urlwebsite;
- }
-
- public function getSchemeCallback()
- {
- return '';
- }
+ /**
+ *
+ * @var string
+ */
+ public $name;
/**
- *
- * @param ClassMetadata $metadata
- * @return API_OAuth2_Form_DevApp
- */
- static public function loadValidatorMetadata(ClassMetadata $metadata)
- {
- $blank = array('message' => _('Cette valeur ne peut être vide'));
- $url = array('message' => _('Url non valide'));
+ *
+ * @var string
+ */
+ public $description;
- $metadata->addPropertyConstraint('name', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('description', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('urlwebsite', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('urlwebsite', new Constraints\Url($url));
+ /**
+ *
+ * @var string
+ */
+ public $website;
- return;
- }
+ /**
+ *
+ * @var string
+ */
+ public $callback;
+ /**
+ *
+ * @var string
+ */
+ public $type;
+ public $scheme_website;
+ public $urlwebsite;
+
+ /**
+ *
+ * @param Request $request
+ * @return API_OAuth2_Form_DevApp
+ */
+ public function __construct(Request $request)
+ {
+ $this->name = $request->get('name', '');
+ $this->description = $request->get('description', '');
+ $this->scheme_website = $request->get('scheme-website', 'http://');
+ $this->website = $request->get('website', '');
+ $this->callback = API_OAuth2_Application::NATIVE_APP_REDIRECT_URI;
+ $this->type = API_OAuth2_Application::DESKTOP_TYPE;
+
+ $this->urlwebsite = $this->scheme_website . $this->website;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getDescription()
+ {
+ return $this->description;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getWebsite()
+ {
+ return $this->website;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getCallback()
+ {
+ return $this->callback;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function getSchemeWebsite()
+ {
+ return $this->scheme_website;
+ }
+
+ public function getUrlwebsite()
+ {
+ return $this->urlwebsite;
+ }
+
+ public function getSchemeCallback()
+ {
+ return '';
+ }
+
+ /**
+ *
+ * @param ClassMetadata $metadata
+ * @return API_OAuth2_Form_DevApp
+ */
+ static public function loadValidatorMetadata(ClassMetadata $metadata)
+ {
+ $blank = array('message' => _('Cette valeur ne peut être vide'));
+ $url = array('message' => _('Url non valide'));
+
+ $metadata->addPropertyConstraint('name', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('description', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('urlwebsite', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('urlwebsite', new Constraints\Url($url));
+
+ return;
+ }
}
diff --git a/lib/classes/API/OAuth2/Form/DevAppInternet.class.php b/lib/classes/API/OAuth2/Form/DevAppInternet.class.php
index 4e93dca0a3..c22517f248 100644
--- a/lib/classes/API/OAuth2/Form/DevAppInternet.class.php
+++ b/lib/classes/API/OAuth2/Form/DevAppInternet.class.php
@@ -26,141 +26,137 @@ use Symfony\Component\Validator\Constraints;
class API_OAuth2_Form_DevAppInternet
{
-
- /**
- *
- * @var string
- */
- public $name;
-
- /**
- *
- * @var string
- */
- public $description;
-
- /**
- *
- * @var string
- */
- public $website;
-
- /**
- *
- * @var string
- */
- public $callback;
-
- public $scheme_website;
- public $scheme_callback;
-
- public $urlwebsite;
- public $urlcallback;
-
- /**
- *
- * @param Request $request
- * @return API_OAuth2_Form_DevApp
- */
- public function __construct(Request $request)
- {
- $this->name = $request->get('name', '');
- $this->description = $request->get('description', '');
- $this->website = $request->get('website', '');
- $this->callback = $request->get('callback', '');
- $this->scheme_website = $request->get('scheme-website', 'http://');
- $this->scheme_callback = $request->get('scheme-callback', 'http://');
- $this->type = API_OAuth2_Application::WEB_TYPE;
-
- $this->urlwebsite = $this->scheme_website.$this->website;
- $this->urlcallback = $this->scheme_callback.$this->callback;
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- *
- * @return string
- */
- public function getDescription()
- {
- return $this->description;
- }
-
- /**
- *
- * @return string
- */
- public function getWebsite()
- {
- return $this->website;
- }
-
- /**
- *
- * @return string
- */
- public function getCallback()
- {
- return $this->callback;
- }
-
- /**
- *
- * @return string
- */
- public function getType()
- {
- return $this->type;
- }
-
- public function getSchemeWebsite()
- {
- return $this->scheme_website;
- }
-
- public function getSchemeCallback()
- {
- return $this->scheme_callback;
- }
-
- public function getUrlwebsite()
- {
- return $this->urlwebsite;
- }
-
- public function getUrlcallback()
- {
- return $this->urlcallback;
- }
+ /**
+ *
+ * @var string
+ */
+ public $name;
/**
- *
- * @param ClassMetadata $metadata
- * @return API_OAuth2_Form_DevApp
- */
- static public function loadValidatorMetadata(ClassMetadata $metadata)
- {
- $blank = array('message' => _('Cette valeur ne peut être vide'));
- $url = array('message' => _('Url non valide'));
+ *
+ * @var string
+ */
+ public $description;
- $metadata->addPropertyConstraint('name', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('description', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('urlwebsite', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('urlwebsite', new Constraints\Url($url));
- $metadata->addPropertyConstraint('urlcallback', new Constraints\NotBlank($blank));
- $metadata->addPropertyConstraint('urlcallback', new Constraints\Url($url));
+ /**
+ *
+ * @var string
+ */
+ public $website;
- return;
- }
+ /**
+ *
+ * @var string
+ */
+ public $callback;
+ public $scheme_website;
+ public $scheme_callback;
+ public $urlwebsite;
+ public $urlcallback;
+ /**
+ *
+ * @param Request $request
+ * @return API_OAuth2_Form_DevApp
+ */
+ public function __construct(Request $request)
+ {
+ $this->name = $request->get('name', '');
+ $this->description = $request->get('description', '');
+ $this->website = $request->get('website', '');
+ $this->callback = $request->get('callback', '');
+ $this->scheme_website = $request->get('scheme-website', 'http://');
+ $this->scheme_callback = $request->get('scheme-callback', 'http://');
+ $this->type = API_OAuth2_Application::WEB_TYPE;
+
+ $this->urlwebsite = $this->scheme_website . $this->website;
+ $this->urlcallback = $this->scheme_callback . $this->callback;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getDescription()
+ {
+ return $this->description;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getWebsite()
+ {
+ return $this->website;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getCallback()
+ {
+ return $this->callback;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function getSchemeWebsite()
+ {
+ return $this->scheme_website;
+ }
+
+ public function getSchemeCallback()
+ {
+ return $this->scheme_callback;
+ }
+
+ public function getUrlwebsite()
+ {
+ return $this->urlwebsite;
+ }
+
+ public function getUrlcallback()
+ {
+ return $this->urlcallback;
+ }
+
+ /**
+ *
+ * @param ClassMetadata $metadata
+ * @return API_OAuth2_Form_DevApp
+ */
+ static public function loadValidatorMetadata(ClassMetadata $metadata)
+ {
+ $blank = array('message' => _('Cette valeur ne peut être vide'));
+ $url = array('message' => _('Url non valide'));
+
+ $metadata->addPropertyConstraint('name', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('description', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('urlwebsite', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('urlwebsite', new Constraints\Url($url));
+ $metadata->addPropertyConstraint('urlcallback', new Constraints\NotBlank($blank));
+ $metadata->addPropertyConstraint('urlcallback', new Constraints\Url($url));
+
+ return;
+ }
}
diff --git a/lib/classes/API/OAuth2/RefreshToken.class.php b/lib/classes/API/OAuth2/RefreshToken.class.php
index 4c9ce9d650..1e10cf0b30 100644
--- a/lib/classes/API/OAuth2/RefreshToken.class.php
+++ b/lib/classes/API/OAuth2/RefreshToken.class.php
@@ -21,129 +21,126 @@
*/
class API_OAuth2_RefreshToken
{
+ protected $appbox;
+ protected $token;
+ protected $account_id;
+ protected $account;
+ protected $expires;
+ protected $scope;
- protected $appbox;
- protected $token;
- protected $account_id;
- protected $account;
- protected $expires;
- protected $scope;
+ public function __construct(appbox &$appbox, $token)
+ {
+ $this->appbox = $appbox;
+ $this->token = $token;
- public function __construct(appbox &$appbox, $token)
- {
- $this->appbox = $appbox;
- $this->token = $token;
-
- $sql = 'SELECT api_account_id, UNIX_TIMESTAMP(expires) AS expires, scope
+ $sql = 'SELECT api_account_id, UNIX_TIMESTAMP(expires) AS expires, scope
FROM api_oauth_refresh_tokens WHERE refresh_token = :token';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':token' => $this->token));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':token' => $this->token));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->account_id = (int) $row['api_account_id'];
- $this->expires = $row['expires'];
- $this->scope = $row['scope'];
+ $this->account_id = (int) $row['api_account_id'];
+ $this->expires = $row['expires'];
+ $this->scope = $row['scope'];
- return $this;
- }
-
- public function get_value()
- {
- return $this->token;
- }
-
- /**
- *
- * @return API_OAuth2_Account
- */
- public function get_account()
- {
- if (!$this->account)
- $this->account = new API_OAuth2_Account($this->appbox, $this->account_id);
-
- return $this->account;
- }
-
- /**
- *
- * @return int
- */
- public function get_expires()
- {
- return $this->expires;
- }
-
- public function get_scope()
- {
- return $this->scope;
- }
-
- public function delete()
- {
- $sql = 'DELETE FROM api_oauth_refresh_tokens
- WHERE refresh_token = :refresh_token';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(":refresh_token" => $this->token));
- $stmt->closeCursor();
-
- return;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @return array
- */
- public static function load_by_account(appbox &$appbox, API_OAuth2_Account $account)
- {
- $sql = 'SELECT refresh_token FROM api_oauth_refresh_tokens
- WHERE api_account_id = :account_id';
-
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':account_id' => $account->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $tokens = array();
-
- foreach ($rs as $row)
- {
- $tokens[] = new API_OAuth2_RefreshToken($appbox, $row['refresh_token']);
+ return $this;
}
- return $tokens;
- }
+ public function get_value()
+ {
+ return $this->token;
+ }
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @param int $expires
- * @param type $refresh_token
- * @param type $scope
- * @return API_OAuth2_RefreshToken
- */
- public static function create(appbox &$appbox, API_OAuth2_Account $account, $expires, $refresh_token, $scope)
- {
- $sql = 'INSERT INTO api_oauth_refresh_tokens
+ /**
+ *
+ * @return API_OAuth2_Account
+ */
+ public function get_account()
+ {
+ if ( ! $this->account)
+ $this->account = new API_OAuth2_Account($this->appbox, $this->account_id);
+
+ return $this->account;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_expires()
+ {
+ return $this->expires;
+ }
+
+ public function get_scope()
+ {
+ return $this->scope;
+ }
+
+ public function delete()
+ {
+ $sql = 'DELETE FROM api_oauth_refresh_tokens
+ WHERE refresh_token = :refresh_token';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(":refresh_token" => $this->token));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @return array
+ */
+ public static function load_by_account(appbox &$appbox, API_OAuth2_Account $account)
+ {
+ $sql = 'SELECT refresh_token FROM api_oauth_refresh_tokens
+ WHERE api_account_id = :account_id';
+
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':account_id' => $account->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $tokens = array();
+
+ foreach ($rs as $row) {
+ $tokens[] = new API_OAuth2_RefreshToken($appbox, $row['refresh_token']);
+ }
+
+ return $tokens;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @param int $expires
+ * @param type $refresh_token
+ * @param type $scope
+ * @return API_OAuth2_RefreshToken
+ */
+ public static function create(appbox &$appbox, API_OAuth2_Account $account, $expires, $refresh_token, $scope)
+ {
+ $sql = 'INSERT INTO api_oauth_refresh_tokens
(refresh_token, api_account_id, expires, scope)
VALUES (:refresh_token, :account_id, :expires, :scope)';
- $stmt = $appbox->get_connection()->prepare($sql);
- $params = array(
- ":refresh_token" => $refresh_token,
- ":account_id" => $account->get_id(),
- ":expires" => $expires,
- ":scope" => $scope
- );
- $stmt->execute($params);
- $stmt->closeCursor();
-
- return new self($appbox, $refresh_token);
- }
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $params = array(
+ ":refresh_token" => $refresh_token,
+ ":account_id" => $account->get_id(),
+ ":expires" => $expires,
+ ":scope" => $scope
+ );
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ return new self($appbox, $refresh_token);
+ }
}
diff --git a/lib/classes/API/OAuth2/Token.class.php b/lib/classes/API/OAuth2/Token.class.php
index 6edf045ba8..16fa955204 100644
--- a/lib/classes/API/OAuth2/Token.class.php
+++ b/lib/classes/API/OAuth2/Token.class.php
@@ -21,311 +21,309 @@
*/
class API_OAuth2_Token
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var API_OAuth2_Account
+ */
+ protected $account;
- /**
- *
- * @var API_OAuth2_Account
- */
- protected $account;
+ /**
+ *
+ * @var string
+ */
+ protected $token;
- /**
- *
- * @var string
- */
- protected $token;
+ /**
+ *
+ * @var int
+ */
+ protected $session_id;
- /**
- *
- * @var int
- */
- protected $session_id;
+ /**
+ *
+ * @var int
+ */
+ protected $expires;
- /**
- *
- * @var int
- */
- protected $expires;
+ /**
+ *
+ * @var string
+ */
+ protected $scope;
- /**
- *
- * @var string
- */
- protected $scope;
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @return API_OAuth2_Token
+ */
+ public function __construct(appbox &$appbox, API_OAuth2_Account &$account)
+ {
+ $this->appbox = $appbox;
+ $this->account = $account;
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @return API_OAuth2_Token
- */
- public function __construct(appbox &$appbox, API_OAuth2_Account &$account)
- {
- $this->appbox = $appbox;
- $this->account = $account;
-
- $sql = 'SELECT oauth_token, session_id, UNIX_TIMESTAMP(expires) as expires, scope
+ $sql = 'SELECT oauth_token, session_id, UNIX_TIMESTAMP(expires) as expires, scope
FROM api_oauth_tokens
WHERE api_account_id = :account_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':account_id' => $this->account->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':account_id' => $this->account->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
- if (!$row)
- throw new Exception_NotFound();
+ if ( ! $row)
+ throw new Exception_NotFound();
- $stmt->closeCursor();
+ $stmt->closeCursor();
- $this->token = $row['oauth_token'];
- $this->session_id = is_null($row['session_id']) ? null : (int) $row['session_id'];
- $this->expires = $row['expires'];
- $this->scope = $row['scope'];
+ $this->token = $row['oauth_token'];
+ $this->session_id = is_null($row['session_id']) ? null : (int) $row['session_id'];
+ $this->expires = $row['expires'];
+ $this->scope = $row['scope'];
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_value()
- {
- return $this->token;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_value()
+ {
+ return $this->token;
+ }
- /**
- *
- * @param string $oauth_token
- * @return API_OAuth2_Token
- */
- public function set_value($oauth_token)
- {
- $sql = 'UPDATE api_oauth_tokens SET oauth_token = :oauth_token
+ /**
+ *
+ * @param string $oauth_token
+ * @return API_OAuth2_Token
+ */
+ public function set_value($oauth_token)
+ {
+ $sql = 'UPDATE api_oauth_tokens SET oauth_token = :oauth_token
WHERE oauth_token = :current_token';
- $params = array(
- ':oauth_token' => $oauth_token
- , ':current_token' => $this->token
- );
+ $params = array(
+ ':oauth_token' => $oauth_token
+ , ':current_token' => $this->token
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->token = $oauth_token;
+ $this->token = $oauth_token;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_session_id()
- {
- return $this->session_id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_session_id()
+ {
+ return $this->session_id;
+ }
- /**
- *
- * @param int $session_id
- * @return API_OAuth2_Token
- */
- public function set_session_id($session_id)
- {
- $sql = 'UPDATE api_oauth_tokens SET session_id = :session_id
+ /**
+ *
+ * @param int $session_id
+ * @return API_OAuth2_Token
+ */
+ public function set_session_id($session_id)
+ {
+ $sql = 'UPDATE api_oauth_tokens SET session_id = :session_id
WHERE oauth_token = :current_token';
- $params = array(
- ':session_id' => $session_id
- , ':current_token' => $this->token
- );
+ $params = array(
+ ':session_id' => $session_id
+ , ':current_token' => $this->token
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->session_id = (int) $session_id;
+ $this->session_id = (int) $session_id;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_expires()
- {
- return $this->expires;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_expires()
+ {
+ return $this->expires;
+ }
- /**
- *
- * @param int $expires
- * @return API_OAuth2_Token
- */
- public function set_expires($expires)
- {
- $sql = 'UPDATE api_oauth_tokens SET expires = FROM_UNIXTIME(:expires)
+ /**
+ *
+ * @param int $expires
+ * @return API_OAuth2_Token
+ */
+ public function set_expires($expires)
+ {
+ $sql = 'UPDATE api_oauth_tokens SET expires = FROM_UNIXTIME(:expires)
WHERE oauth_token = :oauth_token';
- $params = array(
- ':expires' => $expires
- , ':oauth_token' => $this->get_value()
- );
+ $params = array(
+ ':expires' => $expires
+ , ':oauth_token' => $this->get_value()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->expires = $expires;
+ $this->expires = $expires;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_scope()
- {
- return $this->scope;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_scope()
+ {
+ return $this->scope;
+ }
- public function set_scope($scope)
- {
- $sql = 'UPDATE api_oauth_tokens SET scope = :scope
+ public function set_scope($scope)
+ {
+ $sql = 'UPDATE api_oauth_tokens SET scope = :scope
WHERE oauth_token = :oauth_token';
- $params = array(
- ':scope' => $scope
- , ':oauth_token' => $this->get_value()
- );
+ $params = array(
+ ':scope' => $scope
+ , ':oauth_token' => $this->get_value()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->scope = $scope;
+ $this->scope = $scope;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return API_OAuth2_Account
- */
- public function get_account()
- {
- return $this->account;
- }
+ /**
+ *
+ * @return API_OAuth2_Account
+ */
+ public function get_account()
+ {
+ return $this->account;
+ }
- /**
- *
- * @return API_OAuth2_Token
- */
- public function renew()
- {
- $sql = 'UPDATE api_oauth_tokens SET oauth_token = :new_token
+ /**
+ *
+ * @return API_OAuth2_Token
+ */
+ public function renew()
+ {
+ $sql = 'UPDATE api_oauth_tokens SET oauth_token = :new_token
WHERE oauth_token = :old_token';
- $new_token = self::generate_token();
+ $new_token = self::generate_token();
- $params = array(
- ':new_token' => $new_token
- , ':old_token' => $this->get_value()
- );
+ $params = array(
+ ':new_token' => $new_token
+ , ':old_token' => $this->get_value()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $this->token = $new_token;
+ $this->token = $new_token;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return void
- */
- public function delete()
- {
- $sql = 'DELETE FROM api_oauth_tokens WHERE oauth_token = :oauth_token';
+ /**
+ *
+ * @return void
+ */
+ public function delete()
+ {
+ $sql = 'DELETE FROM api_oauth_tokens WHERE oauth_token = :oauth_token';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':oauth_token' => $this->get_value()));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':oauth_token' => $this->get_value()));
+ $stmt->closeCursor();
- return;
- }
+ return;
+ }
- /**
- *
- * @param appbox $appbox
- * @param type $oauth_token
- * @return API_OAuth2_Token
- */
- public static function load_by_oauth_token(appbox &$appbox, $oauth_token)
- {
- $sql = 'SELECT a.api_account_id
+ /**
+ *
+ * @param appbox $appbox
+ * @param type $oauth_token
+ * @return API_OAuth2_Token
+ */
+ public static function load_by_oauth_token(appbox &$appbox, $oauth_token)
+ {
+ $sql = 'SELECT a.api_account_id
FROM api_oauth_tokens a, api_accounts b
WHERE a.oauth_token = :oauth_token
AND a.api_account_id = b.api_account_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $params = array(":oauth_token" => $oauth_token);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $params = array(":oauth_token" => $oauth_token);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_NotFound();
+ if ( ! $row)
+ throw new Exception_NotFound();
- $account = new API_OAuth2_Account($appbox, $row['api_account_id']);
+ $account = new API_OAuth2_Account($appbox, $row['api_account_id']);
- return new self($appbox, $account);
- }
+ return new self($appbox, $account);
+ }
- /**
- *
- * @param appbox $appbox
- * @param API_OAuth2_Account $account
- * @param string $scope
- * @return API_OAuth2_Token
- */
- public static function create(appbox &$appbox, API_OAuth2_Account &$account, $scope = null)
- {
- $sql = 'INSERT INTO api_oauth_tokens
+ /**
+ *
+ * @param appbox $appbox
+ * @param API_OAuth2_Account $account
+ * @param string $scope
+ * @return API_OAuth2_Token
+ */
+ public static function create(appbox &$appbox, API_OAuth2_Account &$account, $scope = null)
+ {
+ $sql = 'INSERT INTO api_oauth_tokens
(oauth_token, session_id, api_account_id, expires, scope)
VALUES (:token, null, :account_id, :expire, :scope)';
- $params = array(
- ':token' => self::generate_token()
- , ':account_id' => $account->get_id()
- , ':expire' => time() + 3600
- , ':scope' => $scope
- );
+ $params = array(
+ ':token' => self::generate_token()
+ , ':account_id' => $account->get_id()
+ , ':expire' => time() + 3600
+ , ':scope' => $scope
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return new API_OAuth2_Token($appbox, $account);
- }
-
- /**
- *
- * @return string
- */
- public static function generate_token()
- {
- return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
- }
+ return new API_OAuth2_Token($appbox, $account);
+ }
+ /**
+ *
+ * @return string
+ */
+ public static function generate_token()
+ {
+ return md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
+ }
}
diff --git a/lib/classes/API/V1/Interface.class.php b/lib/classes/API/V1/Interface.class.php
index 88c5898536..b82ecb0200 100644
--- a/lib/classes/API/V1/Interface.class.php
+++ b/lib/classes/API/V1/Interface.class.php
@@ -17,300 +17,301 @@
*/
interface API_V1_Interface
{
- public function get_version();
- /**
- * Route : /databoxes/list/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- *
- */
- public function get_databoxes(\Symfony\Component\HttpFoundation\Request $request);
+ public function get_version();
- /**
- * Route /databoxes/DATABOX_ID/collections/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- public function get_databox_collections(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
+ /**
+ * Route : /databoxes/list/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ *
+ */
+ public function get_databoxes(\Symfony\Component\HttpFoundation\Request $request);
- /**
- * Route /databoxes/DATABOX_ID/status/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- public function get_databox_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
+ /**
+ * Route /databoxes/DATABOX_ID/collections/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ public function get_databox_collections(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
- /**
- * Route /databoxes/DATABOX_ID/metadatas/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- public function get_databox_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
+ /**
+ * Route /databoxes/DATABOX_ID/status/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ public function get_databox_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
- /**
- * Route /databoxes/DATABOX_ID/termsOfUse/FORMAT/
- *
- * Method : GET
- *
- * Parameters ;
- * DATABOX_ID : required INT
- */
- public function get_databox_terms(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
+ /**
+ * Route /databoxes/DATABOX_ID/metadatas/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ public function get_databox_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
- /**
- * Route : /records/search/FORMAT/
- *
- * Method : GET or POST
- *
- * Parameters :
- * bases[] : array
- * status[] : array
- * fields[] : array
- * record_type : boolean
- * media_type : string
- *
- * Response :
- * Array of record objects
- *
- */
- public function search_records(\Symfony\Component\HttpFoundation\Request $request);
+ /**
+ * Route /databoxes/DATABOX_ID/termsOfUse/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters ;
+ * DATABOX_ID : required INT
+ */
+ public function get_databox_terms(\Symfony\Component\HttpFoundation\Request $request, $databox_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/related/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function get_record_related(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/search/FORMAT/
+ *
+ * Method : GET or POST
+ *
+ * Parameters :
+ * bases[] : array
+ * status[] : array
+ * fields[] : array
+ * record_type : boolean
+ * media_type : string
+ *
+ * Response :
+ * Array of record objects
+ *
+ */
+ public function search_records(\Symfony\Component\HttpFoundation\Request $request);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/metadatas/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function get_record_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/related/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function get_record_related(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/status/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function get_record_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/metadatas/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function get_record_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/embed/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function get_record_embed(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/status/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function get_record_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function set_record_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/embed/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function get_record_embed(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setstatus/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function set_record_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function set_record_metadatas(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/setcollection/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function set_record_collection(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setstatus/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function set_record_status(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /records/DATABOX_ID/RECORD_ID/addtobasket/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * DATABOX_ID : required INT
- * RECORD_ID : required INT
- *
- */
- public function add_record_tobasket(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/setcollection/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function set_record_collection(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /baskets/list/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- public function search_baskets(\Symfony\Component\HttpFoundation\Request $request);
+ /**
+ * Route : /records/DATABOX_ID/RECORD_ID/addtobasket/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * DATABOX_ID : required INT
+ * RECORD_ID : required INT
+ *
+ */
+ public function add_record_tobasket(\Symfony\Component\HttpFoundation\Request $request, $databox_id, $record_id);
- /**
- * Route : /baskets/add/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- public function create_basket(\Symfony\Component\HttpFoundation\Request $request);
+ /**
+ * Route : /baskets/list/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ public function search_baskets(\Symfony\Component\HttpFoundation\Request $request);
- /**
- * Route : /baskets/BASKET_ID/delete/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- public function delete_basket(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
+ /**
+ * Route : /baskets/add/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ public function create_basket(\Symfony\Component\HttpFoundation\Request $request);
- /**
- * Route : /baskets/BASKET_ID/content/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- public function get_basket(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/delete/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ public function delete_basket(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
- /**
- * Route : /baskets/BASKET_ID/title/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- public function set_basket_title(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/content/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ public function get_basket(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
- /**
- * Route : /baskets/BASKET_ID/description/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- * BASKET_ID : required INT
- *
- */
- public function set_basket_description(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
+ /**
+ * Route : /baskets/BASKET_ID/title/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ public function set_basket_title(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
- /**
- * Route : /publications/list/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- public function search_publications(\Symfony\Component\HttpFoundation\Request $request, User_Adapter &$user);
+ /**
+ * Route : /baskets/BASKET_ID/description/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ * BASKET_ID : required INT
+ *
+ */
+ public function set_basket_description(\Symfony\Component\HttpFoundation\Request $request, $basket_id);
- /**
- * Route : /publications/PUBLICATION_ID/remove/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * PUBLICATION_ID : required INT
- *
- */
- public function remove_publications(\Symfony\Component\HttpFoundation\Request $request, $publication_id);
+ /**
+ * Route : /publications/list/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ public function search_publications(\Symfony\Component\HttpFoundation\Request $request, User_Adapter &$user);
- /**
- * Route : /publications/PUBLICATION_ID/content/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * PUBLICATION_ID : required INT
- *
- */
- public function get_publication(\Symfony\Component\HttpFoundation\Request $request, $publication_id, User_Adapter &$user);
+ /**
+ * Route : /publications/PUBLICATION_ID/remove/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * PUBLICATION_ID : required INT
+ *
+ */
+ public function remove_publications(\Symfony\Component\HttpFoundation\Request $request, $publication_id);
- /**
- * Route : /users/search/FORMAT/
- *
- * Method : POST-GET
- *
- * Parameters :
- *
- */
- public function search_users(\Symfony\Component\HttpFoundation\Request $request);
+ /**
+ * Route : /publications/PUBLICATION_ID/content/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * PUBLICATION_ID : required INT
+ *
+ */
+ public function get_publication(\Symfony\Component\HttpFoundation\Request $request, $publication_id, User_Adapter &$user);
- /**
- * Route : /users/USER_ID/access/FORMAT/
- *
- * Method : GET
- *
- * Parameters :
- * USER_ID : required INT
- *
- */
- public function get_user_acces(\Symfony\Component\HttpFoundation\Request $request, $usr_id);
+ /**
+ * Route : /users/search/FORMAT/
+ *
+ * Method : POST-GET
+ *
+ * Parameters :
+ *
+ */
+ public function search_users(\Symfony\Component\HttpFoundation\Request $request);
- /**
- * Route : /users/add/FORMAT/
- *
- * Method : POST
- *
- * Parameters :
- *
- */
- public function add_user(\Symfony\Component\HttpFoundation\Request $request);
+ /**
+ * Route : /users/USER_ID/access/FORMAT/
+ *
+ * Method : GET
+ *
+ * Parameters :
+ * USER_ID : required INT
+ *
+ */
+ public function get_user_acces(\Symfony\Component\HttpFoundation\Request $request, $usr_id);
- public function get_error_message(\Symfony\Component\HttpFoundation\Request $request, $error);
+ /**
+ * Route : /users/add/FORMAT/
+ *
+ * Method : POST
+ *
+ * Parameters :
+ *
+ */
+ public function add_user(\Symfony\Component\HttpFoundation\Request $request);
- public function get_error_code(\Symfony\Component\HttpFoundation\Request $request, $code);
+ public function get_error_message(\Symfony\Component\HttpFoundation\Request $request, $error);
+
+ public function get_error_code(\Symfony\Component\HttpFoundation\Request $request, $code);
}
diff --git a/lib/classes/API/V1/Log.class.php b/lib/classes/API/V1/Log.class.php
index e562c4e143..1c1db4519d 100644
--- a/lib/classes/API/V1/Log.class.php
+++ b/lib/classes/API/V1/Log.class.php
@@ -10,89 +10,89 @@ use Symfony\Component\HttpFoundation\Response;
class API_V1_Log
{
+ const DATABOXES_RESSOURCE = 'databoxes';
+ const RECORDS_RESSOURCE = 'record';
+ const BASKETS_RESSOURCE = 'baskets';
+ const FEEDS_RESSOURCE = 'feeds';
- const DATABOXES_RESSOURCE = 'databoxes';
- const RECORDS_RESSOURCE = 'record';
- const BASKETS_RESSOURCE = 'baskets';
- const FEEDS_RESSOURCE = 'feeds';
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $account_id;
+ /**
+ *
+ * @var int
+ */
+ protected $account_id;
- /**
- *
- * @var DateTime
- */
- protected $date;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $date;
- /**
- *
- * @var int
- */
- protected $status_code;
+ /**
+ *
+ * @var int
+ */
+ protected $status_code;
- /**
- *
- * @var string
- */
- protected $format;
+ /**
+ *
+ * @var string
+ */
+ protected $format;
- /**
- *
- * @var string
- */
- protected $ressource;
+ /**
+ *
+ * @var string
+ */
+ protected $ressource;
- /**
- *
- * @var string
- */
- protected $general;
+ /**
+ *
+ * @var string
+ */
+ protected $general;
- /**
- *
- * @var string
- */
- protected $aspect;
+ /**
+ *
+ * @var string
+ */
+ protected $aspect;
- /**
- *
- * @var string
- */
- protected $action;
+ /**
+ *
+ * @var string
+ */
+ protected $action;
- /**
- *
- * @var API_OAuth2_Account
- */
- protected $account;
+ /**
+ *
+ * @var API_OAuth2_Account
+ */
+ protected $account;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @param appbox $appbox
- * @param Request $request
- * @param API_OAuth2_Account $account
- */
- public function __construct(appbox &$appbox, $log_id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $log_id;
+ /**
+ *
+ * @param appbox $appbox
+ * @param Request $request
+ * @param API_OAuth2_Account $account
+ */
+ public function __construct(appbox &$appbox, $log_id)
+ {
+ $this->appbox = $appbox;
+ $this->id = (int) $log_id;
- $sql = '
+ $sql = '
SELECT
api_log_id,
api_account_id,
@@ -109,239 +109,238 @@ class API_V1_Log
WHERE
api_log_id = :log_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':log_id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':log_id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->account_id = $row['api_account_id'];
- $this->account = new API_OAuth2_Account($this->appbox, (int) $row['api_account_id']);
- $this->aspect = $row['api_log_aspect'];
- $this->date = new DateTime($row['api_log_date']);
- $this->format = $row['api_log_format'];
- $this->general = $row['api_log_general'];
- $this->ressource = $row['api_log_ressource'];
- $this->status_code = (int) $row['api_log_status_code'];
+ $this->account_id = $row['api_account_id'];
+ $this->account = new API_OAuth2_Account($this->appbox, (int) $row['api_account_id']);
+ $this->aspect = $row['api_log_aspect'];
+ $this->date = new DateTime($row['api_log_date']);
+ $this->format = $row['api_log_format'];
+ $this->general = $row['api_log_general'];
+ $this->ressource = $row['api_log_ressource'];
+ $this->status_code = (int) $row['api_log_status_code'];
- return $this;
- }
+ return $this;
+ }
- public function get_account_id()
- {
- return $this->account_id;
- }
+ public function get_account_id()
+ {
+ return $this->account_id;
+ }
- public function set_account_id($account_id)
- {
- $this->account_id = $account_id;
+ public function set_account_id($account_id)
+ {
+ $this->account_id = $account_id;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_account_id = :account_id
WHERE api_log_id = :log_id';
- $params = array(
- ':api_account_id' => $this->account_id
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':api_account_id' => $this->account_id
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_date()
- {
- return $this->date;
- }
+ public function get_date()
+ {
+ return $this->date;
+ }
- public function set_date(DateTime $date)
- {
- $this->date = $date;
+ public function set_date(DateTime $date)
+ {
+ $this->date = $date;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_date = :date
WHERE api_log_id = :log_id';
- $params = array(
- ':date' => $this->date->format("Y-m-d H:i:s")
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':date' => $this->date->format("Y-m-d H:i:s")
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_status_code()
- {
- return $this->status_code;
- }
+ public function get_status_code()
+ {
+ return $this->status_code;
+ }
- public function set_status_code($status_code)
- {
- $this->status_code = (int) $status_code;
+ public function set_status_code($status_code)
+ {
+ $this->status_code = (int) $status_code;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_status_code = :code
WHERE api_log_id = :log_id';
- $params = array(
- ':code' => $this->status_code
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':code' => $this->status_code
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_format()
- {
- return $this->format;
- }
+ public function get_format()
+ {
+ return $this->format;
+ }
- public function set_format($format)
- {
+ public function set_format($format)
+ {
- if (!in_array($format, array('json', 'jsonp', 'yaml', 'unknow')))
- throw new Exception_InvalidArgument();
+ if ( ! in_array($format, array('json', 'jsonp', 'yaml', 'unknow')))
+ throw new Exception_InvalidArgument();
- $this->format = $format;
+ $this->format = $format;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_format = :format
WHERE api_log_id = :log_id';
- $params = array(
- ':format' => $this->format
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':format' => $this->format
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_ressource()
- {
- return $this->ressource;
- }
+ public function get_ressource()
+ {
+ return $this->ressource;
+ }
- public function set_ressource($ressource)
- {
- if (!in_array($format, array(self::DATABOXES_RESSOURCE,self::BASKETS_RESSOURCE, self::FEEDS_RESSOURCE, self::RECORDS_RESSOURCE)))
- throw new Exception_InvalidArgument();
+ public function set_ressource($ressource)
+ {
+ if ( ! in_array($format, array(self::DATABOXES_RESSOURCE, self::BASKETS_RESSOURCE, self::FEEDS_RESSOURCE, self::RECORDS_RESSOURCE)))
+ throw new Exception_InvalidArgument();
- $this->ressource = $ressource;
+ $this->ressource = $ressource;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_ressource = :ressource
WHERE api_log_id = :log_id';
- $params = array(
- ':ressource' => $this->ressource
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':ressource' => $this->ressource
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_general()
- {
- return $this->general;
- }
+ public function get_general()
+ {
+ return $this->general;
+ }
- public function set_general($general)
- {
- $this->general = $general;
+ public function set_general($general)
+ {
+ $this->general = $general;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_general = :general
WHERE api_log_id = :log_id';
- $params = array(
- ':general' => $this->general
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':general' => $this->general
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_aspect()
- {
- return $this->aspect;
- }
+ public function get_aspect()
+ {
+ return $this->aspect;
+ }
- public function set_aspect($aspect)
- {
- $this->aspect = $aspect;
+ public function set_aspect($aspect)
+ {
+ $this->aspect = $aspect;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_aspect = :aspect
WHERE api_log_id = :log_id';
- $params = array(
- ':aspect' => $this->aspect
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':aspect' => $this->aspect
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_action()
- {
- return $this->action;
- }
+ public function get_action()
+ {
+ return $this->action;
+ }
- public function set_action($action)
- {
- $this->action = $action;
+ public function set_action($action)
+ {
+ $this->action = $action;
- $sql = 'UPDATE api_log
+ $sql = 'UPDATE api_log
SET api_log_action = :action
WHERE api_log_id = :log_id';
- $params = array(
- ':action' => $this->action
- , ':log_id' => $this->id
- );
+ $params = array(
+ ':action' => $this->action
+ , ':log_id' => $this->id
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- public function get_account()
- {
- return $this->account;
- }
+ public function get_account()
+ {
+ return $this->account;
+ }
-
- public static function create(appbox &$appbox, API_OAuth2_Account $account, $route, $status_code, $format, $ressource, $general = null, $aspect = null, $action = null)
- {
- $sql = '
+ public static function create(appbox &$appbox, API_OAuth2_Account $account, $route, $status_code, $format, $ressource, $general = null, $aspect = null, $action = null)
+ {
+ $sql = '
INSERT INTO
api_logs (
api_log_id,
@@ -368,23 +367,23 @@ class API_V1_Log
:action
)';
- $params = array(
- ':account_id' => $account->get_id(),
- ':route' => $route,
- ':status_code' => $status_code,
- ':format' => $format,
- ':ressource' => $ressource,
- ':general' => $general,
- ':aspect' => $aspect,
- ':action' => $action
- );
+ $params = array(
+ ':account_id' => $account->get_id(),
+ ':route' => $route,
+ ':status_code' => $status_code,
+ ':format' => $format,
+ ':ressource' => $ressource,
+ ':general' => $general,
+ ':aspect' => $aspect,
+ ':action' => $action
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $log_id = $appbox->get_connection()->lastInsertId();
+ $log_id = $appbox->get_connection()->lastInsertId();
- return new self($appbox, $log_id);
- }
+ return new self($appbox, $log_id);
+ }
}
diff --git a/lib/classes/API/V1/adapter.class.php b/lib/classes/API/V1/adapter.class.php
index 94e64e2f37..b149fe1495 100644
--- a/lib/classes/API/V1/adapter.class.php
+++ b/lib/classes/API/V1/adapter.class.php
@@ -19,1388 +19,1339 @@ use Symfony\Component\HttpFoundation\Request;
class API_V1_adapter extends API_V1_Abstract
{
-
- /**
- * API Version
- *
- * @var string
- */
- protected $version = '1.1';
-
- /**
- * Appbox where the API works
- *
- * @var appbox
- */
- protected $appbox;
-
- /**
- * Phraseanet Core
- *
- * @var \Alchemy\Phrasea\Core
- */
- protected $core;
-
- /**
- * API constructor
- *
- * @param string $auth_token Authentification Token
- * @param appbox $appbox Appbox object
- * @return API_V1_adapter
- */
- public function __construct($auth_token, appbox &$appbox, Alchemy\Phrasea\Core $core)
- {
- $this->appbox = $appbox;
- $this->core = $core;
-
- return $this;
- }
-
- /**
- * Retrieve http status error code according to the message
- * @param Request $request
- * @param string $error
- * @return API_V1_result `
- */
- public function get_error_message(Request $request, $error)
- {
- $result = new API_V1_result($request, $this);
- $result->set_error_message($error);
-
- return $result;
- }
-
- /**
- * Retrieve http status error message according to the http status error code
- * @param Request $request
- * @param int $code
- * @return API_V1_result
- */
- public function get_error_code(Request $request, $code)
- {
- $result = new API_V1_result($request, $this);
- $result->set_error_code($code);
-
- return $result;
- }
-
- /**
- * Get the current version
- *
- * @return string
- */
- public function get_version()
- {
- return $this->version;
- }
-
- /**
- * Get an API_V1_result containing the databoxes
- *
- * @param Request $request
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_databoxes(Request $request)
- {
- $result = new API_V1_result($request, $this);
-
- $result->set_datas(array("databoxes" => $this->list_databoxes()));
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the collections of a databox
- *
- * @param Request $request
- * @param int $databox_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_databox_collections(Request $request, $databox_id)
- {
- $result = new API_V1_result($request, $this);
-
- $result->set_datas(
- array(
- "collections" => $this->list_databox_collections(
- $this->appbox->get_databox($databox_id)
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the status of a databox
- *
- * @param Request $request
- * @param int $databox_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_databox_status(Request $request, $databox_id)
- {
- $result = new API_V1_result($request, $this);
-
- $result->set_datas(
- array(
- "status" =>
- $this->list_databox_status(
- $this->appbox->get_databox($databox_id)->get_statusbits()
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the metadatas of a databox
- *
- * @param Request $request
- * @param int $databox_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_databox_metadatas(Request $request, $databox_id)
- {
- $result = new API_V1_result($request, $this);
-
- $result->set_datas(
- array(
- "metadatas" =>
- $this->list_databox_metadatas_fields(
- $this->appbox->get_databox($databox_id)
- ->get_meta_structure()
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the terms of use of a databox
- *
- * @param Request $request
- * @param int $databox_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_databox_terms(Request $request, $databox_id)
- {
- $result = new API_V1_result($request, $this);
-
- $result->set_datas(
- array(
- "termsOfUse" =>
- $this->list_databox_terms($this->appbox->get_databox($databox_id))
- )
- );
-
- return $result;
- }
-
- public function caption_records(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
-
- $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
- $fields = $record->get_caption()->get_fields();
- $ret = array();
- foreach ($fields as $field)
- {
- $ret[$field->get_meta_struct_id()] = array(
- 'meta_structure_id' => $field->get_meta_struct_id()
- , 'name' => $field->get_name()
- , 'value' => $field->get_serialized_values(";")
- );
- }
- $result->set_datas($ret);
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the results of a records search
- *
- * @param Request $request
- * @param int $databox_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function search_records(Request $request)
- {
- $session = $this->appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
- $registry = $this->appbox->get_registry();
- $result = new API_V1_result($request, $this);
-
- $search_type = ($request->get('search_type')
- && in_array($request->get('search_type'), array(0, 1))) ?
- $request->get('search_type') : 0;
-
- $record_type = ($request->get('record_type')
- && in_array(
- $request->get('record_type')
- , array('audio', 'video', 'image', 'document', 'flash'))
- ) ?
- $request->get('record_type') : '';
-
- $params = array(
- 'fields' => is_array($request->get('fields')) ? $request->get('fields') : array()
- , 'status' => is_array($request->get('status')) ? $request->get('status') : array()
- , 'bases' => is_array($request->get('bases')) ? $request->get('bases') : array()
- , 'search_type' => $search_type
- , 'recordtype' => $record_type
- , 'datemin' => $request->get('datemin') ? : ''
- , 'datemax' => $request->get('datemax') ? : ''
- , 'datefield' => $request->get('datefield') ? : ''
- , 'sort' => $request->get('sort') ? : ''
- , 'ord' => $request->get('ord') ? : ''
- , 'stemme' => $request->get('stemme') ? : ''
- , 'per_page' => $request->get('per_page') ? : 10
- , 'query' => $request->get('query') ? : ''
- , 'page' => (int) ($request->get('page') ? : 0)
- );
-
- if (is_array($request->get('bases')) === false)
- {
- $params['bases'] = array();
- foreach ($this->appbox->get_databoxes() as $databox)
- {
- foreach ($databox->get_collections() as $collection)
- $params['bases'][] = $collection->get_base_id();
- }
- }
-
- $options = new searchEngine_options();
-
- $params['bases'] = is_array($params['bases']) ? $params['bases'] : array_keys($user->ACL()->get_granted_base());
-
- /* @var $user \User_Adapter */
- if ($user->ACL()->has_right('modifyrecord'))
- {
- $options->set_business_fields(array());
-
- $BF = array();
-
- foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection)
- {
- if (count($params['bases']) === 0 || in_array($collection->get_base_id(), $params['bases']))
- {
- $BF[] = $collection->get_base_id();
- }
- }
- $options->set_business_fields($BF);
- }
- else
- {
- $options->set_business_fields(array());
- }
-
- $options->set_bases($params['bases'], $user->ACL());
-
- if ( ! is_array($params['fields']))
- $params['fields'] = array();
- $options->set_fields($params['fields']);
- if ( ! is_array($params['status']))
- $params['status'] = array();
- $options->set_status($params['status']);
- $options->set_search_type($params['search_type']);
- $options->set_record_type($params['recordtype']);
- $options->set_min_date($params['datemin']);
- $options->set_max_date($params['datemax']);
- $options->set_date_fields(explode('|', $params['datefield']));
- $options->set_sort($params['sort'], $params['ord']);
- $options->set_use_stemming($params['stemme']);
-
- $perPage = (int) $params['per_page'];
- $search_engine = new searchEngine_adapter($registry);
- $search_engine->set_options($options);
-
+ /**
+ * API Version
+ *
+ * @var string
+ */
+ protected $version = '1.1';
/**
- * @todo ameliorer this shit
+ * Appbox where the API works
+ *
+ * @var appbox
*/
- if ($params['page'] < 1)
+ protected $appbox;
+
+ /**
+ * Phraseanet Core
+ *
+ * @var \Alchemy\Phrasea\Core
+ */
+ protected $core;
+
+ /**
+ * API constructor
+ *
+ * @param string $auth_token Authentification Token
+ * @param appbox $appbox Appbox object
+ * @return API_V1_adapter
+ */
+ public function __construct($auth_token, appbox &$appbox, Alchemy\Phrasea\Core $core)
{
- $search_engine->set_is_first_page(true);
- $params['page'] = 1;
- }
+ $this->appbox = $appbox;
+ $this->core = $core;
- $search_engine->reset_cache();
-
- $search_result = $search_engine->query_per_page($params['query'], $params["page"], $perPage);
-
- $ret = array(
- 'total_pages' => $search_result->get_total_pages()
- , 'current_page' => $search_result->get_current_page()
- , 'available_results' => $search_result->get_count_available_results()
- , 'total_results' => $search_result->get_count_total_results()
- , 'error' => $search_result->get_error()
- , 'warning' => $search_result->get_warning()
- , 'query_time' => $search_result->get_query_time()
- , 'search_indexes' => $search_result->get_search_indexes()
- , 'suggestions' => $search_result->get_suggestions()
- , 'results' => array()
- , 'query' => $search_engine->get_query()
- );
-
- foreach ($search_result->get_datas()->get_elements() as $record)
- {
- $ret['results'][] = $this->list_record($record);
+ return $this;
}
/**
- * @todo donner des highlights
+ * Retrieve http status error code according to the message
+ * @param Request $request
+ * @param string $error
+ * @return API_V1_result `
*/
- $result->set_datas($ret);
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the baskets where the record is in
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_record_related(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
-
- $containers = $this->appbox
- ->get_databox($databox_id)
- ->get_record($record_id)
- ->get_container_baskets();
-
- $ret = array();
- foreach ($containers as $basket)
+ public function get_error_message(Request $request, $error)
{
- $ret[$basket->getId()] = $this->list_basket($basket);
+ $result = new API_V1_result($request, $this);
+ $result->set_error_message($error);
+
+ return $result;
}
- $result->set_datas(array("baskets" => $ret));
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the record metadatas
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_record_metadatas(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
-
- $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
-
- $result->set_datas(
- array(
- "metadatas" => $this->list_record_caption($record->get_caption())
- )
- );
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the record status
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_record_status(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
-
- $record = $this->appbox
- ->get_databox($databox_id)
- ->get_record($record_id);
-
- $result->set_datas(
- array(
- "status" =>
- $this->list_record_status(
- $this->appbox->get_databox($databox_id)
- , $record->get_status()
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Get an API_V1_result containing the record embed files
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @param string $response_type
- * @return API_V1_result
- */
- public function get_record_embed(Request $request, $databox_id, $record_id)
- {
-
- $result = new API_V1_result($request, $this);
-
- $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
-
- $ret = array();
- foreach ($record->get_embedable_medias() as $name => $media)
+ /**
+ * Retrieve http status error message according to the http status error code
+ * @param Request $request
+ * @param int $code
+ * @return API_V1_result
+ */
+ public function get_error_code(Request $request, $code)
{
- $ret[$name] = $this->list_embedable_media($media, $this->appbox->get_registry());
+ $result = new API_V1_result($request, $this);
+ $result->set_error_code($code);
+
+ return $result;
}
- $result->set_datas(array("embed" => $ret));
-
- return $result;
- }
-
- public function set_record_metadatas(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
- $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
-
- try
+ /**
+ * Get the current version
+ *
+ * @return string
+ */
+ public function get_version()
{
- $metadatas = $request->get('metadatas');
-
- if ( ! is_array($metadatas))
- {
- throw new Exception('Metadatas should be an array');
- }
-
- foreach ($metadatas as $metadata)
- {
- if ( ! is_array($metadata))
- {
- throw new Exception('Each Metadata value should be an array');
- }
- }
-
- $record->set_metadatas($metadatas);
- $result->set_datas(array("metadatas" => $this->list_record_caption($record->get_caption())));
- }
- catch (Exception $e)
- {
- $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ return $this->version;
}
- return $result;
- }
-
- public function set_record_status(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
- $databox = $this->appbox->get_databox($databox_id);
- $record = $databox->get_record($record_id);
- $status_bits = $databox->get_statusbits();
-
- try
+ /**
+ * Get an API_V1_result containing the databoxes
+ *
+ * @param Request $request
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_databoxes(Request $request)
{
- $status = $request->get('status');
+ $result = new API_V1_result($request, $this);
- $datas = strrev($record->get_status());
+ $result->set_datas(array("databoxes" => $this->list_databoxes()));
- if ( ! is_array($status))
- throw new API_V1_exception_badrequest();
- foreach ($status as $n => $value)
- {
- if ($n > 63 || $n < 4)
- throw new API_V1_exception_badrequest();
- if ( ! in_array($value, array('0', '1')))
- throw new API_V1_exception_badrequest();
- if ( ! isset($status_bits[$n]))
- throw new API_V1_exception_badrequest ();
-
- $datas = substr($datas, 0, ($n - 1)) . $value . substr($datas, ($n + 1));
- }
- $datas = strrev($datas);
-
- $record->set_binary_status($datas);
- $result->set_datas(array(
- "status" =>
- $this->list_record_status($databox, $record->get_status())
- )
- );
- }
- catch (Exception $e)
- {
- $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ return $result;
}
- return $result;
- }
-
- /**
- * Move a record to another collection
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @return API_V1_result
- */
- public function set_record_collection(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
- $databox = $this->appbox->get_databox($databox_id);
- $record = $databox->get_record($record_id);
-
- try
+ /**
+ * Get an API_V1_result containing the collections of a databox
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_databox_collections(Request $request, $databox_id)
{
- $collection = collection::get_from_base_id($request->get('base_id'));
+ $result = new API_V1_result($request, $this);
- $record->move_to_collection($collection, $this->appbox);
- $result->set_datas(array("record" => $this->list_record($record)));
- }
- catch (Exception $e)
- {
- $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
- }
-
- return $result;
- }
-
- /**
- * Return detailed informations about one record
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- * @return API_V1_result
- */
- public function get_record(Request $request, $databox_id, $record_id)
- {
- $result = new API_V1_result($request, $this);
- $databox = $this->appbox->get_databox($databox_id);
- try
- {
- $record = $databox->get_record($record_id);
- $result->set_datas(array('record' => $this->list_record($record)));
- }
- catch (Exception $e)
- {
- $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
- }
-
- return $result;
- }
-
- /**
- * @todo
- *
- * @param Request $request
- * @param int $databox_id
- * @param int $record_id
- */
- public function add_record_tobasket(Request $request, $databox_id, $record_id)
- {
-
- }
-
- /**
- * Return the baskets list of the authenticated user
- *
- * @param Request $request
- * @return API_V1_result
- */
- public function search_baskets(Request $request)
- {
- $result = new API_V1_result($request, $this);
-
- $usr_id = $session = $this->appbox->get_session()->get_usr_id();
-
- $result->set_datas(array('baskets' => $this->list_baskets($usr_id)));
-
- return $result;
- }
-
- /**
- * Return a baskets list
- *
- * @param int $usr_id
- * @return array
- */
- protected function list_baskets($usr_id)
- {
- $em = $this->core->getEntityManager();
- $repo = $em->getRepository('\Entities\Basket');
- /* @var $repo \Repositories\BasketRepository */
-
- $baskets = $repo->findActiveByUser($this->core->getAuthenticatedUser());
-
- $ret = array();
- foreach ($baskets as $basket)
- {
- $ret[$basket->getId()] = $this->list_basket($basket);
- }
-
- return $ret;
- }
-
- /**
- * Create a new basket
- *
- * @param Request $request
- * @return API_V1_result
- */
- public function create_basket(Request $request)
- {
- $result = new API_V1_result($request, $this);
-
- $name = $request->get('name');
-
- if (trim(strip_tags($name)) === '')
- throw new API_V1_exception_badrequest ();
-
- $user = $this->core->getAuthenticatedUser();
-
- $Basket = new \Entities\Basket();
- $Basket->setOwner($user);
- $Basket->setName($name);
-
- $em = $this->core->getEntityManager();
- $em->persist($Basket);
- $em->flush();
-
- $ret = array();
- $ret[$Basket->getId()] = $this->list_basket($Basket);
- $result->set_datas(array("basket" => $ret));
-
- return $result;
- }
-
- /**
- * Delete a basket
- *
- * @param Request $request
- * @param int $basket_id
- * @return array
- */
- public function delete_basket(Request $request, $basket_id)
- {
- $result = new API_V1_result($request, $this);
-
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
-
- /* @var $repository \Repositories\BasketRepository */
-
- $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
- $em->remove($Basket);
- $em->flush();
-
- return $this->search_baskets($request);
- }
-
- /**
- * Retrieve a basket
- *
- * @param Request $request
- * @param int $basket_id
- * @return API_V1_result
- */
- public function get_basket(Request $request, $basket_id)
- {
- $result = new API_V1_result($request, $this);
-
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- /* @var $repository \Repositories\BasketRepository */
-
- $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), false);
-
- $result->set_datas(
- array("basket_elements" =>
- array(
- $Basket->getId() => $this->list_basket_content($Basket)
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Retrieve elements of one basket
- *
- * @param \Entities\Basket $Basket
- * @return type
- */
- protected function list_basket_content(\Entities\Basket $Basket)
- {
- $ret = $this->list_basket($Basket);
-
- $ret['basket_elements'] = array();
-
- foreach ($Basket->getElements() as $basket_element)
- {
- $ret['basket_elements'][$basket_element->getId()] = $this->list_basket_element($basket_element);
- }
-
- return $ret;
- }
-
- /**
- * Retrieve detailled informations about a basket element
- *
- * @param \Entities\BasketElement $basket_element
- * @return type
- */
- protected function list_basket_element(\Entities\BasketElement $basket_element)
- {
- $ret = array(
- 'basket_element_id' => $basket_element->getId()
- , 'order' => $basket_element->getOrd()
- , 'record' => $this->list_record($basket_element->getRecord())
- , 'validation_item' => ! ! $basket_element->getValidationDatas()
- );
-
- if ($basket_element->getValidationDatas())
- {
- $choices = array();
- $agreement = $note = null;
-
- foreach ($basket_element->getValidationDatas() as $validation_datas)
- {
- $user = $validation_datas->getParticipant()->getUser();
- /* @var $validation_datas Entities\ValidationData */
- $choices[$user->get_id()] = array(
- 'usr_id' => $user->get_id(),
- 'usr_name' => $user->get_display_name(),
- 'is_mine' => $user->get_id() == $this->core->getAuthenticatedUser()->get_id(),
- 'agreement' => $validation_datas->getAgreement(),
- 'updated_on' => $validation_datas->getUpdated()->format(DATE_ATOM),
- 'note' => $validation_datas->getNote()
+ $result->set_datas(
+ array(
+ "collections" => $this->list_databox_collections(
+ $this->appbox->get_databox($databox_id)
+ )
+ )
);
- if ($user->get_id() == $this->core->getAuthenticatedUser()->get_id())
- {
- $agreement = $validation_datas->getAgreement();
- $note = $validation_datas->getNote();
- }
- }
-
- $ret['choices'] = $choices();
- $ret['agreement'] = $agreement();
- $ret['note'] = $note();
+ return $result;
}
- return $ret;
- }
-
- /**
- * Change the name of one basket
- *
- * @param Request $request
- * @param int $basket_id
- * @return API_V1_result
- */
- public function set_basket_title(Request $request, $basket_id)
- {
- $result = new API_V1_result($request, $this);
-
- $name = $request->get('name');
-
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
-
- /* @var $repository \Repositories\BasketRepository */
-
- $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
- $Basket->setName($name);
-
- $em->merge($Basket);
- $em->flush();
-
- $result->set_datas(
- array(
- "basket" =>
- array($Basket->getId() => $this->list_basket_content($Basket)
- )
- )
- );
-
- return $result;
- }
-
- /**
- * Change the description of one basket
- *
- * @param Request $request
- * @param type $basket_id
- * @return API_V1_result
- */
- public function set_basket_description(Request $request, $basket_id)
- {
- $result = new API_V1_result($request, $this);
-
- $desc = $request->get('description');
-
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
-
- /* @var $repository \Repositories\BasketRepository */
-
- $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
- $Basket->setDescription($desc);
-
- $em->merge($Basket);
- $em->flush();
-
- $result->set_datas(
- array(
- "basket" =>
- array($Basket->getId() => $this->list_basket_content($Basket)
- )
- )
- );
-
- return $result;
- }
-
- /**
- * List all avalaible feeds
- *
- * @param Request $request
- * @param User_Adapter $user
- * @return API_V1_result
- */
- public function search_publications(Request $request, User_Adapter &$user)
- {
- $result = new API_V1_result($request, $this);
-
- $coll = Feed_Collection::load_all($this->appbox, $user);
-
- $datas = array();
- foreach ($coll->get_feeds() as $feed)
- {
- $datas[$feed->get_id()] = $this->list_publication($feed, $user);
- }
-
- $result->set_datas(array("feeds" => $datas));
-
- return $result;
- }
-
- /**
- * @todo
- *
- * @param Request $request
- * @param int $publication_id
- */
- public function remove_publications(Request $request, $publication_id)
- {
-
- }
-
- /**
- * Retrieve one feed
- *
- * @param Request $request
- * @param int $publication_id
- * @param User_Adapter $user
- * @return API_V1_result
- */
- public function get_publication(Request $request, $publication_id, User_Adapter &$user)
- {
- $result = new API_V1_result($request, $this);
-
- $feed = Feed_Adapter::load_with_user($this->appbox, $user, $publication_id);
-
- $offset_start = (int) ($request->get('offset_start') ? : 0);
- $per_page = (int) ($request->get('per_page') ? : 5);
-
- $per_page = (($per_page >= 1) && ($per_page <= 20)) ? $per_page : 5;
-
- $datas = array(
- 'feed' => $this->list_publication($feed, $user)
- , 'offset_start' => $offset_start
- , 'per_page' => $per_page
- , 'entries' => $this->list_publications_entries($feed, $offset_start, $per_page)
- );
-
- $result->set_datas($datas);
-
- return $result;
- }
-
- /**
- * Retrieve detailled informations about one feed
- *
- * @param Feed_Adapter $feed
- * @param type $user
- * @return array
- */
- protected function list_publication(Feed_Adapter $feed, $user)
- {
- return array(
- 'id' => $feed->get_id()
- , 'title' => $feed->get_title()
- , 'subtitle' => $feed->get_subtitle()
- , 'total_entries' => $feed->get_count_total_entries()
- , 'icon' => $feed->get_icon_url()
- , 'public' => $feed->is_public()
- , 'is_mine' => $feed->is_owner($user)
- , 'created_on' => $feed->get_created_on()->format(DATE_ATOM)
- , 'updated_on' => $feed->get_updated_on()->format(DATE_ATOM)
- );
- }
-
- /**
- * Retrieve all entries of one feed
- *
- * @param Feed_Adapter $feed
- * @param int $offset_start
- * @param int $how_many
- * @return array
- */
- protected function list_publications_entries(Feed_Adapter $feed, $offset_start = 0, $how_many = 5)
- {
-
- $entries = $feed->get_entries($offset_start, $how_many)->get_entries();
-
- $out = array();
- foreach ($entries as $entry)
- {
- $out[$entry->get_id()] = $this->list_publication_entry($entry);
- }
-
- return array(
- 'offset_start' => $offset_start
- , 'entries' => $out
- );
- }
-
- /**
- * Retrieve detailled information about one feed entry
- *
- * @param Feed_Entry_Adapter $entry
- * @return array
- */
- protected function list_publication_entry(Feed_Entry_Adapter $entry)
- {
- $items = array();
- foreach ($entry->get_content() as $item)
- {
- $items[] = $this->list_publication_entry_item($item);
- }
-
- return array(
- 'author_email' => $entry->get_author_email()
- , 'author_name' => $entry->get_author_name()
- , 'created_on' => $entry->get_created_on()->format(DATE_ATOM)
- , 'updated_on' => $entry->get_updated_on()->format(DATE_ATOM)
- , 'title' => $entry->get_title()
- , 'subtitle' => $entry->get_subtitle()
- , 'items' => $items
- );
- }
-
- /**
- * Retrieve detailled informations about one feed entry item
- *
- * @param Feed_Entry_Item $item
- * @return array
- */
- protected function list_publication_entry_item(Feed_Entry_Item $item)
- {
- $datas = array(
- 'item_id' => $item->get_id()
- , 'record' => $this->list_record($item->get_record())
- );
-
- return $datas;
- }
-
- /**
- * @todo
- * @param Request $request
- */
- public function search_users(Request $request)
- {
-
- }
-
- /**
- * @todo
- * @param Request $request
- * @param int $usr_id
- */
- public function get_user_acces(Request $request, $usr_id)
- {
-
- }
-
- /**
- * @todo
- * @param Request $request
- */
- public function add_user(Request $request)
- {
-
- }
-
- /**
- * @retrieve detailled informations about one suddef
- *
- * @param media_subdef $media
- * @return array
- */
- protected function list_embedable_media(media_subdef &$media, registryInterface &$registry)
- {
- if ($media->get_permalink() instanceof media_Permalink_Adapter)
- $permalink = $this->list_permalink($media->get_permalink(), $registry);
- else
- $permalink = null;
-
- return array(
- 'permalink' => $permalink
- , 'height' => $media->get_height()
- , 'width' => $media->get_width()
- , 'filesize' => $media->get_size()
- , 'player_type' => $media->get_type()
- , 'mime_type' => $media->get_mime()
- );
- }
-
- /**
- * Retrieve detailled information about one permalink
- *
- * @param media_Permalink_Adapter $permalink
- * @param registryInterface $registry
- * @return type
- */
- protected function list_permalink(media_Permalink_Adapter &$permalink, registryInterface &$registry)
- {
- return array(
- 'created_on' => $permalink->get_created_on()->format(DATE_ATOM)
- , 'id' => $permalink->get_id()
- , 'is_activated' => $permalink->get_is_activated()
- , 'label' => $permalink->get_label()
- , 'last_modified' => $permalink->get_last_modified()->format(DATE_ATOM)
- , 'page_url' => $permalink->get_page($registry)
- , 'url' => $permalink->get_url($registry)
- );
- }
-
- /**
- * Retrieve detailled information about one status
- *
- * @param databox $databox
- * @param string $status
- * @return array
- */
- protected function list_record_status(databox $databox, $status)
- {
- $status = strrev($status);
- $ret = array();
- foreach ($databox->get_statusbits() as $bit => $status_datas)
- {
- $ret[$bit] = array('bit' => $bit, 'state' => ! ! substr($status, ($bit - 1), 1));
- }
-
- return $ret;
- }
-
- /**
- * List all field about a specified caption
- *
- * @param caption_record $caption
- * @return array
- */
- protected function list_record_caption(caption_record $caption)
- {
- $ret = array();
- foreach ($caption->get_fields() as $field)
- {
- foreach ($field->get_values() as $value)
- {
- $ret[$value->getId()] = $this->list_record_caption_field($value, $field);
- }
- }
-
- return $ret;
- }
-
- /**
- * Retrieve information about a caption field
- *
- * @param caption_field $field
- * @return array
- */
- protected function list_record_caption_field(caption_Field_Value $value, caption_field $field)
- {
/**
- * @todo ajouter une option pour avoir les values serialisées
- * dans un cas multi
+ * Get an API_V1_result containing the status of a databox
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param string $response_type
+ * @return API_V1_result
*/
-
- return array(
- 'meta_id' => $value->getId()
- , 'meta_structure_id' => $field->get_meta_struct_id()
- , 'name' => $field->get_name()
- , 'value' => $value->getValue()
- );
- }
-
- /**
- * Retirve information about one basket
- *
- * @param \Entities\Basket $basket
- * @return array
- */
- protected function list_basket(\Entities\Basket $basket)
- {
- $ret = array(
- 'created_on' => $basket->getCreated()->format(DATE_ATOM)
- , 'description' => (string) $basket->getDescription()
- , 'name' => $basket->getName()
- , 'pusher_usr_id' => $basket->getPusherId()
- , 'ssel_id' => $basket->getId()
- , 'updated_on' => $basket->getUpdated()->format(DATE_ATOM)
- , 'unread' => ! $basket->getIsRead()
- );
-
- if ($basket->getValidation())
+ public function get_databox_status(Request $request, $databox_id)
{
- $users = array();
+ $result = new API_V1_result($request, $this);
- foreach ($basket->getValidation()->getParticipants() as $participant)
- {
- /* @var $participant \Entities\ValidationParticipant */
- $user = $participant->getUser();
-
- $users[$user->get_id()] = array(
- 'usr_id' => $user->get_id(),
- 'usr_name' => $user->get_display_name(),
- 'confirmed' => $participant->getIsConfirmed(),
- 'can_agree' => $participant->getCanAgree(),
- 'can_see_others' => $participant->getCanSeeOthers()
+ $result->set_datas(
+ array(
+ "status" =>
+ $this->list_databox_status(
+ $this->appbox->get_databox($databox_id)->get_statusbits()
+ )
+ )
);
- }
- $expires_on_atom = $basket->getValidation()->getExpires();
-
- if ($expires_on_atom instanceof DateTime)
- $expires_on_atom = $expires_on_atom->format(DATE_ATOM);
-
- $user = \User_Adapter::getInstance($this->appbox->get_session()->get_usr_id(), $this->appbox);
-
- $ret = array_merge(
- array(
- 'validation_users' => $users
- , 'validation_end_date' => $expires_on_atom
- , 'validation_infos' => $basket->getValidation()->getValidationString($user)
- , 'validation_confirmed' => $basket->getValidation()->getParticipant($user)->getIsConfirmed()
- , 'mine' => $basket->getValidation()->isInitiator($user)
- )
- , $ret
- );
+ return $result;
}
- return $ret;
- }
-
- /**
- * Retrieve detailled informations about one record
- *
- * @param record_adapter $record
- * @return array
- */
- protected function list_record(record_adapter $record)
- {
- return array(
- 'databox_id' => $record->get_sbas_id()
- , 'record_id' => $record->get_record_id()
- , 'mime_type' => $record->get_mime()
- , 'title' => $record->get_title()
- , 'original_name' => $record->get_original_name()
- , 'last_modification' => $record->get_modification_date()->format(DATE_ATOM)
- , 'created_on' => $record->get_creation_date()->format(DATE_ATOM)
- , 'collection_id' => phrasea::collFromBas($record->get_base_id())
- , 'sha256' => $record->get_sha256()
- , 'thumbnail' => $this->list_embedable_media(
- $record->get_thumbnail(), registry::get_instance()
- )
- , 'technical_informations' => $record->get_technical_infos()
- , 'phrasea_type' => $record->get_type()
- , 'uuid' => $record->get_uuid()
- );
- }
-
- /**
- * List all databoxes of the current appbox
- *
- * @return array
- */
- protected function list_databoxes()
- {
- $ret = array();
- foreach ($this->appbox->get_databoxes() as $databox)
+ /**
+ * Get an API_V1_result containing the metadatas of a databox
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_databox_metadatas(Request $request, $databox_id)
{
- $ret[$databox->get_sbas_id()] = $this->list_databox($databox);
+ $result = new API_V1_result($request, $this);
+
+ $result->set_datas(
+ array(
+ "metadatas" =>
+ $this->list_databox_metadatas_fields(
+ $this->appbox->get_databox($databox_id)
+ ->get_meta_structure()
+ )
+ )
+ );
+
+ return $result;
}
- return $ret;
- }
-
- /**
- * Retrieve CGU's for the specified databox
- *
- * @param databox $databox
- * @return array
- */
- protected function list_databox_terms(databox $databox)
- {
- $ret = array();
- foreach ($databox->get_cgus() as $locale => $array_terms)
+ /**
+ * Get an API_V1_result containing the terms of use of a databox
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_databox_terms(Request $request, $databox_id)
{
- $ret[$locale] = array('locale' => $locale, 'terms' => $array_terms['value']);
+ $result = new API_V1_result($request, $this);
+
+ $result->set_datas(
+ array(
+ "termsOfUse" =>
+ $this->list_databox_terms($this->appbox->get_databox($databox_id))
+ )
+ );
+
+ return $result;
}
- return $ret;
- }
-
- /**
- * Retrieve detailled informations about one databox
- * @param databox $databox
- * @return array
- */
- protected function list_databox(databox $databox)
- {
- $ret = array();
-
- $ret['databox_id'] = $databox->get_sbas_id();
- $ret['name'] = $databox->get_viewname();
- $ret['version'] = $databox->get_version();
-
- return $ret;
- }
-
- /**
- * List all available collections for a specified databox
- *
- * @param databox $databox
- * @return array
- */
- protected function list_databox_collections(databox $databox)
- {
- $ret = array();
-
- foreach ($databox->get_collections() as $collection)
+ public function caption_records(Request $request, $databox_id, $record_id)
{
- $ret[$collection->get_coll_id()] = $this->list_collection($collection);
+ $result = new API_V1_result($request, $this);
+
+ $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
+ $fields = $record->get_caption()->get_fields();
+ $ret = array();
+ foreach ($fields as $field) {
+ $ret[$field->get_meta_struct_id()] = array(
+ 'meta_structure_id' => $field->get_meta_struct_id()
+ , 'name' => $field->get_name()
+ , 'value' => $field->get_serialized_values(";")
+ );
+ }
+ $result->set_datas($ret);
+
+ return $result;
}
- return $ret;
- }
-
- /**
- * Retrieve detailled informations about one collection
- *
- * @param collection $collection
- * @return array
- */
- protected function list_collection(collection $collection)
- {
- $ret = array(
- 'base_id' => $collection->get_base_id()
- , 'coll_id' => $collection->get_coll_id()
- , 'name' => $collection->get_name()
- , 'record_amount' => $collection->get_record_amount()
- );
-
- return $ret;
- }
-
- /**
- * Retrieve informations for a list of status
- *
- * @param array $status
- * @return array
- */
- protected function list_databox_status(array $status)
- {
- $ret = array();
- foreach ($status as $n => $datas)
+ /**
+ * Get an API_V1_result containing the results of a records search
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function search_records(Request $request)
{
- $ret[$n] = array(
- 'bit' => $n
- , 'label_on' => $datas['labelon']
- , 'label_off' => $datas['labeloff']
- , 'img_on' => $datas['img_on']
- , 'img_off' => $datas['img_off']
- , 'searchable' => $datas['searchable']
- , 'printable' => $datas['printable']
- );
+ $session = $this->appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
+ $registry = $this->appbox->get_registry();
+ $result = new API_V1_result($request, $this);
+
+ $search_type = ($request->get('search_type')
+ && in_array($request->get('search_type'), array(0, 1))) ?
+ $request->get('search_type') : 0;
+
+ $record_type = ($request->get('record_type')
+ && in_array(
+ $request->get('record_type')
+ , array('audio', 'video', 'image', 'document', 'flash'))
+ ) ?
+ $request->get('record_type') : '';
+
+ $params = array(
+ 'fields' => is_array($request->get('fields')) ? $request->get('fields') : array()
+ , 'status' => is_array($request->get('status')) ? $request->get('status') : array()
+ , 'bases' => is_array($request->get('bases')) ? $request->get('bases') : array()
+ , 'search_type' => $search_type
+ , 'recordtype' => $record_type
+ , 'datemin' => $request->get('datemin') ? : ''
+ , 'datemax' => $request->get('datemax') ? : ''
+ , 'datefield' => $request->get('datefield') ? : ''
+ , 'sort' => $request->get('sort') ? : ''
+ , 'ord' => $request->get('ord') ? : ''
+ , 'stemme' => $request->get('stemme') ? : ''
+ , 'per_page' => $request->get('per_page') ? : 10
+ , 'query' => $request->get('query') ? : ''
+ , 'page' => (int) ($request->get('page') ? : 0)
+ );
+
+ if (is_array($request->get('bases')) === false) {
+ $params['bases'] = array();
+ foreach ($this->appbox->get_databoxes() as $databox) {
+ foreach ($databox->get_collections() as $collection)
+ $params['bases'][] = $collection->get_base_id();
+ }
+ }
+
+ $options = new searchEngine_options();
+
+ $params['bases'] = is_array($params['bases']) ? $params['bases'] : array_keys($user->ACL()->get_granted_base());
+
+ /* @var $user \User_Adapter */
+ if ($user->ACL()->has_right('modifyrecord')) {
+ $options->set_business_fields(array());
+
+ $BF = array();
+
+ foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) {
+ if (count($params['bases']) === 0 || in_array($collection->get_base_id(), $params['bases'])) {
+ $BF[] = $collection->get_base_id();
+ }
+ }
+ $options->set_business_fields($BF);
+ } else {
+ $options->set_business_fields(array());
+ }
+
+ $options->set_bases($params['bases'], $user->ACL());
+
+ if ( ! is_array($params['fields']))
+ $params['fields'] = array();
+ $options->set_fields($params['fields']);
+ if ( ! is_array($params['status']))
+ $params['status'] = array();
+ $options->set_status($params['status']);
+ $options->set_search_type($params['search_type']);
+ $options->set_record_type($params['recordtype']);
+ $options->set_min_date($params['datemin']);
+ $options->set_max_date($params['datemax']);
+ $options->set_date_fields(explode('|', $params['datefield']));
+ $options->set_sort($params['sort'], $params['ord']);
+ $options->set_use_stemming($params['stemme']);
+
+ $perPage = (int) $params['per_page'];
+ $search_engine = new searchEngine_adapter($registry);
+ $search_engine->set_options($options);
+
+
+ /**
+ * @todo ameliorer this shit
+ */
+ if ($params['page'] < 1) {
+ $search_engine->set_is_first_page(true);
+ $params['page'] = 1;
+ }
+
+ $search_engine->reset_cache();
+
+ $search_result = $search_engine->query_per_page($params['query'], $params["page"], $perPage);
+
+ $ret = array(
+ 'total_pages' => $search_result->get_total_pages()
+ , 'current_page' => $search_result->get_current_page()
+ , 'available_results' => $search_result->get_count_available_results()
+ , 'total_results' => $search_result->get_count_total_results()
+ , 'error' => $search_result->get_error()
+ , 'warning' => $search_result->get_warning()
+ , 'query_time' => $search_result->get_query_time()
+ , 'search_indexes' => $search_result->get_search_indexes()
+ , 'suggestions' => $search_result->get_suggestions()
+ , 'results' => array()
+ , 'query' => $search_engine->get_query()
+ );
+
+ foreach ($search_result->get_datas()->get_elements() as $record) {
+ $ret['results'][] = $this->list_record($record);
+ }
+
+ /**
+ * @todo donner des highlights
+ */
+ $result->set_datas($ret);
+
+ return $result;
}
- return $ret;
- }
-
- /**
- * List all metadatas field using a databox meta structure
- *
- * @param databox_descriptionStructure $meta_struct
- * @return array
- */
- protected function list_databox_metadatas_fields(databox_descriptionStructure $meta_struct)
- {
- $ret = array();
- foreach ($meta_struct as $meta)
+ /**
+ * Get an API_V1_result containing the baskets where the record is in
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_record_related(Request $request, $databox_id, $record_id)
{
- $ret[$meta->get_id()] = $this->list_databox_metadata_field_properties($meta);
+ $result = new API_V1_result($request, $this);
+
+ $containers = $this->appbox
+ ->get_databox($databox_id)
+ ->get_record($record_id)
+ ->get_container_baskets();
+
+ $ret = array();
+ foreach ($containers as $basket) {
+ $ret[$basket->getId()] = $this->list_basket($basket);
+ }
+
+ $result->set_datas(array("baskets" => $ret));
+
+ return $result;
}
- return $ret;
- }
+ /**
+ * Get an API_V1_result containing the record metadatas
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_record_metadatas(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
- /**
- * Retirve informations about one databox metadata field
- *
- * @param databox_field $databox_field
- * @return array
- */
- protected function list_databox_metadata_field_properties(databox_field $databox_field)
- {
- $ret = array(
- 'id' => $databox_field->get_id()
- , 'namespace' => $databox_field->get_metadata_namespace()
- , 'source' => $databox_field->get_metadata_source()
- , 'tagname' => $databox_field->get_metadata_tagname()
- , 'name' => $databox_field->get_name()
- , 'separator' => $databox_field->get_separator()
- , 'thesaurus_branch' => $databox_field->get_tbranch()
- , 'type' => $databox_field->get_type()
- , 'indexable' => $databox_field->is_indexable()
- , 'multivalue' => $databox_field->is_multi()
- , 'readonly' => $databox_field->is_readonly()
- , 'required' => $databox_field->is_required()
- );
+ $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
- return $ret;
- }
+ $result->set_datas(
+ array(
+ "metadatas" => $this->list_record_caption($record->get_caption())
+ )
+ );
+ return $result;
+ }
+
+ /**
+ * Get an API_V1_result containing the record status
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_record_status(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $record = $this->appbox
+ ->get_databox($databox_id)
+ ->get_record($record_id);
+
+ $result->set_datas(
+ array(
+ "status" =>
+ $this->list_record_status(
+ $this->appbox->get_databox($databox_id)
+ , $record->get_status()
+ )
+ )
+ );
+
+ return $result;
+ }
+
+ /**
+ * Get an API_V1_result containing the record embed files
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @param string $response_type
+ * @return API_V1_result
+ */
+ public function get_record_embed(Request $request, $databox_id, $record_id)
+ {
+
+ $result = new API_V1_result($request, $this);
+
+ $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
+
+ $ret = array();
+ foreach ($record->get_embedable_medias() as $name => $media) {
+ $ret[$name] = $this->list_embedable_media($media, $this->appbox->get_registry());
+ }
+
+ $result->set_datas(array("embed" => $ret));
+
+ return $result;
+ }
+
+ public function set_record_metadatas(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
+ $record = $this->appbox->get_databox($databox_id)->get_record($record_id);
+
+ try {
+ $metadatas = $request->get('metadatas');
+
+ if ( ! is_array($metadatas)) {
+ throw new Exception('Metadatas should be an array');
+ }
+
+ foreach ($metadatas as $metadata) {
+ if ( ! is_array($metadata)) {
+ throw new Exception('Each Metadata value should be an array');
+ }
+ }
+
+ $record->set_metadatas($metadatas);
+ $result->set_datas(array("metadatas" => $this->list_record_caption($record->get_caption())));
+ } catch (Exception $e) {
+ $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ }
+
+ return $result;
+ }
+
+ public function set_record_status(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
+ $databox = $this->appbox->get_databox($databox_id);
+ $record = $databox->get_record($record_id);
+ $status_bits = $databox->get_statusbits();
+
+ try {
+ $status = $request->get('status');
+
+ $datas = strrev($record->get_status());
+
+ if ( ! is_array($status))
+ throw new API_V1_exception_badrequest();
+ foreach ($status as $n => $value) {
+ if ($n > 63 || $n < 4)
+ throw new API_V1_exception_badrequest();
+ if ( ! in_array($value, array('0', '1')))
+ throw new API_V1_exception_badrequest();
+ if ( ! isset($status_bits[$n]))
+ throw new API_V1_exception_badrequest ();
+
+ $datas = substr($datas, 0, ($n - 1)) . $value . substr($datas, ($n + 1));
+ }
+ $datas = strrev($datas);
+
+ $record->set_binary_status($datas);
+ $result->set_datas(array(
+ "status" =>
+ $this->list_record_status($databox, $record->get_status())
+ )
+ );
+ } catch (Exception $e) {
+ $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Move a record to another collection
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @return API_V1_result
+ */
+ public function set_record_collection(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
+ $databox = $this->appbox->get_databox($databox_id);
+ $record = $databox->get_record($record_id);
+
+ try {
+ $collection = collection::get_from_base_id($request->get('base_id'));
+
+ $record->move_to_collection($collection, $this->appbox);
+ $result->set_datas(array("record" => $this->list_record($record)));
+ } catch (Exception $e) {
+ $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Return detailed informations about one record
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ * @return API_V1_result
+ */
+ public function get_record(Request $request, $databox_id, $record_id)
+ {
+ $result = new API_V1_result($request, $this);
+ $databox = $this->appbox->get_databox($databox_id);
+ try {
+ $record = $databox->get_record($record_id);
+ $result->set_datas(array('record' => $this->list_record($record)));
+ } catch (Exception $e) {
+ $result->set_error_message(API_V1_result::ERROR_BAD_REQUEST);
+ }
+
+ return $result;
+ }
+
+ /**
+ * @todo
+ *
+ * @param Request $request
+ * @param int $databox_id
+ * @param int $record_id
+ */
+ public function add_record_tobasket(Request $request, $databox_id, $record_id)
+ {
+
+ }
+
+ /**
+ * Return the baskets list of the authenticated user
+ *
+ * @param Request $request
+ * @return API_V1_result
+ */
+ public function search_baskets(Request $request)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $usr_id = $session = $this->appbox->get_session()->get_usr_id();
+
+ $result->set_datas(array('baskets' => $this->list_baskets($usr_id)));
+
+ return $result;
+ }
+
+ /**
+ * Return a baskets list
+ *
+ * @param int $usr_id
+ * @return array
+ */
+ protected function list_baskets($usr_id)
+ {
+ $em = $this->core->getEntityManager();
+ $repo = $em->getRepository('\Entities\Basket');
+ /* @var $repo \Repositories\BasketRepository */
+
+ $baskets = $repo->findActiveByUser($this->core->getAuthenticatedUser());
+
+ $ret = array();
+ foreach ($baskets as $basket) {
+ $ret[$basket->getId()] = $this->list_basket($basket);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Create a new basket
+ *
+ * @param Request $request
+ * @return API_V1_result
+ */
+ public function create_basket(Request $request)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $name = $request->get('name');
+
+ if (trim(strip_tags($name)) === '')
+ throw new API_V1_exception_badrequest ();
+
+ $user = $this->core->getAuthenticatedUser();
+
+ $Basket = new \Entities\Basket();
+ $Basket->setOwner($user);
+ $Basket->setName($name);
+
+ $em = $this->core->getEntityManager();
+ $em->persist($Basket);
+ $em->flush();
+
+ $ret = array();
+ $ret[$Basket->getId()] = $this->list_basket($Basket);
+ $result->set_datas(array("basket" => $ret));
+
+ return $result;
+ }
+
+ /**
+ * Delete a basket
+ *
+ * @param Request $request
+ * @param int $basket_id
+ * @return array
+ */
+ public function delete_basket(Request $request, $basket_id)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+
+ /* @var $repository \Repositories\BasketRepository */
+
+ $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
+ $em->remove($Basket);
+ $em->flush();
+
+ return $this->search_baskets($request);
+ }
+
+ /**
+ * Retrieve a basket
+ *
+ * @param Request $request
+ * @param int $basket_id
+ * @return API_V1_result
+ */
+ public function get_basket(Request $request, $basket_id)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ /* @var $repository \Repositories\BasketRepository */
+
+ $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), false);
+
+ $result->set_datas(
+ array("basket_elements" =>
+ array(
+ $Basket->getId() => $this->list_basket_content($Basket)
+ )
+ )
+ );
+
+ return $result;
+ }
+
+ /**
+ * Retrieve elements of one basket
+ *
+ * @param \Entities\Basket $Basket
+ * @return type
+ */
+ protected function list_basket_content(\Entities\Basket $Basket)
+ {
+ $ret = $this->list_basket($Basket);
+
+ $ret['basket_elements'] = array();
+
+ foreach ($Basket->getElements() as $basket_element) {
+ $ret['basket_elements'][$basket_element->getId()] = $this->list_basket_element($basket_element);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve detailled informations about a basket element
+ *
+ * @param \Entities\BasketElement $basket_element
+ * @return type
+ */
+ protected function list_basket_element(\Entities\BasketElement $basket_element)
+ {
+ $ret = array(
+ 'basket_element_id' => $basket_element->getId()
+ , 'order' => $basket_element->getOrd()
+ , 'record' => $this->list_record($basket_element->getRecord())
+ , 'validation_item' => ! ! $basket_element->getValidationDatas()
+ );
+
+ if ($basket_element->getValidationDatas()) {
+ $choices = array();
+ $agreement = $note = null;
+
+ foreach ($basket_element->getValidationDatas() as $validation_datas) {
+ $user = $validation_datas->getParticipant()->getUser();
+ /* @var $validation_datas Entities\ValidationData */
+ $choices[$user->get_id()] = array(
+ 'usr_id' => $user->get_id(),
+ 'usr_name' => $user->get_display_name(),
+ 'is_mine' => $user->get_id() == $this->core->getAuthenticatedUser()->get_id(),
+ 'agreement' => $validation_datas->getAgreement(),
+ 'updated_on' => $validation_datas->getUpdated()->format(DATE_ATOM),
+ 'note' => $validation_datas->getNote()
+ );
+
+ if ($user->get_id() == $this->core->getAuthenticatedUser()->get_id()) {
+ $agreement = $validation_datas->getAgreement();
+ $note = $validation_datas->getNote();
+ }
+ }
+
+ $ret['choices'] = $choices();
+ $ret['agreement'] = $agreement();
+ $ret['note'] = $note();
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Change the name of one basket
+ *
+ * @param Request $request
+ * @param int $basket_id
+ * @return API_V1_result
+ */
+ public function set_basket_title(Request $request, $basket_id)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $name = $request->get('name');
+
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+
+ /* @var $repository \Repositories\BasketRepository */
+
+ $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
+ $Basket->setName($name);
+
+ $em->merge($Basket);
+ $em->flush();
+
+ $result->set_datas(
+ array(
+ "basket" =>
+ array($Basket->getId() => $this->list_basket_content($Basket)
+ )
+ )
+ );
+
+ return $result;
+ }
+
+ /**
+ * Change the description of one basket
+ *
+ * @param Request $request
+ * @param type $basket_id
+ * @return API_V1_result
+ */
+ public function set_basket_description(Request $request, $basket_id)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $desc = $request->get('description');
+
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+
+ /* @var $repository \Repositories\BasketRepository */
+
+ $Basket = $repository->findUserBasket($basket_id, $this->core->getAuthenticatedUser(), true);
+ $Basket->setDescription($desc);
+
+ $em->merge($Basket);
+ $em->flush();
+
+ $result->set_datas(
+ array(
+ "basket" =>
+ array($Basket->getId() => $this->list_basket_content($Basket)
+ )
+ )
+ );
+
+ return $result;
+ }
+
+ /**
+ * List all avalaible feeds
+ *
+ * @param Request $request
+ * @param User_Adapter $user
+ * @return API_V1_result
+ */
+ public function search_publications(Request $request, User_Adapter &$user)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $coll = Feed_Collection::load_all($this->appbox, $user);
+
+ $datas = array();
+ foreach ($coll->get_feeds() as $feed) {
+ $datas[$feed->get_id()] = $this->list_publication($feed, $user);
+ }
+
+ $result->set_datas(array("feeds" => $datas));
+
+ return $result;
+ }
+
+ /**
+ * @todo
+ *
+ * @param Request $request
+ * @param int $publication_id
+ */
+ public function remove_publications(Request $request, $publication_id)
+ {
+
+ }
+
+ /**
+ * Retrieve one feed
+ *
+ * @param Request $request
+ * @param int $publication_id
+ * @param User_Adapter $user
+ * @return API_V1_result
+ */
+ public function get_publication(Request $request, $publication_id, User_Adapter &$user)
+ {
+ $result = new API_V1_result($request, $this);
+
+ $feed = Feed_Adapter::load_with_user($this->appbox, $user, $publication_id);
+
+ $offset_start = (int) ($request->get('offset_start') ? : 0);
+ $per_page = (int) ($request->get('per_page') ? : 5);
+
+ $per_page = (($per_page >= 1) && ($per_page <= 20)) ? $per_page : 5;
+
+ $datas = array(
+ 'feed' => $this->list_publication($feed, $user)
+ , 'offset_start' => $offset_start
+ , 'per_page' => $per_page
+ , 'entries' => $this->list_publications_entries($feed, $offset_start, $per_page)
+ );
+
+ $result->set_datas($datas);
+
+ return $result;
+ }
+
+ /**
+ * Retrieve detailled informations about one feed
+ *
+ * @param Feed_Adapter $feed
+ * @param type $user
+ * @return array
+ */
+ protected function list_publication(Feed_Adapter $feed, $user)
+ {
+ return array(
+ 'id' => $feed->get_id()
+ , 'title' => $feed->get_title()
+ , 'subtitle' => $feed->get_subtitle()
+ , 'total_entries' => $feed->get_count_total_entries()
+ , 'icon' => $feed->get_icon_url()
+ , 'public' => $feed->is_public()
+ , 'is_mine' => $feed->is_owner($user)
+ , 'created_on' => $feed->get_created_on()->format(DATE_ATOM)
+ , 'updated_on' => $feed->get_updated_on()->format(DATE_ATOM)
+ );
+ }
+
+ /**
+ * Retrieve all entries of one feed
+ *
+ * @param Feed_Adapter $feed
+ * @param int $offset_start
+ * @param int $how_many
+ * @return array
+ */
+ protected function list_publications_entries(Feed_Adapter $feed, $offset_start = 0, $how_many = 5)
+ {
+
+ $entries = $feed->get_entries($offset_start, $how_many)->get_entries();
+
+ $out = array();
+ foreach ($entries as $entry) {
+ $out[$entry->get_id()] = $this->list_publication_entry($entry);
+ }
+
+ return array(
+ 'offset_start' => $offset_start
+ , 'entries' => $out
+ );
+ }
+
+ /**
+ * Retrieve detailled information about one feed entry
+ *
+ * @param Feed_Entry_Adapter $entry
+ * @return array
+ */
+ protected function list_publication_entry(Feed_Entry_Adapter $entry)
+ {
+ $items = array();
+ foreach ($entry->get_content() as $item) {
+ $items[] = $this->list_publication_entry_item($item);
+ }
+
+ return array(
+ 'author_email' => $entry->get_author_email()
+ , 'author_name' => $entry->get_author_name()
+ , 'created_on' => $entry->get_created_on()->format(DATE_ATOM)
+ , 'updated_on' => $entry->get_updated_on()->format(DATE_ATOM)
+ , 'title' => $entry->get_title()
+ , 'subtitle' => $entry->get_subtitle()
+ , 'items' => $items
+ );
+ }
+
+ /**
+ * Retrieve detailled informations about one feed entry item
+ *
+ * @param Feed_Entry_Item $item
+ * @return array
+ */
+ protected function list_publication_entry_item(Feed_Entry_Item $item)
+ {
+ $datas = array(
+ 'item_id' => $item->get_id()
+ , 'record' => $this->list_record($item->get_record())
+ );
+
+ return $datas;
+ }
+
+ /**
+ * @todo
+ * @param Request $request
+ */
+ public function search_users(Request $request)
+ {
+
+ }
+
+ /**
+ * @todo
+ * @param Request $request
+ * @param int $usr_id
+ */
+ public function get_user_acces(Request $request, $usr_id)
+ {
+
+ }
+
+ /**
+ * @todo
+ * @param Request $request
+ */
+ public function add_user(Request $request)
+ {
+
+ }
+
+ /**
+ * @retrieve detailled informations about one suddef
+ *
+ * @param media_subdef $media
+ * @return array
+ */
+ protected function list_embedable_media(media_subdef &$media, registryInterface &$registry)
+ {
+ if ($media->get_permalink() instanceof media_Permalink_Adapter)
+ $permalink = $this->list_permalink($media->get_permalink(), $registry);
+ else
+ $permalink = null;
+
+ return array(
+ 'permalink' => $permalink
+ , 'height' => $media->get_height()
+ , 'width' => $media->get_width()
+ , 'filesize' => $media->get_size()
+ , 'player_type' => $media->get_type()
+ , 'mime_type' => $media->get_mime()
+ );
+ }
+
+ /**
+ * Retrieve detailled information about one permalink
+ *
+ * @param media_Permalink_Adapter $permalink
+ * @param registryInterface $registry
+ * @return type
+ */
+ protected function list_permalink(media_Permalink_Adapter &$permalink, registryInterface &$registry)
+ {
+ return array(
+ 'created_on' => $permalink->get_created_on()->format(DATE_ATOM)
+ , 'id' => $permalink->get_id()
+ , 'is_activated' => $permalink->get_is_activated()
+ , 'label' => $permalink->get_label()
+ , 'last_modified' => $permalink->get_last_modified()->format(DATE_ATOM)
+ , 'page_url' => $permalink->get_page($registry)
+ , 'url' => $permalink->get_url($registry)
+ );
+ }
+
+ /**
+ * Retrieve detailled information about one status
+ *
+ * @param databox $databox
+ * @param string $status
+ * @return array
+ */
+ protected function list_record_status(databox $databox, $status)
+ {
+ $status = strrev($status);
+ $ret = array();
+ foreach ($databox->get_statusbits() as $bit => $status_datas) {
+ $ret[$bit] = array('bit' => $bit, 'state' => ! ! substr($status, ($bit - 1), 1));
+ }
+
+ return $ret;
+ }
+
+ /**
+ * List all field about a specified caption
+ *
+ * @param caption_record $caption
+ * @return array
+ */
+ protected function list_record_caption(caption_record $caption)
+ {
+ $ret = array();
+ foreach ($caption->get_fields() as $field) {
+ foreach ($field->get_values() as $value) {
+ $ret[$value->getId()] = $this->list_record_caption_field($value, $field);
+ }
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve information about a caption field
+ *
+ * @param caption_field $field
+ * @return array
+ */
+ protected function list_record_caption_field(caption_Field_Value $value, caption_field $field)
+ {
+ /**
+ * @todo ajouter une option pour avoir les values serialisées
+ * dans un cas multi
+ */
+ return array(
+ 'meta_id' => $value->getId()
+ , 'meta_structure_id' => $field->get_meta_struct_id()
+ , 'name' => $field->get_name()
+ , 'value' => $value->getValue()
+ );
+ }
+
+ /**
+ * Retirve information about one basket
+ *
+ * @param \Entities\Basket $basket
+ * @return array
+ */
+ protected function list_basket(\Entities\Basket $basket)
+ {
+ $ret = array(
+ 'created_on' => $basket->getCreated()->format(DATE_ATOM)
+ , 'description' => (string) $basket->getDescription()
+ , 'name' => $basket->getName()
+ , 'pusher_usr_id' => $basket->getPusherId()
+ , 'ssel_id' => $basket->getId()
+ , 'updated_on' => $basket->getUpdated()->format(DATE_ATOM)
+ , 'unread' => ! $basket->getIsRead()
+ );
+
+ if ($basket->getValidation()) {
+ $users = array();
+
+ foreach ($basket->getValidation()->getParticipants() as $participant) {
+ /* @var $participant \Entities\ValidationParticipant */
+ $user = $participant->getUser();
+
+ $users[$user->get_id()] = array(
+ 'usr_id' => $user->get_id(),
+ 'usr_name' => $user->get_display_name(),
+ 'confirmed' => $participant->getIsConfirmed(),
+ 'can_agree' => $participant->getCanAgree(),
+ 'can_see_others' => $participant->getCanSeeOthers()
+ );
+ }
+
+ $expires_on_atom = $basket->getValidation()->getExpires();
+
+ if ($expires_on_atom instanceof DateTime)
+ $expires_on_atom = $expires_on_atom->format(DATE_ATOM);
+
+ $user = \User_Adapter::getInstance($this->appbox->get_session()->get_usr_id(), $this->appbox);
+
+ $ret = array_merge(
+ array(
+ 'validation_users' => $users
+ , 'validation_end_date' => $expires_on_atom
+ , 'validation_infos' => $basket->getValidation()->getValidationString($user)
+ , 'validation_confirmed' => $basket->getValidation()->getParticipant($user)->getIsConfirmed()
+ , 'mine' => $basket->getValidation()->isInitiator($user)
+ )
+ , $ret
+ );
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve detailled informations about one record
+ *
+ * @param record_adapter $record
+ * @return array
+ */
+ protected function list_record(record_adapter $record)
+ {
+ return array(
+ 'databox_id' => $record->get_sbas_id()
+ , 'record_id' => $record->get_record_id()
+ , 'mime_type' => $record->get_mime()
+ , 'title' => $record->get_title()
+ , 'original_name' => $record->get_original_name()
+ , 'last_modification' => $record->get_modification_date()->format(DATE_ATOM)
+ , 'created_on' => $record->get_creation_date()->format(DATE_ATOM)
+ , 'collection_id' => phrasea::collFromBas($record->get_base_id())
+ , 'sha256' => $record->get_sha256()
+ , 'thumbnail' => $this->list_embedable_media(
+ $record->get_thumbnail(), registry::get_instance()
+ )
+ , 'technical_informations' => $record->get_technical_infos()
+ , 'phrasea_type' => $record->get_type()
+ , 'uuid' => $record->get_uuid()
+ );
+ }
+
+ /**
+ * List all databoxes of the current appbox
+ *
+ * @return array
+ */
+ protected function list_databoxes()
+ {
+ $ret = array();
+ foreach ($this->appbox->get_databoxes() as $databox) {
+ $ret[$databox->get_sbas_id()] = $this->list_databox($databox);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve CGU's for the specified databox
+ *
+ * @param databox $databox
+ * @return array
+ */
+ protected function list_databox_terms(databox $databox)
+ {
+ $ret = array();
+ foreach ($databox->get_cgus() as $locale => $array_terms) {
+ $ret[$locale] = array('locale' => $locale, 'terms' => $array_terms['value']);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve detailled informations about one databox
+ * @param databox $databox
+ * @return array
+ */
+ protected function list_databox(databox $databox)
+ {
+ $ret = array();
+
+ $ret['databox_id'] = $databox->get_sbas_id();
+ $ret['name'] = $databox->get_viewname();
+ $ret['version'] = $databox->get_version();
+
+ return $ret;
+ }
+
+ /**
+ * List all available collections for a specified databox
+ *
+ * @param databox $databox
+ * @return array
+ */
+ protected function list_databox_collections(databox $databox)
+ {
+ $ret = array();
+
+ foreach ($databox->get_collections() as $collection) {
+ $ret[$collection->get_coll_id()] = $this->list_collection($collection);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve detailled informations about one collection
+ *
+ * @param collection $collection
+ * @return array
+ */
+ protected function list_collection(collection $collection)
+ {
+ $ret = array(
+ 'base_id' => $collection->get_base_id()
+ , 'coll_id' => $collection->get_coll_id()
+ , 'name' => $collection->get_name()
+ , 'record_amount' => $collection->get_record_amount()
+ );
+
+ return $ret;
+ }
+
+ /**
+ * Retrieve informations for a list of status
+ *
+ * @param array $status
+ * @return array
+ */
+ protected function list_databox_status(array $status)
+ {
+ $ret = array();
+ foreach ($status as $n => $datas) {
+ $ret[$n] = array(
+ 'bit' => $n
+ , 'label_on' => $datas['labelon']
+ , 'label_off' => $datas['labeloff']
+ , 'img_on' => $datas['img_on']
+ , 'img_off' => $datas['img_off']
+ , 'searchable' => $datas['searchable']
+ , 'printable' => $datas['printable']
+ );
+ }
+
+ return $ret;
+ }
+
+ /**
+ * List all metadatas field using a databox meta structure
+ *
+ * @param databox_descriptionStructure $meta_struct
+ * @return array
+ */
+ protected function list_databox_metadatas_fields(databox_descriptionStructure $meta_struct)
+ {
+ $ret = array();
+ foreach ($meta_struct as $meta) {
+ $ret[$meta->get_id()] = $this->list_databox_metadata_field_properties($meta);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Retirve informations about one databox metadata field
+ *
+ * @param databox_field $databox_field
+ * @return array
+ */
+ protected function list_databox_metadata_field_properties(databox_field $databox_field)
+ {
+ $ret = array(
+ 'id' => $databox_field->get_id()
+ , 'namespace' => $databox_field->get_metadata_namespace()
+ , 'source' => $databox_field->get_metadata_source()
+ , 'tagname' => $databox_field->get_metadata_tagname()
+ , 'name' => $databox_field->get_name()
+ , 'separator' => $databox_field->get_separator()
+ , 'thesaurus_branch' => $databox_field->get_tbranch()
+ , 'type' => $databox_field->get_type()
+ , 'indexable' => $databox_field->is_indexable()
+ , 'multivalue' => $databox_field->is_multi()
+ , 'readonly' => $databox_field->is_readonly()
+ , 'required' => $databox_field->is_required()
+ );
+
+ return $ret;
+ }
}
diff --git a/lib/classes/API/V1/exception/abstract.class.php b/lib/classes/API/V1/exception/abstract.class.php
index 74b8014872..247c507bf0 100644
--- a/lib/classes/API/V1/exception/abstract.class.php
+++ b/lib/classes/API/V1/exception/abstract.class.php
@@ -17,17 +17,15 @@
*/
abstract class API_V1_exception_abstract extends Exception
{
+ protected static $details;
- protected static $details;
-
- public function __construct()
- {
- return $this;
- }
-
- public static function get_details()
- {
- return static::$details;
- }
+ public function __construct()
+ {
+ return $this;
+ }
+ public static function get_details()
+ {
+ return static::$details;
+ }
}
diff --git a/lib/classes/API/V1/exception/badrequest.class.php b/lib/classes/API/V1/exception/badrequest.class.php
index 23b2583e0b..9e5192f822 100644
--- a/lib/classes/API/V1/exception/badrequest.class.php
+++ b/lib/classes/API/V1/exception/badrequest.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_badrequest extends API_V1_exception_abstract
{
-
- protected static $details = 'Parameter is invalid or missing';
+ protected static $details = 'Parameter is invalid or missing';
}
diff --git a/lib/classes/API/V1/exception/forbidden.class.php b/lib/classes/API/V1/exception/forbidden.class.php
index 218aa8295b..9ac40361e0 100644
--- a/lib/classes/API/V1/exception/forbidden.class.php
+++ b/lib/classes/API/V1/exception/forbidden.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_forbidden extends API_V1_exception_abstract
{
-
- protected static $details = 'Access to the requested ressource is forbidden';
+ protected static $details = 'Access to the requested ressource is forbidden';
}
diff --git a/lib/classes/API/V1/exception/internalservererror.class.php b/lib/classes/API/V1/exception/internalservererror.class.php
index 42e5d76d9b..8f30e7fb3c 100644
--- a/lib/classes/API/V1/exception/internalservererror.class.php
+++ b/lib/classes/API/V1/exception/internalservererror.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_internalservererror extends API_V1_exception_abstract
{
-
- protected static $details = 'Internal Server Error';
+ protected static $details = 'Internal Server Error';
}
diff --git a/lib/classes/API/V1/exception/methodnotallowed.class.php b/lib/classes/API/V1/exception/methodnotallowed.class.php
index 180a1836c9..cfa9f6cc2b 100644
--- a/lib/classes/API/V1/exception/methodnotallowed.class.php
+++ b/lib/classes/API/V1/exception/methodnotallowed.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_methodnotallowed extends API_V1_exception_abstract
{
-
- protected static $details = 'Attempting to use POST with a GET-only endpoint, or vice-versa';
+ protected static $details = 'Attempting to use POST with a GET-only endpoint, or vice-versa';
}
diff --git a/lib/classes/API/V1/exception/notfound.class.php b/lib/classes/API/V1/exception/notfound.class.php
index c930a885a8..7091b5e2b0 100644
--- a/lib/classes/API/V1/exception/notfound.class.php
+++ b/lib/classes/API/V1/exception/notfound.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_notfound extends API_V1_exception_abstract
{
-
- protected static $details = 'Requested ressource is not found';
+ protected static $details = 'Requested ressource is not found';
}
diff --git a/lib/classes/API/V1/exception/unauthorized.class.php b/lib/classes/API/V1/exception/unauthorized.class.php
index d14112ddc2..9a1083e193 100644
--- a/lib/classes/API/V1/exception/unauthorized.class.php
+++ b/lib/classes/API/V1/exception/unauthorized.class.php
@@ -17,7 +17,6 @@
*/
class API_V1_exception_unauthorized extends API_V1_exception_abstract
{
-
- protected static $details = 'The OAuth token was provided but was invalid.';
+ protected static $details = 'The OAuth token was provided but was invalid.';
}
diff --git a/lib/classes/API/V1/result.class.php b/lib/classes/API/V1/result.class.php
index ee478fe25e..0e8717b4ec 100644
--- a/lib/classes/API/V1/result.class.php
+++ b/lib/classes/API/V1/result.class.php
@@ -21,356 +21,341 @@ use \Symfony\Component\HttpFoundation\Request;
class API_V1_result
{
+ /**
+ *
+ * @var string
+ */
+ protected $api_version;
- /**
- *
- * @var string
- */
- protected $api_version;
+ /**
+ *
+ * @var string
+ */
+ protected $response_time;
- /**
- *
- * @var string
- */
- protected $response_time;
+ /**
+ *
+ * @var int
+ */
+ protected $http_code = 200;
- /**
- *
- * @var int
- */
- protected $http_code = 200;
+ /**
+ *
+ * @var string
+ */
+ protected $error_message;
- /**
- *
- * @var string
- */
- protected $error_message;
+ /**
+ *
+ * @var string
+ */
+ protected $error_details;
- /**
- *
- * @var string
- */
- protected $error_details;
+ /**
+ *
+ * @var string
+ */
+ protected $request;
- /**
- *
- * @var string
- */
- protected $request;
+ /**
+ *
+ * @var mixed
+ */
+ protected $response;
- /**
- *
- * @var mixed
- */
- protected $response;
+ /**
+ *
+ * @var string
+ */
+ protected $response_type;
- /**
- *
- * @var string
- */
- protected $response_type;
+ /**
+ * Constant for responsetype json
+ */
+ const FORMAT_JSON = 'json';
+ /**
+ * Constant for responsetype yaml
+ */
+ const FORMAT_YAML = 'yaml';
+ /**
+ * Constant for responsetype jsonp
+ */
+ const FORMAT_JSONP = 'jsonp';
+ const ERROR_BAD_REQUEST = 'Bad Request';
+ const ERROR_UNAUTHORIZED = 'Unauthorized';
+ const ERROR_FORBIDDEN = 'Forbidden';
+ const ERROR_NOTFOUND = 'Not Found';
+ const ERROR_METHODNOTALLOWED = 'Method Not Allowed';
+ const ERROR_INTERNALSERVERERROR = 'Internal Server Error';
- /**
- * Constant for responsetype json
- */
-
- const FORMAT_JSON = 'json';
- /**
- * Constant for responsetype yaml
- */
- const FORMAT_YAML = 'yaml';
- /**
- * Constant for responsetype jsonp
- */
- const FORMAT_JSONP = 'jsonp';
- const ERROR_BAD_REQUEST = 'Bad Request';
- const ERROR_UNAUTHORIZED = 'Unauthorized';
- const ERROR_FORBIDDEN = 'Forbidden';
- const ERROR_NOTFOUND = 'Not Found';
- const ERROR_METHODNOTALLOWED = 'Method Not Allowed';
- const ERROR_INTERNALSERVERERROR = 'Internal Server Error';
-
- /**
- * API v1 Result constructor
- *
- * @param Request $request
- * @param API_V1_adapter $api
- * @param string $response_type One of the API_V1_result 'FORMAT_*' constants
- * @return API_V1_result
- */
- public function __construct(Request $request, API_V1_adapter $api)
- {
- $date = new DateTime();
-
- $this->request = $request;
- $this->api_version = $api->get_version();
- $this->response_time = $date->format(DATE_ATOM);
- $this->response = new stdClass();
-
- $this->parse_response_type();
-
- return $this;
- }
-
- protected function parse_response_type()
- {
- if (trim($this->request->get('callback')) !== '')
-
- return $this->response_type = self::FORMAT_JSONP;
-
- $accept = $this->request->getAcceptableContentTypes();
- $response_types = array();
-
- foreach ($accept as $key => $app_type)
+ /**
+ * API v1 Result constructor
+ *
+ * @param Request $request
+ * @param API_V1_adapter $api
+ * @param string $response_type One of the API_V1_result 'FORMAT_*' constants
+ * @return API_V1_result
+ */
+ public function __construct(Request $request, API_V1_adapter $api)
{
- $response_types[strtolower($app_type)] = true;
+ $date = new DateTime();
+
+ $this->request = $request;
+ $this->api_version = $api->get_version();
+ $this->response_time = $date->format(DATE_ATOM);
+ $this->response = new stdClass();
+
+ $this->parse_response_type();
+
+ return $this;
}
- if (array_key_exists('application/json', $response_types))
+ protected function parse_response_type()
{
- return $this->response_type = self::FORMAT_JSON;
- }
- if (array_key_exists('application/yaml', $response_types))
- {
- return $this->response_type = self::FORMAT_YAML;
- }
- if (array_key_exists('text/yaml', $response_types))
- {
- return $this->response_type = self::FORMAT_YAML;
+ if (trim($this->request->get('callback')) !== '')
+ return $this->response_type = self::FORMAT_JSONP;
+
+ $accept = $this->request->getAcceptableContentTypes();
+ $response_types = array();
+
+ foreach ($accept as $key => $app_type) {
+ $response_types[strtolower($app_type)] = true;
+ }
+
+ if (array_key_exists('application/json', $response_types)) {
+ return $this->response_type = self::FORMAT_JSON;
+ }
+ if (array_key_exists('application/yaml', $response_types)) {
+ return $this->response_type = self::FORMAT_YAML;
+ }
+ if (array_key_exists('text/yaml', $response_types)) {
+ return $this->response_type = self::FORMAT_YAML;
+ }
+
+ return $this->response_type = self::FORMAT_JSON;
}
- return $this->response_type = self::FORMAT_JSON;
- }
-
- /**
- * Set datas to the response
- * If no datas provided (aka empty array), a stdClass if set,
- * so the serialized datas will be objects
- *
- * @param array $datas
- * @return API_V1_result
- */
- public function set_datas(array $datas)
- {
- if (count($datas) === 0)
- $datas = new stdClass ();
- $this->response = $datas;
-
- return $this;
- }
-
- /**
- * Format the data and return serialized string
- *
- * @return string
- */
- public function format()
- {
- $request_uri = sprintf('%s %s'
- , $this->request->getMethod()
- , $this->request->getBasePath()
- . $this->request->getPathInfo()
- );
-
- $ret = array(
- 'meta' => array(
- 'api_version' => $this->api_version
- , 'request' => $request_uri
- , 'response_time' => $this->response_time
- , 'http_code' => $this->http_code
- , 'error_message' => $this->error_message
- , 'error_details' => $this->error_details
- , 'charset' => 'UTF-8'
- )
- , 'response' => $this->response
- );
-
- $return_value = false;
-
- switch ($this->response_type)
+ /**
+ * Set datas to the response
+ * If no datas provided (aka empty array), a stdClass if set,
+ * so the serialized datas will be objects
+ *
+ * @param array $datas
+ * @return API_V1_result
+ */
+ public function set_datas(array $datas)
{
- case self::FORMAT_JSON:
- default:
- $return_value = p4string::jsonencode($ret);
- break;
- case self::FORMAT_YAML:
- if ($ret['response'] instanceof stdClass)
- $ret['response'] = array();
+ if (count($datas) === 0)
+ $datas = new stdClass ();
+ $this->response = $datas;
- $dumper = new Symfony\Component\Yaml\Dumper();
- $return_value = $dumper->dump($ret, 8);
- break;
- case self::FORMAT_JSONP:
- $callback = trim($this->request->get('callback'));
- $return_value = $callback . '(' . p4string::jsonencode($ret) . ')';
- break;
+ return $this;
}
- return $return_value;
- }
-
- /**
- * Return serailized datas content type
- *
- * @return string
- */
- public function get_content_type()
- {
- switch ($this->response_type)
+ /**
+ * Format the data and return serialized string
+ *
+ * @return string
+ */
+ public function format()
{
+ $request_uri = sprintf('%s %s'
+ , $this->request->getMethod()
+ , $this->request->getBasePath()
+ . $this->request->getPathInfo()
+ );
- case self::FORMAT_JSON:
- default:
- $return_value = 'application/json';
- break;
- case self::FORMAT_YAML:
- $return_value = 'application/yaml';
- break;
- case self::FORMAT_JSONP:
- $return_value = 'text/javascript';
- break;
+ $ret = array(
+ 'meta' => array(
+ 'api_version' => $this->api_version
+ , 'request' => $request_uri
+ , 'response_time' => $this->response_time
+ , 'http_code' => $this->http_code
+ , 'error_message' => $this->error_message
+ , 'error_details' => $this->error_details
+ , 'charset' => 'UTF-8'
+ )
+ , 'response' => $this->response
+ );
+
+ $return_value = false;
+
+ switch ($this->response_type) {
+ case self::FORMAT_JSON:
+ default:
+ $return_value = p4string::jsonencode($ret);
+ break;
+ case self::FORMAT_YAML:
+ if ($ret['response'] instanceof stdClass)
+ $ret['response'] = array();
+
+ $dumper = new Symfony\Component\Yaml\Dumper();
+ $return_value = $dumper->dump($ret, 8);
+ break;
+ case self::FORMAT_JSONP:
+ $callback = trim($this->request->get('callback'));
+ $return_value = $callback . '(' . p4string::jsonencode($ret) . ')';
+ break;
+ }
+
+ return $return_value;
}
- return $return_value;
- }
-
- /**
- * Set the API_V1_result http_code, error_message and error_details
- * with the appropriate datas
- *
- * @param string $const
- * @return API_V1_result
- */
- public function set_error_message($const)
- {
- switch ($const)
+ /**
+ * Return serailized datas content type
+ *
+ * @return string
+ */
+ public function get_content_type()
{
- case self::ERROR_BAD_REQUEST:
- $this->http_code = 400;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_badrequest::get_details();
- break;
- case self::ERROR_UNAUTHORIZED:
- $this->http_code = 401;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_unauthorized::get_details();
- break;
- case self::ERROR_FORBIDDEN:
- $this->http_code = 403;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_forbidden::get_details();
- break;
- case self::ERROR_NOTFOUND:
- $this->http_code = 404;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_notfound::get_details();
- break;
- case self::ERROR_METHODNOTALLOWED:
- $this->http_code = 405;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_methodnotallowed::get_details();
- break;
- case self::ERROR_INTERNALSERVERERROR:
- $this->http_code = 500;
- $this->error_message = $const;
- $this->error_details = API_V1_exception_internalservererror::get_details();
- break;
- case OAUTH2_ERROR_INVALID_REQUEST:
- $this->error_message = $const;
- break;
+ switch ($this->response_type) {
+
+ case self::FORMAT_JSON:
+ default:
+ $return_value = 'application/json';
+ break;
+ case self::FORMAT_YAML:
+ $return_value = 'application/yaml';
+ break;
+ case self::FORMAT_JSONP:
+ $return_value = 'text/javascript';
+ break;
+ }
+
+ return $return_value;
}
- return $this;
- }
-
- /**
- * Set the API_V1_result http_code, error_message and error_details
- * with the appropriate datas
- *
- * @param string $const
- * @return API_V1_result
- */
- public function set_error_code($code)
- {
- switch ($code = (int) $code)
+ /**
+ * Set the API_V1_result http_code, error_message and error_details
+ * with the appropriate datas
+ *
+ * @param string $const
+ * @return API_V1_result
+ */
+ public function set_error_message($const)
{
- case 400:
- $this->http_code = $code;
- $this->error_message = self::ERROR_BAD_REQUEST;
- $this->error_details = API_V1_exception_badrequest::get_details();
- break;
- case 401:
- $this->http_code = $code;
- $this->error_message = self::ERROR_UNAUTHORIZED;
- $this->error_details = API_V1_exception_unauthorized::get_details();
- break;
- case 403:
- $this->http_code = $code;
- $this->error_message = self::ERROR_FORBIDDEN;
- $this->error_details = API_V1_exception_forbidden::get_details();
- break;
- case 404:
- $this->http_code = $code;
- $this->error_message = self::ERROR_NOTFOUND;
- $this->error_details = API_V1_exception_notfound::get_details();
- break;
- case 405:
- $this->http_code = $code;
- $this->error_message = self::ERROR_METHODNOTALLOWED;
- $this->error_details = API_V1_exception_methodnotallowed::get_details();
- break;
- case 500:
- $this->http_code = $code;
- $this->error_message = self::ERROR_INTERNALSERVERERROR;
- $this->error_details = API_V1_exception_internalservererror::get_details();
- break;
+ switch ($const) {
+ case self::ERROR_BAD_REQUEST:
+ $this->http_code = 400;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_badrequest::get_details();
+ break;
+ case self::ERROR_UNAUTHORIZED:
+ $this->http_code = 401;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_unauthorized::get_details();
+ break;
+ case self::ERROR_FORBIDDEN:
+ $this->http_code = 403;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_forbidden::get_details();
+ break;
+ case self::ERROR_NOTFOUND:
+ $this->http_code = 404;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_notfound::get_details();
+ break;
+ case self::ERROR_METHODNOTALLOWED:
+ $this->http_code = 405;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_methodnotallowed::get_details();
+ break;
+ case self::ERROR_INTERNALSERVERERROR:
+ $this->http_code = 500;
+ $this->error_message = $const;
+ $this->error_details = API_V1_exception_internalservererror::get_details();
+ break;
+ case OAUTH2_ERROR_INVALID_REQUEST:
+ $this->error_message = $const;
+ break;
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- * Returns the correct http code depending on the errors
- *
- * @return int
- */
- public function get_http_code()
- {
- if ($this->response_type == self::FORMAT_JSONP && $this->http_code != 500)
+ /**
+ * Set the API_V1_result http_code, error_message and error_details
+ * with the appropriate datas
+ *
+ * @param string $const
+ * @return API_V1_result
+ */
+ public function set_error_code($code)
{
- return 200;
+ switch ($code = (int) $code) {
+ case 400:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_BAD_REQUEST;
+ $this->error_details = API_V1_exception_badrequest::get_details();
+ break;
+ case 401:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_UNAUTHORIZED;
+ $this->error_details = API_V1_exception_unauthorized::get_details();
+ break;
+ case 403:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_FORBIDDEN;
+ $this->error_details = API_V1_exception_forbidden::get_details();
+ break;
+ case 404:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_NOTFOUND;
+ $this->error_details = API_V1_exception_notfound::get_details();
+ break;
+ case 405:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_METHODNOTALLOWED;
+ $this->error_details = API_V1_exception_methodnotallowed::get_details();
+ break;
+ case 500:
+ $this->http_code = $code;
+ $this->error_message = self::ERROR_INTERNALSERVERERROR;
+ $this->error_details = API_V1_exception_internalservererror::get_details();
+ break;
+ }
+
+ return $this;
}
- else
+
+ /**
+ * Returns the correct http code depending on the errors
+ *
+ * @return int
+ */
+ public function get_http_code()
{
- return $this->http_code;
+ if ($this->response_type == self::FORMAT_JSONP && $this->http_code != 500) {
+ return 200;
+ } else {
+ return $this->http_code;
+ }
}
- }
- /**
- *
- * @param int $code
- */
- public function set_http_code($code)
- {
- $this->http_code = (int) $code;
- }
+ /**
+ *
+ * @param int $code
+ */
+ public function set_http_code($code)
+ {
+ $this->http_code = (int) $code;
+ }
- /**
- * Return a Symfony Response
- *
- * @return \Symfony\Component\HttpFoundation\Response
- */
- public function get_response()
- {
- $response = new Symfony\Component\HttpFoundation\Response(
- $this->format()
- , $this->get_http_code()
- , array('Content-Type' => $this->get_content_type())
- );
+ /**
+ * Return a Symfony Response
+ *
+ * @return \Symfony\Component\HttpFoundation\Response
+ */
+ public function get_response()
+ {
+ $response = new Symfony\Component\HttpFoundation\Response(
+ $this->format()
+ , $this->get_http_code()
+ , array('Content-Type' => $this->get_content_type())
+ );
- $response->setCharset('UTF-8');
-
- return $response;
- }
+ $response->setCharset('UTF-8');
+ return $response;
+ }
}
diff --git a/lib/classes/Bridge/Account.class.php b/lib/classes/Bridge/Account.class.php
index 15646e5842..fae3dd65b0 100644
--- a/lib/classes/Bridge/Account.class.php
+++ b/lib/classes/Bridge/Account.class.php
@@ -17,371 +17,360 @@
*/
class Bridge_Account
{
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var Bridge_Api
+ */
+ protected $api;
- /**
- *
- * @var Bridge_Api
- */
- protected $api;
+ /**
+ *
+ * @var string
+ */
+ protected $dist_id;
- /**
- *
- * @var string
- */
- protected $dist_id;
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @var string
+ */
+ protected $name;
- /**
- *
- * @var string
- */
- protected $name;
+ /**
+ *
+ * @var Bridge_AccountSettings
+ */
+ protected $settings;
- /**
- *
- * @var Bridge_AccountSettings
- */
- protected $settings;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Api $api
+ * @param int $id
+ * @return Bridge_Account
+ */
+ public function __construct(appbox &$appbox, Bridge_Api &$api, $id)
+ {
+ $this->id = (int) $id;
+ $this->appbox = $appbox;
+ $this->api = $api;
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Api $api
- * @param int $id
- * @return Bridge_Account
- */
- public function __construct(appbox &$appbox, Bridge_Api &$api, $id)
- {
- $this->id = (int) $id;
- $this->appbox = $appbox;
- $this->api = $api;
+ $this->api->get_connector()->set_auth_settings($this->get_settings());
- $this->api->get_connector()->set_auth_settings($this->get_settings());
-
- $sql = 'SELECT id, dist_id, usr_id, name, created_on, updated_on
+ $sql = 'SELECT id, dist_id, usr_id, name, created_on, updated_on
FROM bridge_accounts WHERE id = :id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Bridge_Exception_AccountNotFound('Account Not Found');
+ if ( ! $row)
+ throw new Bridge_Exception_AccountNotFound('Account Not Found');
- $this->dist_id = $row['dist_id'];
- $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
- $this->name = $row['name'];
- $this->updated_on = new DateTime($row['updated_on']);
- $this->created_on = new DateTime($row['created_on']);
+ $this->dist_id = $row['dist_id'];
+ $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ $this->name = $row['name'];
+ $this->updated_on = new DateTime($row['updated_on']);
+ $this->created_on = new DateTime($row['created_on']);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Bridge_AccountSettings
- */
- public function get_settings()
- {
- if (!$this->settings)
- $this->settings = new Bridge_AccountSettings($this->appbox, $this);
+ /**
+ *
+ * @return Bridge_AccountSettings
+ */
+ public function get_settings()
+ {
+ if ( ! $this->settings)
+ $this->settings = new Bridge_AccountSettings($this->appbox, $this);
- return $this->settings;
- }
+ return $this->settings;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return Bridge_Api
- */
- public function get_api()
- {
- return $this->api;
- }
+ /**
+ *
+ * @return Bridge_Api
+ */
+ public function get_api()
+ {
+ return $this->api;
+ }
- /**
- *
- * @return string
- */
- public function get_dist_id()
- {
- return $this->dist_id;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_dist_id()
+ {
+ return $this->dist_id;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return $this->updated_on;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return $this->updated_on;
+ }
- /**
- *
- * @param string $name
- * @return Bridge_Account
- */
- public function set_name($name)
- {
- $this->name = $name;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @param string $name
+ * @return Bridge_Account
+ */
+ public function set_name($name)
+ {
+ $this->name = $name;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_accounts
+ $sql = 'UPDATE bridge_accounts
SET name = :name, updated_on = :update WHERE id = :id';
- $params = array(
- ':name' => $this->name
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':name' => $this->name
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
-
- /**
- *
- * @return Void
- */
- public function delete()
- {
- do
- {
- $elements = Bridge_Element::get_elements_by_account($this->appbox, $this);
- foreach ($elements as $element)
- {
- $element->delete();
- }
+ return $this;
}
- while (count($elements) > 0);
- $sql = 'DELETE FROM bridge_accounts WHERE id = :id';
+ /**
+ *
+ * @return Void
+ */
+ public function delete()
+ {
+ do {
+ $elements = Bridge_Element::get_elements_by_account($this->appbox, $this);
+ foreach ($elements as $element) {
+ $element->delete();
+ }
+ } while (count($elements) > 0);
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM bridge_accounts WHERE id = :id';
- return;
- }
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $stmt->closeCursor();
- /**
- *
- * @param appbox $appbox
- * @param int $account_id
- * @return Bridge_Account
- */
- public static function load_account(appbox &$appbox, $account_id)
- {
- $sql = 'SELECT id, api_id FROM bridge_accounts WHERE id = :account_id';
+ return;
+ }
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':account_id' => $account_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ /**
+ *
+ * @param appbox $appbox
+ * @param int $account_id
+ * @return Bridge_Account
+ */
+ public static function load_account(appbox &$appbox, $account_id)
+ {
+ $sql = 'SELECT id, api_id FROM bridge_accounts WHERE id = :account_id';
- if (!$row)
- throw new Bridge_Exception_AccountNotFound('Account Not Found');
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':account_id' => $account_id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $api = new Bridge_Api($appbox, $row['api_id']);
- $api->get_connector()->set_locale($appbox->get_session()->get_locale());
+ if ( ! $row)
+ throw new Bridge_Exception_AccountNotFound('Account Not Found');
- return new self($appbox, $api, $row['id']);
- }
+ $api = new Bridge_Api($appbox, $row['api_id']);
+ $api->get_connector()->set_locale($appbox->get_session()->get_locale());
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Api $api
- * @param User_Adapter $user
- * @param string $distant_id
- * @return Bridge_Account
- */
- public static function load_account_from_distant_id(appbox $appbox, Bridge_Api $api, User_Adapter $user, $distant_id)
- {
- $sql = 'SELECT id FROM bridge_accounts
+ return new self($appbox, $api, $row['id']);
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Api $api
+ * @param User_Adapter $user
+ * @param string $distant_id
+ * @return Bridge_Account
+ */
+ public static function load_account_from_distant_id(appbox $appbox, Bridge_Api $api, User_Adapter $user, $distant_id)
+ {
+ $sql = 'SELECT id FROM bridge_accounts
WHERE api_id = :api_id AND usr_id = :usr_id AND dist_id = :dist_id';
- $params = array(
- ':api_id' => $api->get_id()
- , ':usr_id' => $user->get_id()
- , ':dist_id' => $distant_id
- );
+ $params = array(
+ ':api_id' => $api->get_id()
+ , ':usr_id' => $user->get_id()
+ , ':dist_id' => $distant_id
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Bridge_Exception_AccountNotFound();
+ if ( ! $row)
+ throw new Bridge_Exception_AccountNotFound();
- return new Bridge_Account($appbox, $api, $row['id']);
- }
+ return new Bridge_Account($appbox, $api, $row['id']);
+ }
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Api $api
- * @param int $quantity
- * @return Bridge_Account
- */
- public static function get_accounts_by_api(appbox &$appbox, Bridge_Api &$api, $quantity = 50)
- {
- $sql = 'SELECT id FROM bridge_accounts WHERE api_id = :api_id
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Api $api
+ * @param int $quantity
+ * @return Bridge_Account
+ */
+ public static function get_accounts_by_api(appbox &$appbox, Bridge_Api &$api, $quantity = 50)
+ {
+ $sql = 'SELECT id FROM bridge_accounts WHERE api_id = :api_id
LIMIT 0,' . (int) $quantity;
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':api_id' => $api->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':api_id' => $api->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $results = array();
+ $results = array();
- foreach ($rs as $row)
- {
- $results[] = new Bridge_Account($appbox, $api, $row['id']);
+ foreach ($rs as $row) {
+ $results[] = new Bridge_Account($appbox, $api, $row['id']);
+ }
+
+ return $results;
}
- return $results;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param user_adapter $user
- * @return Bridge_Account
- */
- public static function get_accounts_by_user(appbox &$appbox, user_adapter &$user)
- {
- $sql = 'SELECT id, api_id FROM bridge_accounts WHERE usr_id = :usr_id';
-
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $results = array();
- $apis = array();
-
-
- foreach ($rs as $row)
+ /**
+ *
+ * @param appbox $appbox
+ * @param user_adapter $user
+ * @return Bridge_Account
+ */
+ public static function get_accounts_by_user(appbox &$appbox, user_adapter &$user)
{
- $api_id = $row['api_id'];
- if (!isset($apis[$api_id]))
- {
- try
- {
- $apis[$api_id] = new Bridge_Api($appbox, $api_id);
+ $sql = 'SELECT id, api_id FROM bridge_accounts WHERE usr_id = :usr_id';
+
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $results = array();
+ $apis = array();
+
+
+ foreach ($rs as $row) {
+ $api_id = $row['api_id'];
+ if ( ! isset($apis[$api_id])) {
+ try {
+ $apis[$api_id] = new Bridge_Api($appbox, $api_id);
+ } catch (Exception $e) {
+ continue;
+ }
+ }
+ $results[] = new Bridge_Account($appbox, $apis[$api_id], $row['id']);
}
- catch (Exception $e)
- {
- continue;
- }
- }
- $results[] = new Bridge_Account($appbox, $apis[$api_id], $row['id']);
+
+ return $results;
}
- return $results;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Api $api
- * @param User_Adapter $user
- * @param string $dist_id
- * @param string $name
- * @return Bridge_Account
- */
- public static function create(appbox &$appbox, Bridge_Api &$api, User_Adapter &$user, $dist_id, $name)
- {
- $sql = 'INSERT INTO bridge_accounts
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Api $api
+ * @param User_Adapter $user
+ * @param string $dist_id
+ * @param string $name
+ * @return Bridge_Account
+ */
+ public static function create(appbox &$appbox, Bridge_Api &$api, User_Adapter &$user, $dist_id, $name)
+ {
+ $sql = 'INSERT INTO bridge_accounts
(id, api_id, dist_id, usr_id, name, created_on, updated_on)
VALUES (null, :api_id, :dist_id, :usr_id, :name, NOW(), NOW())';
- $params = array(
- ':api_id' => $api->get_id()
- , ':dist_id' => $dist_id
- , ':usr_id' => $user->get_id()
- , ':name' => $name
- );
+ $params = array(
+ ':api_id' => $api->get_id()
+ , ':dist_id' => $dist_id
+ , ':usr_id' => $user->get_id()
+ , ':name' => $name
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $account_id = $appbox->get_connection()->lastInsertId();
-
- return new self($appbox, $api, $account_id);
- }
+ $account_id = $appbox->get_connection()->lastInsertId();
+ return new self($appbox, $api, $account_id);
+ }
}
diff --git a/lib/classes/Bridge/AccountSettings.class.php b/lib/classes/Bridge/AccountSettings.class.php
index 645aec29d1..bafa666780 100644
--- a/lib/classes/Bridge/AccountSettings.class.php
+++ b/lib/classes/Bridge/AccountSettings.class.php
@@ -17,97 +17,95 @@
*/
class Bridge_AccountSettings
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var Bridge_Account
+ */
+ protected $account;
- /**
- *
- * @var Bridge_Account
- */
- protected $account;
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Account $account
+ * @return Bridge_AccountSettings
+ */
+ public function __construct(appbox &$appbox, Bridge_Account &$account)
+ {
+ $this->appbox = $appbox;
+ $this->account = $account;
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Account $account
- * @return Bridge_AccountSettings
- */
- public function __construct(appbox &$appbox, Bridge_Account &$account)
- {
- $this->appbox = $appbox;
- $this->account = $account;
+ return $this;
+ }
- return $this;
- }
-
- /**
- *
- * @param string $key
- * @param mixed $default_value
- * @return mixed
- */
- public function get($key, $default_value = null)
- {
- $sql = 'SELECT value FROM bridge_account_settings
+ /**
+ *
+ * @param string $key
+ * @param mixed $default_value
+ * @return mixed
+ */
+ public function get($key, $default_value = null)
+ {
+ $sql = 'SELECT value FROM bridge_account_settings
WHERE account_id = :account_id AND `key` = :key';
- $params = array(':account_id' => $this->account->get_id(), ':key' => $key);
+ $params = array(':account_id' => $this->account->get_id(), ':key' => $key);
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- return isset($row['value']) ? $row['value'] : $default_value;
- }
+ return isset($row['value']) ? $row['value'] : $default_value;
+ }
- /**
- *
- * @param string $key
- * @param string $value
- * @return string
- */
- public function set($key, $value)
- {
- $sql = 'REPLACE INTO bridge_account_settings
+ /**
+ *
+ * @param string $key
+ * @param string $value
+ * @return string
+ */
+ public function set($key, $value)
+ {
+ $sql = 'REPLACE INTO bridge_account_settings
(account_id, `key`, value) VALUES (:account_id, :key, :value)';
- $params = array(
- ':value' => $value
- , ':account_id' => $this->account->get_id()
- , ':key' => $key
- );
+ $params = array(
+ ':value' => $value
+ , ':account_id' => $this->account->get_id()
+ , ':key' => $key
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $value;
- }
+ return $value;
+ }
- /**
- *
- * @param string $key
- * @return string
- */
- public function delete($key)
- {
- $return_value = $this->get($key);
+ /**
+ *
+ * @param string $key
+ * @return string
+ */
+ public function delete($key)
+ {
+ $return_value = $this->get($key);
- $sql = 'DELETE FROM bridge_account_settings
+ $sql = 'DELETE FROM bridge_account_settings
WHERE account_id = :account_id AND `key` = :key';
- $params = array(':account_id' => $this->account->get_id(), ':key' => $key);
+ $params = array(':account_id' => $this->account->get_id(), ':key' => $key);
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
-
- return $return_value;
- }
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ return $return_value;
+ }
}
diff --git a/lib/classes/Bridge/Api.class.php b/lib/classes/Bridge/Api.class.php
index 76d8407419..717931e524 100644
--- a/lib/classes/Bridge/Api.class.php
+++ b/lib/classes/Bridge/Api.class.php
@@ -19,589 +19,554 @@ use Symfony\Component\HttpFoundation\Request;
*/
class Bridge_Api
{
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $disable_time;
- /**
- *
- * @var DateTime
- */
- protected $disable_time;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
+ /**
+ *
+ * @var Bridge_Api_Interface
+ */
+ protected $connector;
- /**
- *
- * @var Bridge_Api_Interface
- */
- protected $connector;
+ /**
+ *
+ * @param appbox $appbox
+ * @param int $id
+ * @return Bridge_Api
+ */
+ public function __construct(appbox &$appbox, $id)
+ {
+ $this->appbox = $appbox;
+ $this->id = (int) $id;
- /**
- *
- * @param appbox $appbox
- * @param int $id
- * @return Bridge_Api
- */
- public function __construct(appbox &$appbox, $id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $id;
-
- $sql = 'SELECT id, name, disable_time, created_on, updated_on
+ $sql = 'SELECT id, name, disable_time, created_on, updated_on
FROM bridge_apis WHERE id = :id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Bridge_Exception_ApiNotFound('Api Not Found');
+ if ( ! $row)
+ throw new Bridge_Exception_ApiNotFound('Api Not Found');
- $this->connector = self::get_connector_by_name($appbox->get_registry(), $row['name']);
- $this->disable_time = $row['disable_time'] ? new DateTime($row['disable_time']) : null;
- $this->updated_on = new DateTime($row['updated_on']);
- $this->created_on = new DateTime($row['created_on']);
+ $this->connector = self::get_connector_by_name($appbox->get_registry(), $row['name']);
+ $this->disable_time = $row['disable_time'] ? new DateTime($row['disable_time']) : null;
+ $this->updated_on = new DateTime($row['updated_on']);
+ $this->created_on = new DateTime($row['created_on']);
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Interface
- */
- public function get_connector()
- {
- return $this->connector;
- }
-
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_disabled()
- {
- if ($this->disable_time === null)
-
- return false;
- $date_obj = new DateTime();
- if ($date_obj > $this->disable_time)
- {
- $this->enable();
-
- return false;
+ return $this;
}
- return true;
- }
-
- /**
- *
- * @return Bridge_Api
- */
- public function enable()
- {
- $this->disable_time = null;
-
- return $this->update_disable_time(null);
- }
-
- /**
- *
- * @return Bridge_Api
- */
- public function disable(DateTime $date_end)
- {
- $this->disable_time = $date_end;
-
- return $this->update_disable_time($date_end->format(DATE_ISO8601));
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return $this->updated_on;
- }
-
- /**
- *
- * @param string $type
- * @param int $offset_start
- * @param int $quantity
- * @return array
- */
- public function list_elements($type, $offset_start = 0, $quantity = 10)
- {
- $action = function(Bridge_Api &$obj) use ($type, $offset_start, $quantity )
- {
- return $obj->get_connector()->list_elements($type, $offset_start, $quantity);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $type
- * @param int $offset_start
- * @param int $quantity
- * @return array
- */
- public function list_containers($type, $offset_start = 0, $quantity = 10)
- {
- $action = function(Bridge_Api &$obj) use ($type, $offset_start, $quantity )
- {
- return $obj->get_connector()->list_containers($type, $offset_start, $quantity);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @param Request $request
- * @return Bridge_Api_Interface
- */
- public function update_element($object, $object_id, Array $datas)
- {
- $action = function(Bridge_Api &$obj) use ($object, $object_id, $datas)
- {
- return $obj->get_connector()->update_element($object, $object_id, $datas);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $container_type
- * @param Request $request
- * @return Bridge_Api_ContainerInterface
- */
- public function create_container($container_type, Request $request)
- {
- $action = function(Bridge_Api &$obj) use ($container_type, $request)
- {
- return $obj->get_connector()->create_container($container_type, $request);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $element_type
- * @param string $element_id
- * @param string $destination
- * @param string $container_id
- * @return Bridge_Api_ContainerInterface
- */
- public function add_element_to_container($element_type, $element_id, $destination, $container_id)
- {
- $action = function(Bridge_Api &$obj) use ($element_type, $element_id, $destination, $container_id)
- {
- return $obj->get_connector()->add_element_to_container($element_type, $element_id, $destination, $container_id);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @return Void
- */
- public function delete_object($object, $object_id)
- {
- $action = function(Bridge_Api &$obj) use ($object, $object_id)
- {
- return $obj->get_connector()->delete_object($object, $object_id);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @return boolean
- */
- public function acceptable_records()
- {
- $action = function(Bridge_Api &$obj)
- {
- return $obj->get_connector()->acceptable_records();
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param type $element_id
- * @param type $type
- * @return Bridge_Api_ElementInterface
- */
- public function get_element_from_id($element_id, $type)
- {
- $action = function(Bridge_Api &$obj) use ($element_id, $type)
- {
- return $obj->get_connector()->get_element_from_id($element_id, $type);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param int $element_id
- * @param string $type
- * @return Bridge_Api_ContainerInterface
- */
- public function get_container_from_id($element_id, $type)
- {
- $action = function(Bridge_Api &$obj) use ($element_id, $type)
- {
- return $obj->get_connector()->get_container_from_id($element_id, $type);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @return Array
- */
- public function get_category_list()
- {
- $action = function(Bridge_Api &$obj)
- {
- return $obj->get_connector()->get_category_list();
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $element_id
- * @return string
- */
- public function get_element_status(Bridge_Element $element)
- {
- $action = function(Bridge_Api &$obj) use ($element)
- {
- return $obj->get_connector()->get_element_status($element);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $status
- * @return string
- */
- public function map_connector_to_element_status($status)
- {
- $action = function(Bridge_Api &$obj) use ($status)
- {
- return $obj->get_connector()->map_connector_to_element_status($status);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param string $connector_status
- * @return string
- */
- public function get_error_message_from_status($connector_status)
- {
- $action = function(Bridge_Api &$obj) use ($connector_status)
- {
- return $obj->get_connector()->get_error_message_from_status($connector_status);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @param record_adapter $record
- * @param array $options specific option, regarding the connector
- * @return string The distant_id of the created element
- */
- public function upload(record_adapter &$record, array $options = array())
- {
- $action = function(Bridge_Api &$obj) use ($record, $options)
- {
- return $obj->get_connector()->upload($record, $options);
- };
-
- return $this->execute_action($action);
- }
-
- /**
- *
- * @return Void
- */
- public function delete()
- {
- do
+ /**
+ *
+ * @return Bridge_Api_Interface
+ */
+ public function get_connector()
{
- $accounts = Bridge_Account::get_accounts_by_api($this->appbox, $this);
- foreach ($accounts as $account)
- {
- $account->delete();
- }
+ return $this->connector;
}
- while (count($accounts) > 0);
- $sql = 'DELETE FROM bridge_apis WHERE id = :id';
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $stmt->closeCursor();
+ /**
+ *
+ * @return boolean
+ */
+ public function is_disabled()
+ {
+ if ($this->disable_time === null)
+ return false;
+ $date_obj = new DateTime();
+ if ($date_obj > $this->disable_time) {
+ $this->enable();
- return;
- }
+ return false;
+ }
- /**
- *
- * @return Bridge_Api
- */
- protected function update_disable_time($value)
- {
- $this->updated_on = new DateTime();
+ return true;
+ }
- $sql = 'UPDATE bridge_apis SET disable_time = :time, updated_on = :update
+ /**
+ *
+ * @return Bridge_Api
+ */
+ public function enable()
+ {
+ $this->disable_time = null;
+
+ return $this->update_disable_time(null);
+ }
+
+ /**
+ *
+ * @return Bridge_Api
+ */
+ public function disable(DateTime $date_end)
+ {
+ $this->disable_time = $date_end;
+
+ return $this->update_disable_time($date_end->format(DATE_ISO8601));
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return $this->updated_on;
+ }
+
+ /**
+ *
+ * @param string $type
+ * @param int $offset_start
+ * @param int $quantity
+ * @return array
+ */
+ public function list_elements($type, $offset_start = 0, $quantity = 10)
+ {
+ $action = function(Bridge_Api &$obj) use ($type, $offset_start, $quantity ) {
+ return $obj->get_connector()->list_elements($type, $offset_start, $quantity);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $type
+ * @param int $offset_start
+ * @param int $quantity
+ * @return array
+ */
+ public function list_containers($type, $offset_start = 0, $quantity = 10)
+ {
+ $action = function(Bridge_Api &$obj) use ($type, $offset_start, $quantity ) {
+ return $obj->get_connector()->list_containers($type, $offset_start, $quantity);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @param Request $request
+ * @return Bridge_Api_Interface
+ */
+ public function update_element($object, $object_id, Array $datas)
+ {
+ $action = function(Bridge_Api &$obj) use ($object, $object_id, $datas) {
+ return $obj->get_connector()->update_element($object, $object_id, $datas);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $container_type
+ * @param Request $request
+ * @return Bridge_Api_ContainerInterface
+ */
+ public function create_container($container_type, Request $request)
+ {
+ $action = function(Bridge_Api &$obj) use ($container_type, $request) {
+ return $obj->get_connector()->create_container($container_type, $request);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $element_type
+ * @param string $element_id
+ * @param string $destination
+ * @param string $container_id
+ * @return Bridge_Api_ContainerInterface
+ */
+ public function add_element_to_container($element_type, $element_id, $destination, $container_id)
+ {
+ $action = function(Bridge_Api &$obj) use ($element_type, $element_id, $destination, $container_id) {
+ return $obj->get_connector()->add_element_to_container($element_type, $element_id, $destination, $container_id);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @return Void
+ */
+ public function delete_object($object, $object_id)
+ {
+ $action = function(Bridge_Api &$obj) use ($object, $object_id) {
+ return $obj->get_connector()->delete_object($object, $object_id);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function acceptable_records()
+ {
+ $action = function(Bridge_Api &$obj) {
+ return $obj->get_connector()->acceptable_records();
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param type $element_id
+ * @param type $type
+ * @return Bridge_Api_ElementInterface
+ */
+ public function get_element_from_id($element_id, $type)
+ {
+ $action = function(Bridge_Api &$obj) use ($element_id, $type) {
+ return $obj->get_connector()->get_element_from_id($element_id, $type);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param int $element_id
+ * @param string $type
+ * @return Bridge_Api_ContainerInterface
+ */
+ public function get_container_from_id($element_id, $type)
+ {
+ $action = function(Bridge_Api &$obj) use ($element_id, $type) {
+ return $obj->get_connector()->get_container_from_id($element_id, $type);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_category_list()
+ {
+ $action = function(Bridge_Api &$obj) {
+ return $obj->get_connector()->get_category_list();
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $element_id
+ * @return string
+ */
+ public function get_element_status(Bridge_Element $element)
+ {
+ $action = function(Bridge_Api &$obj) use ($element) {
+ return $obj->get_connector()->get_element_status($element);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $status
+ * @return string
+ */
+ public function map_connector_to_element_status($status)
+ {
+ $action = function(Bridge_Api &$obj) use ($status) {
+ return $obj->get_connector()->map_connector_to_element_status($status);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param string $connector_status
+ * @return string
+ */
+ public function get_error_message_from_status($connector_status)
+ {
+ $action = function(Bridge_Api &$obj) use ($connector_status) {
+ return $obj->get_connector()->get_error_message_from_status($connector_status);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @param record_adapter $record
+ * @param array $options specific option, regarding the connector
+ * @return string The distant_id of the created element
+ */
+ public function upload(record_adapter &$record, array $options = array())
+ {
+ $action = function(Bridge_Api &$obj) use ($record, $options) {
+ return $obj->get_connector()->upload($record, $options);
+ };
+
+ return $this->execute_action($action);
+ }
+
+ /**
+ *
+ * @return Void
+ */
+ public function delete()
+ {
+ do {
+ $accounts = Bridge_Account::get_accounts_by_api($this->appbox, $this);
+ foreach ($accounts as $account) {
+ $account->delete();
+ }
+ } while (count($accounts) > 0);
+
+ $sql = 'DELETE FROM bridge_apis WHERE id = :id';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ /**
+ *
+ * @return Bridge_Api
+ */
+ protected function update_disable_time($value)
+ {
+ $this->updated_on = new DateTime();
+
+ $sql = 'UPDATE bridge_apis SET disable_time = :time, updated_on = :update
WHERE id = :id';
- $params = array(
- ':time' => $value
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':time' => $value
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
-
- /**
- *
- * @param Closure $action
- * @return mixed
- */
- protected function execute_action(Closure $action)
- {
- if ($this->is_disabled())
- throw new Bridge_Exception_ApiDisabled($this);
-
- $n = 0;
- do
- {
- $e = null;
- try
- {
- $ret = $action($this);
-
- return $ret;
- }
- catch (Exception $e)
- {
- $this->get_connector()->handle_Exception($e);
-
- if ($e instanceof Bridge_Exception_ActionAuthNeedReconnect)
- {
- $this->get_connector()->reconnect();
- }
- else
- {
- throw $e;
- }
-
- if ($n >= 2)
- {
- throw new Bridge_Exception_ApiConnectorRequestFailed('Request failed');
- }
- }
- $n++;
- }
- while ($n <= 2 && $e instanceof Bridge_Exception_ActionAuthNeedReconnect);
-
- return null;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param string $api_name
- * @return string
- */
- public static function generate_callback_url(registryInterface $registry, $api_name)
- {
- return sprintf(
- '%sprod/bridge/callback/%s/'
- , $registry->get('GV_ServerName')
- , mb_strtolower($api_name)
- );
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param string $api_name
- * @return string
- */
- public static function generate_login_url(registryInterface $registry, $api_name)
- {
- return sprintf(
- '%sprod/bridge/login/%s/'
- , $registry->get('GV_ServerName')
- , mb_strtolower($api_name)
- );
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param string $name
- * @return Bridge_Api_Interface
- */
- public static function get_connector_by_name(registryInterface $registry, $name)
- {
- $name = ucfirst(strtolower($name));
- $classname = 'Bridge_Api_' . $name;
-
- if (!class_exists($classname))
- {
- throw new Bridge_Exception_ApiConnectorNotFound($name . ' connector not found');
+ return $this;
}
- $auth_classname = 'Bridge_Api_Auth_' . $classname::AUTH_TYPE;
- $auth = new $auth_classname;
-
- return new $classname($registry, $auth);
- }
-
- /**
- *
- * @param appbox $appbox
- * @param string $name
- * @return Bridge_Api
- */
- public static function get_by_api_name(appbox $appbox, $name)
- {
- $name = strtolower($name);
-
- $sql = 'SELECT id FROM bridge_apis WHERE name = :name';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':name' => $name));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if (!$row)
- throw new Bridge_Exception_ApiNotFound('Unknown api name ' . $name);
-
- return new self($appbox, $row['id']);
- }
-
- /**
- *
- * @param appbox $appbox
- * @return Bridge_Api
- */
- public static function get_availables(appbox &$appbox)
- {
- $sql = 'SELECT id FROM bridge_apis';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $results = array();
-
- foreach ($rs as $row)
+ /**
+ *
+ * @param Closure $action
+ * @return mixed
+ */
+ protected function execute_action(Closure $action)
{
- try
- {
- $results[] = new Bridge_Api($appbox, $row['id']);
- }
- catch (Exception $e)
- {
+ if ($this->is_disabled())
+ throw new Bridge_Exception_ApiDisabled($this);
- }
+ $n = 0;
+ do {
+ $e = null;
+ try {
+ $ret = $action($this);
+
+ return $ret;
+ } catch (Exception $e) {
+ $this->get_connector()->handle_Exception($e);
+
+ if ($e instanceof Bridge_Exception_ActionAuthNeedReconnect) {
+ $this->get_connector()->reconnect();
+ } else {
+ throw $e;
+ }
+
+ if ($n >= 2) {
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Request failed');
+ }
+ }
+ $n ++;
+ } while ($n <= 2 && $e instanceof Bridge_Exception_ActionAuthNeedReconnect);
+
+ return null;
}
- return $results;
- }
+ /**
+ *
+ * @param registryInterface $registry
+ * @param string $api_name
+ * @return string
+ */
+ public static function generate_callback_url(registryInterface $registry, $api_name)
+ {
+ return sprintf(
+ '%sprod/bridge/callback/%s/'
+ , $registry->get('GV_ServerName')
+ , mb_strtolower($api_name)
+ );
+ }
- /**
- *
- * @param appbox $appbox
- * @param string $name
- * @return Bridge_Api
- */
- public static function create(appbox &$appbox, $name)
- {
- $sql = 'INSERT INTO bridge_apis
+ /**
+ *
+ * @param registryInterface $registry
+ * @param string $api_name
+ * @return string
+ */
+ public static function generate_login_url(registryInterface $registry, $api_name)
+ {
+ return sprintf(
+ '%sprod/bridge/login/%s/'
+ , $registry->get('GV_ServerName')
+ , mb_strtolower($api_name)
+ );
+ }
+
+ /**
+ *
+ * @param registryInterface $registry
+ * @param string $name
+ * @return Bridge_Api_Interface
+ */
+ public static function get_connector_by_name(registryInterface $registry, $name)
+ {
+ $name = ucfirst(strtolower($name));
+ $classname = 'Bridge_Api_' . $name;
+
+ if ( ! class_exists($classname)) {
+ throw new Bridge_Exception_ApiConnectorNotFound($name . ' connector not found');
+ }
+
+ $auth_classname = 'Bridge_Api_Auth_' . $classname::AUTH_TYPE;
+ $auth = new $auth_classname;
+
+ return new $classname($registry, $auth);
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param string $name
+ * @return Bridge_Api
+ */
+ public static function get_by_api_name(appbox $appbox, $name)
+ {
+ $name = strtolower($name);
+
+ $sql = 'SELECT id FROM bridge_apis WHERE name = :name';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':name' => $name));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ( ! $row)
+ throw new Bridge_Exception_ApiNotFound('Unknown api name ' . $name);
+
+ return new self($appbox, $row['id']);
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @return Bridge_Api
+ */
+ public static function get_availables(appbox &$appbox)
+ {
+ $sql = 'SELECT id FROM bridge_apis';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $results = array();
+
+ foreach ($rs as $row) {
+ try {
+ $results[] = new Bridge_Api($appbox, $row['id']);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ return $results;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param string $name
+ * @return Bridge_Api
+ */
+ public static function create(appbox &$appbox, $name)
+ {
+ $sql = 'INSERT INTO bridge_apis
(id, name, disable, disable_time, created_on, updated_on)
VALUES (null, :name, 0, null, NOW(), NOW())';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':name' => strtolower($name)));
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':name' => strtolower($name)));
+ $stmt->closeCursor();
- $api_id = $appbox->get_connection()->lastInsertId();
-
- return new self($appbox, $api_id);
- }
+ $api_id = $appbox->get_connection()->lastInsertId();
+ return new self($appbox, $api_id);
+ }
}
diff --git a/lib/classes/Bridge/Api/Abstract.class.php b/lib/classes/Bridge/Api/Abstract.class.php
index cb776855d4..b7d14794cc 100644
--- a/lib/classes/Bridge/Api/Abstract.class.php
+++ b/lib/classes/Bridge/Api/Abstract.class.php
@@ -17,165 +17,163 @@
*/
abstract class Bridge_Api_Abstract
{
+ /**
+ *
+ * @var Bridge_Api_Auth_Interface
+ */
+ protected $_auth;
- /**
- *
- * @var Bridge_Api_Auth_Interface
- */
- protected $_auth;
+ /**
+ *
+ * @var string
+ */
+ protected $locale = 'en_US';
- /**
- *
- * @var string
- */
- protected $locale = 'en_US';
+ /**
+ *
+ * @param registryInterface $registry
+ * @param Bridge_Api_Auth_Interface $auth
+ * @return Bridge_Api_Abstract
+ */
+ public function __construct(registryInterface $registry, Bridge_Api_Auth_Interface $auth)
+ {
+ $this->registry = $registry;
+ $this->_auth = $auth;
+ $this->initialize_transport();
+ $this->set_auth_params();
- /**
- *
- * @param registryInterface $registry
- * @param Bridge_Api_Auth_Interface $auth
- * @return Bridge_Api_Abstract
- */
- public function __construct(registryInterface $registry, Bridge_Api_Auth_Interface $auth)
- {
- $this->registry = $registry;
- $this->_auth = $auth;
- $this->initialize_transport();
- $this->set_auth_params();
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @param Bridge_AccountSettings $settings
+ * @return Bridge_Api_Abstract
+ */
+ public function set_auth_settings(Bridge_AccountSettings &$settings)
+ {
+ $this->_auth->set_settings($settings);
+ $this->set_transport_authentication_params();
- /**
- *
- * @param Bridge_AccountSettings $settings
- * @return Bridge_Api_Abstract
- */
- public function set_auth_settings(Bridge_AccountSettings &$settings)
- {
- $this->_auth->set_settings($settings);
- $this->set_transport_authentication_params();
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return Array The result of the primary handshake, Including tokens and others
+ */
+ public function connect()
+ {
+ if ( ! $this->is_configured())
+ throw new Bridge_Exception_ApiConnectorNotConfigured('Connector not configured');
+ $request_token = $this->_auth->parse_request_token();
- /**
- *
- * @return Array The result of the primary handshake, Including tokens and others
- */
- public function connect()
- {
- if (!$this->is_configured())
- throw new Bridge_Exception_ApiConnectorNotConfigured('Connector not configured');
- $request_token = $this->_auth->parse_request_token();
+ return $this->_auth->connect($request_token);
+ }
- return $this->_auth->connect($request_token);
- }
+ /**
+ *
+ * @return Bridge_Api_Abstract
+ */
+ public function reconnect()
+ {
+ if ( ! $this->is_configured())
+ throw new Bridge_Exception_ApiConnectorNotConfigured();
+ $this->_auth->reconnect();
- /**
- *
- * @return Bridge_Api_Abstract
- */
- public function reconnect()
- {
- if (!$this->is_configured())
- throw new Bridge_Exception_ApiConnectorNotConfigured();
- $this->_auth->reconnect();
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return Bridge_Api_Abstract
+ */
+ public function disconnect()
+ {
+ if ( ! $this->is_configured())
+ throw new Bridge_Exception_ApiConnectorNotConfigured();
+ $this->_auth->disconnect();
- /**
- *
- * @return Bridge_Api_Abstract
- */
- public function disconnect()
- {
- if (!$this->is_configured())
- throw new Bridge_Exception_ApiConnectorNotConfigured();
- $this->_auth->disconnect();
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_connected()
+ {
+ return $this->_auth->is_connected();
+ }
- /**
- *
- * @return boolean
- */
- public function is_connected()
- {
- return $this->_auth->is_connected();
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_auth_url($supp_params = array())
+ {
+ return $this->_auth->get_auth_url($supp_params);
+ }
- /**
- *
- * @return string
- */
- public function get_auth_url($supp_params = array())
- {
- return $this->_auth->get_auth_url($supp_params);
- }
+ /**
+ *
+ * @param string $locale
+ * @return Bridge_Api_Abstract
+ */
+ public function set_locale($locale)
+ {
+ $this->locale = $locale;
- /**
- *
- * @param string $locale
- * @return Bridge_Api_Abstract
- */
- public function set_locale($locale)
- {
- $this->locale = $locale;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_locale()
+ {
+ return $this->locale;
+ }
- /**
- *
- * @return string
- */
- public function get_locale()
- {
- return $this->locale;
- }
+ /**
+ *
+ * @param type $object_id
+ * @return boolean
+ */
+ public function is_valid_object_id($object_id)
+ {
+ return is_scalar($object_id) && ! is_bool($object_id);
+ }
+ /**
+ * This method is called when calling any API method
+ * This allows use to change the exception object.
+ * For instance, you can set it to a Bridge_Exception_ActionAuthNeedReconnect
+ *
+ * @param Exception $e
+ * @return Void
+ */
+ public function handle_exception(Exception &$e)
+ {
+ return;
+ }
- /**
- *
- * @param type $object_id
- * @return boolean
- */
- public function is_valid_object_id($object_id)
- {
- return is_scalar($object_id) && !is_bool($object_id);
- }
+ /**
+ * The method to initialize Authentication transport
+ * It's called on constructor
+ */
+ abstract protected function initialize_transport();
- /**
- * This method is called when calling any API method
- * This allows use to change the exception object.
- * For instance, you can set it to a Bridge_Exception_ActionAuthNeedReconnect
- *
- * @param Exception $e
- * @return Void
- */
- public function handle_exception(Exception &$e)
- {
- return;
- }
+ /**
+ * The method used to set the connection params to the auth object
+ * It's called after transport initialization
+ */
+ abstract protected function set_auth_params();
- /**
- * The method to initialize Authentication transport
- * It's called on constructor
- */
- abstract protected function initialize_transport();
-
- /**
- * The method used to set the connection params to the auth object
- * It's called after transport initialization
- */
- abstract protected function set_auth_params();
-
- /**
- * Set the transport authentication params to the auth object
- * It's called, every time the settings are set
- */
- abstract protected function set_transport_authentication_params();
+ /**
+ * Set the transport authentication params to the auth object
+ * It's called, every time the settings are set
+ */
+ abstract protected function set_transport_authentication_params();
}
diff --git a/lib/classes/Bridge/Api/AbstractCollection.class.php b/lib/classes/Bridge/Api/AbstractCollection.class.php
index 14c0784f8a..26c4033b3a 100644
--- a/lib/classes/Bridge/Api/AbstractCollection.class.php
+++ b/lib/classes/Bridge/Api/AbstractCollection.class.php
@@ -17,152 +17,150 @@
*/
abstract class Bridge_Api_AbstractCollection
{
+ /**
+ *
+ * @var int
+ */
+ protected $total_page = 1;
- /**
- *
- * @var int
- */
- protected $total_page = 1;
+ /**
+ *
+ * @var int
+ */
+ protected $current_page = 1;
- /**
- *
- * @var int
- */
- protected $current_page = 1;
+ /**
+ *
+ * @var int
+ */
+ protected $total_items;
- /**
- *
- * @var int
- */
- protected $total_items;
+ /**
+ *
+ * @var int
+ */
+ protected $items_per_page;
- /**
- *
- * @var int
- */
- protected $items_per_page;
+ /**
+ *
+ * @var Array
+ */
+ protected $elements = array();
- /**
- *
- * @var Array
- */
- protected $elements = array();
+ /**
+ *
+ * @return int
+ */
+ public function get_total_items()
+ {
+ return $this->total_items;
+ }
- /**
- *
- * @return int
- */
- public function get_total_items()
- {
- return $this->total_items;
- }
+ public function set_total_items($total_items)
+ {
+ $this->total_items = (int) $total_items;
- public function set_total_items($total_items)
- {
- $this->total_items = (int) $total_items;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_items_per_page()
+ {
+ return $this->items_per_page;
+ }
- /**
- *
- * @return int
- */
- public function get_items_per_page()
- {
- return $this->items_per_page;
- }
+ /**
+ *
+ * @param int $items_per_page
+ * @return Bridge_Api_AbstractCollection
+ */
+ public function set_items_per_page($items_per_page)
+ {
+ $this->items_per_page = (int) $items_per_page;
- /**
- *
- * @param int $items_per_page
- * @return Bridge_Api_AbstractCollection
- */
- public function set_items_per_page($items_per_page)
- {
- $this->items_per_page = (int) $items_per_page;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_current_page()
+ {
+ return $this->current_page;
+ }
- /**
- *
- * @return int
- */
- public function get_current_page()
- {
- return $this->current_page;
- }
+ /**
+ *
+ * @param int $current_page
+ * @return Bridge_Api_AbstractCollection
+ */
+ public function set_current_page($current_page)
+ {
+ if ($current_page > 0)
+ $this->current_page = (int) $current_page;
- /**
- *
- * @param int $current_page
- * @return Bridge_Api_AbstractCollection
- */
- public function set_current_page($current_page)
- {
- if ($current_page > 0)
- $this->current_page = (int) $current_page;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_total_page()
+ {
+ return $this->total_page;
+ }
- /**
- *
- * @return int
- */
- public function get_total_page()
- {
- return $this->total_page;
- }
+ /**
+ *
+ * @param int $total_page
+ * @return Bridge_Api_AbstractCollection
+ */
+ public function set_total_page($total_page)
+ {
+ if ($total_page > 0)
+ $this->total_page = (int) $total_page;
- /**
- *
- * @param int $total_page
- * @return Bridge_Api_AbstractCollection
- */
- public function set_total_page($total_page)
- {
- if ($total_page > 0)
- $this->total_page = (int) $total_page;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function has_next_page()
+ {
+ return $this->current_page < $this->total_page;
+ }
- /**
- *
- * @return boolean
- */
- public function has_next_page()
- {
- return $this->current_page < $this->total_page;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function has_previous_page()
+ {
+ return $this->current_page > 1;
+ }
- /**
- *
- * @return boolean
- */
- public function has_previous_page()
- {
- return $this->current_page > 1;
- }
-
- /**
- *
- * @return boolean
- */
- public function has_more_than_one_page()
- {
- return $this->total_page > 1;
- }
-
- /**
- *
- * @return Array
- */
- public function get_elements()
- {
- return $this->elements;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function has_more_than_one_page()
+ {
+ return $this->total_page > 1;
+ }
+ /**
+ *
+ * @return Array
+ */
+ public function get_elements()
+ {
+ return $this->elements;
+ }
}
diff --git a/lib/classes/Bridge/Api/Auth/Abstract.class.php b/lib/classes/Bridge/Api/Auth/Abstract.class.php
index 77b78e0b11..d749c9a55e 100644
--- a/lib/classes/Bridge/Api/Auth/Abstract.class.php
+++ b/lib/classes/Bridge/Api/Auth/Abstract.class.php
@@ -17,23 +17,21 @@
*/
class Bridge_Api_Auth_Abstract
{
+ /**
+ *
+ * @var Bridge_AccountSettings
+ */
+ protected $settings;
- /**
- *
- * @var Bridge_AccountSettings
- */
- protected $settings;
-
- /**
- *
- * @param Bridge_AccountSettings $settings
- * @return Bridge_Api_Auth_Abstract
- */
- public function set_settings(Bridge_AccountSettings $settings)
- {
- $this->settings = $settings;
-
- return $this;
- }
+ /**
+ *
+ * @param Bridge_AccountSettings $settings
+ * @return Bridge_Api_Auth_Abstract
+ */
+ public function set_settings(Bridge_AccountSettings $settings)
+ {
+ $this->settings = $settings;
+ return $this;
+ }
}
diff --git a/lib/classes/Bridge/Api/Auth/Flickr.class.php b/lib/classes/Bridge/Api/Auth/Flickr.class.php
index 454494452a..0a09897b6c 100644
--- a/lib/classes/Bridge/Api/Auth/Flickr.class.php
+++ b/lib/classes/Bridge/Api/Auth/Flickr.class.php
@@ -17,139 +17,137 @@
*/
class Bridge_Api_Auth_Flickr extends Bridge_Api_Auth_Abstract implements Bridge_Api_Auth_Interface
{
+ /**
+ *
+ * @var string
+ */
+ protected $flickr_client_id;
- /**
- *
- * @var string
- */
- protected $flickr_client_id;
- /**
- *
- * @var string
- */
- protected $flickr_client_secret;
- /**
- *
- * @var string
- */
- protected $permissions;
+ /**
+ *
+ * @var string
+ */
+ protected $flickr_client_secret;
- /**
- *
- * @var Phlickr_Api
- */
- protected $_api;
+ /**
+ *
+ * @var string
+ */
+ protected $permissions;
- /**
- *
- * @return Phlickr_Api
- */
- protected function get_api()
- {
- if (!$this->_api)
+ /**
+ *
+ * @var Phlickr_Api
+ */
+ protected $_api;
+
+ /**
+ *
+ * @return Phlickr_Api
+ */
+ protected function get_api()
{
- $this->_api = new Phlickr_Api(
- $this->flickr_client_id,
- $this->flickr_client_secret
- );
+ if ( ! $this->_api) {
+ $this->_api = new Phlickr_Api(
+ $this->flickr_client_id,
+ $this->flickr_client_secret
+ );
+ }
+
+ return $this->_api;
}
- return $this->_api;
- }
-
- /**
- *
- * @return string
- */
- public function parse_request_token()
- {
- return isset($_GET["frob"]) ? $_GET["frob"] : null;
- }
-
- /**
- *
- * @param string $param
- * @return Array
- */
- public function connect($param)
- {
- $auth_token = $this->get_api()->setAuthTokenFromFrob($param);
- if (!$this->get_api()->isAuthValid())
- throw new Bridge_Exception_ApiConnectorAccessTokenFailed();
-
- $this->get_api()->setAuthToken($auth_token);
-
- return array('auth_token'=>$auth_token);
- }
-
- /**
- *
- * @return Bridge_Api_Auth_Flickr
- */
- public function reconnect()
- {
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Auth_Flickr
- */
- public function disconnect()
- {
- $this->settings->set('auth_token', null);
-
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_connected()
- {
- return $this->settings->get('auth_token') !== null;// && $this->get_api()->isAuthValid();
- }
-
- /**
- *
- * @return Array
- */
- public function get_auth_signatures()
- {
- return array(
- 'auth_token' => $this->settings->get('auth_token')
- );
- }
-
- /**
- *
- * @param array $parameters
- * @return Bridge_Api_Auth_Flickr
- */
- public function set_parameters(Array $parameters)
- {
- $avail_parameters = array('flickr_client_id', 'flickr_client_secret', 'permissions');
- foreach ($parameters as $parameter => $value)
+ /**
+ *
+ * @return string
+ */
+ public function parse_request_token()
{
- if (!in_array($parameter, $avail_parameters))
- continue;
-
- $this->$parameter = $value;
+ return isset($_GET["frob"]) ? $_GET["frob"] : null;
}
- return $this;
- }
+ /**
+ *
+ * @param string $param
+ * @return Array
+ */
+ public function connect($param)
+ {
+ $auth_token = $this->get_api()->setAuthTokenFromFrob($param);
+ if ( ! $this->get_api()->isAuthValid())
+ throw new Bridge_Exception_ApiConnectorAccessTokenFailed();
- /**
- *
- * @return string
- */
- public function get_auth_url(Array $supp_params = array())
- {
- $request_token = $this->get_api()->requestFrob();
+ $this->get_api()->setAuthToken($auth_token);
- return $this->get_api()->buildAuthUrl($this->permissions, $request_token);
- }
+ return array('auth_token' => $auth_token);
+ }
+ /**
+ *
+ * @return Bridge_Api_Auth_Flickr
+ */
+ public function reconnect()
+ {
+ return $this;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Auth_Flickr
+ */
+ public function disconnect()
+ {
+ $this->settings->set('auth_token', null);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_connected()
+ {
+ return $this->settings->get('auth_token') !== null; // && $this->get_api()->isAuthValid();
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_auth_signatures()
+ {
+ return array(
+ 'auth_token' => $this->settings->get('auth_token')
+ );
+ }
+
+ /**
+ *
+ * @param array $parameters
+ * @return Bridge_Api_Auth_Flickr
+ */
+ public function set_parameters(Array $parameters)
+ {
+ $avail_parameters = array('flickr_client_id', 'flickr_client_secret', 'permissions');
+ foreach ($parameters as $parameter => $value) {
+ if ( ! in_array($parameter, $avail_parameters))
+ continue;
+
+ $this->$parameter = $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_auth_url(Array $supp_params = array())
+ {
+ $request_token = $this->get_api()->requestFrob();
+
+ return $this->get_api()->buildAuthUrl($this->permissions, $request_token);
+ }
}
diff --git a/lib/classes/Bridge/Api/Auth/Interface.class.php b/lib/classes/Bridge/Api/Auth/Interface.class.php
index ed4db3824e..72b899559e 100644
--- a/lib/classes/Bridge/Api/Auth/Interface.class.php
+++ b/lib/classes/Bridge/Api/Auth/Interface.class.php
@@ -17,25 +17,25 @@
*/
interface Bridge_Api_Auth_Interface
{
- const STATE_NEED_RECO = 'need_reconnect';
- const STATE_BAD = 'not_connected';
- const STATE_OK = 'connection OK';
+ const STATE_NEED_RECO = 'need_reconnect';
+ const STATE_BAD = 'not_connected';
+ const STATE_OK = 'connection OK';
- public function connect($param);
+ public function connect($param);
- public function reconnect();
+ public function reconnect();
- public function disconnect();
+ public function disconnect();
- public function is_connected();
+ public function is_connected();
- public function parse_request_token();
+ public function parse_request_token();
- public function get_auth_url(Array $supp_parameters = array());
+ public function get_auth_url(Array $supp_parameters = array());
- public function get_auth_signatures();
+ public function get_auth_signatures();
- public function set_settings(Bridge_AccountSettings $settings);
+ public function set_settings(Bridge_AccountSettings $settings);
- public function set_parameters(Array $parameters);
+ public function set_parameters(Array $parameters);
}
diff --git a/lib/classes/Bridge/Api/Auth/OAuth2.class.php b/lib/classes/Bridge/Api/Auth/OAuth2.class.php
index 956f65b2df..a30cebf59d 100644
--- a/lib/classes/Bridge/Api/Auth/OAuth2.class.php
+++ b/lib/classes/Bridge/Api/Auth/OAuth2.class.php
@@ -17,178 +17,175 @@
*/
class Bridge_Api_Auth_OAuth2 extends Bridge_Api_Auth_Abstract implements Bridge_Api_Auth_Interface
{
+ /**
+ *
+ * @var string
+ */
+ protected $client_id;
- /**
- *
- * @var string
- */
- protected $client_id;
+ /**
+ *
+ * @var string
+ */
+ protected $client_secret;
- /**
- *
- * @var string
- */
- protected $client_secret;
+ /**
+ *
+ * @var string
+ */
+ protected $redirect_uri;
- /**
- *
- * @var string
- */
- protected $redirect_uri;
+ /**
+ *
+ * @var string
+ */
+ protected $scope;
- /**
- *
- * @var string
- */
- protected $scope;
+ /**
+ *
+ * @var string
+ */
+ protected $response_type;
- /**
- *
- * @var string
- */
- protected $response_type;
+ /**
+ *
+ * @var string
+ */
+ protected $token_endpoint;
- /**
- *
- * @var string
- */
- protected $token_endpoint;
+ /**
+ *
+ * @var string
+ */
+ protected $auth_endpoint;
- /**
- *
- * @var string
- */
- protected $auth_endpoint;
-
- /**
- *
- * @var string
- */
- public function parse_request_token()
- {
- return isset($_GET[$this->response_type]) ? $_GET[$this->response_type] : null;
- }
-
- /**
- *
- * @param string $request_token
- * @return Array
- */
- public function connect($request_token)
- {
- $post_params = array(
- 'code' => $request_token,
- 'client_id' => $this->client_id,
- 'client_secret' => $this->client_secret,
- 'redirect_uri' => $this->redirect_uri,
- 'grant_type' => 'authorization_code'
- );
-
- $response_json = http_query::getUrl($this->token_endpoint, $post_params);
- $response = json_decode($response_json, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS);
-
- if (!is_array($response) || !isset($response['refresh_token']) || !isset($response['access_token']))
- throw new Bridge_Exception_ApiConnectorAccessTokenFailed('Unable to retrieve tokens');
-
- return array('refresh_token' => $response['refresh_token'], 'auth_token' => $response['access_token']);
- }
-
- /**
- *
- * @return Bridge_Api_Auth_OAuth2
- */
- public function reconnect()
- {
- $post_params = array(
- 'client_id' => $this->client_id,
- 'client_secret' => $this->client_secret,
- 'refresh_token' => $this->settings->get('refresh_token'),
- 'grant_type' => 'refresh_token'
- );
-
- $response = http_query::getUrl($this->token_endpoint, $post_params);
- $response = json_decode($response, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS);
-
- if (!is_array($response) || !isset($response['access_token']))
- throw new Bridge_Exception_ApiConnectorAccessTokenFailed();
- $this->settings->set('auth_token', $response['access_token']);
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Auth_OAuth2
- */
- public function disconnect()
- {
- $this->settings->set('auth_token', null);
-
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_connected()
- {
- return $this->settings->get('auth_token') !== null;
- }
-
- /**
- *
- * @return Array
- */
- public function get_auth_signatures()
- {
- return array(
- 'auth_token' => $this->settings->get('auth_token')
- );
- }
-
- /**
- *
- * @param array $parameters
- * @return Bridge_Api_Auth_OAuth2
- */
- public function set_parameters(Array $parameters)
- {
- $avail_parameters = array(
- 'client_id'
- , 'client_secret'
- , 'redirect_uri'
- , 'scope'
- , 'response_type'
- , 'token_endpoint'
- , 'auth_endpoint'
- );
-
- foreach ($parameters as $parameter => $value)
+ /**
+ *
+ * @var string
+ */
+ public function parse_request_token()
{
- if (!in_array($parameter, $avail_parameters))
- continue;
-
- $this->$parameter = $value;
+ return isset($_GET[$this->response_type]) ? $_GET[$this->response_type] : null;
}
- return $this;
- }
+ /**
+ *
+ * @param string $request_token
+ * @return Array
+ */
+ public function connect($request_token)
+ {
+ $post_params = array(
+ 'code' => $request_token,
+ 'client_id' => $this->client_id,
+ 'client_secret' => $this->client_secret,
+ 'redirect_uri' => $this->redirect_uri,
+ 'grant_type' => 'authorization_code'
+ );
- /**
- *
- * @return string
- */
- public function get_auth_url(Array $supp_parameters = array())
- {
- $params = array_merge(array(
- 'response_type' => 'code',
- 'client_id' => $this->client_id,
- 'redirect_uri' => $this->redirect_uri,
- 'scope' => $this->scope
+ $response_json = http_query::getUrl($this->token_endpoint, $post_params);
+ $response = json_decode($response_json, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS);
+
+ if ( ! is_array($response) || ! isset($response['refresh_token']) || ! isset($response['access_token']))
+ throw new Bridge_Exception_ApiConnectorAccessTokenFailed('Unable to retrieve tokens');
+
+ return array('refresh_token' => $response['refresh_token'], 'auth_token' => $response['access_token']);
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Auth_OAuth2
+ */
+ public function reconnect()
+ {
+ $post_params = array(
+ 'client_id' => $this->client_id,
+ 'client_secret' => $this->client_secret,
+ 'refresh_token' => $this->settings->get('refresh_token'),
+ 'grant_type' => 'refresh_token'
+ );
+
+ $response = http_query::getUrl($this->token_endpoint, $post_params);
+ $response = json_decode($response, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS);
+
+ if ( ! is_array($response) || ! isset($response['access_token']))
+ throw new Bridge_Exception_ApiConnectorAccessTokenFailed();
+ $this->settings->set('auth_token', $response['access_token']);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Auth_OAuth2
+ */
+ public function disconnect()
+ {
+ $this->settings->set('auth_token', null);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_connected()
+ {
+ return $this->settings->get('auth_token') !== null;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_auth_signatures()
+ {
+ return array(
+ 'auth_token' => $this->settings->get('auth_token')
+ );
+ }
+
+ /**
+ *
+ * @param array $parameters
+ * @return Bridge_Api_Auth_OAuth2
+ */
+ public function set_parameters(Array $parameters)
+ {
+ $avail_parameters = array(
+ 'client_id'
+ , 'client_secret'
+ , 'redirect_uri'
+ , 'scope'
+ , 'response_type'
+ , 'token_endpoint'
+ , 'auth_endpoint'
+ );
+
+ foreach ($parameters as $parameter => $value) {
+ if ( ! in_array($parameter, $avail_parameters))
+ continue;
+
+ $this->$parameter = $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_auth_url(Array $supp_parameters = array())
+ {
+ $params = array_merge(array(
+ 'response_type' => 'code',
+ 'client_id' => $this->client_id,
+ 'redirect_uri' => $this->redirect_uri,
+ 'scope' => $this->scope
), $supp_parameters);
- return sprintf('%s?%s', $this->auth_endpoint, http_build_query($params, null, '&'));
- }
-
+ return sprintf('%s?%s', $this->auth_endpoint, http_build_query($params, null, '&'));
+ }
}
diff --git a/lib/classes/Bridge/Api/ContainerCollection.class.php b/lib/classes/Bridge/Api/ContainerCollection.class.php
index b5f14de11f..f0f1c93329 100644
--- a/lib/classes/Bridge/Api/ContainerCollection.class.php
+++ b/lib/classes/Bridge/Api/ContainerCollection.class.php
@@ -18,16 +18,15 @@
class Bridge_Api_ContainerCollection extends Bridge_Api_AbstractCollection
{
- /**
- *
- * @param Bridge_Api_ContainerInterface $container
- * @return Bridge_Api_ContainerCollection
- */
- public function add_element(Bridge_Api_ContainerInterface $container)
- {
- $this->elements[] = $container;
-
- return $this;
- }
+ /**
+ *
+ * @param Bridge_Api_ContainerInterface $container
+ * @return Bridge_Api_ContainerCollection
+ */
+ public function add_element(Bridge_Api_ContainerInterface $container)
+ {
+ $this->elements[] = $container;
+ return $this;
+ }
}
diff --git a/lib/classes/Bridge/Api/ContainerInterface.class.php b/lib/classes/Bridge/Api/ContainerInterface.class.php
index b827d1876a..8b92dff40d 100644
--- a/lib/classes/Bridge/Api/ContainerInterface.class.php
+++ b/lib/classes/Bridge/Api/ContainerInterface.class.php
@@ -18,19 +18,19 @@
interface Bridge_Api_ContainerInterface
{
- public function get_id();
+ public function get_id();
- public function get_thumbnail($width = 120, $height = 90);
+ public function get_thumbnail($width = 120, $height = 90);
- public function get_url();
+ public function get_url();
- public function get_title();
+ public function get_title();
- public function get_description();
+ public function get_description();
- public function get_updated_on();
+ public function get_updated_on();
- public function get_created_on();
+ public function get_created_on();
- public function get_type();
+ public function get_type();
}
diff --git a/lib/classes/Bridge/Api/Dailymotion.class.php b/lib/classes/Bridge/Api/Dailymotion.class.php
index 57a916af15..1702f6c5e4 100644
--- a/lib/classes/Bridge/Api/Dailymotion.class.php
+++ b/lib/classes/Bridge/Api/Dailymotion.class.php
@@ -21,236 +21,724 @@ use \Symfony\Component\HttpFoundation\Request;
*/
class Bridge_Api_Dailymotion extends Bridge_Api_Abstract implements Bridge_Api_Interface
{
- const OAUTH2_TOKEN_ENDPOINT = "https://api.dailymotion.com/oauth/token";
- const OAUTH2_AUTHORIZE_ENDPOINT = "https://api.dailymotion.com/oauth/authorize";
- const ELEMENT_TYPE_VIDEO = 'video';
- const CONTAINER_TYPE_PLAYLIST = 'playlist';
- const AUTH_TYPE = 'OAuth2';
- const AUTH_VIDEO_DURATION = 3600;
- const AUTH_VIDEO_SIZE = 2147483648; //in bytes = 2GB
- /**
- * @see http://www.dailymotion.com/doc/api/obj-video.html
- */
- const UPLOAD_STATE_PROCESSING = 'processing';
- const UPLOAD_STATE_READY = 'ready';
- const UPLOAD_STATE_WAITING = 'waiting';
- const UPLOAD_STATE_DONE = 'published';
- const UPLOAD_STATE_DELETED = 'deleted';
- const UPLOAD_STATE_REJECTED = 'rejected';
- const UPLOAD_STATE_ENCODING_ERROR = 'encoding_error';
+ const OAUTH2_TOKEN_ENDPOINT = "https://api.dailymotion.com/oauth/token";
+ const OAUTH2_AUTHORIZE_ENDPOINT = "https://api.dailymotion.com/oauth/authorize";
+ const ELEMENT_TYPE_VIDEO = 'video';
+ const CONTAINER_TYPE_PLAYLIST = 'playlist';
+ const AUTH_TYPE = 'OAuth2';
+ const AUTH_VIDEO_DURATION = 3600;
+ const AUTH_VIDEO_SIZE = 2147483648; //in bytes = 2GB
+ /**
+ * @see http://www.dailymotion.com/doc/api/obj-video.html
+ */
+ const UPLOAD_STATE_PROCESSING = 'processing';
+ const UPLOAD_STATE_READY = 'ready';
+ const UPLOAD_STATE_WAITING = 'waiting';
+ const UPLOAD_STATE_DONE = 'published';
+ const UPLOAD_STATE_DELETED = 'deleted';
+ const UPLOAD_STATE_REJECTED = 'rejected';
+ const UPLOAD_STATE_ENCODING_ERROR = 'encoding_error';
+ /**
+ *
+ * @var registryInterface
+ */
+ protected $registry;
- /**
- *
- * @var registryInterface
- */
- protected $registry;
+ /**
+ *
+ * @var DailymotionWithoutOauth2
+ */
+ protected $_api;
- /**
- *
- * @var DailymotionWithoutOauth2
- */
- protected $_api;
+ /**
+ * No transport for Dailymotion SDK
+ * Store oauth token here once you get it
+ * And pass it to the request as one of parameter
+ * @var string
+ */
+ private $oauth_token;
- /**
- * No transport for Dailymotion SDK
- * Store oauth token here once you get it
- * And pass it to the request as one of parameter
- * @var string
- */
- private $oauth_token;
-
- /**
- *
- * @return Array
- */
- public function connect()
- {
- $response = parent::connect();
- $this->oauth_token = $response["auth_token"]; //set token
-
- return $response;
- }
-
- /**
- *
- * @return Bridge_Api_Dailymotion
- */
- public function reconnect()
- {
- parent::reconnect();
- $this->set_transport_authentication_params();
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_user_id()
- {
- $result = $this->_api->call("/me", array('fields' => array('id')), $this->oauth_token);
-
- return $result["id"];
- }
-
- /**
- *
- * @return string
- */
- public function get_user_name()
- {
- $result = $this->_api->call("/me", array('fields' => array('username')), $this->oauth_token);
-
- return $result["username"];
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return 'Dailymotion';
- }
-
- /**
- * @todo
- * @return string
- */
- public function get_icon_url()
- {
- return '/skins/icons/dailymotion-small.gif';
- }
-
- /**
- * @todo
- * @return string
- */
- public function get_image_url()
- {
- return '/skins/icons/dailymotion-logo.png';
- }
-
- /**
- *
- * @return string
- */
- public function get_terms_url()
- {
- return 'https://www.dailymotion.com/legal/terms';
- }
-
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return 'http://www.dailymotion.com/';
- }
-
- /**
- *
- * @return string
- */
- public function get_infos()
- {
- return 'http://www.dailymotion.com/';
- }
-
- /**
- *
- * @return string
- */
- public function get_default_element_type()
- {
- return self::ELEMENT_TYPE_VIDEO;
- }
-
- /**
- *
- * @return string
- */
- public function get_default_container_type()
- {
- return self::CONTAINER_TYPE_PLAYLIST;
- }
-
- /**
- *
- * @return Array
- */
- public function get_element_types()
- {
- return array(self::ELEMENT_TYPE_VIDEO => _('Videos'));
- }
-
- /**
- *
- * @return Array
- */
- public function get_container_types()
- {
- return array(self::CONTAINER_TYPE_PLAYLIST => _('Playlists'));
- }
-
- /**
- *
- * @param string $type
- * @return string
- */
- public function get_object_class_from_type($type)
- {
- switch ($type)
+ /**
+ *
+ * @return Array
+ */
+ public function connect()
{
- case self::ELEMENT_TYPE_VIDEO:
- return self::OBJECT_CLASS_ELEMENT;
- break;
- case self::CONTAINER_TYPE_PLAYLIST:
- return self::OBJECT_CLASS_CONTAINER;
- break;
- default:
- throw new Exception('Unknown type');
- break;
+ $response = parent::connect();
+ $this->oauth_token = $response["auth_token"]; //set token
+
+ return $response;
}
- }
- /**
- * @todo Pagination system
- *
- * @see http://www.dailymotion.com/doc/api/advanced-api.html
- * @param string $object
- * @param int $offset_start
- * @param int $quantity
- * @return Bridge_Api_ElementCollection
- */
- public function list_elements($object, $offset_start = 0, $quantity = 10)
- {
- switch ($object)
+ /**
+ *
+ * @return Bridge_Api_Dailymotion
+ */
+ public function reconnect()
{
- case self::ELEMENT_TYPE_VIDEO:
+ parent::reconnect();
+ $this->set_transport_authentication_params();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_user_id()
+ {
+ $result = $this->_api->call("/me", array('fields' => array('id')), $this->oauth_token);
+
+ return $result["id"];
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_user_name()
+ {
+ $result = $this->_api->call("/me", array('fields' => array('username')), $this->oauth_token);
+
+ return $result["username"];
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return 'Dailymotion';
+ }
+
+ /**
+ * @todo
+ * @return string
+ */
+ public function get_icon_url()
+ {
+ return '/skins/icons/dailymotion-small.gif';
+ }
+
+ /**
+ * @todo
+ * @return string
+ */
+ public function get_image_url()
+ {
+ return '/skins/icons/dailymotion-logo.png';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_terms_url()
+ {
+ return 'https://www.dailymotion.com/legal/terms';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return 'http://www.dailymotion.com/';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_infos()
+ {
+ return 'http://www.dailymotion.com/';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_element_type()
+ {
+ return self::ELEMENT_TYPE_VIDEO;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_container_type()
+ {
+ return self::CONTAINER_TYPE_PLAYLIST;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_element_types()
+ {
+ return array(self::ELEMENT_TYPE_VIDEO => _('Videos'));
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_container_types()
+ {
+ return array(self::CONTAINER_TYPE_PLAYLIST => _('Playlists'));
+ }
+
+ /**
+ *
+ * @param string $type
+ * @return string
+ */
+ public function get_object_class_from_type($type)
+ {
+ switch ($type) {
+ case self::ELEMENT_TYPE_VIDEO:
+ return self::OBJECT_CLASS_ELEMENT;
+ break;
+ case self::CONTAINER_TYPE_PLAYLIST:
+ return self::OBJECT_CLASS_CONTAINER;
+ break;
+ default:
+ throw new Exception('Unknown type');
+ break;
+ }
+ }
+
+ /**
+ * @todo Pagination system
+ *
+ * @see http://www.dailymotion.com/doc/api/advanced-api.html
+ * @param string $object
+ * @param int $offset_start
+ * @param int $quantity
+ * @return Bridge_Api_ElementCollection
+ */
+ public function list_elements($object, $offset_start = 0, $quantity = 10)
+ {
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
- $result = $this->_api->call('/me/videos', array('fields' => array(
- 'created_time'
- , 'description'
- , 'duration'
- , 'modified_time'
- , 'private'
- , 'rating'
- , 'ratings_total'
- , 'thumbnail_small_url'
- , 'thumbnail_medium_url'
- , 'title'
- , 'url'
- , 'views_total'
- , 'id'
- , 'channel'
- ),
- 'page' => !$offset_start ? 1 : $offset_start,
- 'limit' => $quantity), $this->oauth_token);
+ $result = $this->_api->call('/me/videos', array('fields' => array(
+ 'created_time'
+ , 'description'
+ , 'duration'
+ , 'modified_time'
+ , 'private'
+ , 'rating'
+ , 'ratings_total'
+ , 'thumbnail_small_url'
+ , 'thumbnail_medium_url'
+ , 'title'
+ , 'url'
+ , 'views_total'
+ , 'id'
+ , 'channel'
+ ),
+ 'page' => ! $offset_start ? 1 : $offset_start,
+ 'limit' => $quantity), $this->oauth_token);
+ $element_collection = new Bridge_Api_ElementCollection();
+ $element_collection->set_items_per_page($result["limit"]);
+
+ $total = sizeof($result["list"]);
+ $current_page = $result["page"];
+ $total_page = null;
+
+ $element_collection->set_total_items($total);
+ $element_collection->set_current_page($current_page);
+ $element_collection->set_total_page($total_page);
+
+ foreach ($result["list"] as $entry) {
+ $element_collection->add_element(new Bridge_Api_Dailymotion_Element($entry, $object));
+ }
+
+ return $element_collection;
+ break;
+
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
+ }
+ }
+
+ /**
+ * @Todo recupérer la thumbnail d'une playlist
+ *
+ * @param string $object
+ * @param int $offset_start
+ * @param int $quantity
+ * @return Bridge_Api_ContainerCollection
+ */
+ public function list_containers($object, $offset_start = 0, $quantity = 10)
+ {
+ switch ($object) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+
+ $username = $this->get_user_name();
+
+ $params = array('fields' => array(
+ 'description'
+ , 'id'
+ , 'name'
+ ),
+ 'page' => ! $offset_start ? 1 : $offset_start);
+ //add quantity
+ if ( ! ! $quantity) {
+ $params["limit"] = $quantity;
+ }
+ $url = sprintf('/me/%ss', $object);
+ $result = $this->_api->call($url, $params, $this->oauth_token);
+
+ $container_collection = new Bridge_Api_ContainerCollection();
+
+ $container_collection->set_items_per_page($result["limit"]);
+
+ $total = sizeof($result["list"]);
+ $current_page = $result["limit"];
+ $total_page = null;
+
+ $container_collection->set_total_items($total);
+ $container_collection->set_current_page($current_page);
+ $container_collection->set_total_page($total_page);
+
+ foreach ($result['list'] as $entry) {
+ //get 1st image
+ $list_element = $this->list_containers_content($object, $entry['id'], array('thumbnail_medium_url'), 1);
+ $first_element = array_shift($list_element->get_elements());
+ $thumbnail = $first_element instanceof Bridge_Api_Dailymotion_Element ? $first_element->get_thumbnail() : '';
+
+ $url = $this->get_url_playlist($entry['id'], $entry['name'], $username);
+
+ $container_collection->add_element(new Bridge_Api_Dailymotion_Container($entry, $object, $thumbnail, $url));
+ }
+
+ return $container_collection;
+ break;
+
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @see http://www.dailymotion.com/doc/api/obj-video.html
+ * @param string $object
+ * @param string $object_id
+ * @param Request $request
+ * @return Bridge_Api_Dailymotion
+ */
+ public function update_element($object, $object_id, Array $datas)
+ {
+ $required_fields = array("title", "description", "category", "privacy");
+ foreach ($required_fields as $field) {
+ if ( ! array_key_exists($field, $datas))
+ throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
+ }
+
+ $params = array(
+ 'title' => $datas["title"]
+ , 'description' => $datas["description"]
+ , 'channel' => $datas["category"]
+ , 'private' => ! $datas["private"]
+ );
+
+ if ( ! $this->is_valid_object_id($object_id))
+ throw new Bridge_Exception_InvalidObjectId($object_id);
+
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO :
+ $url = sprintf("POST /video/%s", $object_id);
+ $result = $this->_api->call($url, $params, $this->oauth_token);
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ * @see http://www.dailymotion.com/doc/api/obj-playlist.html
+ * @param string $container_type
+ * @param Request $request
+ * @return Bridge_Api_Dailymotion_Container
+ */
+ public function create_container($container_type, Request $request)
+ {
+ switch ($container_type) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $url = sprintf("POST /me/%ss", $container_type);
+ $playlist = $this->_api->call($url, array('name' => $request->get("name")), $this->oauth_token);
+
+ return $playlist["id"];
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
+ }
+ }
+
+ /**
+ * @see http://www.dailymotion.com/doc/api/obj-playlist.html
+ * @param type $element_type
+ * @param type $element_id
+ * @param type $destination
+ * @param type $container_id
+ * @return Bridge_Api_Dailymotion_Container
+ */
+ public function add_element_to_container($element_type, $element_id, $destination, $container_id)
+ {
+ switch ($element_type) {
+ case self::ELEMENT_TYPE_VIDEO:
+ switch ($destination) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+
+ $array = array($element_id);
+ //get containers content
+ foreach ($this->list_containers_content($destination, $container_id, array('id'))->get_elements() as $element) {
+ $array[] = $element->get_id();
+ }
+
+ $array = array_unique($array);
+
+ $url = sprintf('POST /%s/%s/%ss', $destination, $container_id, $element_type);
+
+ $result = $this->_api->call($url, array('ids' => implode(",", $array)), $this->oauth_token);
+
+ return $this->get_container_from_id(self::CONTAINER_TYPE_PLAYLIST, $container_id);
+ break;
+ default:
+ throw new Bridge_Exception_ContainerUnknown('Unknown element ' . $container);
+ break;
+ }
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown container ' . $element_type);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @return Void
+ */
+ public function delete_object($object, $object_id)
+ {
+ $url = sprintf("DELETE /%s/%s", $object, $object_id);
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ $result = $this->_api->call($url, array(), $this->oauth_token);
+ break;
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $result = $this->_api->call($url, array(), $this->oauth_token);
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
+ break;
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @return Closure
+ */
+ public function acceptable_records()
+ {
+ return function (record_adapter &$record) {
+ return $record->get_type() === 'video';
+ };
+ }
+
+ /**
+ *
+ * @param string $element_id
+ * @return Array
+ */
+ public function get_element_status(Bridge_Element $element)
+ {
+ $url = sprintf("/%s/%s", $element->get_type(), $element->get_dist_id());
+
+ $result = $this->_api->call($url, array('fields' => array(
+ 'status'
+ )), $this->oauth_token);
+
+ return $result["status"];
+ }
+
+ /**
+ *
+ * @param string $status
+ * @return string
+ */
+ public function map_connector_to_element_status($status)
+ {
+ switch ($status) {
+ case self::UPLOAD_STATE_PROCESSING:
+ return Bridge_Element::STATUS_PROCESSING_SERVER;
+ break;
+ case self::UPLOAD_STATE_DONE:
+ case self::UPLOAD_STATE_READY:
+ return Bridge_Element::STATUS_DONE;
+ break;
+ case self::UPLOAD_STATE_DELETED:
+ case self::UPLOAD_STATE_ENCODING_ERROR:
+ case self::UPLOAD_STATE_REJECTED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ default:
+ return null;
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $connector_status
+ * @return string
+ */
+ public function get_error_message_from_status($connector_status)
+ {
+ switch ($connector_status) {
+ case self::UPLOAD_STATE_DELETED:
+ return _('La video a ete supprimee');
+ break;
+ case self::UPLOAD_STATE_REJECTED:
+ return _('La video a ete rejetee');
+ break;
+ case self::UPLOAD_STATE_ENCODING_ERROR:
+ return _('Erreur d\'encodage');
+ break;
+ case self::UPLOAD_STATE_PROCESSING:
+ return _('En cours d\'encodage');
+ break;
+ default:
+ return '';
+ break;
+ case self::UPLOAD_STATE_DONE:
+ return _('OK');
+ break;
+ }
+ }
+
+ /**
+ * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
+ * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
+ *
+ * @param Exception $e
+ * @return Void
+ */
+ public function handle_exception(Exception &$e)
+ {
+ if ($e instanceof DailymotionAuthException) {
+ $e = new Bridge_Exception_ActionAuthNeedReconnect($e->getMessage());
+ } elseif ($e instanceof DailymotionApiException || $e instanceof DailymotionAuthRequiredException) {
+ $e = new Exception($e->getMessage(), $e->getCode());
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param record_adapter $record
+ * @param array $options
+ * @return string
+ */
+ public function upload(record_adapter &$record, array $options = array())
+ {
+ switch ($record->get_type()) {
+ case self::ELEMENT_TYPE_VIDEO :
+ $url_file = $this->_api->uploadFile($record->get_hd_file()->getRealPath(), $this->oauth_token);
+ $options = array_merge(array('url' => $url_file), $options);
+ $video = $this->_api->call('POST /me/videos', $options, $this->oauth_token);
+
+ return $video["id"];
+ break;
+ default:
+ throw new Bridge_Exception_InvalidRecordType('Unknown format');
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $element_id
+ * @return Bridge_Api_Dailymotion_Element
+ */
+ public function get_element_from_id($element_id, $object)
+ {
+ $url = sprintf("/%s/%s", $object, $element_id);
+
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ $entry = $this->_api->call($url, array('fields' => array(
+ 'created_time'
+ , 'description'
+ , 'duration'
+ , 'modified_time'
+ , 'private'
+ , 'rating'
+ , 'ratings_total'
+ , 'thumbnail_small_url'
+ , 'thumbnail_medium_url'
+ , 'title'
+ , 'url'
+ , 'views_total'
+ , 'id'
+ , 'channel'
+ , 'tags'
+ )), $this->oauth_token);
+
+ return new Bridge_Api_Dailymotion_Element($entry, $object);
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $element_id
+ * @return Bridge_Api_Dailymotion_Container
+ */
+ public function get_container_from_id($object, $element_id)
+ {
+ $url = sprintf("/%s/%s", $object, $element_id);
+
+ switch ($object) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $entry = $this->_api->call($url, array('fields' => array(
+ 'description'
+ , 'id'
+ , 'name'
+ )), $this->oauth_token);
+ /**
+ * @todo Retieve thumb
+ */
+ return new Bridge_Api_Dailymotion_Container($entry, $object, '');
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ public function is_configured()
+ {
+ if ( ! $this->registry->get('GV_dailymotion_api'))
+ return false;
+
+ if (trim($this->registry->get('GV_dailymotion_client_id')) === '')
+ return false;
+
+ if (trim($this->registry->get('GV_dailymotion_client_secret')) === '')
+ return false;
+
+ return true;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Dailymotion
+ */
+ protected function set_auth_params()
+ {
+ $this->_auth->set_parameters(
+ array(
+ 'client_id' => $this->registry->get('GV_dailymotion_client_id')
+ , 'client_secret' => $this->registry->get('GV_dailymotion_client_secret')
+ , 'redirect_uri' => Bridge_Api::generate_callback_url($this->registry, $this->get_name())
+ , 'scope' => ''
+ , 'response_type' => 'code'
+ , 'token_endpoint' => self::OAUTH2_TOKEN_ENDPOINT
+ , 'auth_endpoint' => self::OAUTH2_AUTHORIZE_ENDPOINT
+ )
+ );
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Dailymotion
+ */
+ protected function initialize_transport()
+ {
+ $this->_api = new DailymotionWithoutOauth2();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Dailymotion
+ */
+ protected function set_transport_authentication_params()
+ {
+ if ($this->_auth->is_connected()) {
+ $signatures = $this->_auth->get_auth_signatures();
+ $this->oauth_token = $signatures['auth_token'];
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_category_list()
+ {
+ $locale = explode("_", $this->locale);
+ $result = $this->_api->call("/channels", array("language" => $locale[0]));
+
+ return $result["list"];
+ }
+
+ /**
+ * @Override get_auth_url
+ * @param type $supp_params
+ * @return type
+ */
+ public function get_auth_url($supp_params = array())
+ {
+ $params = array_merge(array('display' => 'popup', 'scope' => 'read write delete manage_playlists'), $supp_params);
+
+ return parent::get_auth_url($params);
+ }
+
+ /**
+ *
+ * @param string $id
+ * @return Bridge_Api_ElementCollection
+ */
+ protected function list_containers_content($object, $id, Array $fields = array(), $iteration = 0)
+ {
+ $url = sprintf("/%s/%s/videos", $object, $id);
+ $result = $this->_api->call($url, array('fields' => $fields), $this->oauth_token);
+
$element_collection = new Bridge_Api_ElementCollection();
$element_collection->set_items_per_page($result["limit"]);
@@ -262,722 +750,197 @@ class Bridge_Api_Dailymotion extends Bridge_Api_Abstract implements Bridge_Api_I
$element_collection->set_current_page($current_page);
$element_collection->set_total_page($total_page);
- foreach ($result["list"] as $entry)
- {
- $element_collection->add_element(new Bridge_Api_Dailymotion_Element($entry, $object));
+ $i = 0;
+ foreach ($result["list"] as $entry) {
+ $i ++;
+ $element_collection->add_element(new Bridge_Api_Dailymotion_Element($entry, $object));
+ if ($i == $iteration)
+ break;
}
return $element_collection;
- break;
-
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
}
- }
- /**
- * @Todo recupérer la thumbnail d'une playlist
- *
- * @param string $object
- * @param int $offset_start
- * @param int $quantity
- * @return Bridge_Api_ContainerCollection
- */
- public function list_containers($object, $offset_start = 0, $quantity = 10)
- {
- switch ($object)
+ /**
+ *
+ * @param string $id
+ * @param string $playlistname
+ * @param string $username
+ * @return string
+ */
+ protected function get_url_playlist($id, $playlistname, $username)
{
- case self::CONTAINER_TYPE_PLAYLIST:
-
- $username = $this->get_user_name();
-
- $params = array('fields' => array(
- 'description'
- , 'id'
- , 'name'
- ),
- 'page' => !$offset_start ? 1 : $offset_start);
- //add quantity
- if (!!$quantity)
- {
- $params["limit"] = $quantity;
- }
- $url = sprintf('/me/%ss', $object);
- $result = $this->_api->call($url, $params, $this->oauth_token);
-
- $container_collection = new Bridge_Api_ContainerCollection();
-
- $container_collection->set_items_per_page($result["limit"]);
-
- $total = sizeof($result["list"]);
- $current_page = $result["limit"];
- $total_page = null;
-
- $container_collection->set_total_items($total);
- $container_collection->set_current_page($current_page);
- $container_collection->set_total_page($total_page);
-
- foreach ($result['list'] as $entry)
- {
- //get 1st image
- $list_element = $this->list_containers_content($object, $entry['id'], array('thumbnail_medium_url'), 1);
- $first_element = array_shift($list_element->get_elements());
- $thumbnail = $first_element instanceof Bridge_Api_Dailymotion_Element ? $first_element->get_thumbnail() : '';
-
- $url = $this->get_url_playlist($entry['id'], $entry['name'], $username);
-
- $container_collection->add_element(new Bridge_Api_Dailymotion_Container($entry, $object, $thumbnail, $url));
- }
-
- return $container_collection;
- break;
-
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
+ return sprintf("%s/playlist/%s_%s_%s/", $this->get_url(), $id, $username, $playlistname);
}
- }
- /**
- *
- * @see http://www.dailymotion.com/doc/api/obj-video.html
- * @param string $object
- * @param string $object_id
- * @param Request $request
- * @return Bridge_Api_Dailymotion
- */
- public function update_element($object, $object_id, Array $datas)
- {
- $required_fields = array("title", "description", "category", "privacy" );
- foreach ($required_fields as $field)
+ /**
+ * @todo implement in bridge_api°interface
+ *
+ * Check if data uploaded via the current connector is conform
+ * @param Request $request
+ * @param record_adapter $record
+ * @return array
+ */
+ public function check_upload_constraints(Array $datas, record_adapter $record)
{
- if (!array_key_exists($field, $datas))
- throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
- }
+ $errors = $this->check_record_constraints($record);
+ $check = function($field) use (&$errors, $datas, $record) {
+ $key = $record->get_serialize_key();
+ $required = ! ! $field["required"];
+ $name = $field["name"];
+ $length = (int) $field["length"];
+ $length_min = (int) $field["length_min"];
- $params = array(
- 'title' => $datas["title"]
- , 'description' => $datas["description"]
- , 'channel' => $datas["category"]
- , 'private' => !$datas["private"]
- );
- if (!$this->is_valid_object_id($object_id))
- throw new Bridge_Exception_InvalidObjectId($object_id);
-
- switch ($object)
- {
- case self::ELEMENT_TYPE_VIDEO :
- $url = sprintf("POST /video/%s", $object_id);
- $result = $this->_api->call($url, $params, $this->oauth_token);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
- }
-
- return $this;
- }
-
- /**
- *
- * @see http://www.dailymotion.com/doc/api/obj-playlist.html
- * @param string $container_type
- * @param Request $request
- * @return Bridge_Api_Dailymotion_Container
- */
- public function create_container($container_type, Request $request)
- {
- switch ($container_type)
- {
- case self::CONTAINER_TYPE_PLAYLIST:
- $url = sprintf("POST /me/%ss", $container_type);
- $playlist = $this->_api->call($url, array('name' => $request->get("name")), $this->oauth_token);
-
- return $playlist["id"];
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
- }
- }
-
- /**
- * @see http://www.dailymotion.com/doc/api/obj-playlist.html
- * @param type $element_type
- * @param type $element_id
- * @param type $destination
- * @param type $container_id
- * @return Bridge_Api_Dailymotion_Container
- */
- public function add_element_to_container($element_type, $element_id, $destination, $container_id)
- {
- switch ($element_type)
- {
- case self::ELEMENT_TYPE_VIDEO:
- switch ($destination)
- {
- case self::CONTAINER_TYPE_PLAYLIST:
-
- $array = array($element_id);
- //get containers content
- foreach ($this->list_containers_content($destination, $container_id, array('id'))->get_elements() as $element)
- {
- $array[] = $element->get_id();
- }
-
- $array = array_unique($array);
-
- $url = sprintf('POST /%s/%s/%ss', $destination, $container_id, $element_type);
-
- $result = $this->_api->call($url, array('ids' => implode(",", $array)), $this->oauth_token);
-
- return $this->get_container_from_id(self::CONTAINER_TYPE_PLAYLIST, $container_id);
- break;
- default:
- throw new Bridge_Exception_ContainerUnknown('Unknown element ' . $container);
- break;
- }
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown container ' . $element_type);
- break;
- }
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @return Void
- */
- public function delete_object($object, $object_id)
- {
- $url = sprintf("DELETE /%s/%s", $object, $object_id);
- switch ($object)
- {
- case self::ELEMENT_TYPE_VIDEO:
- $result = $this->_api->call($url, array(), $this->oauth_token);
- break;
- case self::CONTAINER_TYPE_PLAYLIST:
- $result = $this->_api->call($url, array(), $this->oauth_token);
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
- break;
- }
-
- return;
- }
-
- /**
- *
- * @return Closure
- */
- public function acceptable_records()
- {
- return function (record_adapter &$record)
- {
- return $record->get_type() === 'video';
+ if ( ! isset($datas[$name]) || trim($datas[$name]) === '') {
+ if ($required)
+ $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
+ }
+ else {
+ if ($length != 0 && mb_strlen($datas[$name]) > $length)
+ $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ if ($length_min != 0 && mb_strlen($datas[$name]) < $length_min)
+ $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop court %s caracteres min"), $length_min);
+ }
};
- }
- /**
- *
- * @param string $element_id
- * @return Array
- */
- public function get_element_status(Bridge_Element $element)
- {
- $url = sprintf("/%s/%s", $element->get_type(), $element->get_dist_id());
+ array_map($check, $this->get_fields());
- $result = $this->_api->call($url, array('fields' => array(
- 'status'
- )), $this->oauth_token);
-
- return $result["status"];
- }
-
- /**
- *
- * @param string $status
- * @return string
- */
- public function map_connector_to_element_status($status)
- {
- switch ($status)
- {
- case self::UPLOAD_STATE_PROCESSING:
- return Bridge_Element::STATUS_PROCESSING_SERVER;
- break;
- case self::UPLOAD_STATE_DONE:
- case self::UPLOAD_STATE_READY:
- return Bridge_Element::STATUS_DONE;
- break;
- case self::UPLOAD_STATE_DELETED:
- case self::UPLOAD_STATE_ENCODING_ERROR:
- case self::UPLOAD_STATE_REJECTED:
- return Bridge_Element::STATUS_ERROR;
- break;
- default:
- return null;
- break;
- }
- }
-
- /**
- *
- * @param string $connector_status
- * @return string
- */
- public function get_error_message_from_status($connector_status)
- {
- switch ($connector_status)
- {
- case self::UPLOAD_STATE_DELETED:
- return _('La video a ete supprimee');
- break;
- case self::UPLOAD_STATE_REJECTED:
- return _('La video a ete rejetee');
- break;
- case self::UPLOAD_STATE_ENCODING_ERROR:
- return _('Erreur d\'encodage');
- break;
- case self::UPLOAD_STATE_PROCESSING:
- return _('En cours d\'encodage');
- break;
- default:
- return '';
- break;
- case self::UPLOAD_STATE_DONE:
- return _('OK');
- break;
- }
- }
-
- /**
- * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
- * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
- *
- * @param Exception $e
- * @return Void
- */
- public function handle_exception(Exception &$e)
- {
- if ($e instanceof DailymotionAuthException)
- {
- $e = new Bridge_Exception_ActionAuthNeedReconnect($e->getMessage());
- }
- elseif ($e instanceof DailymotionApiException || $e instanceof DailymotionAuthRequiredException)
- {
- $e = new Exception($e->getMessage(), $e->getCode());
+ return $errors;
}
- return;
- }
-
- /**
- *
- * @param record_adapter $record
- * @param array $options
- * @return string
- */
- public function upload(record_adapter &$record, array $options = array())
- {
- switch ($record->get_type())
+ public function check_update_constraints(Array $datas)
{
- case self::ELEMENT_TYPE_VIDEO :
- $url_file = $this->_api->uploadFile($record->get_hd_file()->getRealPath(), $this->oauth_token);
- $options = array_merge(array('url' => $url_file), $options);
- $video = $this->_api->call('POST /me/videos', $options, $this->oauth_token);
+ $errors = array();
+ $check = function($field) use (&$errors, $datas) {
+ $required = ! ! $field["required"];
+ $name = $field["name"];
+ $length = (int) $field["length"];
+ $length_min = (int) $field["length_min"];
- return $video["id"];
- break;
- default:
- throw new Bridge_Exception_InvalidRecordType('Unknown format');
- break;
+
+ if ( ! isset($datas[$name]) || trim($datas[$name]) === '') {
+ if ($required)
+ $errors[$name] = _("Ce champ est obligatoire");
+ }
+ else {
+ if ($length != 0 && mb_strlen($datas[$name]) > $length)
+ $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ if ($length_min != 0 && mb_strlen($datas[$name]) < $length_min)
+ $errors[$name] = sprintf(_("Ce champ est trop court %s caracteres min"), $length_min);
+ }
+ };
+
+ array_map($check, $this->get_fields());
+
+ return $errors;
}
- }
- /**
- *
- * @param string $object
- * @param string $element_id
- * @return Bridge_Api_Dailymotion_Element
- */
- public function get_element_from_id($element_id, $object)
- {
- $url = sprintf("/%s/%s", $object, $element_id);
-
- switch ($object)
+ /**
+ * Returns dats needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_upload_datas(Request $request, record_adapter $record)
{
- case self::ELEMENT_TYPE_VIDEO:
- $entry = $this->_api->call($url, array('fields' => array(
- 'created_time'
- , 'description'
- , 'duration'
- , 'modified_time'
- , 'private'
- , 'rating'
- , 'ratings_total'
- , 'thumbnail_small_url'
- , 'thumbnail_medium_url'
- , 'title'
- , 'url'
- , 'views_total'
- , 'id'
- , 'channel'
- , 'tags'
- )), $this->oauth_token);
+ $key = $record->get_serialize_key();
+ $datas = array(
+ 'title' => $request->get('title_' . $key),
+ 'description' => $request->get('description_' . $key),
+ 'category' => $request->get('category_' . $key),
+ 'tag' => $request->get('tags_' . $key),
+ 'privacy' => $request->get('privacy_' . $key),
+ );
- return new Bridge_Api_Dailymotion_Element($entry, $object);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
+ return $datas;
}
- }
- /**
- *
- * @param string $object
- * @param string $element_id
- * @return Bridge_Api_Dailymotion_Container
- */
- public function get_container_from_id($object, $element_id)
- {
- $url = sprintf("/%s/%s", $object, $element_id);
-
- switch ($object)
+ /**
+ * Returns datas needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_update_datas(Request $request)
{
- case self::CONTAINER_TYPE_PLAYLIST:
- $entry = $this->_api->call($url, array('fields' => array(
- 'description'
- , 'id'
- , 'name'
- )), $this->oauth_token);
- /**
- * @todo Retieve thumb
- */
+ $datas = array(
+ 'title' => $request->get('modif_title'),
+ 'description' => $request->get('modif_description'),
+ 'category' => $request->get('modif_category'),
+ 'tags' => $request->get('modif_tags'),
+ 'privacy' => $request->get('modif_privacy'),
+ );
- return new Bridge_Api_Dailymotion_Container($entry, $object, '');
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
+ return $datas;
}
- }
- public function is_configured()
- {
- if (!$this->registry->get('GV_dailymotion_api'))
+ /**
+ * @todo implements in bridge_api_interface
+ * &todo write test
+ * Tell if the current connector can upload multiple file
+ * @return boolean
+ */
+ public function is_multiple_upload()
+ {
+ return false;
+ }
- return false;
+ /**
+ *
+ * @param record_adapter $record
+ * @return array
+ */
+ private function check_record_constraints(record_adapter $record)
+ {
+ $errors = array();
+ if ( ! $record->get_hd_file() instanceof SplFileObject)
+ $errors["file_size"] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
- if (trim($this->registry->get('GV_dailymotion_client_id')) === '')
+ if ($record->get_duration() > self::AUTH_VIDEO_DURATION)
+ $errors["duration"] = sprintf(_("La taille maximale d'une video est de %d minutes."), self::AUTH_VIDEO_DURATION / 60);
- return false;
+ if ($record->get_technical_infos('size') > self::AUTH_VIDEO_SIZE)
+ $errors["size"] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_VIDEO_SIZE));
- if (trim($this->registry->get('GV_dailymotion_client_secret')) === '')
+ return $errors;
+ }
- return false;
-
- return true;
- }
-
- /**
- *
- * @return Bridge_Api_Dailymotion
- */
- protected function set_auth_params()
- {
- $this->_auth->set_parameters(
+ /**
+ *
+ * @return array
+ */
+ private function get_fields()
+ {
+ return array(
array(
- 'client_id' => $this->registry->get('GV_dailymotion_client_id')
- , 'client_secret' => $this->registry->get('GV_dailymotion_client_secret')
- , 'redirect_uri' => Bridge_Api::generate_callback_url($this->registry, $this->get_name())
- , 'scope' => ''
- , 'response_type' => 'code'
- , 'token_endpoint' => self::OAUTH2_TOKEN_ENDPOINT
- , 'auth_endpoint' => self::OAUTH2_AUTHORIZE_ENDPOINT
+ 'name' => 'title',
+ 'length' => '255',
+ 'length_min' => '5',
+ 'required' => true
)
- );
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Dailymotion
- */
- protected function initialize_transport()
- {
- $this->_api = new DailymotionWithoutOauth2();
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Dailymotion
- */
- protected function set_transport_authentication_params()
- {
- if ($this->_auth->is_connected())
- {
- $signatures = $this->_auth->get_auth_signatures();
- $this->oauth_token = $signatures['auth_token'];
+ , array(
+ 'name' => 'description',
+ 'length' => '2000',
+ 'length_min' => '0',
+ 'required' => false
+ )
+ , array(
+ 'name' => 'tags',
+ 'length' => '150',
+ 'length_min' => '0',
+ 'required' => false
+ )
+ , array(
+ 'name' => 'privacy',
+ 'length' => '0',
+ 'length_min' => '0',
+ 'required' => true
+ )
+ , array(
+ 'name' => 'category',
+ 'length' => '0',
+ 'length_min' => '0',
+ 'required' => true
+ )
+ );
}
-
- return $this;
- }
-
- /**
- *
- * @return Array
- */
- public function get_category_list()
- {
- $locale = explode("_", $this->locale);
- $result = $this->_api->call("/channels", array("language" => $locale[0]));
-
- return $result["list"];
- }
-
- /**
- * @Override get_auth_url
- * @param type $supp_params
- * @return type
- */
- public function get_auth_url($supp_params = array())
- {
- $params = array_merge(array('display' => 'popup', 'scope' => 'read write delete manage_playlists'), $supp_params);
-
- return parent::get_auth_url($params);
- }
-
-
- /**
- *
- * @param string $id
- * @return Bridge_Api_ElementCollection
- */
- protected function list_containers_content($object, $id, Array $fields = array(), $iteration = 0)
- {
- $url = sprintf("/%s/%s/videos", $object, $id);
- $result = $this->_api->call($url, array('fields' => $fields), $this->oauth_token);
-
- $element_collection = new Bridge_Api_ElementCollection();
- $element_collection->set_items_per_page($result["limit"]);
-
- $total = sizeof($result["list"]);
- $current_page = $result["page"];
- $total_page = null;
-
- $element_collection->set_total_items($total);
- $element_collection->set_current_page($current_page);
- $element_collection->set_total_page($total_page);
-
- $i = 0;
- foreach ($result["list"] as $entry)
- {
- $i++;
- $element_collection->add_element(new Bridge_Api_Dailymotion_Element($entry, $object));
- if ($i == $iteration)
- break;
- }
-
- return $element_collection;
- }
-
- /**
- *
- * @param string $id
- * @param string $playlistname
- * @param string $username
- * @return string
- */
- protected function get_url_playlist($id, $playlistname, $username)
- {
- return sprintf("%s/playlist/%s_%s_%s/", $this->get_url(), $id, $username, $playlistname);
- }
-
- /**
- * @todo implement in bridge_api°interface
- *
- * Check if data uploaded via the current connector is conform
- * @param Request $request
- * @param record_adapter $record
- * @return array
- */
- public function check_upload_constraints(Array $datas, record_adapter $record)
- {
- $errors = $this->check_record_constraints($record);
- $check = function($field) use (&$errors, $datas, $record)
- {
- $key = $record->get_serialize_key();
- $required = !!$field["required"];
- $name = $field["name"];
- $length = (int) $field["length"];
- $length_min = (int) $field["length_min"];
-
-
- if (!isset($datas[$name]) || trim($datas[$name]) === '')
- {
- if ($required)
- $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
- }
- else
- {
- if ($length != 0 && mb_strlen($datas[$name]) > $length)
- $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- if ($length_min != 0 && mb_strlen($datas[$name]) < $length_min)
- $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop court %s caracteres min"), $length_min);
- }
- };
-
- array_map($check, $this->get_fields());
-
- return $errors;
- }
-
- public function check_update_constraints(Array $datas)
- {
- $errors = array();
- $check = function($field) use (&$errors, $datas)
- {
- $required = !!$field["required"];
- $name = $field["name"];
- $length = (int) $field["length"];
- $length_min = (int) $field["length_min"];
-
-
- if (!isset($datas[$name]) || trim($datas[$name]) === '')
- {
- if ($required)
- $errors[$name] = _("Ce champ est obligatoire");
- }
- else
- {
- if ($length != 0 && mb_strlen($datas[$name]) > $length)
- $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- if ($length_min != 0 && mb_strlen($datas[$name]) < $length_min)
- $errors[$name] = sprintf(_("Ce champ est trop court %s caracteres min"), $length_min);
- }
- };
-
- array_map($check, $this->get_fields());
-
- return $errors;
- }
-
- /**
- * Returns dats needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_upload_datas(Request $request, record_adapter $record)
- {
- $key = $record->get_serialize_key();
- $datas = array(
- 'title' => $request->get('title_' . $key),
- 'description' => $request->get('description_' . $key),
- 'category' => $request->get('category_' . $key),
- 'tag' => $request->get('tags_' . $key),
- 'privacy' => $request->get('privacy_' . $key),
- );
-
- return $datas;
- }
-
- /**
- * Returns datas needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_update_datas(Request $request)
- {
- $datas = array(
- 'title' => $request->get('modif_title'),
- 'description' => $request->get('modif_description'),
- 'category' => $request->get('modif_category'),
- 'tags' => $request->get('modif_tags'),
- 'privacy' => $request->get('modif_privacy'),
- );
-
- return $datas;
- }
-
- /**
- * @todo implements in bridge_api_interface
- * &todo write test
- * Tell if the current connector can upload multiple file
- * @return boolean
- */
- public function is_multiple_upload()
- {
- return false;
- }
-
- /**
- *
- * @param record_adapter $record
- * @return array
- */
- private function check_record_constraints(record_adapter $record)
- {
- $errors = array();
- if (!$record->get_hd_file() instanceof SplFileObject)
- $errors["file_size"] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
-
- if ($record->get_duration() > self::AUTH_VIDEO_DURATION)
- $errors["duration"] = sprintf(_("La taille maximale d'une video est de %d minutes."), self::AUTH_VIDEO_DURATION / 60);
-
- if ($record->get_technical_infos('size') > self::AUTH_VIDEO_SIZE)
- $errors["size"] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_VIDEO_SIZE));
-
- return $errors;
- }
-
- /**
- *
- * @return array
- */
- private function get_fields()
- {
- return array(
- array(
- 'name' => 'title',
- 'length' => '255',
- 'length_min' => '5',
- 'required' => true
- )
- , array(
- 'name' => 'description',
- 'length' => '2000',
- 'length_min' => '0',
- 'required' => false
- )
- , array(
- 'name' => 'tags',
- 'length' => '150',
- 'length_min' => '0',
- 'required' => false
- )
- , array(
- 'name' => 'privacy',
- 'length' => '0',
- 'length_min' => '0',
- 'required' => true
- )
- , array(
- 'name' => 'category',
- 'length' => '0',
- 'length_min' => '0',
- 'required' => true
- )
- );
- }
-
}
diff --git a/lib/classes/Bridge/Api/Dailymotion/Container.class.php b/lib/classes/Bridge/Api/Dailymotion/Container.class.php
index d40265c2ec..1e45077b7d 100644
--- a/lib/classes/Bridge/Api/Dailymotion/Container.class.php
+++ b/lib/classes/Bridge/Api/Dailymotion/Container.class.php
@@ -12,137 +12,136 @@
*/
class Bridge_Api_Dailymotion_Container implements Bridge_Api_ContainerInterface
{
+ /**
+ *
+ * @var Array
+ */
+ protected $entry;
- /**
- *
- * @var Array
- */
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var string
+ */
+ protected $thumbnail;
- /**
- *
- * @var string
- */
- protected $thumbnail;
+ /**
+ *
+ * @param array $entry
+ * @param type $type
+ * @param type $thumbnail
+ * @return Bridge_Api_Dailymotion_Container
+ */
+ public function __construct(Array $entry, $type, $thumbnail = '', $url = '')
+ {
+ $this->entry = $entry;
+ $this->type = $type;
+ $this->thumbnail = $thumbnail;
+ $this->url = $url;
- /**
- *
- * @param array $entry
- * @param type $type
- * @param type $thumbnail
- * @return Bridge_Api_Dailymotion_Container
- */
- public function __construct(Array $entry, $type, $thumbnail = '', $url = '')
- {
- $this->entry = $entry;
- $this->type = $type;
- $this->thumbnail = $thumbnail;
- $this->url = $url;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return mixed
+ */
+ private function get($key, $default = null)
+ {
+ return isset($this->entry[$key]) ? $this->entry[$key] : $default;
+ }
- /**
- *
- * @return mixed
- */
- private function get($key, $default = null)
- {
- return isset($this->entry[$key]) ? $this->entry[$key] : $default;
- }
+ /**
+ *
+ * @return void
+ */
+ public function get_created_on()
+ {
+ return;
+ }
- /**
- *
- * @return void
- */
- public function get_created_on()
- {
- return;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return $this->get("description", '');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return $this->get("description", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_id()
+ {
+ return $this->get("id", '');
+ }
- /**
- *
- * @return string
- */
- public function get_id()
- {
- return $this->get("id", '');
- }
+ /**
+ *
+ * @param type $width
+ * @param type $height
+ * @return string
+ */
+ public function get_thumbnail($width = 120, $height = 90)
+ {
+ return $this->thumbnail;
+ }
- /**
- *
- * @param type $width
- * @param type $height
- * @return string
- */
- public function get_thumbnail($width = 120, $height = 90)
- {
- return $this->thumbnail;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->get("name", '');
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->get("name", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ /**
+ *
+ * @return void
+ */
+ public function get_updated_on()
+ {
+ return;
+ }
- /**
- *
- * @return void
- */
- public function get_updated_on()
- {
- return;
- }
+ /**
+ *
+ * @return void
+ */
+ public function get_url()
+ {
+ return $this->url;
+ }
- /**
- *
- * @return void
- */
- public function get_url()
- {
- return $this->url;
- }
+ public function get_duration()
+ {
+ return '';
+ }
- public function get_duration()
- {
- return '';
- }
+ public function get_category()
+ {
+ return '';
+ }
- public function get_category()
- {
- return '';
- }
-
- public function is_private()
- {
- return null;
- }
+ public function is_private()
+ {
+ return null;
+ }
}
diff --git a/lib/classes/Bridge/Api/Dailymotion/Element.class.php b/lib/classes/Bridge/Api/Dailymotion/Element.class.php
index 72376a4c6d..c27ca92a04 100644
--- a/lib/classes/Bridge/Api/Dailymotion/Element.class.php
+++ b/lib/classes/Bridge/Api/Dailymotion/Element.class.php
@@ -12,165 +12,164 @@
*/
class Bridge_Api_Dailymotion_Element implements Bridge_Api_ElementInterface
{
+ /**
+ *
+ * @var array
+ */
+ protected $entry;
- /**
- *
- * @var array
- */
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @param array $entry
+ * @param type $type
+ * @return Bridge_Api_Dailymotion_Element
+ */
+ public function __construct(Array $entry, $type)
+ {
+ $this->entry = $entry;
+ $this->type = $type;
- /**
- *
- * @param array $entry
- * @param type $type
- * @return Bridge_Api_Dailymotion_Element
- */
- public function __construct(Array $entry, $type)
- {
- $this->entry = $entry;
- $this->type = $type;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return mixed
+ */
+ private function get($key, $default = null)
+ {
+ return isset($this->entry[$key]) ? $this->entry[$key] : $default;
+ }
- /**
- *
- * @return mixed
- */
- private function get($key, $default = null)
- {
- return isset($this->entry[$key]) ? $this->entry[$key] : $default;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return DateTime::createFromFormat('U', $this->get("created_time"));
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return DateTime::createFromFormat('U', $this->get("created_time"));
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return $this->get("description", '');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return $this->get("description", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_id()
+ {
+ return $this->get("id", '');
+ }
- /**
- *
- * @return string
- */
- public function get_id()
- {
- return $this->get("id", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_thumbnail($width = 120, $height = 90)
+ {
+ return $this->get("thumbnail_medium_url", '');
+ }
- /**
- *
- * @return string
- */
- public function get_thumbnail($width = 120, $height = 90)
- {
- return $this->get("thumbnail_medium_url", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->get("title", '');
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->get("title", '');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return DateTime::createFromFormat('U', $this->get("modified_time"));
+ }
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return DateTime::createFromFormat('U', $this->get("modified_time"));
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return $this->get("url", '');
+ }
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return $this->get("url", '');
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_private()
+ {
+ return ! ! $this->get("private", 0);
+ }
- /**
- *
- * @return boolean
- */
- public function is_private()
- {
- return !!$this->get("private", 0);
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_duration()
+ {
+ return p4string::format_seconds((int) $this->get('duration', '0'));
+ }
- /**
- *
- * @return string
- */
- public function get_duration()
- {
- return p4string::format_seconds((int) $this->get('duration', '0'));
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_view_count()
+ {
+ return (int) $this->get('views_total', 0);
+ }
- /**
- *
- * @return int
- */
- public function get_view_count()
- {
- return (int) $this->get('views_total', 0);
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_rating()
+ {
+ return (int) $this->get('ratings_total', 0);
+ }
- /**
- *
- * @return int
- */
- public function get_rating()
- {
- return (int) $this->get('ratings_total', 0);
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_category()
+ {
+ return $this->get('channel', '');
+ }
- /**
- *
- * @return string
- */
- public function get_category()
- {
- return $this->get('channel','');
- }
-
- /**
- *
- * @return string
- */
- public function get_tags()
- {
- return implode(",",$this->get('tags',array()));
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_tags()
+ {
+ return implode(",", $this->get('tags', array()));
+ }
}
diff --git a/lib/classes/Bridge/Api/ElementCollection.class.php b/lib/classes/Bridge/Api/ElementCollection.class.php
index f101e9faf9..f2a9f91f7b 100644
--- a/lib/classes/Bridge/Api/ElementCollection.class.php
+++ b/lib/classes/Bridge/Api/ElementCollection.class.php
@@ -18,16 +18,15 @@
class Bridge_Api_ElementCollection extends Bridge_Api_AbstractCollection
{
- /**
- *
- * @param Bridge_Api_ElementInterface $element
- * @return Bridge_Api_ElementCollection
- */
- public function add_element(Bridge_Api_ElementInterface $element)
- {
- $this->elements[] = $element;
-
- return $this;
- }
+ /**
+ *
+ * @param Bridge_Api_ElementInterface $element
+ * @return Bridge_Api_ElementCollection
+ */
+ public function add_element(Bridge_Api_ElementInterface $element)
+ {
+ $this->elements[] = $element;
+ return $this;
+ }
}
diff --git a/lib/classes/Bridge/Api/ElementInterface.class.php b/lib/classes/Bridge/Api/ElementInterface.class.php
index d905501269..033abba6c5 100644
--- a/lib/classes/Bridge/Api/ElementInterface.class.php
+++ b/lib/classes/Bridge/Api/ElementInterface.class.php
@@ -18,43 +18,41 @@
interface Bridge_Api_ElementInterface
{
- /**
- * @return int
- */
+ /**
+ * @return int
+ */
+ public function get_duration();
- public function get_duration();
+ public function get_view_count();
- public function get_view_count();
+ public function get_rating();
- public function get_rating();
+ /**
+ * @return string
+ */
+ public function get_id();
- /**
- * @return string
- */
+ public function get_url();
- public function get_id();
+ public function get_thumbnail();
- public function get_url();
+ public function get_title();
- public function get_thumbnail();
+ public function get_description();
- public function get_title();
+ public function get_category();
- public function get_description();
+ public function get_type();
- public function get_category();
+ /**
+ * @return Datetime
+ */
+ public function get_updated_on();
- public function get_type();
+ public function get_created_on();
- /**
- * @return Datetime
- */
- public function get_updated_on();
-
- public function get_created_on();
-
- /**
- * @return boolean
- */
- public function is_private();
+ /**
+ * @return boolean
+ */
+ public function is_private();
}
diff --git a/lib/classes/Bridge/Api/Flickr.class.php b/lib/classes/Bridge/Api/Flickr.class.php
index 7cb64a173c..21684155cc 100644
--- a/lib/classes/Bridge/Api/Flickr.class.php
+++ b/lib/classes/Bridge/Api/Flickr.class.php
@@ -19,868 +19,829 @@ use \Symfony\Component\HttpFoundation\Request;
*/
class Bridge_Api_Flickr extends Bridge_Api_Abstract implements Bridge_Api_Interface
{
+ /**
+ *
+ * @var Phlickr_Api
+ */
+ protected $_api;
- /**
- *
- * @var Phlickr_Api
- */
- protected $_api;
+ /**
+ *
+ * @var registryInterface
+ */
+ protected $registry;
- /**
- *
- * @var registryInterface
- */
- protected $registry;
+ const ELEMENT_TYPE_PHOTO = 'photo';
+ const CONTAINER_TYPE_PHOTOSET = 'photoset';
+ const AUTH_TYPE = 'Flickr';
+ const AUTH_PHOTO_SIZE = 15728640; //15 mo
+ const UPLOAD_STATE_DONE = 'done';
+ const UPLOAD_STATE_FAILED = 'failed';
+ const UPLOAD_STATE_FAILED_CONVERTING = 'failed_converting';
+ const UPLOAD_STATE_NOT_COMPLETED = 'not_completed';
- const ELEMENT_TYPE_PHOTO = 'photo';
- const CONTAINER_TYPE_PHOTOSET = 'photoset';
- const AUTH_TYPE = 'Flickr';
- const AUTH_PHOTO_SIZE = 15728640; //15 mo
- const UPLOAD_STATE_DONE = 'done';
- const UPLOAD_STATE_FAILED = 'failed';
- const UPLOAD_STATE_FAILED_CONVERTING = 'failed_converting';
- const UPLOAD_STATE_NOT_COMPLETED = 'not_completed';
-
- /**
- *
- * @return Array
- */
- public function connect()
- {
- $response = parent::connect();
- $this->_api->setAuthToken($response['auth_token']);
-
- return $response;
- }
-
- /**
- *
- * @return Bridge_Api_Flickr
- */
- public function disconnect()
- {
- parent::disconnect();
- $this->_api->setAuthToken(null);
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_user_name()
- {
- $response = $this->_api->executeMethod('flickr.auth.checkToken');
- if (!$response->isOk())
+ /**
+ *
+ * @return Array
+ */
+ public function connect()
{
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve FlickR username');
+ $response = parent::connect();
+ $this->_api->setAuthToken($response['auth_token']);
+
+ return $response;
}
- return (string) $response->xml->auth->user['username'];
- }
-
- /**
- *
- * @return string
- */
- public function get_user_id()
- {
- return $this->_api->getUserId();
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return 'Flickr';
- }
-
- /**
- *
- * @return string
- */
- public function get_icon_url()
- {
- return '/skins/icons/flickr-small.gif';
- }
-
- /**
- *
- * @return string
- */
- public function get_image_url()
- {
- return '/skins/icons/flickr.gif';
- }
-
- /**
- *
- * @return string
- */
- public function get_terms_url()
- {
- return 'https://secure.flickr.com/services/api/tos/';
- }
-
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return 'https://secure.flickr.com/';
- }
-
- /**
- *
- * @return string
- */
- public function get_infos()
- {
- return _('Ce produit utilise l\'API Flickr mais n\'est ni soutenu, ni certifie par Flickr');
- }
-
- /**
- *
- * @return string
- */
- public function get_default_element_type()
- {
- return self::ELEMENT_TYPE_PHOTO;
- }
-
- /**
- *
- * @return string
- */
- public function get_default_container_type()
- {
- return self::CONTAINER_TYPE_PHOTOSET;
- }
-
- /**
- *
- * @param type $element_id
- * @param type $object
- * @return type
- */
- public function get_element_from_id($element_id, $object)
- {
- switch ($object)
+ /**
+ *
+ * @return Bridge_Api_Flickr
+ */
+ public function disconnect()
{
- case self::ELEMENT_TYPE_PHOTO:
- $params = array('photo_id' => $element_id);
- $th_response = $this->_api->executeMethod('flickr.photos.getInfo', $params);
+ parent::disconnect();
+ $this->_api->setAuthToken(null);
- if (!$th_response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element infos for ' . $object . ' ' . $element_id);
-
- $th_xml = $th_response->getXml();
-
- return new Bridge_Api_Flickr_Element($th_xml, $this->get_user_id(), $object, false);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
+ return $this;
}
- return null;
- }
-
- /**
- *
- * @param type $object
- * @param type $element_id
- * @return type
- */
- public function get_container_from_id($object, $element_id)
- {
- switch ($object)
+ /**
+ *
+ * @return string
+ */
+ public function get_user_name()
{
- case self::CONTAINER_TYPE_PHOTOSET:
-
- $params = array('photoset_id' => $element_id);
- $response = $this->_api->executeMethod('flickr.photoset.getInfo', $params);
-
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve photoset infos for ' . $object);
-
- $xml = $response->getXml();
- $primary_photo = $this->get_element_from_id((string) $child['primary'], self::ELEMENT_TYPE_PHOTO);
-
- return new Bridge_Api_Flickr_Container($xml, $this->get_user_id(), $type, $primary_photo->get_thumbnail());
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
- }
-
- return null;
- }
-
- /**
- *
- * @param type $object
- * @param type $offset_start
- * @param type $quantity
- */
- public function list_containers($object, $offset_start = 0, $quantity = 10)
- {
- switch ($object)
- {
- case self::CONTAINER_TYPE_PHOTOSET:
- $params = array();
- if ($quantity)
- $params['per_page'] = $quantity;
- $params['page'] = $quantity != 0 ? floor($offset_start / $quantity) + 1 : 1;
- $params['user_id'] = $user_id = $this->get_user_id();
- $response = $this->_api->executeMethod('flickr.photosets.getList', $params);
-
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve container list ' . $object);
-
- $photosets = new Bridge_Api_ContainerCollection();
- $xml = $response->getXml();
-
- $photosets->set_current_page((int) $xml->photosets['page'])
- ->set_items_per_page((int) $xml->photosets['perpage'])
- ->set_total_items((int) $xml->photosets['total'])
- ->set_total_page((int) $xml->photosets['pages']);
-
- foreach ($xml->photosets->children() as $child)
- {
- $primary_photo = $this->get_element_from_id((string) $child['primary'], self::ELEMENT_TYPE_PHOTO);
- $photosets->add_element(new Bridge_Api_Flickr_Container($child, $user_id, $object, $primary_photo->get_thumbnail()));
+ $response = $this->_api->executeMethod('flickr.auth.checkToken');
+ if ( ! $response->isOk()) {
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve FlickR username');
}
- $photosets->set_total_items(count($photosets->get_elements()));
- return $photosets;
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
- break;
- }
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @param Request $request
- * @return Void
- */
- public function update_element($object, $object_id, Array $datas)
- {
- $required_fields = array("title");
- foreach ($required_fields as $field)
- {
- if (!array_key_exists($field, $datas) || trim($datas[$field]) === '')
- throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
+ return (string) $response->xml->auth->user['username'];
}
- $params = array(
- 'title' => $datas["title"]
- , 'photo_id' => $object_id
- , 'description' => $datas["description"]
- );
-
- switch ($object)
+ /**
+ *
+ * @return string
+ */
+ public function get_user_id()
{
- case self::ELEMENT_TYPE_PHOTO :
- $response = $this->_api->executeMethod('flickr.photos.setMeta', $params);
-
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed();
-
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
+ return $this->_api->getUserId();
}
- return $this;
- }
-
- /**
- *
- * @param string $container_type
- * @param Request $request
- * @return Bridge_Api_Flickr_Container
- */
- public function create_container($container_type, Request $request)
- {
- switch ($container_type)
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
{
- case self::CONTAINER_TYPE_PHOTOSET:
- $pid = $request->get('f_container_primary_photo');
- if (is_null($pid))
- throw new Bridge_Exception_ActionMandatoryField('You must define a default photo for the photoset');
+ return 'Flickr';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_icon_url()
+ {
+ return '/skins/icons/flickr-small.gif';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_image_url()
+ {
+ return '/skins/icons/flickr.gif';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_terms_url()
+ {
+ return 'https://secure.flickr.com/services/api/tos/';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return 'https://secure.flickr.com/';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_infos()
+ {
+ return _('Ce produit utilise l\'API Flickr mais n\'est ni soutenu, ni certifie par Flickr');
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_element_type()
+ {
+ return self::ELEMENT_TYPE_PHOTO;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_container_type()
+ {
+ return self::CONTAINER_TYPE_PHOTOSET;
+ }
+
+ /**
+ *
+ * @param type $element_id
+ * @param type $object
+ * @return type
+ */
+ public function get_element_from_id($element_id, $object)
+ {
+ switch ($object) {
+ case self::ELEMENT_TYPE_PHOTO:
+ $params = array('photo_id' => $element_id);
+ $th_response = $this->_api->executeMethod('flickr.photos.getInfo', $params);
+
+ if ( ! $th_response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element infos for ' . $object . ' ' . $element_id);
+
+ $th_xml = $th_response->getXml();
+
+ return new Bridge_Api_Flickr_Element($th_xml, $this->get_user_id(), $object, false);
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+
+ return null;
+ }
+
+ /**
+ *
+ * @param type $object
+ * @param type $element_id
+ * @return type
+ */
+ public function get_container_from_id($object, $element_id)
+ {
+ switch ($object) {
+ case self::CONTAINER_TYPE_PHOTOSET:
+
+ $params = array('photoset_id' => $element_id);
+ $response = $this->_api->executeMethod('flickr.photoset.getInfo', $params);
+
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve photoset infos for ' . $object);
+
+ $xml = $response->getXml();
+ $primary_photo = $this->get_element_from_id((string) $child['primary'], self::ELEMENT_TYPE_PHOTO);
+
+ return new Bridge_Api_Flickr_Container($xml, $this->get_user_id(), $type, $primary_photo->get_thumbnail());
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+
+ return null;
+ }
+
+ /**
+ *
+ * @param type $object
+ * @param type $offset_start
+ * @param type $quantity
+ */
+ public function list_containers($object, $offset_start = 0, $quantity = 10)
+ {
+ switch ($object) {
+ case self::CONTAINER_TYPE_PHOTOSET:
+ $params = array();
+ if ($quantity)
+ $params['per_page'] = $quantity;
+ $params['page'] = $quantity != 0 ? floor($offset_start / $quantity) + 1 : 1;
+ $params['user_id'] = $user_id = $this->get_user_id();
+ $response = $this->_api->executeMethod('flickr.photosets.getList', $params);
+
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve container list ' . $object);
+
+ $photosets = new Bridge_Api_ContainerCollection();
+ $xml = $response->getXml();
+
+ $photosets->set_current_page((int) $xml->photosets['page'])
+ ->set_items_per_page((int) $xml->photosets['perpage'])
+ ->set_total_items((int) $xml->photosets['total'])
+ ->set_total_page((int) $xml->photosets['pages']);
+
+ foreach ($xml->photosets->children() as $child) {
+ $primary_photo = $this->get_element_from_id((string) $child['primary'], self::ELEMENT_TYPE_PHOTO);
+ $photosets->add_element(new Bridge_Api_Flickr_Container($child, $user_id, $object, $primary_photo->get_thumbnail()));
+ }
+ $photosets->set_total_items(count($photosets->get_elements()));
+
+ return $photosets;
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @param Request $request
+ * @return Void
+ */
+ public function update_element($object, $object_id, Array $datas)
+ {
+ $required_fields = array("title");
+ foreach ($required_fields as $field) {
+ if ( ! array_key_exists($field, $datas) || trim($datas[$field]) === '')
+ throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
+ }
$params = array(
- 'title' => $request->get('title')
- , 'primary_photo_id' => $pid
- , 'description' => $request->get('description')
+ 'title' => $datas["title"]
+ , 'photo_id' => $object_id
+ , 'description' => $datas["description"]
);
- $response = $this->_api->executeMethod('flickr.photosets.create', $params);
+ switch ($object) {
+ case self::ELEMENT_TYPE_PHOTO :
+ $response = $this->_api->executeMethod('flickr.photos.setMeta', $params);
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed();
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed();
- $user_id = $this->get_user_id();
- $xml = $response->getXml();
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
+ }
- $photoset = $xml->photoset;
- $primary_photo = $this->get_element_from_id($pid, self::ELEMENT_TYPE_PHOTO);
-
- return new Bridge_Api_Flickr_Container($photoset, $user_id, $container_type, $primary_photo->get_thumbnail());
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $container_type);
- break;
+ return $this;
}
- }
- /**
- *
- * @param string $element_type
- * @param string $element_id
- * @param string $destination
- * @param string $container_id
- * @return Void
- */
- public function add_element_to_container($element_type, $element_id, $destination, $container_id)
- {
- switch ($element_type)
+ /**
+ *
+ * @param string $container_type
+ * @param Request $request
+ * @return Bridge_Api_Flickr_Container
+ */
+ public function create_container($container_type, Request $request)
{
- case self::ELEMENT_TYPE_PHOTO:
- switch ($destination)
- {
- case self::CONTAINER_TYPE_PHOTOSET:
- $params = array('photo_id' => $element_id, 'photoset_id' => $container_id);
- $response = $this->_api->executeMethod('flickr.photosets.addPhoto', $params);
+ switch ($container_type) {
+ case self::CONTAINER_TYPE_PHOTOSET:
+ $pid = $request->get('f_container_primary_photo');
+ if (is_null($pid))
+ throw new Bridge_Exception_ActionMandatoryField('You must define a default photo for the photoset');
- if (!$response->isOk())
- {
- if ($response->err_code === 3) //Already exists in photoset
+ $params = array(
+ 'title' => $request->get('title')
+ , 'primary_photo_id' => $pid
+ , 'description' => $request->get('description')
+ );
- return;
- throw new Bridge_Exception_ApiConnectorRequestFailed();
+ $response = $this->_api->executeMethod('flickr.photosets.create', $params);
+
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed();
+
+ $user_id = $this->get_user_id();
+ $xml = $response->getXml();
+
+ $photoset = $xml->photoset;
+ $primary_photo = $this->get_element_from_id($pid, self::ELEMENT_TYPE_PHOTO);
+
+ return new Bridge_Api_Flickr_Container($photoset, $user_id, $container_type, $primary_photo->get_thumbnail());
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $container_type);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $element_type
+ * @param string $element_id
+ * @param string $destination
+ * @param string $container_id
+ * @return Void
+ */
+ public function add_element_to_container($element_type, $element_id, $destination, $container_id)
+ {
+ switch ($element_type) {
+ case self::ELEMENT_TYPE_PHOTO:
+ switch ($destination) {
+ case self::CONTAINER_TYPE_PHOTOSET:
+ $params = array('photo_id' => $element_id, 'photoset_id' => $container_id);
+ $response = $this->_api->executeMethod('flickr.photosets.addPhoto', $params);
+
+ if ( ! $response->isOk()) {
+ if ($response->err_code === 3) //Already exists in photoset
+ return;
+ throw new Bridge_Exception_ApiConnectorRequestFailed();
+ }
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $destination);
+ break;
+ }
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $element_type);
+ break;
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @return Void
+ */
+ public function delete_object($object, $object_id)
+ {
+ switch ($object) {
+ case self::ELEMENT_TYPE_PHOTO:
+ $response = $this->_api->executeMethod(
+ 'flickr.photos.delete'
+ , array('photo_id' => $object_id)
+ );
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed();
+ break;
+ case self::CONTAINER_TYPE_PHOTOSET:
+ $response = $this->_api->executeMethod(
+ 'flickr.photosets.delete'
+ , array('photoset_id' => $object_id)
+ );
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed();
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
+ break;
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param string $type
+ * @param int $offset_start
+ * @param int $quantity
+ * @return Bridge_Api_ElementCollection
+ */
+ public function list_elements($type, $offset_start = 0, $quantity = 10)
+ {
+ switch ($type) {
+ case self::ELEMENT_TYPE_PHOTO:
+ $params = array();
+ //info to display during search
+ $extras = array(
+ 'description'
+ , 'license'
+ , 'date_upload'
+ , 'date_taken'
+ , 'owner_name'
+ , 'last_update'
+ , 'tags'
+ , 'views'
+ , 'url_sq'
+ , 'url_t'
+ );
+
+ $params['user_id'] = $this->get_user_id();
+ $params['extras'] = implode(",", $extras);
+
+ if ($quantity)
+ $params['per_page'] = $quantity;
+ $params['page'] = $quantity != 0 ? floor($offset_start / $quantity) + 1 : 1;
+ $response = $this->_api->executeMethod('flickr.photos.search', $params);
+
+ $photos = new Bridge_Api_ElementCollection();
+
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element list ' . $type);
+ $xml = $response->getXml();
+ $photos->set_current_page((int) $xml->photos['page'])
+ ->set_items_per_page((int) $xml->photos['perpage'])
+ ->set_total_items((int) $xml->photos['total'])
+ ->set_total_page((int) $xml->photos['pages']);
+ foreach ($xml->photos->children() as $child) {
+ $photos->add_element(new Bridge_Api_Flickr_Element($child, $params['user_id'], $type));
+ }
+
+ return $photos;
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
+ }
+ }
+
+ public function get_element_status(Bridge_Element $element)
+ {
+ try {
+ $ticket = $this->checkTicket($element->get_dist_id(), $element->get_type());
+ if ($ticket["status"] == self::UPLOAD_STATE_DONE) {
+ $this->get_element_from_id($ticket["dist_id"], $element->get_type());
+ $element->set_dist_id($ticket["dist_id"]);
}
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $destination);
- break;
+ } catch (Exception $e) {
+ return self::UPLOAD_STATE_FAILED;
}
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $element_type);
- break;
+
+ return $ticket["status"];
}
- return;
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @return Void
- */
- public function delete_object($object, $object_id)
- {
- switch ($object)
+ public function map_connector_to_element_status($status)
{
- case self::ELEMENT_TYPE_PHOTO:
- $response = $this->_api->executeMethod(
- 'flickr.photos.delete'
- , array('photo_id' => $object_id)
- );
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed();
- break;
- case self::CONTAINER_TYPE_PHOTOSET:
- $response = $this->_api->executeMethod(
- 'flickr.photosets.delete'
- , array('photoset_id' => $object_id)
- );
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed();
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
- break;
+ switch ($status) {
+ case self::UPLOAD_STATE_DONE:
+ return Bridge_Element::STATUS_DONE;
+ break;
+ case self::UPLOAD_STATE_FAILED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ default:
+ return null;
+ break;
+ }
}
- return;
- }
-
- /**
- *
- * @param string $type
- * @param int $offset_start
- * @param int $quantity
- * @return Bridge_Api_ElementCollection
- */
- public function list_elements($type, $offset_start = 0, $quantity = 10)
- {
- switch ($type)
+ public function get_error_message_from_status($connector_status)
{
- case self::ELEMENT_TYPE_PHOTO:
- $params = array();
- //info to display during search
- $extras = array(
- 'description'
- , 'license'
- , 'date_upload'
- , 'date_taken'
- , 'owner_name'
- , 'last_update'
- , 'tags'
- , 'views'
- , 'url_sq'
- , 'url_t'
- );
+ switch ($connector_status) {
+ case self::UPLOAD_STATE_FAILED:
+ return _('L\'upload a echoue');
+ break;
+ default:
+ case self::UPLOAD_STATE_DONE:
+ return '';
+ break;
+ }
+ }
- $params['user_id'] = $this->get_user_id();
- $params['extras'] = implode(",", $extras);
+ /**
+ *
+ * @param record_adapter $record
+ * @param array $options
+ * @return string The new distant Id
+ */
+ public function upload(record_adapter &$record, Array $options = array())
+ {
+ $uploader = new Phlickr_Uploader($this->_api);
- if ($quantity)
- $params['per_page'] = $quantity;
- $params['page'] = $quantity != 0 ? floor($offset_start / $quantity) + 1 : 1;
- $response = $this->_api->executeMethod('flickr.photos.search', $params);
+ $privacy = $this->get_default_privacy();
+ $uploader->setPerms($privacy['public'], $privacy['friends'], $privacy['family']);
+ $type = $record->get_type() == 'image' ? self::ELEMENT_TYPE_PHOTO : $record->get_type();
+ switch ($type) {
+ case self::ELEMENT_TYPE_PHOTO :
+ return $uploader->upload($record->get_hd_file()->getRealPath(), $options['title'], $options['description'], $options['tags'], true);
+ break;
+ default:
+ throw new Bridge_Exception_InvalidRecordType('Unknown format');
+ break;
+ }
+ }
- $photos = new Bridge_Api_ElementCollection();
+ /**
+ *
+ * @return Closure
+ */
+ public function acceptable_records()
+ {
+ return function (record_adapter &$record) {
+ return in_array($record->get_type(), array('image'));
+ };
+ }
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element list ' . $type);
+ protected function get_default_privacy()
+ {
+ $privacy = null;
+ $response = $this->_api->executeMethod('flickr.prefs.getPrivacy');
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve default privacy settings');
$xml = $response->getXml();
- $photos->set_current_page((int) $xml->photos['page'])
- ->set_items_per_page((int) $xml->photos['perpage'])
- ->set_total_items((int) $xml->photos['total'])
- ->set_total_page((int) $xml->photos['pages']);
- foreach ($xml->photos->children() as $child)
- {
- $photos->add_element(new Bridge_Api_Flickr_Element($child, $params['user_id'], $type));
+ $privacy = (string) $xml->person['privacy'];
+ switch ($privacy) {
+ case '1':
+ default:
+ $public = true;
+ $friends = $family = false;
+ break;
+ case '2':
+ $friends = true;
+ $public = $family = false;
+ break;
+ case '3':
+ $family = true;
+ $public = $friends = false;
+ break;
+ case '4':
+ $friends = $family = true;
+ $public = false;
+ break;
+ case '5':
+ $family = $friends = $public = false;
+ break;
+ }
+ $ret = array('friends' => $friends, 'family' => $family, 'public' => $public);
+
+ return $ret;
+ }
+
+ /**
+ *
+ * @param string $type
+ * @return string
+ */
+ public function get_object_class_from_type($type)
+ {
+ switch ($type) {
+ case self::ELEMENT_TYPE_PHOTO:
+ return self::OBJECT_CLASS_ELEMENT;
+ break;
+ case self::CONTAINER_TYPE_PHOTOSET:
+ return self::OBJECT_CLASS_CONTAINER;
+ break;
+ default:
+ throw new Exception('Unknown type');
+ break;
}
- return $photos;
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
+ return;
}
- }
- public function get_element_status(Bridge_Element $element)
- {
- try
+ /**
+ *
+ * @return Array
+ */
+ public function get_element_types()
{
- $ticket = $this->checkTicket($element->get_dist_id(), $element->get_type());
- if ($ticket["status"] == self::UPLOAD_STATE_DONE)
- {
- $this->get_element_from_id($ticket["dist_id"], $element->get_type());
- $element->set_dist_id($ticket["dist_id"]);
- }
+ return array(self::ELEMENT_TYPE_PHOTO => _('Photos'));
}
- catch (Exception $e)
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_container_types()
{
- return self::UPLOAD_STATE_FAILED;
+ return array(self::CONTAINER_TYPE_PHOTOSET => _('Photosets'));
}
- return $ticket["status"];
- }
-
- public function map_connector_to_element_status($status)
- {
- switch ($status)
+ /**
+ * Returns all categories for elements
+ * But there's not categories in FlickR.
+ * Just to satisfy the interface
+ *
+ * @return bridge_request_result;
+ */
+ public function get_category_list()
{
- case self::UPLOAD_STATE_DONE:
- return Bridge_Element::STATUS_DONE;
- break;
- case self::UPLOAD_STATE_FAILED:
- return Bridge_Element::STATUS_ERROR;
- break;
- default:
- return null;
- break;
+ return array();
}
- }
- public function get_error_message_from_status($connector_status)
- {
- switch ($connector_status)
+ public function is_configured()
{
- case self::UPLOAD_STATE_FAILED:
- return _('L\'upload a echoue');
- break;
- default:
- case self::UPLOAD_STATE_DONE:
- return '';
- break;
+
+ if ( ! $this->registry->get('GV_flickr_api'))
+ return false;
+
+ if (trim($this->registry->get('GV_flickr_client_id')) === '')
+ return false;
+
+ if (trim($this->registry->get('GV_flickr_client_secret')) === '')
+ return false;
+
+ return true;
}
- }
- /**
- *
- * @param record_adapter $record
- * @param array $options
- * @return string The new distant Id
- */
- public function upload(record_adapter &$record, Array $options = array())
- {
- $uploader = new Phlickr_Uploader($this->_api);
-
- $privacy = $this->get_default_privacy();
- $uploader->setPerms($privacy['public'], $privacy['friends'], $privacy['family']);
- $type = $record->get_type() == 'image' ? self::ELEMENT_TYPE_PHOTO : $record->get_type();
- switch ($type)
+ /**
+ *
+ * @return Bridge_Api_Flickr
+ */
+ protected function initialize_transport()
{
- case self::ELEMENT_TYPE_PHOTO :
- return $uploader->upload($record->get_hd_file()->getRealPath(), $options['title'], $options['description'], $options['tags'], true);
- break;
- default:
- throw new Bridge_Exception_InvalidRecordType('Unknown format');
- break;
+ $this->_api = new Phlickr_Api(
+ $this->registry->get('GV_flickr_client_id'),
+ $this->registry->get('GV_flickr_client_secret')
+ );
+
+ return $this;
}
- }
- /**
- *
- * @return Closure
- */
- public function acceptable_records()
- {
- return function (record_adapter &$record)
- {
- return in_array($record->get_type(), array('image'));
- };
- }
-
- protected function get_default_privacy()
- {
- $privacy = null;
- $response = $this->_api->executeMethod('flickr.prefs.getPrivacy');
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve default privacy settings');
- $xml = $response->getXml();
- $privacy = (string) $xml->person['privacy'];
- switch ($privacy)
+ /**
+ *
+ * @return Bridge_Api_Flickr
+ */
+ protected function set_transport_authentication_params()
{
- case '1':
- default:
- $public = true;
- $friends = $family = false;
- break;
- case '2':
- $friends = true;
- $public = $family = false;
- break;
- case '3':
- $family = true;
- $public = $friends = false;
- break;
- case '4':
- $friends = $family = true;
- $public = false;
- break;
- case '5':
- $family = $friends = $public = false;
- break;
- }
- $ret = array('friends' => $friends, 'family' => $family, 'public' => $public);
-
- return $ret;
- }
-
- /**
- *
- * @param string $type
- * @return string
- */
- public function get_object_class_from_type($type)
- {
- switch ($type)
- {
- case self::ELEMENT_TYPE_PHOTO:
- return self::OBJECT_CLASS_ELEMENT;
- break;
- case self::CONTAINER_TYPE_PHOTOSET:
- return self::OBJECT_CLASS_CONTAINER;
- break;
- default:
- throw new Exception('Unknown type');
- break;
- }
-
- return;
- }
-
- /**
- *
- * @return Array
- */
- public function get_element_types()
- {
- return array(self::ELEMENT_TYPE_PHOTO => _('Photos'));
- }
-
- /**
- *
- * @return Array
- */
- public function get_container_types()
- {
- return array(self::CONTAINER_TYPE_PHOTOSET => _('Photosets'));
- }
-
- /**
- * Returns all categories for elements
- * But there's not categories in FlickR.
- * Just to satisfy the interface
- *
- * @return bridge_request_result;
- */
- public function get_category_list()
- {
- return array();
- }
-
- public function is_configured()
- {
-
- if (!$this->registry->get('GV_flickr_api'))
-
- return false;
-
- if (trim($this->registry->get('GV_flickr_client_id')) === '')
-
- return false;
-
- if (trim($this->registry->get('GV_flickr_client_secret')) === '')
-
- return false;
-
- return true;
- }
-
- /**
- *
- * @return Bridge_Api_Flickr
- */
- protected function initialize_transport()
- {
- $this->_api = new Phlickr_Api(
- $this->registry->get('GV_flickr_client_id'),
- $this->registry->get('GV_flickr_client_secret')
- );
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Flickr
- */
- protected function set_transport_authentication_params()
- {
- if ($this->_auth->is_connected())
- {
- $signatures = $this->_auth->get_auth_signatures();
- $this->_api->setAuthToken($signatures['auth_token']);
- }
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Flickr
- */
- protected function set_auth_params()
- {
- $this->_auth->set_parameters(
- array(
- 'flickr_client_id' => $this->registry->get('GV_flickr_client_id')
- , 'flickr_client_secret' => $this->registry->get('GV_flickr_client_secret')
- , 'permissions' => 'delete'
- )
- );
-
- return $this;
- }
-
- /**
- * Not implmented
- * @param array $datas
- * @param record_adapter $record
- * @return array
- */
- public function check_upload_constraints(array $datas, record_adapter $record)
- {
- $errors = $this->check_record_constraints($record);
- $check = function($field) use (&$errors, $datas, $record)
- {
- $key = $record->get_serialize_key();
- $name = $field['name'];
- $length = (int) $field['length'];
- $required = !!$field['required'];
-
- if (!isset($datas[$name]) || trim($datas[$name]) === '')
- {
- if ($required)
- $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
+ if ($this->_auth->is_connected()) {
+ $signatures = $this->_auth->get_auth_signatures();
+ $this->_api->setAuthToken($signatures['auth_token']);
}
- elseif ($length !== 0)
- {
- if (mb_strlen($datas[$name]) > $length)
- $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- }
- };
- array_map($check, $this->get_fields());
-
- return $errors;
- }
-
- public function check_update_constraints(Array $datas)
- {
- $errors = array();
- $check = function($field) use (&$errors, $datas)
- {
- $name = $field['name'];
- $length = (int) $field['length'];
- $required = !!$field['required'];
-
- if (!isset($datas[$name]) || trim($datas[$name]) === '')
- {
- if ($required)
- $errors[$name] = _("Ce champ est obligatoire");
- }
- elseif ($length !== 0)
- {
- if (mb_strlen($datas[$name]) > $length)
- $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- }
- };
-
- array_map($check, $this->get_fields());
-
- return $errors;
- }
-
- /**
- * Returns datas needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_update_datas(Request $request)
- {
- $datas = array(
- 'title' => $request->get('modif_title', ''),
- 'description' => $request->get('modif_description', '')
- );
-
- return $datas;
- }
-
- /**
- * Returns datas needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_upload_datas(Request $request, record_adapter $record)
- {
- $key = $record->get_serialize_key();
- $datas = array(
- 'title' => $request->get('title_' . $key),
- 'description' => $request->get('description_' . $key),
- 'category' => $request->get('category_' . $key),
- 'tags' => $request->get('tags_' . $key),
- 'privacy' => $request->get('privacy_' . $key),
- );
-
- return $datas;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_multiple_upload()
- {
- return true;
- }
-
- /**
- *
- * @return array
- */
- private function get_fields()
- {
- return array(
- array(
- 'name' => 'title',
- 'length' => '100',
- 'required' => true
- )
- , array(
- 'name' => 'description',
- 'length' => '500',
- 'required' => false
- )
- , array(
- 'name' => 'tags',
- 'length' => '200',
- 'required' => false
- )
- );
- }
-
- /**
- *
- * @param record_adapter $record
- * @return array
- */
- private function check_record_constraints(record_adapter $record)
- {
- $errors = array();
- if (!$record->get_hd_file() instanceof SplFileObject)
- $errors["file_size"] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
- if ($record->get_technical_infos('size') > self::AUTH_PHOTO_SIZE)
- $errors["size"] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_PHOTO_SIZE));
-
- return $errors;
- }
-
- private function checkTicket($ticketsId, $type)
- {
- $return = array("status" => self::UPLOAD_STATE_FAILED, "dist_id" => null);
- $response = $this->_api->executeMethod("flickr.photos.upload.checkTickets", array("tickets" => $ticketsId));
- if (!$response->isOk())
- throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element list ' . $type);
-
- $xml = $response->getXml();
- $complete = isset($xml->uploader->ticket["complete"]) ? (string) $xml->uploader->ticket["complete"] : null;
- $invalid = isset($xml->uploader->ticket["invalid"]) ? (string) $xml->uploader->ticket["invalid"] : null;
-
- if ($complete)
- {
- if ((int) $complete == 0)
- $return["status"] = self::UPLOAD_STATE_NOT_COMPLETED;
- elseif ((int) $complete == 2)
- $return["status"] = self::UPLOAD_STATE_FAILED_CONVERTING;
- else
- {
- $return["dist_id"] = (string) $xml->uploader->ticket["photoid"];
- $return["status"] = self::UPLOAD_STATE_DONE;
- }
+ return $this;
}
- return $return;
- }
+ /**
+ *
+ * @return Bridge_Api_Flickr
+ */
+ protected function set_auth_params()
+ {
+ $this->_auth->set_parameters(
+ array(
+ 'flickr_client_id' => $this->registry->get('GV_flickr_client_id')
+ , 'flickr_client_secret' => $this->registry->get('GV_flickr_client_secret')
+ , 'permissions' => 'delete'
+ )
+ );
+ return $this;
+ }
+
+ /**
+ * Not implmented
+ * @param array $datas
+ * @param record_adapter $record
+ * @return array
+ */
+ public function check_upload_constraints(array $datas, record_adapter $record)
+ {
+ $errors = $this->check_record_constraints($record);
+ $check = function($field) use (&$errors, $datas, $record) {
+ $key = $record->get_serialize_key();
+ $name = $field['name'];
+ $length = (int) $field['length'];
+ $required = ! ! $field['required'];
+
+ if ( ! isset($datas[$name]) || trim($datas[$name]) === '') {
+ if ($required)
+ $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
+ }
+ elseif ($length !== 0) {
+ if (mb_strlen($datas[$name]) > $length)
+ $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ }
+ };
+
+ array_map($check, $this->get_fields());
+
+ return $errors;
+ }
+
+ public function check_update_constraints(Array $datas)
+ {
+ $errors = array();
+ $check = function($field) use (&$errors, $datas) {
+ $name = $field['name'];
+ $length = (int) $field['length'];
+ $required = ! ! $field['required'];
+
+ if ( ! isset($datas[$name]) || trim($datas[$name]) === '') {
+ if ($required)
+ $errors[$name] = _("Ce champ est obligatoire");
+ }
+ elseif ($length !== 0) {
+ if (mb_strlen($datas[$name]) > $length)
+ $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ }
+ };
+
+ array_map($check, $this->get_fields());
+
+ return $errors;
+ }
+
+ /**
+ * Returns datas needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_update_datas(Request $request)
+ {
+ $datas = array(
+ 'title' => $request->get('modif_title', ''),
+ 'description' => $request->get('modif_description', '')
+ );
+
+ return $datas;
+ }
+
+ /**
+ * Returns datas needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_upload_datas(Request $request, record_adapter $record)
+ {
+ $key = $record->get_serialize_key();
+ $datas = array(
+ 'title' => $request->get('title_' . $key),
+ 'description' => $request->get('description_' . $key),
+ 'category' => $request->get('category_' . $key),
+ 'tags' => $request->get('tags_' . $key),
+ 'privacy' => $request->get('privacy_' . $key),
+ );
+
+ return $datas;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_multiple_upload()
+ {
+ return true;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ private function get_fields()
+ {
+ return array(
+ array(
+ 'name' => 'title',
+ 'length' => '100',
+ 'required' => true
+ )
+ , array(
+ 'name' => 'description',
+ 'length' => '500',
+ 'required' => false
+ )
+ , array(
+ 'name' => 'tags',
+ 'length' => '200',
+ 'required' => false
+ )
+ );
+ }
+
+ /**
+ *
+ * @param record_adapter $record
+ * @return array
+ */
+ private function check_record_constraints(record_adapter $record)
+ {
+ $errors = array();
+ if ( ! $record->get_hd_file() instanceof SplFileObject)
+ $errors["file_size"] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
+ if ($record->get_technical_infos('size') > self::AUTH_PHOTO_SIZE)
+ $errors["size"] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_PHOTO_SIZE));
+
+ return $errors;
+ }
+
+ private function checkTicket($ticketsId, $type)
+ {
+ $return = array("status" => self::UPLOAD_STATE_FAILED, "dist_id" => null);
+ $response = $this->_api->executeMethod("flickr.photos.upload.checkTickets", array("tickets" => $ticketsId));
+ if ( ! $response->isOk())
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Unable to retrieve element list ' . $type);
+
+ $xml = $response->getXml();
+ $complete = isset($xml->uploader->ticket["complete"]) ? (string) $xml->uploader->ticket["complete"] : null;
+ $invalid = isset($xml->uploader->ticket["invalid"]) ? (string) $xml->uploader->ticket["invalid"] : null;
+
+ if ($complete) {
+ if ((int) $complete == 0)
+ $return["status"] = self::UPLOAD_STATE_NOT_COMPLETED;
+ elseif ((int) $complete == 2)
+ $return["status"] = self::UPLOAD_STATE_FAILED_CONVERTING;
+ else {
+ $return["dist_id"] = (string) $xml->uploader->ticket["photoid"];
+ $return["status"] = self::UPLOAD_STATE_DONE;
+ }
+ }
+
+ return $return;
+ }
}
diff --git a/lib/classes/Bridge/Api/Flickr/Container.class.php b/lib/classes/Bridge/Api/Flickr/Container.class.php
index b542d58058..44d0ac20aa 100644
--- a/lib/classes/Bridge/Api/Flickr/Container.class.php
+++ b/lib/classes/Bridge/Api/Flickr/Container.class.php
@@ -17,140 +17,138 @@
*/
class Bridge_Api_Flickr_Container implements Bridge_Api_ContainerInterface
{
+ /**
+ *
+ * @var SimpleXMLElement
+ */
+ protected $entry;
- /**
- *
- * @var SimpleXMLElement
- */
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var string
+ */
+ protected $thumbnail;
- /**
- *
- * @var string
- */
- protected $thumbnail;
+ /**
+ *
+ * @var string
+ */
+ protected $user_id;
- /**
- *
- * @var string
- */
- protected $user_id;
+ /**
+ *
+ * @param SimpleXMLElement $entry
+ * @param string $user_id
+ * @param string $type
+ * @param string $thumbnail
+ * @return Bridge_Api_Flickr_Container
+ */
+ public function __construct(SimpleXMLElement $entry, $user_id, $type, $thumbnail)
+ {
+ $this->entry = $entry;
+ $this->type = $type;
+ $this->thumbnail = $thumbnail;
- /**
- *
- * @param SimpleXMLElement $entry
- * @param string $user_id
- * @param string $type
- * @param string $thumbnail
- * @return Bridge_Api_Flickr_Container
- */
- public function __construct(SimpleXMLElement $entry, $user_id, $type, $thumbnail)
- {
- $this->entry = $entry;
- $this->type = $type;
- $this->thumbnail = $thumbnail;
+ $this->user_id = (string) $user_id;
- $this->user_id = (string) $user_id;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_id()
+ {
+ return (string) $this->entry['id'];
+ }
- /**
- *
- * @return string
- */
- public function get_id()
- {
- return (string) $this->entry['id'];
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_thumbnail($width = 120, $height = 90)
+ {
- /**
- *
- * @return string
- */
- public function get_thumbnail($width = 120, $height = 90)
- {
+ return $this->thumbnail;
+ }
- return $this->thumbnail;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return sprintf(
+ 'https://secure.flickr.com/photos/%s/sets/%s'
+ , $this->user_id
+ , $this->entry['id']
+ );
+ }
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return sprintf(
- 'https://secure.flickr.com/photos/%s/sets/%s'
- , $this->user_id
- , $this->entry['id']
- );
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return (string) $this->entry->title;
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return (string) $this->entry->title;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return (string) $this->entry->description;
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return (string) $this->entry->description;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return DateTime::createFromFormat('U', (string) $this->entry['date_update']);
+ }
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return DateTime::createFromFormat('U', (string) $this->entry['date_update']);
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return DateTime::createFromFormat('U', (string) $this->entry['date_create']);
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return DateTime::createFromFormat('U', (string) $this->entry['date_create']);
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ public function get_duration()
+ {
+ return '';
+ }
+ public function get_category()
+ {
+ return '';
+ }
- public function get_duration()
- {
- return '';
- }
-
- public function get_category()
- {
- return '';
- }
-
- public function is_private()
- {
- return null;
- }
+ public function is_private()
+ {
+ return null;
+ }
}
diff --git a/lib/classes/Bridge/Api/Flickr/Element.class.php b/lib/classes/Bridge/Api/Flickr/Element.class.php
index a62874740d..6a7be08913 100644
--- a/lib/classes/Bridge/Api/Flickr/Element.class.php
+++ b/lib/classes/Bridge/Api/Flickr/Element.class.php
@@ -17,266 +17,255 @@
*/
class Bridge_Api_Flickr_Element implements Bridge_Api_ElementInterface
{
+ protected $entry;
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var string
+ */
+ protected $user_id;
- /**
- *
- * @var string
- */
- protected $user_id;
-
- /**
- *
- * @param SimpleXMLElement $entry
- * @param string $user_id
- * @param string $type
- * @return Bridge_Api_Flickr_Element
- */
- public function __construct(SimpleXMLElement $entry, $user_id, $type, $entry_from_list = true)
- {
- $this->entry = array();
- $this->type = $type;
-
- if ($entry_from_list)
- $this->init_from_list_entry($entry);
- else
- $this->init_from_single_entry($entry);
-
-
- $this->user_id = (string) $user_id;
-
- return $this;
- }
-
- private function init_from_list_entry($entry)
- {
- $this->entry["id"] = isset($entry["id"]) ? (string) $entry["id"] : "";
- $this->entry["url"] = $this->generate_page_url($entry);
- $this->entry["thumbnail"] = $this->generate_thumb_url($entry, 's');
- $this->entry["title"] = isset($entry["title"]) ? (string) $entry["title"] : "";
- $this->entry["updated_on"] = isset($entry["lastupdate"]) ? (string) $entry["lastupdate"] : null;
- $this->entry["created_on"] = isset($entry["dateupload"]) ? (string) $entry["dateupload"] : null;
- $this->entry["views"] = isset($entry["views"]) ? (string) $entry["views"] : 0;
- $this->entry["ispublic"] = isset($entry["ispublic"]) ? !!(string)$entry["ispublic"] : false;
- $this->entry["description"] = isset($entry->description) ? (string) $entry->description : "";
- $this->entry["tags"] = isset($entry["tags"]) ? (string) $entry["tags"] : "";
- }
-
- private function init_from_single_entry($entry)
- {
- $photo = $entry->photo;
- $url = '';
-
- foreach ($photo->urls->url as $one_url)
+ /**
+ *
+ * @param SimpleXMLElement $entry
+ * @param string $user_id
+ * @param string $type
+ * @return Bridge_Api_Flickr_Element
+ */
+ public function __construct(SimpleXMLElement $entry, $user_id, $type, $entry_from_list = true)
{
- if ($one_url["type"] == "photopage")
- $url = (string) $one_url;
- }
- $dates = $photo->dates;
- $visibility = $photo->visibility;
- $tags = array();
- foreach ($photo->tags->tag as $one_tag)
- {
- $tags[] = $one_tag;
+ $this->entry = array();
+ $this->type = $type;
+
+ if ($entry_from_list)
+ $this->init_from_list_entry($entry);
+ else
+ $this->init_from_single_entry($entry);
+
+
+ $this->user_id = (string) $user_id;
+
+ return $this;
}
- $this->entry["id"] = isset($photo["id"]) ? (string) $photo["id"] : '';
- $this->entry["url"] = $url;
- $this->entry["thumbnail"] = $this->generate_thumb_url($photo, 's');
- $this->entry["title"] = isset($photo->title) ? (string) $photo->title : '';
- $this->entry["updated_on"] = isset($dates["lastupdate"]) ? (string) $dates["lastupdate"] : null;
- $this->entry["created_on"] = isset($dates["posted"]) ? (string) $dates["posted"] : null;
- $this->entry["views"] = isset($photo["views"]) ? (string) $photo["views"] : 0;
- $this->entry["ispublic"] = isset($visibility["ispublic"]) ? !!(string) $visibility["ispublic"] : false;
- $this->entry["description"] = isset($photo->description) ? (string) $photo->description : "";
- $this->entry["tags"] = implode(" ", $tags);
- }
+ private function init_from_list_entry($entry)
+ {
+ $this->entry["id"] = isset($entry["id"]) ? (string) $entry["id"] : "";
+ $this->entry["url"] = $this->generate_page_url($entry);
+ $this->entry["thumbnail"] = $this->generate_thumb_url($entry, 's');
+ $this->entry["title"] = isset($entry["title"]) ? (string) $entry["title"] : "";
+ $this->entry["updated_on"] = isset($entry["lastupdate"]) ? (string) $entry["lastupdate"] : null;
+ $this->entry["created_on"] = isset($entry["dateupload"]) ? (string) $entry["dateupload"] : null;
+ $this->entry["views"] = isset($entry["views"]) ? (string) $entry["views"] : 0;
+ $this->entry["ispublic"] = isset($entry["ispublic"]) ? ! ! (string) $entry["ispublic"] : false;
+ $this->entry["description"] = isset($entry->description) ? (string) $entry->description : "";
+ $this->entry["tags"] = isset($entry["tags"]) ? (string) $entry["tags"] : "";
+ }
- private function generate_page_url($entry)
- {
- if (isset($entry["owner"]) && isset($entry["id"]))
+ private function init_from_single_entry($entry)
+ {
+ $photo = $entry->photo;
+ $url = '';
- return sprintf("http://www.flickr.com/%ss/%s/%s/", $this->type, (string) $entry["owner"], (string) $entry["id"]);
- return "";
- }
+ foreach ($photo->urls->url as $one_url) {
+ if ($one_url["type"] == "photopage")
+ $url = (string) $one_url;
+ }
+ $dates = $photo->dates;
+ $visibility = $photo->visibility;
+ $tags = array();
+ foreach ($photo->tags->tag as $one_tag) {
+ $tags[] = $one_tag;
+ }
- /**
- *
- * @param type $entry
- * @param type $size
- * @param type $extension
- * @return string
- */
- private function generate_thumb_url($entry, $size = '', $extension = '')
- {
- if (isset($entry["url_t"]))
+ $this->entry["id"] = isset($photo["id"]) ? (string) $photo["id"] : '';
+ $this->entry["url"] = $url;
+ $this->entry["thumbnail"] = $this->generate_thumb_url($photo, 's');
+ $this->entry["title"] = isset($photo->title) ? (string) $photo->title : '';
+ $this->entry["updated_on"] = isset($dates["lastupdate"]) ? (string) $dates["lastupdate"] : null;
+ $this->entry["created_on"] = isset($dates["posted"]) ? (string) $dates["posted"] : null;
+ $this->entry["views"] = isset($photo["views"]) ? (string) $photo["views"] : 0;
+ $this->entry["ispublic"] = isset($visibility["ispublic"]) ? ! ! (string) $visibility["ispublic"] : false;
+ $this->entry["description"] = isset($photo->description) ? (string) $photo->description : "";
+ $this->entry["tags"] = implode(" ", $tags);
+ }
- return (string) $entry["url_t"];
+ private function generate_page_url($entry)
+ {
+ if (isset($entry["owner"]) && isset($entry["id"]))
+ return sprintf("http://www.flickr.com/%ss/%s/%s/", $this->type, (string) $entry["owner"], (string) $entry["id"]);
+ return "";
+ }
- if (!isset($entry["farm"]) || !isset($entry["farm"]) || !isset($entry["farm"]) || !isset($entry["farm"]) || !isset($entry["farm"]))
+ /**
+ *
+ * @param type $entry
+ * @param type $size
+ * @param type $extension
+ * @return string
+ */
+ private function generate_thumb_url($entry, $size = '', $extension = '')
+ {
+ if (isset($entry["url_t"]))
+ return (string) $entry["url_t"];
- return '';
+ if ( ! isset($entry["farm"]) || ! isset($entry["farm"]) || ! isset($entry["farm"]) || ! isset($entry["farm"]) || ! isset($entry["farm"]))
+ return '';
- $farm = (string) $entry["farm"];
- $server_id = (string) $entry["server"];
- $id_photo = (string) $entry["id"];
- $secret = (string) $entry["secret"];
+ $farm = (string) $entry["farm"];
+ $server_id = (string) $entry["server"];
+ $id_photo = (string) $entry["id"];
+ $secret = (string) $entry["secret"];
- if (empty($size) && empty($extension))
+ if (empty($size) && empty($extension))
+ return sprintf('https://farm%s.static.flickr.com/%s/%s_%s.jpg', $farm, $server_id, $id_photo, $secret);
+ elseif ( ! empty($size) && ! empty($extension))
+ return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_%s.jpg', $farm, $server_id, $id_photo, $secret, $size);
+ elseif ( ! empty($size))
+ return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_%s.jpg', $farm, $server_id, $id_photo, $secret, $size, '.jpg');
+ elseif ( ! empty($extension))
+ return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_o.%s', $farm, $server_id, $id_photo, $secret, $extension);
+ else
+ return "";
+ }
- return sprintf('https://farm%s.static.flickr.com/%s/%s_%s.jpg', $farm, $server_id, $id_photo, $secret);
- elseif (!empty($size) && !empty($extension))
+ /**
+ *
+ * @return string
+ */
+ public function get_id()
+ {
+ return $this->entry["id"];
+ }
- return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_%s.jpg', $farm, $server_id, $id_photo, $secret, $size);
- elseif (!empty($size))
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return $this->entry["url"];
+ }
- return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_%s.jpg', $farm, $server_id, $id_photo, $secret, $size, '.jpg');
- elseif (!empty($extension))
+ /**
+ *
+ * @return string
+ */
+ public function get_thumbnail()
+ {
+ return $this->entry["thumbnail"];
+ }
- return sprintf('https://farm%s.static.flickr.com/%s/%s_%s_o.%s', $farm, $server_id, $id_photo, $secret, $extension);
- else
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->entry["title"];
+ }
- return "";
- }
+ /**
+ *
+ * @return null
+ */
+ public function get_description()
+ {
+ return $this->entry["description"];
+ }
- /**
- *
- * @return string
- */
- public function get_id()
- {
- return $this->entry["id"];
- }
+ /**
+ *
+ * @return null
+ */
+ public function get_updated_on()
+ {
+ $date = $this->entry["updated_on"];
+ if ($date)
+ $date = DateTime::createFromFormat('U', $date);
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return $this->entry["url"];
- }
+ return $date;
+ }
- /**
- *
- * @return string
- */
- public function get_thumbnail()
- {
- return $this->entry["thumbnail"];
- }
+ /**
+ *
+ * @return null
+ */
+ public function get_category()
+ {
+ return '';
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->entry["title"];
- }
+ /**
+ *
+ * @return null
+ */
+ public function get_duration()
+ {
+ return '';
+ }
- /**
- *
- * @return null
- */
- public function get_description()
- {
- return $this->entry["description"];
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_view_count()
+ {
+ return (int) $this->entry["views"];
+ }
- /**
- *
- * @return null
- */
- public function get_updated_on()
- {
- $date = $this->entry["updated_on"];
- if ($date)
- $date = DateTime::createFromFormat('U', $date);
+ /**
+ *
+ * @return null
+ */
+ public function get_rating()
+ {
+ return null;
+ }
- return $date;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ $date = $this->entry["created_on"];
+ if ($date)
+ $date = DateTime::createFromFormat('U', $date);
- /**
- *
- * @return null
- */
- public function get_category()
- {
- return '';
- }
+ return $date;
+ }
- /**
- *
- * @return null
- */
- public function get_duration()
- {
- return '';
- }
+ /**
+ *
+ * @return null
+ */
+ public function is_private()
+ {
+ return ! $this->entry["ispublic"];
+ }
- /**
- *
- * @return int
- */
- public function get_view_count()
- {
- return (int) $this->entry["views"];
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @return null
- */
- public function get_rating()
- {
- return null;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- $date = $this->entry["created_on"];
- if ($date)
- $date = DateTime::createFromFormat('U', $date);
-
- return $date;
- }
-
- /**
- *
- * @return null
- */
- public function is_private()
- {
- return !$this->entry["ispublic"];
- }
-
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
-
- /**
- *
- * @return string
- */
- public function get_tags()
- {
- return $this->entry["tags"];
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_tags()
+ {
+ return $this->entry["tags"];
+ }
}
diff --git a/lib/classes/Bridge/Api/Interface.class.php b/lib/classes/Bridge/Api/Interface.class.php
index 06d2ef2844..c0b3d32bd2 100644
--- a/lib/classes/Bridge/Api/Interface.class.php
+++ b/lib/classes/Bridge/Api/Interface.class.php
@@ -19,158 +19,158 @@ use \Symfony\Component\HttpFoundation;
*/
interface Bridge_Api_Interface
{
- const OBJECT_CLASS_ELEMENT = 'element';
- const OBJECT_CLASS_CONTAINER = 'container';
+ const OBJECT_CLASS_ELEMENT = 'element';
+ const OBJECT_CLASS_CONTAINER = 'container';
- public function __construct(registryInterface $registry, Bridge_Api_Auth_Interface $auth);
+ public function __construct(registryInterface $registry, Bridge_Api_Auth_Interface $auth);
- /**
- *
- * @return Array
- */
- public function connect();
+ /**
+ *
+ * @return Array
+ */
+ public function connect();
- /**
- *
- * @return Bridge_Api_Interface
- */
- public function reconnect();
+ /**
+ *
+ * @return Bridge_Api_Interface
+ */
+ public function reconnect();
- /**
- *
- * @return Bridge_Api_Interface
- */
- public function disconnect();
+ /**
+ *
+ * @return Bridge_Api_Interface
+ */
+ public function disconnect();
- /**
- *
- * @return boolean
- */
- public function is_configured();
+ /**
+ *
+ * @return boolean
+ */
+ public function is_configured();
- /**
- *
- * @return boolean
- */
- public function is_connected();
+ /**
+ *
+ * @return boolean
+ */
+ public function is_connected();
- /**
- *
- * @return Bridge_Api_Interface
- */
- public function set_locale($locale);
+ /**
+ *
+ * @return Bridge_Api_Interface
+ */
+ public function set_locale($locale);
- /**
- *
- * @return Bridge_Api_Interface
- */
- public function set_auth_settings(Bridge_AccountSettings &$settings);
+ /**
+ *
+ * @return Bridge_Api_Interface
+ */
+ public function set_auth_settings(Bridge_AccountSettings &$settings);
- /**
- *
- * @return string
- */
- public function get_name();
+ /**
+ *
+ * @return string
+ */
+ public function get_name();
- /**
- *
- * @return string
- */
- public function get_icon_url();
+ /**
+ *
+ * @return string
+ */
+ public function get_icon_url();
- /**
- *
- * @return string
- */
- public function get_auth_url();
+ /**
+ *
+ * @return string
+ */
+ public function get_auth_url();
- /**
- *
- * @return string
- */
- public function get_image_url();
+ /**
+ *
+ * @return string
+ */
+ public function get_image_url();
- /**
- *
- * @return string
- */
- public function get_terms_url();
+ /**
+ *
+ * @return string
+ */
+ public function get_terms_url();
- /**
- *
- * @return string
- */
- public function get_url();
+ /**
+ *
+ * @return string
+ */
+ public function get_url();
- /**
- *
- * @return string
- */
- public function get_infos();
+ /**
+ *
+ * @return string
+ */
+ public function get_infos();
- public function get_object_class_from_type($type);
+ public function get_object_class_from_type($type);
- public function get_default_element_type();
+ public function get_default_element_type();
- public function get_default_container_type();
+ public function get_default_container_type();
- public function get_element_types();
+ public function get_element_types();
- public function get_container_types();
+ public function get_container_types();
- public function get_element_from_id($element_id, $object);
+ public function get_element_from_id($element_id, $object);
- public function get_container_from_id($element_id, $object);
+ public function get_container_from_id($element_id, $object);
- public function get_category_list();
+ public function get_category_list();
- public function get_user_name();
+ public function get_user_name();
- public function get_user_id();
+ public function get_user_id();
- public function list_elements($type, $offset_start = 0, $quantity = 10);
+ public function list_elements($type, $offset_start = 0, $quantity = 10);
- public function list_containers($type, $offset_start = 0, $quantity = 10);
+ public function list_containers($type, $offset_start = 0, $quantity = 10);
- public function update_element($object, $object_id, Array $datas);
+ public function update_element($object, $object_id, Array $datas);
- public function create_container($container_type, Request $request);
+ public function create_container($container_type, Request $request);
- public function add_element_to_container($element_type, $element_id, $destination, $container_id);
+ public function add_element_to_container($element_type, $element_id, $destination, $container_id);
- public function delete_object($object, $object_id);
+ public function delete_object($object, $object_id);
- /**
- *
- * @return Closure
- */
- public function acceptable_records();
+ /**
+ *
+ * @return Closure
+ */
+ public function acceptable_records();
- public function get_element_status(Bridge_Element $element);
+ public function get_element_status(Bridge_Element $element);
- public function map_connector_to_element_status($status);
+ public function map_connector_to_element_status($status);
- public function get_error_message_from_status($connector_status);
+ public function get_error_message_from_status($connector_status);
- public function upload(record_adapter &$record, array $options = array());
+ public function upload(record_adapter &$record, array $options = array());
- public function is_valid_object_id($object_id);
+ public function is_valid_object_id($object_id);
- /**
- *
- * @return boolean
- */
- public function is_multiple_upload();
+ /**
+ *
+ * @return boolean
+ */
+ public function is_multiple_upload();
- /**
- *
- * @return array
- */
- public function check_upload_constraints(Array $datas, record_adapter $record);
+ /**
+ *
+ * @return array
+ */
+ public function check_upload_constraints(Array $datas, record_adapter $record);
- public function get_upload_datas(Request $request, record_adapter $record);
+ public function get_upload_datas(Request $request, record_adapter $record);
- public function get_update_datas(Request $request);
+ public function get_update_datas(Request $request);
- public function check_update_constraints(Array $datas);
+ public function check_update_constraints(Array $datas);
}
diff --git a/lib/classes/Bridge/Api/Youtube.class.php b/lib/classes/Bridge/Api/Youtube.class.php
index 827045f548..df9a0e8b5a 100644
--- a/lib/classes/Bridge/Api/Youtube.class.php
+++ b/lib/classes/Bridge/Api/Youtube.class.php
@@ -19,1111 +19,1053 @@ use \Symfony\Component\HttpFoundation\Request;
*/
class Bridge_Api_Youtube extends Bridge_Api_Abstract implements Bridge_Api_Interface
{
+ /**
+ *
+ * @var registryInterface
+ */
+ protected $registry;
- /**
- *
- * @var registryInterface
- */
- protected $registry;
+ /**
+ *
+ * @var Zend_Gdata_YouTube
+ */
+ protected $_api;
- /**
- *
- * @var Zend_Gdata_YouTube
- */
- protected $_api;
+ const OAUTH2_AUTHORIZE_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth';
+ const OAUTH2_TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token';
+ const UPLOAD_URL = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
+ const CATEGORY_URL = 'http://gdata.youtube.com/schemas/2007/categories.cat';
+ const AUTH_VIDEO_DURATION = 900;
+ const AUTH_VIDEO_SIZE = 68719476736; //in bytes = 64GB
+ const ELEMENT_TYPE_VIDEO = 'video';
+ const CONTAINER_TYPE_PLAYLIST = 'playlist';
+ const AUTH_TYPE = 'OAuth2';
+ const UPLOAD_STATE_PROCESSING = 'processing';
+ const UPLOAD_STATE_RESTRICTED = 'restricted';
+ const UPLOAD_STATE_DONE = 'done';
+ const UPLOAD_STATE_DELETED = 'deleted';
+ const UPLOAD_STATE_REJECTED = 'rejected';
+ const UPLOAD_STATE_FAILED = 'failed';
- const OAUTH2_AUTHORIZE_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth';
- const OAUTH2_TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token';
- const UPLOAD_URL = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
- const CATEGORY_URL = 'http://gdata.youtube.com/schemas/2007/categories.cat';
- const AUTH_VIDEO_DURATION = 900;
- const AUTH_VIDEO_SIZE = 68719476736; //in bytes = 64GB
- const ELEMENT_TYPE_VIDEO = 'video';
- const CONTAINER_TYPE_PLAYLIST = 'playlist';
- const AUTH_TYPE = 'OAuth2';
-
- const UPLOAD_STATE_PROCESSING = 'processing';
- const UPLOAD_STATE_RESTRICTED = 'restricted';
- const UPLOAD_STATE_DONE = 'done';
- const UPLOAD_STATE_DELETED = 'deleted';
- const UPLOAD_STATE_REJECTED = 'rejected';
- const UPLOAD_STATE_FAILED = 'failed';
-
- /**
- *
- * @return Array
- */
- public function connect()
- {
- $response = parent::connect();
- $this->_api->getHttpClient()->setAuthSubToken($response['auth_token']);
-
- return $response;
- }
-
- /**
- *
- * @return Bridge_Api_Youtube
- */
- public function reconnect()
- {
- parent::reconnect();
- $this->set_transport_authentication_params();
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_user_id()
- {
- return $this->_api->getUserProfile('default')->getUsername();
- }
-
- /**
- *
- * @return string
- */
- public function get_user_name()
- {
- return $this->_api->getUserProfile('default')->getUsername();
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return 'Youtube';
- }
-
- /**
- *
- * @return string
- */
- public function get_icon_url()
- {
- return '/skins/icons/youtube-small.gif';
- }
-
- /**
- *
- * @return string
- */
- public function get_image_url()
- {
- return '/skins/icons/youtube-white.gif';
- }
-
- /**
- *
- * @return string
- */
- public function get_terms_url()
- {
- return 'https://code.google.com/apis/youtube/terms.html';
- }
-
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return 'https://www.youtube.com/';
- }
-
- /**
- *
- * @return string
- */
- public function get_infos()
- {
- return 'www.youtube.com';
- }
-
- /**
- *
- * @return string
- */
- public function get_default_element_type()
- {
- return self::ELEMENT_TYPE_VIDEO;
- }
-
- /**
- *
- * @return string
- */
- public function get_default_container_type()
- {
- return self::CONTAINER_TYPE_PLAYLIST;
- }
-
- /**
- *
- * @return Array
- */
- public function get_element_types()
- {
- return array(self::ELEMENT_TYPE_VIDEO => _('Videos'));
- }
-
- /**
- *
- * @return Array
- */
- public function get_container_types()
- {
- return array(self::CONTAINER_TYPE_PLAYLIST => _('Playlists'));
- }
-
- /**
- *
- * @param string $type
- * @return string
- */
- public function get_object_class_from_type($type)
- {
- switch ($type)
+ /**
+ *
+ * @return Array
+ */
+ public function connect()
{
- case self::ELEMENT_TYPE_VIDEO:
- return self::OBJECT_CLASS_ELEMENT;
- break;
- case self::CONTAINER_TYPE_PLAYLIST:
- return self::OBJECT_CLASS_CONTAINER;
- break;
- default:
- throw new Exception('Unknown type');
- break;
+ $response = parent::connect();
+ $this->_api->getHttpClient()->setAuthSubToken($response['auth_token']);
+
+ return $response;
}
- }
- /**
- *
- * @param string $object
- * @param int $offset_start
- * @param int $quantity
- * @return Bridge_Api_ElementCollection
- */
- public function list_elements($object, $offset_start = 0, $quantity = 10)
- {
- switch ($object)
+ /**
+ *
+ * @return Bridge_Api_Youtube
+ */
+ public function reconnect()
{
- case self::ELEMENT_TYPE_VIDEO:
- $video_feed = $this->get_user_object_list_feed($object, $offset_start, $quantity);
+ parent::reconnect();
+ $this->set_transport_authentication_params();
- $element_collection = new Bridge_Api_ElementCollection();
- $element_collection->set_items_per_page($video_feed->getItemsPerPage()->getText());
+ return $this;
+ }
- $total = $video_feed->getTotalResults()->getText();
- $current_page = floor((int) $video_feed->getStartIndex()->getText() / (int) $video_feed->getItemsPerPage()->getText()) + 1;
- $total_page = ceil((int) $total / (int) $video_feed->getItemsPerPage()->getText());
+ /**
+ *
+ * @return string
+ */
+ public function get_user_id()
+ {
+ return $this->_api->getUserProfile('default')->getUsername();
+ }
- $element_collection->set_total_items($total);
- $element_collection->set_current_page($current_page);
- $element_collection->set_total_page($total_page);
+ /**
+ *
+ * @return string
+ */
+ public function get_user_name()
+ {
+ return $this->_api->getUserProfile('default')->getUsername();
+ }
- foreach ($video_feed as $entry)
- {
- $element_collection->add_element(new Bridge_Api_Youtube_Element($entry, $object));
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return 'Youtube';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_icon_url()
+ {
+ return '/skins/icons/youtube-small.gif';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_image_url()
+ {
+ return '/skins/icons/youtube-white.gif';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_terms_url()
+ {
+ return 'https://code.google.com/apis/youtube/terms.html';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return 'https://www.youtube.com/';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_infos()
+ {
+ return 'www.youtube.com';
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_element_type()
+ {
+ return self::ELEMENT_TYPE_VIDEO;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_default_container_type()
+ {
+ return self::CONTAINER_TYPE_PLAYLIST;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_element_types()
+ {
+ return array(self::ELEMENT_TYPE_VIDEO => _('Videos'));
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_container_types()
+ {
+ return array(self::CONTAINER_TYPE_PLAYLIST => _('Playlists'));
+ }
+
+ /**
+ *
+ * @param string $type
+ * @return string
+ */
+ public function get_object_class_from_type($type)
+ {
+ switch ($type) {
+ case self::ELEMENT_TYPE_VIDEO:
+ return self::OBJECT_CLASS_ELEMENT;
+ break;
+ case self::CONTAINER_TYPE_PLAYLIST:
+ return self::OBJECT_CLASS_CONTAINER;
+ break;
+ default:
+ throw new Exception('Unknown type');
+ break;
}
-
- return $element_collection;
- break;
-
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
}
- }
- /**
- *
- * @param string $object
- * @param int $offset_start
- * @param int $quantity
- * @return Bridge_Api_ContainerCollection
- */
- public function list_containers($object, $offset_start = 0, $quantity = 10)
- {
- switch ($object)
+ /**
+ *
+ * @param string $object
+ * @param int $offset_start
+ * @param int $quantity
+ * @return Bridge_Api_ElementCollection
+ */
+ public function list_elements($object, $offset_start = 0, $quantity = 10)
{
- case self::CONTAINER_TYPE_PLAYLIST:
- $playlist_feed = $this->get_user_object_list_feed($object, $offset_start, $quantity);
- $container_collection = new Bridge_Api_ContainerCollection();
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ $video_feed = $this->get_user_object_list_feed($object, $offset_start, $quantity);
- $container_collection->set_items_per_page($playlist_feed->getItemsPerPage()->getText());
+ $element_collection = new Bridge_Api_ElementCollection();
+ $element_collection->set_items_per_page($video_feed->getItemsPerPage()->getText());
- $total = $playlist_feed->getTotalResults()->getText();
- $current_page = floor((int) $playlist_feed->getStartIndex()->getText() / (int) $playlist_feed->getItemsPerPage()->getText());
- $total_page = ceil((int) $total / (int) $playlist_feed->getItemsPerPage()->getText());
+ $total = $video_feed->getTotalResults()->getText();
+ $current_page = floor((int) $video_feed->getStartIndex()->getText() / (int) $video_feed->getItemsPerPage()->getText()) + 1;
+ $total_page = ceil((int) $total / (int) $video_feed->getItemsPerPage()->getText());
- $container_collection->set_total_items($total);
- $container_collection->set_current_page($current_page);
- $container_collection->set_total_page($total_page);
+ $element_collection->set_total_items($total);
+ $element_collection->set_current_page($current_page);
+ $element_collection->set_total_page($total_page);
- foreach ($playlist_feed as $entry)
- {
- $playlist_video_feed = $this->_api->getPlaylistVideoFeed($entry->getPlaylistVideoFeedUrl());
- $thumbnail = null;
- if (!is_null($playlist_video_feed))
- {
- foreach ($playlist_video_feed as $entry2)
- {
- $playlist_thumbnails = $entry2->getVideoThumbnails();
- foreach ($playlist_thumbnails as $playlist_thumbnail)
- {
- if (120 == $playlist_thumbnail['width'] && 90 == $playlist_thumbnail['height'])
- {
- $thumbnail = $playlist_thumbnail['url'];
- break;
+ foreach ($video_feed as $entry) {
+ $element_collection->add_element(new Bridge_Api_Youtube_Element($entry, $object));
}
- }
- break;
- }
- }
- $container_collection->add_element(new Bridge_Api_Youtube_Container($entry, $object, $thumbnail));
+ return $element_collection;
+ break;
+
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param int $offset_start
+ * @param int $quantity
+ * @return Bridge_Api_ContainerCollection
+ */
+ public function list_containers($object, $offset_start = 0, $quantity = 10)
+ {
+ switch ($object) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $playlist_feed = $this->get_user_object_list_feed($object, $offset_start, $quantity);
+ $container_collection = new Bridge_Api_ContainerCollection();
+
+ $container_collection->set_items_per_page($playlist_feed->getItemsPerPage()->getText());
+
+ $total = $playlist_feed->getTotalResults()->getText();
+ $current_page = floor((int) $playlist_feed->getStartIndex()->getText() / (int) $playlist_feed->getItemsPerPage()->getText());
+ $total_page = ceil((int) $total / (int) $playlist_feed->getItemsPerPage()->getText());
+
+ $container_collection->set_total_items($total);
+ $container_collection->set_current_page($current_page);
+ $container_collection->set_total_page($total_page);
+
+ foreach ($playlist_feed as $entry) {
+ $playlist_video_feed = $this->_api->getPlaylistVideoFeed($entry->getPlaylistVideoFeedUrl());
+ $thumbnail = null;
+ if ( ! is_null($playlist_video_feed)) {
+ foreach ($playlist_video_feed as $entry2) {
+ $playlist_thumbnails = $entry2->getVideoThumbnails();
+ foreach ($playlist_thumbnails as $playlist_thumbnail) {
+ if (120 == $playlist_thumbnail['width'] && 90 == $playlist_thumbnail['height']) {
+ $thumbnail = $playlist_thumbnail['url'];
+ break;
+ }
+ }
+ break;
+ }
+ }
+
+ $container_collection->add_element(new Bridge_Api_Youtube_Container($entry, $object, $thumbnail));
+ }
+
+ return $container_collection;
+ break;
+
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @param Request $request
+ * @return Bridge_Api_Youtube
+ */
+ public function update_element($object, $object_id, Array $datas)
+ {
+ $required_fields = array("description", "category", "tags", "title", "privacy");
+ foreach ($required_fields as $field) {
+ if ( ! array_key_exists($field, $datas))
+ throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
}
- return $container_collection;
- break;
+ if ( ! $this->is_valid_object_id($object_id))
+ throw new Bridge_Exception_InvalidObjectId($object_id);
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
- }
- }
+ switch ($object) {
+ case "video" :
+ $videoEntry = $this->_api->getFullVideoEntry($object_id);
+ if ($videoEntry->getEditLink() === null)
+ throw new Bridge_Exception_ActionForbidden("You cannot edit this video object");
- /**
- *
- * @param string $object
- * @param string $object_id
- * @param Request $request
- * @return Bridge_Api_Youtube
- */
- public function update_element($object, $object_id, Array $datas)
- {
- $required_fields = array("description", "category", "tags", "title", "privacy");
- foreach ($required_fields as $field)
- {
- if (!array_key_exists($field, $datas))
- throw new Bridge_Exception_ActionMandatoryField("Le paramétre " . $field . " est manquant");
- }
+ $videoEntry->setVideoDescription(trim($datas['description']));
+ $videoEntry->setVideoCategory(trim($datas['category']));
+ $videoEntry->setVideoTags(trim($datas['tags']));
+ $videoEntry->setVideoTitle(trim($datas['title']));
- if (!$this->is_valid_object_id($object_id))
- throw new Bridge_Exception_InvalidObjectId($object_id);
+ if ($params["privacy"] == "public") {
+ $videoEntry->setVideoPublic();
+ } else {
+ $videoEntry->setVideoPrivate();
+ }
- switch ($object)
- {
- case "video" :
- $videoEntry = $this->_api->getFullVideoEntry($object_id);
- if ($videoEntry->getEditLink() === null)
- throw new Bridge_Exception_ActionForbidden("You cannot edit this video object");
+ $this->_api->updateEntry($videoEntry, $videoEntry->getEditLink()->getHref());
+ break;
- $videoEntry->setVideoDescription(trim($datas['description']));
- $videoEntry->setVideoCategory(trim($datas['category']));
- $videoEntry->setVideoTags(trim($datas['tags']));
- $videoEntry->setVideoTitle(trim($datas['title']));
-
- if ($params["privacy"] == "public")
- {
- $videoEntry->setVideoPublic();
- }
- else
- {
- $videoEntry->setVideoPrivate();
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
}
- $this->_api->updateEntry($videoEntry, $videoEntry->getEditLink()->getHref());
- break;
-
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param string $container_type
- * @param Request $request
- * @return Bridge_Api_Youtube_Container
- */
- public function create_container($container_type, Request $request)
- {
- switch ($container_type)
+ /**
+ *
+ * @param string $container_type
+ * @param Request $request
+ * @return Bridge_Api_Youtube_Container
+ */
+ public function create_container($container_type, Request $request)
{
- case self::CONTAINER_TYPE_PLAYLIST:
- $container_desc = $request->get('f_container_description');
- $container_title = $request->get('f_container_title');
+ switch ($container_type) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $container_desc = $request->get('f_container_description');
+ $container_title = $request->get('f_container_title');
- $new_playlist = $this->_api->newPlaylistListEntry();
- if (trim($description) !== '')
- $new_playlist->description = $this->_api->newDescription()->setText($container_desc);
- $new_playlist->title = $this->_api->newTitle()->setText($container_title);
+ $new_playlist = $this->_api->newPlaylistListEntry();
+ if (trim($description) !== '')
+ $new_playlist->description = $this->_api->newDescription()->setText($container_desc);
+ $new_playlist->title = $this->_api->newTitle()->setText($container_title);
- $post_location = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
- $entry = $this->_api->insertEntry($new_playlist, $post_location);
+ $post_location = 'http://gdata.youtube.com/feeds/api/users/default/playlists';
+ $entry = $this->_api->insertEntry($new_playlist, $post_location);
- return new Bridge_Api_Youtube_Container($entry, $container_type, null);
+ return new Bridge_Api_Youtube_Container($entry, $container_type, null);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
- break;
- }
- }
-
- /**
- *
- * @param type $element_type
- * @param type $element_id
- * @param type $destination
- * @param type $container_id
- * @return Bridge_Api_Youtube_Container
- */
- public function add_element_to_container($element_type, $element_id, $destination, $container_id)
- {
- switch ($element_type)
- {
- case self::ELEMENT_TYPE_VIDEO:
- switch ($destination)
- {
- case self::CONTAINER_TYPE_PLAYLIST:
- $playlistEntry = $this->get_PlaylistEntry_from_Id($container_id);
- $postUrl = $playlistEntry->getPlaylistVideoFeedUrl();
-
- $videoEntryToAdd = $this->_api->getVideoEntry($element_id);
- $newPlaylistListEntry = $this->_api->newPlaylistListEntry($videoEntryToAdd->getDOM());
- $this->_api->insertEntry($newPlaylistListEntry, $postUrl);
- $playlistEntry = $this->get_PlaylistEntry_from_Id($container_id);
-
- return new Bridge_Api_Youtube_Container($playlistEntry, $destination, null);
- break;
- default:
- throw new Bridge_Exception_ContainerUnknown('Unknown element ' . $container);
- break;
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $type);
+ break;
}
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown container ' . $element_type);
- break;
- }
- }
-
- /**
- *
- * @param string $object
- * @param string $object_id
- * @return Void
- */
- public function delete_object($object, $object_id)
- {
- switch ($object)
- {
- case self::ELEMENT_TYPE_VIDEO:
- $this->_api->delete($this->_api->getFullVideoEntry($object_id));
- break;
- case self::CONTAINER_TYPE_PLAYLIST:
- $this->get_PlaylistEntry_from_Id($object_id)->delete();
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
- break;
}
- return;
- }
-
- /**
- *
- * @return Closure
- */
- public function acceptable_records()
- {
- return function (record_adapter &$record)
- {
- return $record->get_type() === 'video';
- };
- }
-
- /**
- *
- * @param string $element_id
- * @return string
- */
- public function get_element_status(Bridge_Element $element)
- {
- $this->_api->setMajorProtocolVersion(1);
- $state = $this->_api->getFullVideoEntry($element->get_dist_id())->getVideoState();
-
- if (is_null($state))
- $result = Bridge_Element::STATUS_DONE;
- else
- $result = $state->getName();
-
- $this->_api->setMajorProtocolVersion(2);
-
- return $result;
- }
-
- /**
- *
- * @param string $status
- * @return string
- */
- public function map_connector_to_element_status($status)
- {
- switch ($status)
+ /**
+ *
+ * @param type $element_type
+ * @param type $element_id
+ * @param type $destination
+ * @param type $container_id
+ * @return Bridge_Api_Youtube_Container
+ */
+ public function add_element_to_container($element_type, $element_id, $destination, $container_id)
{
- case self::UPLOAD_STATE_PROCESSING:
- return Bridge_Element::STATUS_PROCESSING_SERVER;
- break;
- case self::UPLOAD_STATE_RESTRICTED:
- return Bridge_Element::STATUS_ERROR;
- break;
- case self::UPLOAD_STATE_DONE:
- return Bridge_Element::STATUS_DONE;
- break;
- case self::UPLOAD_STATE_DELETED:
- return Bridge_Element::STATUS_ERROR;
- break;
- case self::UPLOAD_STATE_REJECTED:
- return Bridge_Element::STATUS_ERROR;
- break;
- case self::UPLOAD_STATE_FAILED:
- return Bridge_Element::STATUS_ERROR;
- break;
- default:
- return null;
- break;
+ switch ($element_type) {
+ case self::ELEMENT_TYPE_VIDEO:
+ switch ($destination) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $playlistEntry = $this->get_PlaylistEntry_from_Id($container_id);
+ $postUrl = $playlistEntry->getPlaylistVideoFeedUrl();
+
+ $videoEntryToAdd = $this->_api->getVideoEntry($element_id);
+ $newPlaylistListEntry = $this->_api->newPlaylistListEntry($videoEntryToAdd->getDOM());
+ $this->_api->insertEntry($newPlaylistListEntry, $postUrl);
+ $playlistEntry = $this->get_PlaylistEntry_from_Id($container_id);
+
+ return new Bridge_Api_Youtube_Container($playlistEntry, $destination, null);
+ break;
+ default:
+ throw new Bridge_Exception_ContainerUnknown('Unknown element ' . $container);
+ break;
+ }
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown container ' . $element_type);
+ break;
+ }
}
- }
- /**
- *
- * @param string $connector_status
- * @return string
- */
- public function get_error_message_from_status($connector_status)
- {
- switch ($connector_status)
+ /**
+ *
+ * @param string $object
+ * @param string $object_id
+ * @return Void
+ */
+ public function delete_object($object, $object_id)
{
- case self::UPLOAD_STATE_RESTRICTED:
- return _('La video est restreinte');
- break;
- case self::UPLOAD_STATE_DELETED:
- return _('La video a ete supprimee');
- break;
- case self::UPLOAD_STATE_REJECTED:
- return _('La video a ete rejetee');
- break;
- case self::UPLOAD_STATE_FAILED:
- return _('L\'upload a echoue');
- break;
- default:
- case self::UPLOAD_STATE_PROCESSING:
- return _('En cours d\'encodage');
- break;
- default:
- return '';
- break;
- case self::UPLOAD_STATE_DONE:
- return _('OK');
- break;
- }
- }
-
- /**
- * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
- * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
- *
- * @param Exception $e
- * @return Void
- */
- public function handle_exception(Exception &$e)
- {
- if ($e instanceof Zend_Gdata_App_HttpException)
- {
- $response = $e->getResponse();
-
- $http_code = $response->getStatus();
- if ($http_code == 401)
- {
- $e = new Bridge_Exception_ActionAuthNeedReconnect();
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ $this->_api->delete($this->_api->getFullVideoEntry($object_id));
+ break;
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $this->get_PlaylistEntry_from_Id($object_id)->delete();
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
+ break;
+ }
return;
- }
-
- $message = $code = "";
- switch ($response->getStatus())
- {
- case 400:
- $message = _("Erreur la requête a été mal formée ou contenait des données valides.");
- break;
- case 401:
- $message = _("Erreur lors de l'authentification au service Youtube, Veuillez vous déconnecter, puis vous reconnecter.");
- break;
- case 403:
- $message = _("Erreur lors de l'envoi de la requête. Erreur d'authentification.");
- break;
- case 404:
- $message = _("Erreur la ressource que vous tentez de modifier n'existe pas.");
- break;
- case 500:
- $message = _("Erreur YouTube a rencontré une erreur lors du traitement de la requête.");
- break;
- case 501:
- $message = _("Erreur vous avez essayé d'exécuter une requête non prise en charge par Youtube");
- break;
- case 503:
- $message = _("Erreur le service Youtube n'est pas accessible pour le moment. Veuillez réessayer plus tard.");
- break;
- }
-
-
- if ($error = $this->parse_xml_error($response->getBody()))
- {
- $type = $error['type'];
- $code = $error['code'];
-
- if ($code == "too_many_recent_calls")
- {
- $this->block_api(10 * 60 * 60);
- $e = new Bridge_Exception_ApiDisabled($this->get_api_manager());
-
- return;
- }
-
- $reason = '';
- switch ($code)
- {
- case "required":
- $reason = _("A required field is missing or has an empty value");
- break;
- case "deprecated":
- $reason = _("A value has been deprecated and is no longer valid");
- break;
- case "invalid_format":
- $reason = _("A value does not match an expected format");
- break;
- case "invalid_character":
- $reason = _("A field value contains an invalid character");
- break;
- case "too_long":
- $reason = _("A value exceeds the maximum allowable length");
- break;
- case "too_many_recent_calls":
- $reason = _("The Youtube servers have received too many calls from the same caller in a short amount of time.");
- break;
- case "too_many_entries":
- $reason = _("You are attempting to exceed the storage limit on your account and must delete existing entries before inserting new entries");
- break;
- case "InvalidToken";
- $reason = _("The authentication token specified in the Authorization header is invalid");
- break;
- case "TokenExpired";
- $reason = _("The authentication token specified in the Authorization header has expired.");
- break;
- case "disabled_in_maintenance_mode":
- $reason = _("Current operations cannot be executed because the site is temporarily in maintenance mode. Wait a few minutes and try your request again");
- break;
- }
-
- $message .= ' ' . $reason . ' Youtube said : ' . $error['message'];
- }
-
- if ($error == false && $response->getStatus() == 404)
- {
- $message = _("Service youtube introuvable.");
- }
- $e = new Exception($message);
}
- return;
- }
-
- /**
- *
- * @param string $string
- * @return Array
- */
- protected function parse_xml_error($string)
- {
- $rs = array();
- libxml_use_internal_errors(true);
- $xml = simplexml_load_string($string);
- libxml_clear_errors();
-
- if (!$xml)
-
- return false;
-
- if (isset($xml->HEAD) || isset($xml->head))
+ /**
+ *
+ * @return Closure
+ */
+ public function acceptable_records()
{
- return array();
- }
- else
- {
- $domaine = explode(":", (string)$xml->error[0]->domain);
- $rs['type'] = count($domaine) > 1 ? $domaine[1] : $domaine[0];
- $rs['code'] = (string)$xml->error[0]->code;
- $rs['message'] = (string)$xml->error[0]->internalReason;
+ return function (record_adapter &$record) {
+ return $record->get_type() === 'video';
+ };
}
- libxml_use_internal_errors(false);
-
- return $rs;
- }
-
- /**
- *
- * @param record_adapter $record
- * @param array $options
- * @return string The new distant Id
- */
- public function upload(record_adapter &$record, array $options = array())
- {
- switch ($record->get_type())
+ /**
+ *
+ * @param string $element_id
+ * @return string
+ */
+ public function get_element_status(Bridge_Element $element)
{
- case 'video':
+ $this->_api->setMajorProtocolVersion(1);
+ $state = $this->_api->getFullVideoEntry($element->get_dist_id())->getVideoState();
- $video_entry = new Zend_Gdata_YouTube_VideoEntry();
-
- $filesource = new Zend_Gdata_App_MediaFileSource($record->get_hd_file()->getRealPath());
- $filesource->setContentType($record->get_hd_file()->get_mime());
- $filesource->setSlug($record->get_title());
-
- $video_entry->setMediaSource($filesource);
- $video_entry->setVideoTitle($options['title']);
- $video_entry->setVideoDescription($options['description']);
- $video_entry->setVideoCategory($options['category']);
- $video_entry->SetVideoTags(explode(' ', $options['tags']));
- $video_entry->setVideoDeveloperTags(array('phraseanet'));
-
- if ($options['privacy'] == "public")
- $video_entry->setVideoPublic();
+ if (is_null($state))
+ $result = Bridge_Element::STATUS_DONE;
else
- $video_entry->setVideoPrivate();
+ $result = $state->getName();
- $app_entry = $this->_api->insertEntry($video_entry, self::UPLOAD_URL, 'Zend_Gdata_YouTube_VideoEntry');
+ $this->_api->setMajorProtocolVersion(2);
- /*
- * set major protocole version to 2 otherwise you get exception when calling getVideoId
- * but setting setMajorProtocolVersion to 2 at the new entry introduce a new bug with getVideoState
- * @see http://groups.google.com/group/youtube-api-gdata/browse_thread/thread/7d86cac0d3f90e3f/d9291d7314f99be7?pli=1
- */
- $app_entry->setMajorProtocolVersion(2);
-
- return $app_entry->getVideoId();
- break;
- default:
- throw new Bridge_Exception_InvalidRecordType('Unknown format');
- break;
+ return $result;
}
- }
- /**
- *
- * @param string $object
- * @param string $element_id
- * @return Bridge_Api_Youtube_Element
- */
- public function get_element_from_id($element_id, $object)
- {
- switch ($object)
+ /**
+ *
+ * @param string $status
+ * @return string
+ */
+ public function map_connector_to_element_status($status)
{
- case self::ELEMENT_TYPE_VIDEO:
- return new Bridge_Api_Youtube_Element($this->_api->getVideoEntry($element_id), $object);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
+ switch ($status) {
+ case self::UPLOAD_STATE_PROCESSING:
+ return Bridge_Element::STATUS_PROCESSING_SERVER;
+ break;
+ case self::UPLOAD_STATE_RESTRICTED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ case self::UPLOAD_STATE_DONE:
+ return Bridge_Element::STATUS_DONE;
+ break;
+ case self::UPLOAD_STATE_DELETED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ case self::UPLOAD_STATE_REJECTED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ case self::UPLOAD_STATE_FAILED:
+ return Bridge_Element::STATUS_ERROR;
+ break;
+ default:
+ return null;
+ break;
+ }
}
- }
- /**
- * get available youtube categories as an array
- *
- * @return array
- */
- public function get_category_list()
- {
- $cat = array();
- $url_cat = sprintf('%s?hl=%s', self::CATEGORY_URL, $this->get_locale());
-
- $cxml = @simplexml_load_file($url_cat);
-
- if (!$cxml)
- throw new Bridge_Exception_ApiConnectorRequestFailed('Failed to retrive youtube categories');
-
- $cxml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
- $categories = $cxml->xpath('//atom:category');
-
- foreach ($categories as $c)
+ /**
+ *
+ * @param string $connector_status
+ * @return string
+ */
+ public function get_error_message_from_status($connector_status)
{
- $cat[(string) $c['term']] = (string) $c['label'];
+ switch ($connector_status) {
+ case self::UPLOAD_STATE_RESTRICTED:
+ return _('La video est restreinte');
+ break;
+ case self::UPLOAD_STATE_DELETED:
+ return _('La video a ete supprimee');
+ break;
+ case self::UPLOAD_STATE_REJECTED:
+ return _('La video a ete rejetee');
+ break;
+ case self::UPLOAD_STATE_FAILED:
+ return _('L\'upload a echoue');
+ break;
+ default:
+ case self::UPLOAD_STATE_PROCESSING:
+ return _('En cours d\'encodage');
+ break;
+ default:
+ return '';
+ break;
+ case self::UPLOAD_STATE_DONE:
+ return _('OK');
+ break;
+ }
}
- return $cat;
- }
-
- /**
- *
- * @param string $object
- * @param string $element_id
- * @return Bridge_Api_Youtube_Container
- */
- public function get_container_from_id($object, $element_id)
- {
- switch ($object)
+ /**
+ * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
+ * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
+ *
+ * @param Exception $e
+ * @return Void
+ */
+ public function handle_exception(Exception &$e)
{
- case self::CONTAINER_TYPE_PLAYLIST:
- return new Bridge_Api_Youtube_Container($this->get_PlaylistEntry_from_Id($element_id), $object, null);
- break;
- default:
- throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
- break;
- }
- }
+ if ($e instanceof Zend_Gdata_App_HttpException) {
+ $response = $e->getResponse();
- /**
- *
- * @param string $object
- * @param int $offset_start
- * @param int $quantity
- * @return string
- */
- protected function get_user_object_list_feed($object, $offset_start, $quantity)
- {
- $feed = null;
- switch ($object)
+ $http_code = $response->getStatus();
+ if ($http_code == 401) {
+ $e = new Bridge_Exception_ActionAuthNeedReconnect();
+
+ return;
+ }
+
+ $message = $code = "";
+ switch ($response->getStatus()) {
+ case 400:
+ $message = _("Erreur la requête a été mal formée ou contenait des données valides.");
+ break;
+ case 401:
+ $message = _("Erreur lors de l'authentification au service Youtube, Veuillez vous déconnecter, puis vous reconnecter.");
+ break;
+ case 403:
+ $message = _("Erreur lors de l'envoi de la requête. Erreur d'authentification.");
+ break;
+ case 404:
+ $message = _("Erreur la ressource que vous tentez de modifier n'existe pas.");
+ break;
+ case 500:
+ $message = _("Erreur YouTube a rencontré une erreur lors du traitement de la requête.");
+ break;
+ case 501:
+ $message = _("Erreur vous avez essayé d'exécuter une requête non prise en charge par Youtube");
+ break;
+ case 503:
+ $message = _("Erreur le service Youtube n'est pas accessible pour le moment. Veuillez réessayer plus tard.");
+ break;
+ }
+
+
+ if ($error = $this->parse_xml_error($response->getBody())) {
+ $type = $error['type'];
+ $code = $error['code'];
+
+ if ($code == "too_many_recent_calls") {
+ $this->block_api(10 * 60 * 60);
+ $e = new Bridge_Exception_ApiDisabled($this->get_api_manager());
+
+ return;
+ }
+
+ $reason = '';
+ switch ($code) {
+ case "required":
+ $reason = _("A required field is missing or has an empty value");
+ break;
+ case "deprecated":
+ $reason = _("A value has been deprecated and is no longer valid");
+ break;
+ case "invalid_format":
+ $reason = _("A value does not match an expected format");
+ break;
+ case "invalid_character":
+ $reason = _("A field value contains an invalid character");
+ break;
+ case "too_long":
+ $reason = _("A value exceeds the maximum allowable length");
+ break;
+ case "too_many_recent_calls":
+ $reason = _("The Youtube servers have received too many calls from the same caller in a short amount of time.");
+ break;
+ case "too_many_entries":
+ $reason = _("You are attempting to exceed the storage limit on your account and must delete existing entries before inserting new entries");
+ break;
+ case "InvalidToken";
+ $reason = _("The authentication token specified in the Authorization header is invalid");
+ break;
+ case "TokenExpired";
+ $reason = _("The authentication token specified in the Authorization header has expired.");
+ break;
+ case "disabled_in_maintenance_mode":
+ $reason = _("Current operations cannot be executed because the site is temporarily in maintenance mode. Wait a few minutes and try your request again");
+ break;
+ }
+
+ $message .= ' ' . $reason . ' Youtube said : ' . $error['message'];
+ }
+
+ if ($error == false && $response->getStatus() == 404) {
+ $message = _("Service youtube introuvable.");
+ }
+ $e = new Exception($message);
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param string $string
+ * @return Array
+ */
+ protected function parse_xml_error($string)
{
- case self::ELEMENT_TYPE_VIDEO:
- $uri = Zend_Gdata_YouTube::USER_URI . '/default/' . Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX;
- $query = new Zend_Gdata_Query($uri);
- if ($quantity !== 0)
- $query->setMaxResults($quantity);
- $query->setStartIndex($offset_start);
- $feed = $this->_api->getUserUploads(null, $query);
- break;
- case self::CONTAINER_TYPE_PLAYLIST:
- $uri = Zend_Gdata_YouTube::USER_URI . '/default/playlists';
- $query = new Zend_Gdata_Query($uri);
- if ($quantity !== 0)
- $query->setMaxResults($quantity);
- $query->setStartIndex($offset_start);
- $feed = $this->_api->getPlaylistListFeed(null, $query);
- break;
- default:
- throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
- break;
+ $rs = array();
+ libxml_use_internal_errors(true);
+ $xml = simplexml_load_string($string);
+ libxml_clear_errors();
+
+ if ( ! $xml)
+ return false;
+
+ if (isset($xml->HEAD) || isset($xml->head)) {
+ return array();
+ } else {
+ $domaine = explode(":", (string) $xml->error[0]->domain);
+ $rs['type'] = count($domaine) > 1 ? $domaine[1] : $domaine[0];
+ $rs['code'] = (string) $xml->error[0]->code;
+ $rs['message'] = (string) $xml->error[0]->internalReason;
+ }
+
+ libxml_use_internal_errors(false);
+
+ return $rs;
}
- return $feed;
- }
+ /**
+ *
+ * @param record_adapter $record
+ * @param array $options
+ * @return string The new distant Id
+ */
+ public function upload(record_adapter &$record, array $options = array())
+ {
+ switch ($record->get_type()) {
+ case 'video':
- public function is_configured()
- {
- if (!$this->registry->get('GV_youtube_api'))
+ $video_entry = new Zend_Gdata_YouTube_VideoEntry();
- return false;
+ $filesource = new Zend_Gdata_App_MediaFileSource($record->get_hd_file()->getRealPath());
+ $filesource->setContentType($record->get_hd_file()->get_mime());
+ $filesource->setSlug($record->get_title());
- if (trim($this->registry->get('GV_youtube_client_id')) === '')
+ $video_entry->setMediaSource($filesource);
+ $video_entry->setVideoTitle($options['title']);
+ $video_entry->setVideoDescription($options['description']);
+ $video_entry->setVideoCategory($options['category']);
+ $video_entry->SetVideoTags(explode(' ', $options['tags']));
+ $video_entry->setVideoDeveloperTags(array('phraseanet'));
- return false;
+ if ($options['privacy'] == "public")
+ $video_entry->setVideoPublic();
+ else
+ $video_entry->setVideoPrivate();
- if (trim($this->registry->get('GV_youtube_dev_key')) === '')
+ $app_entry = $this->_api->insertEntry($video_entry, self::UPLOAD_URL, 'Zend_Gdata_YouTube_VideoEntry');
- return false;
+ /*
+ * set major protocole version to 2 otherwise you get exception when calling getVideoId
+ * but setting setMajorProtocolVersion to 2 at the new entry introduce a new bug with getVideoState
+ * @see http://groups.google.com/group/youtube-api-gdata/browse_thread/thread/7d86cac0d3f90e3f/d9291d7314f99be7?pli=1
+ */
+ $app_entry->setMajorProtocolVersion(2);
- return true;
- }
+ return $app_entry->getVideoId();
+ break;
+ default:
+ throw new Bridge_Exception_InvalidRecordType('Unknown format');
+ break;
+ }
+ }
- /**
- *
- * @return Bridge_Api_Youtube
- */
- protected function set_auth_params()
- {
- $this->_auth->set_parameters(
+ /**
+ *
+ * @param string $object
+ * @param string $element_id
+ * @return Bridge_Api_Youtube_Element
+ */
+ public function get_element_from_id($element_id, $object)
+ {
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ return new Bridge_Api_Youtube_Element($this->_api->getVideoEntry($element_id), $object);
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ * get available youtube categories as an array
+ *
+ * @return array
+ */
+ public function get_category_list()
+ {
+ $cat = array();
+ $url_cat = sprintf('%s?hl=%s', self::CATEGORY_URL, $this->get_locale());
+
+ $cxml = @simplexml_load_file($url_cat);
+
+ if ( ! $cxml)
+ throw new Bridge_Exception_ApiConnectorRequestFailed('Failed to retrive youtube categories');
+
+ $cxml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
+ $categories = $cxml->xpath('//atom:category');
+
+ foreach ($categories as $c) {
+ $cat[(string) $c['term']] = (string) $c['label'];
+ }
+
+ return $cat;
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param string $element_id
+ * @return Bridge_Api_Youtube_Container
+ */
+ public function get_container_from_id($object, $element_id)
+ {
+ switch ($object) {
+ case self::CONTAINER_TYPE_PLAYLIST:
+ return new Bridge_Api_Youtube_Container($this->get_PlaylistEntry_from_Id($element_id), $object, null);
+ break;
+ default:
+ throw new Bridge_Exception_ElementUnknown('Unknown element ' . $object);
+ break;
+ }
+ }
+
+ /**
+ *
+ * @param string $object
+ * @param int $offset_start
+ * @param int $quantity
+ * @return string
+ */
+ protected function get_user_object_list_feed($object, $offset_start, $quantity)
+ {
+ $feed = null;
+ switch ($object) {
+ case self::ELEMENT_TYPE_VIDEO:
+ $uri = Zend_Gdata_YouTube::USER_URI . '/default/' . Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX;
+ $query = new Zend_Gdata_Query($uri);
+ if ($quantity !== 0)
+ $query->setMaxResults($quantity);
+ $query->setStartIndex($offset_start);
+ $feed = $this->_api->getUserUploads(null, $query);
+ break;
+ case self::CONTAINER_TYPE_PLAYLIST:
+ $uri = Zend_Gdata_YouTube::USER_URI . '/default/playlists';
+ $query = new Zend_Gdata_Query($uri);
+ if ($quantity !== 0)
+ $query->setMaxResults($quantity);
+ $query->setStartIndex($offset_start);
+ $feed = $this->_api->getPlaylistListFeed(null, $query);
+ break;
+ default:
+ throw new Bridge_Exception_ObjectUnknown('Unknown object ' . $object);
+ break;
+ }
+
+ return $feed;
+ }
+
+ public function is_configured()
+ {
+ if ( ! $this->registry->get('GV_youtube_api'))
+ return false;
+
+ if (trim($this->registry->get('GV_youtube_client_id')) === '')
+ return false;
+
+ if (trim($this->registry->get('GV_youtube_dev_key')) === '')
+ return false;
+
+ return true;
+ }
+
+ /**
+ *
+ * @return Bridge_Api_Youtube
+ */
+ protected function set_auth_params()
+ {
+ $this->_auth->set_parameters(
array(
- 'client_id' => $this->registry->get('GV_youtube_client_id')
- , 'client_secret' => $this->registry->get('GV_youtube_client_secret')
- , 'redirect_uri' => Bridge_Api::generate_callback_url($this->registry, $this->get_name())
- , 'scope' => 'http://gdata.youtube.com'
- , 'response_type' => 'code'
+ 'client_id' => $this->registry->get('GV_youtube_client_id')
+ , 'client_secret' => $this->registry->get('GV_youtube_client_secret')
+ , 'redirect_uri' => Bridge_Api::generate_callback_url($this->registry, $this->get_name())
+ , 'scope' => 'http://gdata.youtube.com'
+ , 'response_type' => 'code'
, 'token_endpoint' => self::OAUTH2_TOKEN_ENDPOINT
- , 'auth_endpoint' => self::OAUTH2_AUTHORIZE_ENDPOINT
+ , 'auth_endpoint' => self::OAUTH2_AUTHORIZE_ENDPOINT
)
- );
+ );
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Youtube
- */
- protected function initialize_transport()
- {
- $http_client = new Zend_Gdata_HttpClient();
- $http_client->setHeaders('Accept', 'application/atom+xml');
-
- $this->_api = new Zend_Gdata_YouTube(
- $http_client,
- uuid::generate_v4(),
- $this->registry->get('GV_youtube_client_id'),
- $this->registry->get('GV_youtube_dev_key'));
- $this->_api->setMajorProtocolVersion(2);
-
- return $this;
- }
-
- /**
- *
- * @return Bridge_Api_Youtube
- */
- protected function set_transport_authentication_params()
- {
- if ($this->_auth->is_connected())
- {
- $signatures = $this->_auth->get_auth_signatures();
- $this->_api->getHttpClient()->setAuthSubToken($signatures['auth_token']);
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param string $element_id
- * @return Zend_Gdata_YouTube_PlaylistListFeed
- */
- protected function get_PlaylistEntry_from_Id($element_id)
- {
- foreach ($this->_api->getPlaylistListFeed('default') as $playlist_entry)
+ /**
+ *
+ * @return Bridge_Api_Youtube
+ */
+ protected function initialize_transport()
{
- if ($element_id == $playlist_entry->getPlaylistId()->getText())
+ $http_client = new Zend_Gdata_HttpClient();
+ $http_client->setHeaders('Accept', 'application/atom+xml');
- return $playlist_entry;
+ $this->_api = new Zend_Gdata_YouTube(
+ $http_client,
+ uuid::generate_v4(),
+ $this->registry->get('GV_youtube_client_id'),
+ $this->registry->get('GV_youtube_dev_key'));
+ $this->_api->setMajorProtocolVersion(2);
+
+ return $this;
}
- return null;
- }
-
- /**
- *
- * @return string
- */
- public function get_locale()
- {
- $youtube_available_locale = array(
- 'zh-CN', 'zh-TW', 'cs-CZ', 'nl-NL', 'en-GB', 'en-US', 'fr-FR', 'de-DE',
- 'it-IT', 'ja-JP', 'ko-KR', 'pl-PL', 'pt-PT', 'ru-RU', 'es-ES', 'es-MX',
- 'sv-SE'
- );
- if (!is_null($this->locale))
+ /**
+ *
+ * @return Bridge_Api_Youtube
+ */
+ protected function set_transport_authentication_params()
{
- $youtube_format_locale = str_replace('_', '-', $this->locale);
- if (in_array(trim($youtube_format_locale), $youtube_available_locale))
+ if ($this->_auth->is_connected()) {
+ $signatures = $this->_auth->get_auth_signatures();
+ $this->_api->getHttpClient()->setAuthSubToken($signatures['auth_token']);
+ }
- return $this->locale;
+ return $this;
}
- return "en-US";
- }
+ /**
+ *
+ * @param string $element_id
+ * @return Zend_Gdata_YouTube_PlaylistListFeed
+ */
+ protected function get_PlaylistEntry_from_Id($element_id)
+ {
+ foreach ($this->_api->getPlaylistListFeed('default') as $playlist_entry) {
+ if ($element_id == $playlist_entry->getPlaylistId()->getText())
+ return $playlist_entry;
+ }
- /**
- *
- * Check if data uploaded via the current connector is conform
- * @param Request $request
- * @param record_adapter $record
- * @return array
- */
- public function check_upload_constraints(Array $datas, record_adapter $record)
- {
- $errors = $this->check_record_constraints($record);
+ return null;
+ }
- $check = function($field) use (&$errors, $datas, $record)
- {
- $key = $record->get_serialize_key();
- $name = $field['name'];
- $length = (int) $field['length'];
- $required = !!$field['required'];
- $empty = !!$field['empty'];
+ /**
+ *
+ * @return string
+ */
+ public function get_locale()
+ {
+ $youtube_available_locale = array(
+ 'zh-CN', 'zh-TW', 'cs-CZ', 'nl-NL', 'en-GB', 'en-US', 'fr-FR', 'de-DE',
+ 'it-IT', 'ja-JP', 'ko-KR', 'pl-PL', 'pt-PT', 'ru-RU', 'es-ES', 'es-MX',
+ 'sv-SE'
+ );
+ if ( ! is_null($this->locale)) {
+ $youtube_format_locale = str_replace('_', '-', $this->locale);
+ if (in_array(trim($youtube_format_locale), $youtube_available_locale))
+ return $this->locale;
+ }
- if (!isset($datas[$name]))
- {
- if ($required)
- $errors[$name . '_' .$key] = _("Ce champ est obligatoire");
- }
- elseif(trim($datas[$name]) === '')
- {
- if (!$empty)
- $errors[$name . '_' .$key] = _("Ce champ est obligatoire");
- }
- elseif ($length !== 0)
- {
- if (mb_strlen($datas[$name]) > $length)
- $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- }
+ return "en-US";
+ }
+
+ /**
+ *
+ * Check if data uploaded via the current connector is conform
+ * @param Request $request
+ * @param record_adapter $record
+ * @return array
+ */
+ public function check_upload_constraints(Array $datas, record_adapter $record)
+ {
+ $errors = $this->check_record_constraints($record);
+
+ $check = function($field) use (&$errors, $datas, $record) {
+ $key = $record->get_serialize_key();
+ $name = $field['name'];
+ $length = (int) $field['length'];
+ $required = ! ! $field['required'];
+ $empty = ! ! $field['empty'];
+
+ if ( ! isset($datas[$name])) {
+ if ($required)
+ $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
+ }
+ elseif (trim($datas[$name]) === '') {
+ if ( ! $empty)
+ $errors[$name . '_' . $key] = _("Ce champ est obligatoire");
+ }
+ elseif ($length !== 0) {
+ if (mb_strlen($datas[$name]) > $length)
+ $errors[$name . '_' . $key] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ }
};
- array_map($check, $this->get_fields());
+ array_map($check, $this->get_fields());
- return $errors;
- }
+ return $errors;
+ }
- public function check_update_constraints(Array $datas)
- {
- $errors = array();
- $check = function($field) use (&$errors, $datas)
- {
- $name = $field['name'];
- $length = (int) $field['length'];
- $required = !!$field['required'];
- $empty = !!$field['empty'];
+ public function check_update_constraints(Array $datas)
+ {
+ $errors = array();
+ $check = function($field) use (&$errors, $datas) {
+ $name = $field['name'];
+ $length = (int) $field['length'];
+ $required = ! ! $field['required'];
+ $empty = ! ! $field['empty'];
- if (!isset($datas[$name]))
- {
- if ($required)
- $errors[$name] = _("Ce champ est obligatoire");
- }
- elseif(trim($datas[$name]) === '')
- {
- if (!$empty)
- $errors[$name] = _("Ce champ est obligatoire");
- }
- elseif ($length !== 0)
- {
- if (mb_strlen($datas[$name]) > $length)
- $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
- }
+ if ( ! isset($datas[$name])) {
+ if ($required)
+ $errors[$name] = _("Ce champ est obligatoire");
+ }
+ elseif (trim($datas[$name]) === '') {
+ if ( ! $empty)
+ $errors[$name] = _("Ce champ est obligatoire");
+ }
+ elseif ($length !== 0) {
+ if (mb_strlen($datas[$name]) > $length)
+ $errors[$name] = sprintf(_("Ce champ est trop long %s caracteres max"), $length);
+ }
};
- array_map($check, $this->get_fields());
+ array_map($check, $this->get_fields());
- return $errors;
- }
+ return $errors;
+ }
- /**
- * Returns datas needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_update_datas(Request $request)
- {
- $datas = array(
- 'title' => $request->get('modif_title'),
- 'description' => $request->get('modif_description'),
- 'category' => $request->get('modif_category'),
- 'tags' => $request->get('modif_tags'),
- 'privacy' => $request->get('modif_privacy'),
- );
+ /**
+ * Returns datas needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_update_datas(Request $request)
+ {
+ $datas = array(
+ 'title' => $request->get('modif_title'),
+ 'description' => $request->get('modif_description'),
+ 'category' => $request->get('modif_category'),
+ 'tags' => $request->get('modif_tags'),
+ 'privacy' => $request->get('modif_privacy'),
+ );
- return $datas;
- }
+ return $datas;
+ }
- /**
- * Returns datas needed for an uploaded record
- * @param record_adapter $record
- * @return array
- */
- public function get_upload_datas(Request $request, record_adapter $record)
- {
- $key = $record->get_serialize_key();
- $datas = array(
- 'title' => $request->get('title_' . $key),
- 'description' => $request->get('description_' . $key),
- 'category' => $request->get('category_' . $key),
- 'tags' => $request->get('tags_' . $key),
- 'privacy' => $request->get('privacy_' . $key),
- );
+ /**
+ * Returns datas needed for an uploaded record
+ * @param record_adapter $record
+ * @return array
+ */
+ public function get_upload_datas(Request $request, record_adapter $record)
+ {
+ $key = $record->get_serialize_key();
+ $datas = array(
+ 'title' => $request->get('title_' . $key),
+ 'description' => $request->get('description_' . $key),
+ 'category' => $request->get('category_' . $key),
+ 'tags' => $request->get('tags_' . $key),
+ 'privacy' => $request->get('privacy_' . $key),
+ );
- return $datas;
- }
+ return $datas;
+ }
- /**
- * @todo implements in bridge_api_interface
- * @todo write test
- * Tell if the current connector can upload multiple file
- * @return boolean
- */
- public function is_multiple_upload()
- {
- return false;
- }
+ /**
+ * @todo implements in bridge_api_interface
+ * @todo write test
+ * Tell if the current connector can upload multiple file
+ * @return boolean
+ */
+ public function is_multiple_upload()
+ {
+ return false;
+ }
- /**
- *
- * @param record_adapter $record
- * @return array
- */
- private function check_record_constraints(record_adapter $record)
- {
- $errors = array();
- $key = $record->get_serialize_key();
- if (!$record->get_hd_file() instanceof SplFileObject)
- $errors["file_size_" . $key] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
+ /**
+ *
+ * @param record_adapter $record
+ * @return array
+ */
+ private function check_record_constraints(record_adapter $record)
+ {
+ $errors = array();
+ $key = $record->get_serialize_key();
+ if ( ! $record->get_hd_file() instanceof SplFileObject)
+ $errors["file_size_" . $key] = _("Le record n'a pas de fichier physique"); //Record must rely on real file
- if ($record->get_duration() > self::AUTH_VIDEO_DURATION)
- $errors["duration_" . $key] = sprintf(_("La taille maximale d'une video est de %d minutes."), self::AUTH_VIDEO_DURATION / 60);
+ if ($record->get_duration() > self::AUTH_VIDEO_DURATION)
+ $errors["duration_" . $key] = sprintf(_("La taille maximale d'une video est de %d minutes."), self::AUTH_VIDEO_DURATION / 60);
- if ($record->get_technical_infos('size') > self::AUTH_VIDEO_SIZE)
- $errors["size_" . $key] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_VIDEO_SIZE));
+ if ($record->get_technical_infos('size') > self::AUTH_VIDEO_SIZE)
+ $errors["size_" . $key] = sprintf(_("Le poids maximum d'un fichier est de %s"), p4string::format_octets(self::AUTH_VIDEO_SIZE));
- return $errors;
- }
-
- /**
- *
- * @return array
- */
- private function get_fields()
- {
- return array(
- array(
- 'name' => 'title',
- 'length' => '100',
- 'required' => true,
- 'empty' => false
- )
- , array(
- 'name' => 'description',
- 'length' => '2000',
- 'required' => true,
- 'empty' => true
- )
- , array(
- 'name' => 'tags',
- 'length' => '500',
- 'tag_length' => '30',
- 'required' => true,
- 'empty' => true
-
- )
- , array(
- 'name' => 'privacy',
- 'length' => '0',
- 'required' => true,
- 'empty' => false
-
- )
- , array(
- 'name' => 'category',
- 'length' => '0',
- 'required' => true,
- 'empty' => false
- )
- );
- }
+ return $errors;
+ }
+ /**
+ *
+ * @return array
+ */
+ private function get_fields()
+ {
+ return array(
+ array(
+ 'name' => 'title',
+ 'length' => '100',
+ 'required' => true,
+ 'empty' => false
+ )
+ , array(
+ 'name' => 'description',
+ 'length' => '2000',
+ 'required' => true,
+ 'empty' => true
+ )
+ , array(
+ 'name' => 'tags',
+ 'length' => '500',
+ 'tag_length' => '30',
+ 'required' => true,
+ 'empty' => true
+ )
+ , array(
+ 'name' => 'privacy',
+ 'length' => '0',
+ 'required' => true,
+ 'empty' => false
+ )
+ , array(
+ 'name' => 'category',
+ 'length' => '0',
+ 'required' => true,
+ 'empty' => false
+ )
+ );
+ }
}
diff --git a/lib/classes/Bridge/Api/Youtube/Container.class.php b/lib/classes/Bridge/Api/Youtube/Container.class.php
index 1775c17d9f..483c3ff964 100644
--- a/lib/classes/Bridge/Api/Youtube/Container.class.php
+++ b/lib/classes/Bridge/Api/Youtube/Container.class.php
@@ -17,120 +17,117 @@
*/
class Bridge_Api_Youtube_Container implements Bridge_Api_ContainerInterface
{
+ /**
+ *
+ * @var Zend_Gdata_App_Entry
+ */
+ protected $entry;
- /**
- *
- * @var Zend_Gdata_App_Entry
- */
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var string
+ */
+ protected $thumbnail;
- /**
- *
- * @var string
- */
- protected $thumbnail;
+ public function __construct(Zend_Gdata_App_Entry $entry, $type, $thumbnail)
+ {
+ $this->entry = $entry;
+ $this->type = $type;
+ $this->thumbnail = $thumbnail;
- public function __construct(Zend_Gdata_App_Entry $entry, $type, $thumbnail)
- {
- $this->entry = $entry;
- $this->type = $type;
- $this->thumbnail = $thumbnail;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_id()
+ {
+ return $this->entry->getPlaylistId()->getText();
+ }
- /**
- *
- * @var string
- */
- public function get_id()
- {
- return $this->entry->getPlaylistId()->getText();
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_thumbnail($width = 120, $height = 90)
+ {
+ return $this->thumbnail;
+ }
- /**
- *
- * @var string
- */
- public function get_thumbnail($width = 120, $height = 90)
- {
- return $this->thumbnail;
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_url()
+ {
+ return $this->entry->getAlternateLink()->getHref();
+ }
- /**
- *
- * @var string
- */
- public function get_url()
- {
- return $this->entry->getAlternateLink()->getHref();
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_title()
+ {
+ return $this->entry->getTitle()->getText();
+ }
- /**
- *
- * @var string
- */
- public function get_title()
- {
- return $this->entry->getTitle()->getText();
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_description()
+ {
+ return $this->entry->getDescription()->getText();
+ }
- /**
- *
- * @var string
- */
- public function get_description()
- {
- return $this->entry->getDescription()->getText();
- }
+ /**
+ *
+ * @var DateTime
+ */
+ public function get_updated_on()
+ {
+ return new DateTime($this->entry->getUpdated()->getText());
+ }
- /**
- *
- * @var DateTime
- */
- public function get_updated_on()
- {
- return new DateTime($this->entry->getUpdated()->getText());
- }
+ /**
+ *
+ * @var DateTime
+ */
+ public function get_created_on()
+ {
+ return new DateTime($this->entry->getPublished()->getText());
+ }
- /**
- *
- * @var DateTime
- */
- public function get_created_on()
- {
- return new DateTime($this->entry->getPublished()->getText());
- }
+ /**
+ *
+ * @var string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- /**
- *
- * @var string
- */
- public function get_type()
- {
- return $this->type;
- }
+ public function get_duration()
+ {
+ return '';
+ }
- public function get_duration()
- {
- return '';
- }
+ public function get_category()
+ {
+ return '';
+ }
-
- public function get_category()
- {
- return '';
- }
-
-
- public function is_private()
- {
- return null;
- }
+ public function is_private()
+ {
+ return null;
+ }
}
diff --git a/lib/classes/Bridge/Api/Youtube/Element.class.php b/lib/classes/Bridge/Api/Youtube/Element.class.php
index b2788ef38c..d3117ce940 100644
--- a/lib/classes/Bridge/Api/Youtube/Element.class.php
+++ b/lib/classes/Bridge/Api/Youtube/Element.class.php
@@ -17,164 +17,160 @@
*/
class Bridge_Api_Youtube_Element implements Bridge_Api_ElementInterface
{
+ /**
+ *
+ * @var Zend_Gdata_App_Entry
+ */
+ protected $entry;
- /**
- *
- * @var Zend_Gdata_App_Entry
- */
- protected $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
-
- /**
- *
- * @param Zend_Gdata_App_Entry $entry
- * @param string $type
- * @return Bridge_Api_Youtube_Element
- */
- public function __construct(Zend_Gdata_App_Entry $entry, $type)
- {
- $this->entry = $entry;
- $this->type = $type;
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_id()
- {
- return $this->entry->getVideoId();
- }
-
- /**
- * Return the thumbnail of the element
- * Available size : 120*90;480*360;
- *
- * @return string
- */
- public function get_thumbnail()
- {
- $video_thumbnails = $this->entry->getVideoThumbnails();
-
- foreach ($video_thumbnails as $thumb)
+ /**
+ *
+ * @param Zend_Gdata_App_Entry $entry
+ * @param string $type
+ * @return Bridge_Api_Youtube_Element
+ */
+ public function __construct(Zend_Gdata_App_Entry $entry, $type)
{
- if (120 == $thumb['width'] && 90 == $thumb['height'])
+ $this->entry = $entry;
+ $this->type = $type;
- return $thumb['url'];
+ return $this;
}
- }
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return $this->entry->getVideoWatchPageUrl();
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_id()
+ {
+ return $this->entry->getVideoId();
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->entry->getVideoTitle();
- }
+ /**
+ * Return the thumbnail of the element
+ * Available size : 120*90;480*360;
+ *
+ * @return string
+ */
+ public function get_thumbnail()
+ {
+ $video_thumbnails = $this->entry->getVideoThumbnails();
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return $this->entry->getVideoDescription();
- }
+ foreach ($video_thumbnails as $thumb) {
+ if (120 == $thumb['width'] && 90 == $thumb['height'])
+ return $thumb['url'];
+ }
+ }
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return new DateTime($this->entry->getUpdated()->getText());
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return $this->entry->getVideoWatchPageUrl();
+ }
- /**
- *
- * @return string
- */
- public function get_category()
- {
- return $this->entry->getVideoCategory();
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->entry->getVideoTitle();
+ }
- /**
- *
- * @return string
- */
- public function get_duration()
- {
- return p4string::format_seconds($this->entry->getVideoDuration());
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return $this->entry->getVideoDescription();
+ }
- /**
- *
- * @return int
- */
- public function get_view_count()
- {
- return (int) $this->entry->getVideoViewCount();
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return new DateTime($this->entry->getUpdated()->getText());
+ }
- /**
- *
- * @return int
- */
- public function get_rating()
- {
- $rating_info = $this->entry->getVideoRatingInfo();
+ /**
+ *
+ * @return string
+ */
+ public function get_category()
+ {
+ return $this->entry->getVideoCategory();
+ }
- return (int) $rating_info["numRaters"];
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_duration()
+ {
+ return p4string::format_seconds($this->entry->getVideoDuration());
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return new DateTime($this->entry->getPublished()->getText());
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_view_count()
+ {
+ return (int) $this->entry->getVideoViewCount();
+ }
- /**
- *
- * @return boolean
- */
- public function is_private()
- {
- return !!$this->entry->isVideoPrivate();
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_rating()
+ {
+ $rating_info = $this->entry->getVideoRatingInfo();
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ return (int) $rating_info["numRaters"];
+ }
- public function get_tags()
- {
- return implode(",", $this->entry->getVideoTags());
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return new DateTime($this->entry->getPublished()->getText());
+ }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_private()
+ {
+ return ! ! $this->entry->isVideoPrivate();
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
+
+ public function get_tags()
+ {
+ return implode(",", $this->entry->getVideoTags());
+ }
}
diff --git a/lib/classes/Bridge/Element.class.php b/lib/classes/Bridge/Element.class.php
index 20f396c92e..0b41e18d41 100644
--- a/lib/classes/Bridge/Element.class.php
+++ b/lib/classes/Bridge/Element.class.php
@@ -17,504 +17,498 @@
*/
class Bridge_Element
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var account
+ */
+ protected $account;
- /**
- *
- * @var account
- */
- protected $account;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var record_adapter
+ */
+ protected $record;
- /**
- *
- * @var record_adapter
- */
- protected $record;
+ /**
+ *
+ * @var string
+ */
+ protected $dist_id;
- /**
- *
- * @var string
- */
- protected $dist_id;
+ /**
+ *
+ * @var string
+ */
+ protected $status;
- /**
- *
- * @var string
- */
- protected $status;
+ /**
+ *
+ * @var string
+ */
+ protected $connector_status;
- /**
- *
- * @var string
- */
- protected $connector_status;
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @var string
- */
- protected $title;
+ /**
+ *
+ * @var string
+ */
+ protected $type;
- /**
- *
- * @var string
- */
- protected $type;
+ /**
+ *
+ * @var array
+ */
+ protected $datas;
- /**
- *
- * @var array
- */
- protected $datas;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $uploaded_on;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $uploaded_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
- /**
- *
- * @var Bridge_Api_ElementInterface
- */
- protected $connector_element;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- const STATUS_DONE = 'done';
- const STATUS_PROCESSING_SERVER = 'processing_server';
- const STATUS_PROCESSING = 'processing';
- const STATUS_PENDING = 'pending';
- const STATUS_ERROR = 'error';
+ /**
+ *
+ * @var Bridge_Api_ElementInterface
+ */
+ protected $connector_element;
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Account $account
- * @param int $id
- * @return Bridge_Element
- */
- public function __construct(appbox &$appbox, Bridge_Account &$account, $id)
- {
- $this->appbox = $appbox;
- $this->account = $account;
- $this->id = (int) $id;
+ const STATUS_DONE = 'done';
+ const STATUS_PROCESSING_SERVER = 'processing_server';
+ const STATUS_PROCESSING = 'processing';
+ const STATUS_PENDING = 'pending';
+ const STATUS_ERROR = 'error';
- $sql = 'SELECT sbas_id, record_id, dist_id, status, connector_status, type
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Account $account
+ * @param int $id
+ * @return Bridge_Element
+ */
+ public function __construct(appbox &$appbox, Bridge_Account &$account, $id)
+ {
+ $this->appbox = $appbox;
+ $this->account = $account;
+ $this->id = (int) $id;
+
+ $sql = 'SELECT sbas_id, record_id, dist_id, status, connector_status, type
, title, serialized_datas, created_on, updated_on, uploaded_on
FROM bridge_elements WHERE id = :id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Bridge_Exception_ElementNotFound('Element Not Found');
+ if ( ! $row)
+ throw new Bridge_Exception_ElementNotFound('Element Not Found');
- $this->record = new record_adapter($row['sbas_id'], $row['record_id']);
- $this->dist_id = $row['dist_id'];
- $this->status = $row['status'];
- $this->connector_status = $row['connector_status'];
+ $this->record = new record_adapter($row['sbas_id'], $row['record_id']);
+ $this->dist_id = $row['dist_id'];
+ $this->status = $row['status'];
+ $this->connector_status = $row['connector_status'];
- $this->title = $row['title'];
- $this->type = $row['type'];
- $this->datas = unserialize($row['serialized_datas']);
- $this->updated_on = new DateTime($row['updated_on']);
- $this->created_on = new DateTime($row['created_on']);
- $this->uploaded_on = $row['uploaded_on'] ? new DateTime($row['uploaded_on']) : null;
+ $this->title = $row['title'];
+ $this->type = $row['type'];
+ $this->datas = unserialize($row['serialized_datas']);
+ $this->updated_on = new DateTime($row['updated_on']);
+ $this->created_on = new DateTime($row['created_on']);
+ $this->uploaded_on = $row['uploaded_on'] ? new DateTime($row['uploaded_on']) : null;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Bridge_Account
- */
- public function get_account()
- {
- return $this->account;
- }
+ /**
+ *
+ * @return Bridge_Account
+ */
+ public function get_account()
+ {
+ return $this->account;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return record_adapter
- */
- public function get_record()
- {
- return $this->record;
- }
+ /**
+ *
+ * @return record_adapter
+ */
+ public function get_record()
+ {
+ return $this->record;
+ }
- /**
- *
- * @return string
- */
- public function get_dist_id()
- {
- return $this->dist_id;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_dist_id()
+ {
+ return $this->dist_id;
+ }
- /**
- *
- * @param string $dist_id
- * @return Bridge_Element
- */
- public function set_dist_id($dist_id)
- {
- $this->dist_id = $dist_id;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @param string $dist_id
+ * @return Bridge_Element
+ */
+ public function set_dist_id($dist_id)
+ {
+ $this->dist_id = $dist_id;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_elements
+ $sql = 'UPDATE bridge_elements
SET dist_id = :dist_id, updated_on = :update WHERE id = :id';
- $params = array(
- ':dist_id' => $this->dist_id
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':dist_id' => $this->dist_id
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_status()
- {
- return $this->status;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_status()
+ {
+ return $this->status;
+ }
- /**
- *
- * @param string $status
- * @return Bridge_Element
- */
- public function set_status($status)
- {
- $this->status = $status;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @param string $status
+ * @return Bridge_Element
+ */
+ public function set_status($status)
+ {
+ $this->status = $status;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_elements
+ $sql = 'UPDATE bridge_elements
SET status = :status, updated_on = :update WHERE id = :id';
- $params = array(
- ':status' => $this->status
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':status' => $this->status
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_connector_status()
- {
- return $this->connector_status;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_connector_status()
+ {
+ return $this->connector_status;
+ }
- /**
- *
- * @param string $status
- * @return Bridge_Element
- */
- public function set_connector_status($status)
- {
- $this->connector_status = $status;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @param string $status
+ * @return Bridge_Element
+ */
+ public function set_connector_status($status)
+ {
+ $this->connector_status = $status;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_elements
+ $sql = 'UPDATE bridge_elements
SET connector_status = :connector_status, updated_on = :update
WHERE id = :id';
- $params = array(
- ':connector_status' => $this->connector_status
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':connector_status' => $this->connector_status
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->title;
- }
-
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
-
- /**
- *
- * @return Bridge_Api_ElementInterface
- */
- public function build_connector_element()
- {
- if (!$this->connector_element)
- {
- try
- {
- $this->connector_element = $this->account->get_api()->get_element_from_id($this->dist_id, $this->type);
- }
- catch (Exception $e)
- {
- return null;
- }
+ return $this;
}
- return $this->connector_element;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->title;
+ }
- /**
- *
- * @param string $title
- * @return Bridge_Element
- */
- public function set_title($title)
- {
- $this->title = $title;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
- $sql = 'UPDATE bridge_elements
+ /**
+ *
+ * @return Bridge_Api_ElementInterface
+ */
+ public function build_connector_element()
+ {
+ if ( ! $this->connector_element) {
+ try {
+ $this->connector_element = $this->account->get_api()->get_element_from_id($this->dist_id, $this->type);
+ } catch (Exception $e) {
+ return null;
+ }
+ }
+
+ return $this->connector_element;
+ }
+
+ /**
+ *
+ * @param string $title
+ * @return Bridge_Element
+ */
+ public function set_title($title)
+ {
+ $this->title = $title;
+ $this->updated_on = new DateTime();
+
+ $sql = 'UPDATE bridge_elements
SET title = :title, updated_on = :update WHERE id = :id';
- $params = array(
- ':title' => $this->title
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':title' => $this->title
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return array
- */
- public function get_datas()
- {
- return $this->datas;
- }
+ /**
+ *
+ * @return array
+ */
+ public function get_datas()
+ {
+ return $this->datas;
+ }
- /**
- *
- * @param array $datas
- * @return Bridge_Element
- */
- public function set_datas(Array $datas)
- {
- $this->datas = $datas;
- $this->updated_on = new DateTime();
+ /**
+ *
+ * @param array $datas
+ * @return Bridge_Element
+ */
+ public function set_datas(Array $datas)
+ {
+ $this->datas = $datas;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_elements
+ $sql = 'UPDATE bridge_elements
SET serialized_datas = :datas, updated_on = :update WHERE id = :id';
- $params = array(
- ':datas' => serialize($this->datas)
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':datas' => serialize($this->datas)
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
- /**
- * @todo write tests
- *
- * @return DateTime
- */
- public function get_uploaded_on()
- {
- return $this->uploaded_on;
- }
+ /**
+ * @todo write tests
+ *
+ * @return DateTime
+ */
+ public function get_uploaded_on()
+ {
+ return $this->uploaded_on;
+ }
- /**
- * @todo write tests
- *
- * @return DateTime
- */
- public function set_uploaded_on(DateTime $date = null)
- {
- $this->uploaded_on = $date;
- $this->updated_on = new DateTime();
+ /**
+ * @todo write tests
+ *
+ * @return DateTime
+ */
+ public function set_uploaded_on(DateTime $date = null)
+ {
+ $this->uploaded_on = $date;
+ $this->updated_on = new DateTime();
- $sql = 'UPDATE bridge_elements
+ $sql = 'UPDATE bridge_elements
SET uploaded_on = :uploaded_on, updated_on = :update WHERE id = :id';
- $params = array(
- ':uploaded_on' => $this->uploaded_on ? $this->uploaded_on->format(DATE_ISO8601) : null
- , ':id' => $this->id
- , ':update' => $this->updated_on->format(DATE_ISO8601)
- );
+ $params = array(
+ ':uploaded_on' => $this->uploaded_on ? $this->uploaded_on->format(DATE_ISO8601) : null
+ , ':id' => $this->id
+ , ':update' => $this->updated_on->format(DATE_ISO8601)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return $this->updated_on;
+ }
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return $this->updated_on;
- }
+ /**
+ *
+ * @return Void
+ */
+ public function delete()
+ {
+ $sql = 'DELETE FROM bridge_elements WHERE id = :id';
- /**
- *
- * @return Void
- */
- public function delete()
- {
- $sql = 'DELETE FROM bridge_elements WHERE id = :id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $stmt->closeCursor();
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $stmt->closeCursor();
+ return;
+ }
- return;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Account $account
- * @param int $quantity
- * @return Bridge_Element
- */
- public static function get_elements_by_account(appbox $appbox, Bridge_Account $account, $offset_start = 0, $quantity = 50)
- {
- $sql = 'SELECT id FROM bridge_elements WHERE account_id = :account_id
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Account $account
+ * @param int $quantity
+ * @return Bridge_Element
+ */
+ public static function get_elements_by_account(appbox $appbox, Bridge_Account $account, $offset_start = 0, $quantity = 50)
+ {
+ $sql = 'SELECT id FROM bridge_elements WHERE account_id = :account_id
ORDER BY id DESC
LIMIT ' . (int) $offset_start . ',' . (int) $quantity;
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':account_id' => $account->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':account_id' => $account->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $results = array();
+ $results = array();
- foreach ($rs as $row)
- {
- $results[] = new Bridge_Element($appbox, $account, $row['id']);
+ foreach ($rs as $row) {
+ $results[] = new Bridge_Element($appbox, $account, $row['id']);
+ }
+
+ return $results;
}
- return $results;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param Bridge_Account $account
- * @param record_adapter $record
- * @param string $title
- * @param string $status
- * @param string $type
- * @param array $datas
- * @return Bridge_Element
- */
- public static function create(appbox &$appbox, Bridge_Account &$account, record_adapter &$record, $title, $status, $type, Array $datas = array())
- {
- $sql = 'INSERT INTO bridge_elements
+ /**
+ *
+ * @param appbox $appbox
+ * @param Bridge_Account $account
+ * @param record_adapter $record
+ * @param string $title
+ * @param string $status
+ * @param string $type
+ * @param array $datas
+ * @return Bridge_Element
+ */
+ public static function create(appbox &$appbox, Bridge_Account &$account, record_adapter &$record, $title, $status, $type, Array $datas = array())
+ {
+ $sql = 'INSERT INTO bridge_elements
(id, account_id, sbas_id, record_id, dist_id, title, `type`
, serialized_datas, status, created_on, updated_on)
VALUES
(null, :account_id, :sbas_id, :record_id, null, :title, :type
,:datas , :status, NOW(), NOW())';
- $params = array(
- ':account_id' => $account->get_id()
- , ':sbas_id' => $record->get_sbas_id()
- , ':record_id' => $record->get_record_id()
- , ':status' => $status
- , ':title' => $title
- , ':type' => $type
- , ':datas' => serialize($datas)
- );
+ $params = array(
+ ':account_id' => $account->get_id()
+ , ':sbas_id' => $record->get_sbas_id()
+ , ':record_id' => $record->get_record_id()
+ , ':status' => $status
+ , ':title' => $title
+ , ':type' => $type
+ , ':datas' => serialize($datas)
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $element_id = $appbox->get_connection()->lastInsertId();
-
- return new self($appbox, $account, $element_id);
- }
+ $element_id = $appbox->get_connection()->lastInsertId();
+ return new self($appbox, $account, $element_id);
+ }
}
diff --git a/lib/classes/Bridge/Exception/ApiDisabled.class.php b/lib/classes/Bridge/Exception/ApiDisabled.class.php
index 0089bf2f39..9a62750454 100644
--- a/lib/classes/Bridge/Exception/ApiDisabled.class.php
+++ b/lib/classes/Bridge/Exception/ApiDisabled.class.php
@@ -17,27 +17,25 @@
*/
class Bridge_Exception_ApiDisabled extends Bridge_Exception
{
+ protected $api;
- protected $api;
+ /**
+ *
+ * @param Bridge_Api $api
+ */
+ public function __construct(Bridge_Api $api)
+ {
+ $this->api = $api;
- /**
- *
- * @param Bridge_Api $api
- */
- public function __construct(Bridge_Api $api)
- {
- $this->api = $api;
-
- parent::__construct();
- }
-
- /**
- *
- * @return Bridge_Api
- */
- public function get_api()
- {
- return $this->api;
- }
+ parent::__construct();
+ }
+ /**
+ *
+ * @return Bridge_Api
+ */
+ public function get_api()
+ {
+ return $this->api;
+ }
}
diff --git a/lib/classes/Browser.class.php b/lib/classes/Browser.class.php
index be04833003..ba69df0b79 100644
--- a/lib/classes/Browser.class.php
+++ b/lib/classes/Browser.class.php
@@ -134,1384 +134,1261 @@
*/
class Browser
{
+ private $_agent = '';
+ private $_browser_name = '';
+ private $_version = '';
+ private $_platform = '';
+ private $_os = '';
+ private $_ip = '';
+ private $_is_new_generation = false;
+ private $_is_html5 = false;
+ private $_is_aol = false;
+ private $_is_mobile = false;
+ private $_is_tablet = false;
+ private $_is_robot = false;
+ private $_aol_version = '';
+ private $_chrome_frame = false;
+ private $_chrome_frame_version = false;
+ private static $_instance;
- private $_agent = '';
- private $_browser_name = '';
- private $_version = '';
- private $_platform = '';
- private $_os = '';
- private $_ip = '';
- private $_is_new_generation = false;
- private $_is_html5 = false;
- private $_is_aol = false;
- private $_is_mobile = false;
- private $_is_tablet = false;
- private $_is_robot = false;
- private $_aol_version = '';
- private $_chrome_frame = false;
- private $_chrome_frame_version = false;
- private static $_instance;
+ const BROWSER_UNKNOWN = 'unknown';
+ const VERSION_UNKNOWN = 'unknown';
+ const BROWSER_OPERA = 'Opera'; // http://www.opera.com/
+ const BROWSER_OPERA_MINI = 'Opera Mini'; // http://www.opera.com/mini/
+ const BROWSER_WEBTV = 'WebTV'; // http://www.webtv.net/pc/
+ const BROWSER_IE = 'Internet Explorer'; // http://www.microsoft.com/ie/
+ const BROWSER_POCKET_IE = 'Pocket Internet Explorer'; // http://en.wikipedia.org/wiki/Internet_Explorer_Mobile
+ const BROWSER_KONQUEROR = 'Konqueror'; // http://www.konqueror.org/
+ const BROWSER_ICAB = 'iCab'; // http://www.icab.de/
+ const BROWSER_OMNIWEB = 'OmniWeb'; // http://www.omnigroup.com/applications/omniweb/
+ const BROWSER_FIREBIRD = 'Firebird'; // http://www.ibphoenix.com/
+ const BROWSER_FIREFOX = 'Firefox'; // http://www.mozilla.com/en-US/firefox/firefox.html
+ const BROWSER_ICEWEASEL = 'Iceweasel'; // http://www.geticeweasel.org/
+ const BROWSER_SHIRETOKO = 'Shiretoko'; // http://wiki.mozilla.org/Projects/shiretoko
+ const BROWSER_MOZILLA = 'Mozilla'; // http://www.mozilla.com/en-US/
+ const BROWSER_AMAYA = 'Amaya'; // http://www.w3.org/Amaya/
+ const BROWSER_LYNX = 'Lynx'; // http://en.wikipedia.org/wiki/Lynx
+ const BROWSER_SAFARI = 'Safari'; // http://apple.com
+ const BROWSER_IPHONE = 'iPhone'; // http://apple.com
+ const BROWSER_IPOD = 'iPod'; // http://apple.com
+ const BROWSER_IPAD = 'iPad'; // http://apple.com
+ const BROWSER_CHROME = 'Chrome'; // http://www.google.com/chrome
+ const BROWSER_ANDROID = 'Android'; // http://www.android.com/
+ const BROWSER_GOOGLEBOT = 'GoogleBot'; // http://en.wikipedia.org/wiki/Googlebot
+ const BROWSER_SLURP = 'Yahoo! Slurp'; // http://en.wikipedia.org/wiki/Yahoo!_Slurp
+ const BROWSER_W3CVALIDATOR = 'W3C Validator'; // http://validator.w3.org/
+ const BROWSER_BLACKBERRY = 'BlackBerry'; // http://www.blackberry.com/
+ const BROWSER_ICECAT = 'IceCat'; // http://en.wikipedia.org/wiki/GNU_IceCat
+ const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser'; // http://en.wikipedia.org/wiki/Web_Browser_for_S60
+ const BROWSER_NOKIA = 'Nokia Browser'; // * all other WAP-based browsers on the Nokia Platform
+ const BROWSER_MSN = 'MSN Browser'; // http://explorer.msn.com/
+ const BROWSER_MSNBOT = 'MSN Bot'; // http://search.msn.com/msnbot.htm
+ // http://en.wikipedia.org/wiki/Msnbot (used for Bing as well)
+ const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator'; // http://browser.netscape.com/ (DEPRECATED)
+ const BROWSER_GALEON = 'Galeon'; // http://galeon.sourceforge.net/ (DEPRECATED)
+ const BROWSER_NETPOSITIVE = 'NetPositive'; // http://en.wikipedia.org/wiki/NetPositive (DEPRECATED)
+ const BROWSER_PHOENIX = 'Phoenix'; // http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox (DEPRECATED)
+ const PLATFORM_UNKNOWN = 'unknown';
+ const PLATFORM_WINDOWS = 'Windows';
+ const PLATFORM_WINDOWS_CE = 'Windows CE';
+ const PLATFORM_APPLE = 'Apple';
+ const PLATFORM_LINUX = 'Linux';
+ const PLATFORM_OS2 = 'OS/2';
+ const PLATFORM_BEOS = 'BeOS';
+ const PLATFORM_IPHONE = 'iPhone';
+ const PLATFORM_IPOD = 'iPod';
+ const PLATFORM_IPAD = 'iPad';
+ const PLATFORM_BLACKBERRY = 'BlackBerry';
+ const PLATFORM_NOKIA = 'Nokia';
+ const PLATFORM_FREEBSD = 'FreeBSD';
+ const PLATFORM_OPENBSD = 'OpenBSD';
+ const PLATFORM_NETBSD = 'NetBSD';
+ const PLATFORM_SUNOS = 'SunOS';
+ const PLATFORM_OPENSOLARIS = 'OpenSolaris';
+ const PLATFORM_ANDROID = 'Android';
+ const OPERATING_SYSTEM_UNKNOWN = 'unknown';
- const BROWSER_UNKNOWN = 'unknown';
- const VERSION_UNKNOWN = 'unknown';
-
- const BROWSER_OPERA = 'Opera'; // http://www.opera.com/
- const BROWSER_OPERA_MINI = 'Opera Mini'; // http://www.opera.com/mini/
- const BROWSER_WEBTV = 'WebTV'; // http://www.webtv.net/pc/
- const BROWSER_IE = 'Internet Explorer'; // http://www.microsoft.com/ie/
- const BROWSER_POCKET_IE = 'Pocket Internet Explorer'; // http://en.wikipedia.org/wiki/Internet_Explorer_Mobile
- const BROWSER_KONQUEROR = 'Konqueror'; // http://www.konqueror.org/
- const BROWSER_ICAB = 'iCab'; // http://www.icab.de/
- const BROWSER_OMNIWEB = 'OmniWeb'; // http://www.omnigroup.com/applications/omniweb/
- const BROWSER_FIREBIRD = 'Firebird'; // http://www.ibphoenix.com/
- const BROWSER_FIREFOX = 'Firefox'; // http://www.mozilla.com/en-US/firefox/firefox.html
- const BROWSER_ICEWEASEL = 'Iceweasel'; // http://www.geticeweasel.org/
- const BROWSER_SHIRETOKO = 'Shiretoko'; // http://wiki.mozilla.org/Projects/shiretoko
- const BROWSER_MOZILLA = 'Mozilla'; // http://www.mozilla.com/en-US/
- const BROWSER_AMAYA = 'Amaya'; // http://www.w3.org/Amaya/
- const BROWSER_LYNX = 'Lynx'; // http://en.wikipedia.org/wiki/Lynx
- const BROWSER_SAFARI = 'Safari'; // http://apple.com
- const BROWSER_IPHONE = 'iPhone'; // http://apple.com
- const BROWSER_IPOD = 'iPod'; // http://apple.com
- const BROWSER_IPAD = 'iPad'; // http://apple.com
- const BROWSER_CHROME = 'Chrome'; // http://www.google.com/chrome
- const BROWSER_ANDROID = 'Android'; // http://www.android.com/
- const BROWSER_GOOGLEBOT = 'GoogleBot'; // http://en.wikipedia.org/wiki/Googlebot
- const BROWSER_SLURP = 'Yahoo! Slurp'; // http://en.wikipedia.org/wiki/Yahoo!_Slurp
- const BROWSER_W3CVALIDATOR = 'W3C Validator'; // http://validator.w3.org/
- const BROWSER_BLACKBERRY = 'BlackBerry'; // http://www.blackberry.com/
- const BROWSER_ICECAT = 'IceCat'; // http://en.wikipedia.org/wiki/GNU_IceCat
- const BROWSER_NOKIA_S60 = 'Nokia S60 OSS Browser'; // http://en.wikipedia.org/wiki/Web_Browser_for_S60
- const BROWSER_NOKIA = 'Nokia Browser'; // * all other WAP-based browsers on the Nokia Platform
- const BROWSER_MSN = 'MSN Browser'; // http://explorer.msn.com/
- const BROWSER_MSNBOT = 'MSN Bot'; // http://search.msn.com/msnbot.htm
- // http://en.wikipedia.org/wiki/Msnbot (used for Bing as well)
-
- const BROWSER_NETSCAPE_NAVIGATOR = 'Netscape Navigator'; // http://browser.netscape.com/ (DEPRECATED)
- const BROWSER_GALEON = 'Galeon'; // http://galeon.sourceforge.net/ (DEPRECATED)
- const BROWSER_NETPOSITIVE = 'NetPositive'; // http://en.wikipedia.org/wiki/NetPositive (DEPRECATED)
- const BROWSER_PHOENIX = 'Phoenix'; // http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox (DEPRECATED)
-
- const PLATFORM_UNKNOWN = 'unknown';
- const PLATFORM_WINDOWS = 'Windows';
- const PLATFORM_WINDOWS_CE = 'Windows CE';
- const PLATFORM_APPLE = 'Apple';
- const PLATFORM_LINUX = 'Linux';
- const PLATFORM_OS2 = 'OS/2';
- const PLATFORM_BEOS = 'BeOS';
- const PLATFORM_IPHONE = 'iPhone';
- const PLATFORM_IPOD = 'iPod';
- const PLATFORM_IPAD = 'iPad';
- const PLATFORM_BLACKBERRY = 'BlackBerry';
- const PLATFORM_NOKIA = 'Nokia';
- const PLATFORM_FREEBSD = 'FreeBSD';
- const PLATFORM_OPENBSD = 'OpenBSD';
- const PLATFORM_NETBSD = 'NetBSD';
- const PLATFORM_SUNOS = 'SunOS';
- const PLATFORM_OPENSOLARIS = 'OpenSolaris';
- const PLATFORM_ANDROID = 'Android';
-
- const OPERATING_SYSTEM_UNKNOWN = 'unknown';
-
- /**
- * @return browser
- */
- public static function getInstance()
- {
- if (!self::$_instance)
+ /**
+ * @return browser
+ */
+ public static function getInstance()
{
- self::$_instance = new self();
+ if ( ! self::$_instance) {
+ self::$_instance = new self();
+ }
+
+ return self::$_instance;
}
- return self::$_instance;
- }
-
- public function __construct()
- {
- $this->reset();
- $this->determine();
- }
-
- /**
- * Reset all properties
- */
- public function reset()
- {
- $this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
- $this->_browser_name = self::BROWSER_UNKNOWN;
- $this->_version = self::VERSION_UNKNOWN;
- $this->_platform = self::PLATFORM_UNKNOWN;
- $this->_os = self::OPERATING_SYSTEM_UNKNOWN;
- $this->_is_aol = false;
- $this->_is_mobile = false;
- $this->_is_tablet = false;
- $this->_is_robot = false;
- $this->_aol_version = self::VERSION_UNKNOWN;
- }
-
- /**
- * Check to see if the specific browser is valid
- * @param string $browserName
- * @return True if the browser is the specified browser
- */
- function isBrowser($browserName)
- {
- return( 0 == strcasecmp($this->_browser_name, trim($browserName)));
- }
-
- /**
- * The name of the browser. All return types are from the class contants
- * @return string Name of the browser
- */
- public function getBrowser()
- {
- return $this->_browser_name;
- }
-
- /**
- * The IP address of the client.
- * @return string IP address the browser
- */
- public function getIP()
- {
- return $this->_ip;
- }
-
- /**
- * Is new generation of Browser ? (Chrome, Safari, Webkit, Firefox, Opera ).
- * @return boolean
- */
- public function isNewGeneration()
- {
- return $this->_is_new_generation;
- }
-
- /**
- * Is HTML5 OK ?.
- * @return boolean
- */
- public function isHTML5()
- {
- return $this->_is_html5;
- }
-
- /**
- * Is the Browser very old ?
- * @return boolean
- */
- public function isOldBrowser()
- {
- return $this->_is_old;
- }
-
- /**
- * Is the Browser using chrome frame ?
- * @return boolean
- */
- public function isChromeFrame()
- {
- return $this->_chrome_frame;
- }
-
- /**
- * Set the name of the browser
- * @param $browser The name of the Browser
- */
- public function setBrowser($browser)
- {
- return $this->_browser_name = $browser;
- }
-
- /**
- * The name of the platform. All return types are from the class contants
- * @return string Name of the browser
- */
- public function getPlatform()
- {
- return $this->_platform;
- }
-
- /**
- * Set the name of the platform
- * @param $platform The name of the Platform
- */
- public function setPlatform($platform)
- {
- return $this->_platform = $platform;
- }
-
- /**
- * The version of the browser.
- * @return string Version of the browser (will only contain alpha-numeric characters and a period)
- */
- public function getVersion()
- {
- return $this->_version;
- }
-
- /**
- * The extended version of the browser (include plugins).
- * @return string Version of the browser
- */
- public function getExtendedVersion()
- {
- return $this->getVersion() . ($this->isChromeFrame() ? ' ChromeFrame' : '');
- }
-
- public function getScreenSize()
- {
- return isset($_COOKIE['screen']) ? $_COOKIE['screen'] : 'unknown';
- }
-
- /**
- * Set the version of the browser
- * @param $version The version of the Browser
- */
- public function setVersion($version)
- {
- $this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/', '', $version);
- }
-
- /**
- * The version of AOL.
- * @return string Version of AOL (will only contain alpha-numeric characters and a period)
- */
- public function getAolVersion()
- {
- return $this->_aol_version;
- }
-
- /**
- * Set the version of AOL
- * @param $version The version of AOL
- */
- public function setAolVersion($version)
- {
- $this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/', '', $version);
- }
-
- /**
- * Is the browser from AOL?
- * @return boolean True if the browser is from AOL otherwise false
- */
- public function isAol()
- {
- return $this->_is_aol;
- }
-
- /**
- * Is the browser from a mobile device?
- * @return boolean True if the browser is from a mobile device otherwise false
- */
- public function isMobile()
- {
- return $this->_is_mobile;
- }
-
- /**
- * Is the browser from a mobile device?
- * @return boolean True if the browser is from a mobile device otherwise false
- */
- public function isTablet()
- {
- return $this->_is_tablet;
- }
-
- /**
- * Is the browser from a robot (ex Slurp,GoogleBot)?
- * @return boolean True if the browser is from a robot otherwise false
- */
- public function isRobot()
- {
- return $this->_is_robot;
- }
-
- /**
- * Set the browser to be from AOL
- * @param $isAol
- */
- public function setAol($isAol)
- {
- $this->_is_aol = $isAol;
- }
-
- /**
- * Get the user agent value in use to determine the browser
- * @return string The user agent from the HTTP header
- */
- public function getUserAgent()
- {
- return $this->_agent;
- }
-
- /**
- * Set the user agent value (the construction will use the HTTP header value - this will overwrite it)
- * @param $agent_string The value for the User Agent
- */
- public function setUserAgent($agent_string)
- {
- $this->reset();
- $this->_agent = $agent_string;
- $this->determine();
- }
-
- protected function setMobile($value=true)
- {
- $this->_is_mobile = $value;
- }
-
- protected function setTablet($value=true)
- {
- $this->_is_tablet = $value;
- }
-
- protected function setRobot($value=true)
- {
- $this->_is_robot = $value;
- }
-
- /**
- * Protected routine to calculate and determine what the browser is in use (including platform)
- */
- protected function determine()
- {
- $this->checkPlatform();
- $this->checkBrowsers();
- $this->checkForAol();
- $this->checkIP();
- $this->checkChromeFrame();
- $this->checkNewGeneration();
- $this->checkAge();
- $this->checkHTML5();
- }
-
- /**
- * Protected routine to determine if the browser is chrome frame enabled
- * @return boolean True if the browser was detected otherwise false
- */
- protected function checkChromeFrame()
- {
-
- $this->_chrome_frame = false;
- if (preg_match('/chromeframe/i', $this->_agent))
+ public function __construct()
{
- $this->_chrome_frame = true;
- $aresult = explode('/', stristr($this->_agent, 'chromeframe'));
- $aversion = explode(' ', $aresult[1]);
- $chrome_version = explode('.', $aversion[0]);
- $this->_chrome_frame_version = $chrome_version[0];
+ $this->reset();
+ $this->determine();
}
- return $this->_chrome_frame;
- }
-
- /**
- * Protected routine to determine the browser type
- * @return boolean True if the browser was detected otherwise false
- */
- protected function checkBrowsers()
- {
- return (
- // well-known, well-used
- // Special Notes:
- // (1) Opera must be checked before FireFox due to the odd
- // user agents used in some older versions of Opera
- // (2) WebTV is strapped onto Internet Explorer so we must
- // check for WebTV before IE
- // (3) (deprecated) Galeon is based on Firefox and needs to be
- // tested before Firefox is tested
- // (4) OmniWeb is based on Safari so OmniWeb check must occur
- // before Safari
- // (5) Netscape 9+ is based on Firefox so Netscape checks
- // before FireFox are necessary
- $this->checkBrowserWebTv() ||
- $this->checkBrowserInternetExplorer() ||
- $this->checkBrowserOpera() ||
- $this->checkBrowserGaleon() ||
- $this->checkBrowserNetscapeNavigator9Plus() ||
- $this->checkBrowserIceweasel() ||
- $this->checkBrowserFirefox() ||
- $this->checkBrowserChrome() ||
- $this->checkBrowserOmniWeb() ||
- // common mobile
- $this->checkBrowserAndroid() ||
- $this->checkBrowseriPad() ||
- $this->checkBrowseriPod() ||
- $this->checkBrowseriPhone() ||
- $this->checkBrowserBlackBerry() ||
- $this->checkBrowserNokia() ||
- // common bots
- $this->checkBrowserGoogleBot() ||
- $this->checkBrowserMSNBot() ||
- $this->checkBrowserSlurp() ||
- // WebKit base check (post mobile and others)
- $this->checkBrowserSafari() ||
- // everyone else
- $this->checkBrowserNetPositive() ||
- $this->checkBrowserFirebird() ||
- $this->checkBrowserKonqueror() ||
- $this->checkBrowserIcab() ||
- $this->checkBrowserPhoenix() ||
- $this->checkBrowserAmaya() ||
- $this->checkBrowserLynx() ||
- $this->checkBrowserShiretoko() ||
- $this->checkBrowserIceCat() ||
- $this->checkBrowserW3CValidator() ||
- $this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
- );
- }
-
- /**
- * Determine if the user is using a BlackBerry (last updated 1.7)
- * @return boolean True if the browser is the BlackBerry browser otherwise false
- */
- protected function checkBrowserBlackBerry()
- {
- if (stripos($this->_agent, 'blackberry') !== false)
+ /**
+ * Reset all properties
+ */
+ public function reset()
{
- $aresult = explode("/", stristr($this->_agent, "BlackBerry"));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->_browser_name = self::BROWSER_BLACKBERRY;
- $this->setMobile(true);
-
- return true;
+ $this->_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
+ $this->_browser_name = self::BROWSER_UNKNOWN;
+ $this->_version = self::VERSION_UNKNOWN;
+ $this->_platform = self::PLATFORM_UNKNOWN;
+ $this->_os = self::OPERATING_SYSTEM_UNKNOWN;
+ $this->_is_aol = false;
+ $this->_is_mobile = false;
+ $this->_is_tablet = false;
+ $this->_is_robot = false;
+ $this->_aol_version = self::VERSION_UNKNOWN;
}
- return false;
- }
-
- /**
- * Determine if the user is using an AOL User Agent (last updated 1.7)
- * @return boolean True if the browser is from AOL otherwise false
- */
- protected function checkForAol()
- {
- $this->setAol(false);
- $this->setAolVersion(self::VERSION_UNKNOWN);
-
- if (stripos($this->_agent, 'aol') !== false)
+ /**
+ * Check to see if the specific browser is valid
+ * @param string $browserName
+ * @return True if the browser is the specified browser
+ */
+ function isBrowser($browserName)
{
- $aversion = explode(' ', stristr($this->_agent, 'AOL'));
- $this->setAol(true);
- $this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1]));
-
- return true;
+ return( 0 == strcasecmp($this->_browser_name, trim($browserName)));
}
- return false;
- }
-
- /**
- * Determine if the browser is the GoogleBot or not (last updated 1.7)
- * @return boolean True if the browser is the GoogletBot otherwise false
- */
- protected function checkBrowserGoogleBot()
- {
- if (stripos($this->_agent, 'googlebot') !== false)
+ /**
+ * The name of the browser. All return types are from the class contants
+ * @return string Name of the browser
+ */
+ public function getBrowser()
{
- $aresult = explode('/', stristr($this->_agent, 'googlebot'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion(str_replace(';', '', $aversion[0]));
- $this->_browser_name = self::BROWSER_GOOGLEBOT;
- $this->setRobot(true);
-
- return true;
+ return $this->_browser_name;
}
- return false;
- }
-
- /**
- * Determine if the browser is the MSNBot or not (last updated 1.9)
- * @return boolean True if the browser is the MSNBot otherwise false
- */
- protected function checkBrowserMSNBot()
- {
- if (stripos($this->_agent, "msnbot") !== false)
+ /**
+ * The IP address of the client.
+ * @return string IP address the browser
+ */
+ public function getIP()
{
- $aresult = explode("/", stristr($this->_agent, "msnbot"));
- $aversion = explode(" ", $aresult[1]);
- $this->setVersion(str_replace(";", "", $aversion[0]));
- $this->_browser_name = self::BROWSER_MSNBOT;
- $this->setRobot(true);
-
- return true;
+ return $this->_ip;
}
- return false;
- }
-
- /**
- * Determine if the browser is the W3C Validator or not (last updated 1.7)
- * @return boolean True if the browser is the W3C Validator otherwise false
- */
- protected function checkBrowserW3CValidator()
- {
- if (stripos($this->_agent, 'W3C-checklink') !== false)
+ /**
+ * Is new generation of Browser ? (Chrome, Safari, Webkit, Firefox, Opera ).
+ * @return boolean
+ */
+ public function isNewGeneration()
{
- $aresult = explode('/', stristr($this->_agent, 'W3C-checklink'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->_browser_name = self::BROWSER_W3CVALIDATOR;
-
- return true;
- }
- else if (stripos($this->_agent, 'W3C_Validator') !== false)
- {
- // Some of the Validator versions do not delineate w/ a slash - add it back in
- $ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent);
- $aresult = explode('/', stristr($ua, 'W3C_Validator'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->_browser_name = self::BROWSER_W3CVALIDATOR;
-
- return true;
+ return $this->_is_new_generation;
}
- return false;
- }
-
- /**
- * Determine if the browser is the Yahoo! Slurp Robot or not (last updated 1.7)
- * @return boolean True if the browser is the Yahoo! Slurp Robot otherwise false
- */
- protected function checkBrowserSlurp()
- {
- if (stripos($this->_agent, 'slurp') !== false)
+ /**
+ * Is HTML5 OK ?.
+ * @return boolean
+ */
+ public function isHTML5()
{
- $aresult = explode('/', stristr($this->_agent, 'Slurp'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->_browser_name = self::BROWSER_SLURP;
- $this->setRobot(true);
- $this->setMobile(false);
-
- return true;
+ return $this->_is_html5;
}
- return false;
- }
-
- /**
- * Determine if the browser is Internet Explorer or not (last updated 1.7)
- * @return boolean True if the browser is Internet Explorer otherwise false
- */
- protected function checkBrowserInternetExplorer()
- {
-
- // Test for v1 - v1.5 IE
- if (stripos($this->_agent, 'microsoft internet explorer') !== false)
+ /**
+ * Is the Browser very old ?
+ * @return boolean
+ */
+ public function isOldBrowser()
{
- $this->setBrowser(self::BROWSER_IE);
- $this->setVersion('1.0');
- $aresult = stristr($this->_agent, '/');
- if (preg_match('/308|425|426|474|0b1/i', $aresult))
- {
- $this->setVersion('1.5');
- }
-
- return true;
- }
- // Test for versions > 1.5
- else if (stripos($this->_agent, 'msie') !== false && stripos($this->_agent, 'opera') === false)
- {
- // See if the browser is the odd MSN Explorer
- if (stripos($this->_agent, 'msnb') !== false)
- {
- $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'MSN'));
- $this->setBrowser(self::BROWSER_MSN);
- $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
-
- return true;
- }
- $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'msie'));
- $this->setBrowser(self::BROWSER_IE);
- $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
-
- return true;
- }
- // Test for Pocket IE
- else if (stripos($this->_agent, 'mspie') !== false || stripos($this->_agent, 'pocket') !== false)
- {
- $aresult = explode(' ', stristr($this->_agent, 'mspie'));
- $this->setPlatform(self::PLATFORM_WINDOWS_CE);
- $this->setBrowser(self::BROWSER_POCKET_IE);
- $this->setMobile(true);
-
- if (stripos($this->_agent, 'mspie') !== false)
- {
- $this->setVersion($aresult[1]);
- }
- else
- {
- $aversion = explode('/', $this->_agent);
- $this->setVersion($aversion[1]);
- }
-
- return true;
+ return $this->_is_old;
}
- return false;
- }
-
- /**
- * Determine if the browser is Opera or not (last updated 1.7)
- * @return boolean True if the browser is Opera otherwise false
- */
- protected function checkBrowserOpera()
- {
- if (stripos($this->_agent, 'opera mini') !== false)
+ /**
+ * Is the Browser using chrome frame ?
+ * @return boolean
+ */
+ public function isChromeFrame()
{
- $resultant = stristr($this->_agent, 'opera mini');
- if (preg_match('/\//', $resultant))
- {
- $aresult = explode('/', $resultant);
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $aversion = explode(' ', stristr($resultant, 'opera mini'));
- $this->setVersion($aversion[1]);
- }
- $this->_browser_name = self::BROWSER_OPERA_MINI;
- $this->setMobile(true);
-
- return true;
- }
- else if (stripos($this->_agent, 'opera') !== false)
- {
- $resultant = stristr($this->_agent, 'opera');
- if (preg_match('/Version\/([0-9]{2}.*)$/', $resultant, $matches))
- {
- $this->setVersion($matches[1]);
- }
- else if (preg_match('/\//', $resultant))
- {
- $aresult = explode('/', str_replace("(", " ", $resultant));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $aversion = explode(' ', stristr($resultant, 'opera'));
- $this->setVersion(isset($aversion[1]) ? $aversion[1] : "");
- }
- $this->_browser_name = self::BROWSER_OPERA;
-
- return true;
+ return $this->_chrome_frame;
}
- return false;
- }
-
- /**
- * Determine if the browser is Chrome or not (last updated 1.7)
- * @return boolean True if the browser is Chrome otherwise false
- */
- protected function checkBrowserChrome()
- {
- if (stripos($this->_agent, 'Chrome') !== false)
+ /**
+ * Set the name of the browser
+ * @param $browser The name of the Browser
+ */
+ public function setBrowser($browser)
{
- $aresult = explode('/', stristr($this->_agent, 'Chrome'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_CHROME);
-
- return true;
+ return $this->_browser_name = $browser;
}
- return false;
- }
-
- /**
- * Determine if the browser is WebTv or not (last updated 1.7)
- * @return boolean True if the browser is WebTv otherwise false
- */
- protected function checkBrowserWebTv()
- {
- if (stripos($this->_agent, 'webtv') !== false)
+ /**
+ * The name of the platform. All return types are from the class contants
+ * @return string Name of the browser
+ */
+ public function getPlatform()
{
- $aresult = explode('/', stristr($this->_agent, 'webtv'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_WEBTV);
-
- return true;
+ return $this->_platform;
}
- return false;
- }
-
- /**
- * Determine if the browser is NetPositive or not (last updated 1.7)
- * @return boolean True if the browser is NetPositive otherwise false
- */
- protected function checkBrowserNetPositive()
- {
- if (stripos($this->_agent, 'NetPositive') !== false)
+ /**
+ * Set the name of the platform
+ * @param $platform The name of the Platform
+ */
+ public function setPlatform($platform)
{
- $aresult = explode('/', stristr($this->_agent, 'NetPositive'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion(str_replace(array('(', ')', ';'), '', $aversion[0]));
- $this->setBrowser(self::BROWSER_NETPOSITIVE);
-
- return true;
+ return $this->_platform = $platform;
}
- return false;
- }
-
- /**
- * Determine if the browser is Galeon or not (last updated 1.7)
- * @return boolean True if the browser is Galeon otherwise false
- */
- protected function checkBrowserGaleon()
- {
- if (stripos($this->_agent, 'galeon') !== false)
+ /**
+ * The version of the browser.
+ * @return string Version of the browser (will only contain alpha-numeric characters and a period)
+ */
+ public function getVersion()
{
- $aresult = explode(' ', stristr($this->_agent, 'galeon'));
- $aversion = explode('/', $aresult[0]);
- $this->setVersion($aversion[1]);
- $this->setBrowser(self::BROWSER_GALEON);
-
- return true;
+ return $this->_version;
}
- return false;
- }
-
- /**
- * Determine if the browser is Konqueror or not (last updated 1.7)
- * @return boolean True if the browser is Konqueror otherwise false
- */
- protected function checkBrowserKonqueror()
- {
- if (stripos($this->_agent, 'Konqueror') !== false)
+ /**
+ * The extended version of the browser (include plugins).
+ * @return string Version of the browser
+ */
+ public function getExtendedVersion()
{
- $aresult = explode(' ', stristr($this->_agent, 'Konqueror'));
- $aversion = explode('/', $aresult[0]);
- $this->setVersion($aversion[1]);
- $this->setBrowser(self::BROWSER_KONQUEROR);
-
- return true;
+ return $this->getVersion() . ($this->isChromeFrame() ? ' ChromeFrame' : '');
}
- return false;
- }
-
- /**
- * Determine if the browser is iCab or not (last updated 1.7)
- * @return boolean True if the browser is iCab otherwise false
- */
- protected function checkBrowserIcab()
- {
- if (stripos($this->_agent, 'icab') !== false)
+ public function getScreenSize()
{
- $aversion = explode(' ', stristr(str_replace('/', ' ', $this->_agent), 'icab'));
- $this->setVersion($aversion[1]);
- $this->setBrowser(self::BROWSER_ICAB);
-
- return true;
+ return isset($_COOKIE['screen']) ? $_COOKIE['screen'] : 'unknown';
}
- return false;
- }
-
- /**
- * Determine if the browser is OmniWeb or not (last updated 1.7)
- * @return boolean True if the browser is OmniWeb otherwise false
- */
- protected function checkBrowserOmniWeb()
- {
- if (stripos($this->_agent, 'omniweb') !== false)
+ /**
+ * Set the version of the browser
+ * @param $version The version of the Browser
+ */
+ public function setVersion($version)
{
- $aresult = explode('/', stristr($this->_agent, 'omniweb'));
- $aversion = explode(' ', isset($aresult[1]) ? $aresult[1] : "");
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_OMNIWEB);
-
- return true;
+ $this->_version = preg_replace('/[^0-9,.,a-z,A-Z-]/', '', $version);
}
- return false;
- }
-
- /**
- * Determine if the browser is Phoenix or not (last updated 1.7)
- * @return boolean True if the browser is Phoenix otherwise false
- */
- protected function checkBrowserPhoenix()
- {
- if (stripos($this->_agent, 'Phoenix') !== false)
+ /**
+ * The version of AOL.
+ * @return string Version of AOL (will only contain alpha-numeric characters and a period)
+ */
+ public function getAolVersion()
{
- $aversion = explode('/', stristr($this->_agent, 'Phoenix'));
- $this->setVersion($aversion[1]);
- $this->setBrowser(self::BROWSER_PHOENIX);
-
- return true;
+ return $this->_aol_version;
}
- return false;
- }
-
- /**
- * Determine if the browser is Firebird or not (last updated 1.7)
- * @return boolean True if the browser is Firebird otherwise false
- */
- protected function checkBrowserFirebird()
- {
- if (stripos($this->_agent, 'Firebird') !== false)
+ /**
+ * Set the version of AOL
+ * @param $version The version of AOL
+ */
+ public function setAolVersion($version)
{
- $aversion = explode('/', stristr($this->_agent, 'Firebird'));
- $this->setVersion($aversion[1]);
- $this->setBrowser(self::BROWSER_FIREBIRD);
-
- return true;
+ $this->_aol_version = preg_replace('/[^0-9,.,a-z,A-Z]/', '', $version);
}
- return false;
- }
-
- /**
- * Determine if the browser is Netscape Navigator 9+ or not (last updated 1.7)
- * NOTE: (http://browser.netscape.com/ - Official support ended on March 1st, 2008)
- * @return boolean True if the browser is Netscape Navigator 9+ otherwise false
- */
- protected function checkBrowserNetscapeNavigator9Plus()
- {
- if (stripos($this->_agent, 'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i', $this->_agent, $matches))
+ /**
+ * Is the browser from AOL?
+ * @return boolean True if the browser is from AOL otherwise false
+ */
+ public function isAol()
{
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
-
- return true;
- }
- else if (stripos($this->_agent, 'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i', $this->_agent, $matches))
- {
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
-
- return true;
+ return $this->_is_aol;
}
- return false;
- }
-
- /**
- * Determine if the browser is Shiretoko or not (https://wiki.mozilla.org/Projects/shiretoko) (last updated 1.7)
- * @return boolean True if the browser is Shiretoko otherwise false
- */
- protected function checkBrowserShiretoko()
- {
- if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i', $this->_agent, $matches))
+ /**
+ * Is the browser from a mobile device?
+ * @return boolean True if the browser is from a mobile device otherwise false
+ */
+ public function isMobile()
{
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_SHIRETOKO);
-
- return true;
+ return $this->_is_mobile;
}
- return false;
- }
-
- /**
- * Determine if the browser is Ice Cat or not (http://en.wikipedia.org/wiki/GNU_IceCat) (last updated 1.7)
- * @return boolean True if the browser is Ice Cat otherwise false
- */
- protected function checkBrowserIceCat()
- {
- if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i', $this->_agent, $matches))
+ /**
+ * Is the browser from a mobile device?
+ * @return boolean True if the browser is from a mobile device otherwise false
+ */
+ public function isTablet()
{
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_ICECAT);
-
- return true;
+ return $this->_is_tablet;
}
- return false;
- }
-
- /**
- * Determine if the browser is Nokia or not (last updated 1.7)
- * @return boolean True if the browser is Nokia otherwise false
- */
- protected function checkBrowserNokia()
- {
- if (preg_match("/Nokia([^\/]+)\/([^ SP]+)/i", $this->_agent, $matches))
+ /**
+ * Is the browser from a robot (ex Slurp,GoogleBot)?
+ * @return boolean True if the browser is from a robot otherwise false
+ */
+ public function isRobot()
{
- $this->setVersion($matches[2]);
- if (stripos($this->_agent, 'Series60') !== false || strpos($this->_agent, 'S60') !== false)
- {
- $this->setBrowser(self::BROWSER_NOKIA_S60);
- }
- else
- {
- $this->setBrowser(self::BROWSER_NOKIA);
- }
- $this->setMobile(true);
-
- return true;
+ return $this->_is_robot;
}
- return false;
- }
-
- /**
- * Determine if the browser is Firefox or not (last updated 1.7)
- * @return boolean True if the browser is Firefox otherwise false
- */
- protected function checkBrowserFirefox()
- {
- if (stripos($this->_agent, 'safari') === false)
+ /**
+ * Set the browser to be from AOL
+ * @param $isAol
+ */
+ public function setAol($isAol)
{
- if (preg_match("/Firefox[\/ \(]([^ ;\)]+)/i", $this->_agent, $matches))
- {
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_FIREFOX);
-
- return true;
- }
- else if (preg_match("/Firefox$/i", $this->_agent, $matches))
- {
- $this->setVersion("");
- $this->setBrowser(self::BROWSER_FIREFOX);
-
- return true;
- }
+ $this->_is_aol = $isAol;
}
- return false;
- }
-
- /**
- * Determine if the browser is Firefox or not (last updated 1.7)
- * @return boolean True if the browser is Firefox otherwise false
- */
- protected function checkBrowserIceweasel()
- {
- if (stripos($this->_agent, 'Iceweasel') !== false)
+ /**
+ * Get the user agent value in use to determine the browser
+ * @return string The user agent from the HTTP header
+ */
+ public function getUserAgent()
{
- $aresult = explode('/', stristr($this->_agent, 'Iceweasel'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_ICEWEASEL);
-
- return true;
+ return $this->_agent;
}
- return false;
- }
-
- /**
- * Determine if the browser is Mozilla or not (last updated 1.7)
- * @return boolean True if the browser is Mozilla otherwise false
- */
- protected function checkBrowserMozilla()
- {
- if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent) && stripos($this->_agent, 'netscape') === false)
+ /**
+ * Set the user agent value (the construction will use the HTTP header value - this will overwrite it)
+ * @param $agent_string The value for the User Agent
+ */
+ public function setUserAgent($agent_string)
{
- $aversion = explode(' ', stristr($this->_agent, 'rv:'));
- preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent, $aversion);
- $this->setVersion(str_replace('rv:', '', $aversion[0]));
- $this->setBrowser(self::BROWSER_MOZILLA);
-
- return true;
- }
- else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i', $this->_agent) && stripos($this->_agent, 'netscape') === false)
- {
- $aversion = explode('', stristr($this->_agent, 'rv:'));
- $this->setVersion(str_replace('rv:', '', $aversion[0]));
- $this->setBrowser(self::BROWSER_MOZILLA);
-
- return true;
- }
- else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/mozilla\/([^ ]*)/i', $this->_agent, $matches) && stripos($this->_agent, 'netscape') === false)
- {
- $this->setVersion($matches[1]);
- $this->setBrowser(self::BROWSER_MOZILLA);
-
- return true;
+ $this->reset();
+ $this->_agent = $agent_string;
+ $this->determine();
}
- return false;
- }
-
- /**
- * Determine if the browser is Lynx or not (last updated 1.7)
- * @return boolean True if the browser is Lynx otherwise false
- */
- protected function checkBrowserLynx()
- {
- if (stripos($this->_agent, 'lynx') !== false)
+ protected function setMobile($value = true)
{
- $aresult = explode('/', stristr($this->_agent, 'Lynx'));
- $aversion = explode(' ', (isset($aresult[1]) ? $aresult[1] : ""));
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_LYNX);
-
- return true;
+ $this->_is_mobile = $value;
}
- return false;
- }
-
- /**
- * Determine if the browser is Amaya or not (last updated 1.7)
- * @return boolean True if the browser is Amaya otherwise false
- */
- protected function checkBrowserAmaya()
- {
- if (stripos($this->_agent, 'amaya') !== false)
+ protected function setTablet($value = true)
{
- $aresult = explode('/', stristr($this->_agent, 'Amaya'));
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- $this->setBrowser(self::BROWSER_AMAYA);
-
- return true;
+ $this->_is_tablet = $value;
}
- return false;
- }
-
- /**
- * Determine if the browser is Safari or not (last updated 1.7)
- * @return boolean True if the browser is Safari otherwise false
- */
- protected function checkBrowserSafari()
- {
- if (stripos($this->_agent, 'Safari') !== false && stripos($this->_agent, 'iPhone') === false && stripos($this->_agent, 'iPod') === false)
+ protected function setRobot($value = true)
{
- $aresult = explode('/', stristr($this->_agent, 'Version'));
- if (isset($aresult[1]))
- {
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $this->setVersion(self::VERSION_UNKNOWN);
- }
- $this->setBrowser(self::BROWSER_SAFARI);
-
- return true;
+ $this->_is_robot = $value;
}
- return false;
- }
-
- /**
- * Determine if the browser is iPhone or not (last updated 1.7)
- * @return boolean True if the browser is iPhone otherwise false
- */
- protected function checkBrowseriPhone()
- {
- if (stripos($this->_agent, 'iPhone') !== false)
+ /**
+ * Protected routine to calculate and determine what the browser is in use (including platform)
+ */
+ protected function determine()
{
- $aresult = explode('/', stristr($this->_agent, 'Version'));
- if (isset($aresult[1]))
- {
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $this->setVersion(self::VERSION_UNKNOWN);
- }
- $this->setMobile(true);
- $this->setBrowser(self::BROWSER_IPHONE);
-
- return true;
+ $this->checkPlatform();
+ $this->checkBrowsers();
+ $this->checkForAol();
+ $this->checkIP();
+ $this->checkChromeFrame();
+ $this->checkNewGeneration();
+ $this->checkAge();
+ $this->checkHTML5();
}
- return false;
- }
-
- /**
- * Determine if the browser is iPod or not (last updated 1.7)
- * @return boolean True if the browser is iPod otherwise false
- */
- protected function checkBrowseriPad()
- {
- if (stripos($this->_agent, 'iPad') !== false)
+ /**
+ * Protected routine to determine if the browser is chrome frame enabled
+ * @return boolean True if the browser was detected otherwise false
+ */
+ protected function checkChromeFrame()
{
- $aresult = explode('/', stristr($this->_agent, 'Version'));
- if (isset($aresult[1]))
- {
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $this->setVersion(self::VERSION_UNKNOWN);
- }
- $this->setTablet(true);
- $this->setMobile(true);
- $this->setBrowser(self::BROWSER_IPAD);
- return true;
+ $this->_chrome_frame = false;
+ if (preg_match('/chromeframe/i', $this->_agent)) {
+ $this->_chrome_frame = true;
+ $aresult = explode('/', stristr($this->_agent, 'chromeframe'));
+ $aversion = explode(' ', $aresult[1]);
+ $chrome_version = explode('.', $aversion[0]);
+ $this->_chrome_frame_version = $chrome_version[0];
+ }
+
+ return $this->_chrome_frame;
}
- return false;
- }
-
- /**
- * Determine if the browser is iPod or not (last updated 1.7)
- * @return boolean True if the browser is iPod otherwise false
- */
- protected function checkBrowseriPod()
- {
- if (stripos($this->_agent, 'iPod') !== false)
+ /**
+ * Protected routine to determine the browser type
+ * @return boolean True if the browser was detected otherwise false
+ */
+ protected function checkBrowsers()
{
- $aresult = explode('/', stristr($this->_agent, 'Version'));
- if (isset($aresult[1]))
- {
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $this->setVersion(self::VERSION_UNKNOWN);
- }
- $this->setMobile(true);
- $this->setBrowser(self::BROWSER_IPOD);
-
- return true;
+ return (
+ // well-known, well-used
+ // Special Notes:
+ // (1) Opera must be checked before FireFox due to the odd
+ // user agents used in some older versions of Opera
+ // (2) WebTV is strapped onto Internet Explorer so we must
+ // check for WebTV before IE
+ // (3) (deprecated) Galeon is based on Firefox and needs to be
+ // tested before Firefox is tested
+ // (4) OmniWeb is based on Safari so OmniWeb check must occur
+ // before Safari
+ // (5) Netscape 9+ is based on Firefox so Netscape checks
+ // before FireFox are necessary
+ $this->checkBrowserWebTv() ||
+ $this->checkBrowserInternetExplorer() ||
+ $this->checkBrowserOpera() ||
+ $this->checkBrowserGaleon() ||
+ $this->checkBrowserNetscapeNavigator9Plus() ||
+ $this->checkBrowserIceweasel() ||
+ $this->checkBrowserFirefox() ||
+ $this->checkBrowserChrome() ||
+ $this->checkBrowserOmniWeb() ||
+ // common mobile
+ $this->checkBrowserAndroid() ||
+ $this->checkBrowseriPad() ||
+ $this->checkBrowseriPod() ||
+ $this->checkBrowseriPhone() ||
+ $this->checkBrowserBlackBerry() ||
+ $this->checkBrowserNokia() ||
+ // common bots
+ $this->checkBrowserGoogleBot() ||
+ $this->checkBrowserMSNBot() ||
+ $this->checkBrowserSlurp() ||
+ // WebKit base check (post mobile and others)
+ $this->checkBrowserSafari() ||
+ // everyone else
+ $this->checkBrowserNetPositive() ||
+ $this->checkBrowserFirebird() ||
+ $this->checkBrowserKonqueror() ||
+ $this->checkBrowserIcab() ||
+ $this->checkBrowserPhoenix() ||
+ $this->checkBrowserAmaya() ||
+ $this->checkBrowserLynx() ||
+ $this->checkBrowserShiretoko() ||
+ $this->checkBrowserIceCat() ||
+ $this->checkBrowserW3CValidator() ||
+ $this->checkBrowserMozilla() /* Mozilla is such an open standard that you must check it last */
+ );
}
- return false;
- }
-
- /**
- * Determine if the browser is Android or not (last updated 1.7)
- * @return boolean True if the browser is Android otherwise false
- */
- protected function checkBrowserAndroid()
- {
- if (stripos($this->_agent, 'Android') !== false)
+ /**
+ * Determine if the user is using a BlackBerry (last updated 1.7)
+ * @return boolean True if the browser is the BlackBerry browser otherwise false
+ */
+ protected function checkBrowserBlackBerry()
{
- $aresult = explode(' ', stristr($this->_agent, 'Android'));
- if (isset($aresult[1]))
- {
- $aversion = explode(' ', $aresult[1]);
- $this->setVersion($aversion[0]);
- }
- else
- {
- $this->setVersion(self::VERSION_UNKNOWN);
- }
- $this->setMobile(true);
- $this->setBrowser(self::BROWSER_ANDROID);
+ if (stripos($this->_agent, 'blackberry') !== false) {
+ $aresult = explode("/", stristr($this->_agent, "BlackBerry"));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->_browser_name = self::BROWSER_BLACKBERRY;
+ $this->setMobile(true);
- return true;
+ return true;
+ }
+
+ return false;
}
- return false;
- }
+ /**
+ * Determine if the user is using an AOL User Agent (last updated 1.7)
+ * @return boolean True if the browser is from AOL otherwise false
+ */
+ protected function checkForAol()
+ {
+ $this->setAol(false);
+ $this->setAolVersion(self::VERSION_UNKNOWN);
- /**
- * Determine the user's platform (last updated 1.7)
- */
- protected function checkPlatform()
- {
- if (stripos($this->_agent, 'windows') !== false)
- {
- $this->_platform = self::PLATFORM_WINDOWS;
- }
- else if (stripos($this->_agent, 'iPad') !== false)
- {
- $this->_platform = self::PLATFORM_IPAD;
- }
- else if (stripos($this->_agent, 'iPod') !== false)
- {
- $this->_platform = self::PLATFORM_IPOD;
- }
- else if (stripos($this->_agent, 'iPhone') !== false)
- {
- $this->_platform = self::PLATFORM_IPHONE;
- }
- elseif (stripos($this->_agent, 'mac') !== false)
- {
- $this->_platform = self::PLATFORM_APPLE;
- }
- elseif (stripos($this->_agent, 'android') !== false)
- {
- $this->_platform = self::PLATFORM_ANDROID;
- }
- elseif (stripos($this->_agent, 'linux') !== false)
- {
- $this->_platform = self::PLATFORM_LINUX;
- }
- else if (stripos($this->_agent, 'Nokia') !== false)
- {
- $this->_platform = self::PLATFORM_NOKIA;
- }
- else if (stripos($this->_agent, 'BlackBerry') !== false)
- {
- $this->_platform = self::PLATFORM_BLACKBERRY;
- }
- elseif (stripos($this->_agent, 'FreeBSD') !== false)
- {
- $this->_platform = self::PLATFORM_FREEBSD;
- }
- elseif (stripos($this->_agent, 'OpenBSD') !== false)
- {
- $this->_platform = self::PLATFORM_OPENBSD;
- }
- elseif (stripos($this->_agent, 'NetBSD') !== false)
- {
- $this->_platform = self::PLATFORM_NETBSD;
- }
- elseif (stripos($this->_agent, 'OpenSolaris') !== false)
- {
- $this->_platform = self::PLATFORM_OPENSOLARIS;
- }
- elseif (stripos($this->_agent, 'SunOS') !== false)
- {
- $this->_platform = self::PLATFORM_SUNOS;
- }
- elseif (stripos($this->_agent, 'OS\/2') !== false)
- {
- $this->_platform = self::PLATFORM_OS2;
- }
- elseif (stripos($this->_agent, 'BeOS') !== false)
- {
- $this->_platform = self::PLATFORM_BEOS;
- }
- elseif (stripos($this->_agent, 'win') !== false)
- {
- $this->_platform = self::PLATFORM_WINDOWS;
- }
- }
+ if (stripos($this->_agent, 'aol') !== false) {
+ $aversion = explode(' ', stristr($this->_agent, 'AOL'));
+ $this->setAol(true);
+ $this->setAolVersion(preg_replace('/[^0-9\.a-z]/i', '', $aversion[1]));
- /**
- * Check if is new generation
- */
- protected function checkNewGeneration()
- {
- $this->_is_new_generation = false;
+ return true;
+ }
- if (in_array($this->_browser_name, array('Opera', 'Internet Explorer', 'Firefox', 'Iceweasel', 'Safari', 'Chrome', 'iPhone', 'iPod')))
- {
- switch ($this->_browser_name)
- {
- case 'Opera':
- if ($this->_version >= 10)
- $this->_is_new_generation = true;
- break;
- case 'Internet Explorer':
- if ($this->_version >= 7)
- $this->_is_new_generation = true;
- if ($this->_chrome_frame === true && $this->_chrome_frame_version >= 6)
- $this->_is_new_generation = true;
- break;
- case 'Firefox':
- case 'Iceweasel':
- if ($this->_version >= 3)
- $this->_is_new_generation = true;
- break;
- case 'Safari':
- if ($this->_version >= 4)
- $this->_is_new_generation = true;
- break;
- case 'Chrome':
- if ($this->_version >= 4)
- $this->_is_new_generation = true;
- break;
- case 'iPhone':
- case 'iPod':
- $this->_is_new_generation = true;
- break;
- }
+ return false;
}
- }
- /**
- * Check if is HTML5
- */
- protected function checkHTML5()
- {
- if (in_array($this->_browser_name, array('Opera', 'Internet Explorer', 'Firefox', 'Iceweasel', 'Safari', 'Chrome', 'iPhone', 'iPod')))
+ /**
+ * Determine if the browser is the GoogleBot or not (last updated 1.7)
+ * @return boolean True if the browser is the GoogletBot otherwise false
+ */
+ protected function checkBrowserGoogleBot()
{
- switch ($this->_browser_name)
- {
- case 'Opera':
- if ($this->_version >= 10)
- $this->_is_html5 = true;
- break;
- case 'Internet Explorer':
- if ($this->_version >= 9)
- $this->_is_html5 = true;
- if ($this->_chrome_frame === true && $this->_chrome_frame_version >= 6)
- $this->_is_html5 = true;
- break;
- case 'Firefox':
- case 'Iceweasel':
- if ($this->_version >= 4)
- $this->_is_html5 = true;
- break;
- case 'Safari':
- if ($this->_version >= 5)
- $this->_is_html5 = true;
- break;
- case 'Chrome':
- if ($this->_version >= 9)
- $this->_is_html5 = true;
- break;
- case 'iPhone':
- case 'iPod':
- $this->_is_html5 = true;
- break;
- }
+ if (stripos($this->_agent, 'googlebot') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'googlebot'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion(str_replace(';', '', $aversion[0]));
+ $this->_browser_name = self::BROWSER_GOOGLEBOT;
+ $this->setRobot(true);
+
+ return true;
+ }
+
+ return false;
}
- }
- /**
- * Check the version of browser
- */
- protected function checkAge()
- {
- $this->_is_old = false;
-
- switch ($this->_browser_name)
+ /**
+ * Determine if the browser is the MSNBot or not (last updated 1.9)
+ * @return boolean True if the browser is the MSNBot otherwise false
+ */
+ protected function checkBrowserMSNBot()
{
- case 'Opera':
- if ($this->_version < 10)
- $this->_is_old = true;
- break;
- case 'Firefox':
- case 'Iceweasel':
- if ($this->_version < 3)
- $this->_is_old = true;
- break;
- case 'Safari':
- if ($this->_version < 5)
- $this->_is_old = true;
- break;
- case 'Chrome':
- if (version_compare($this->_version, 5, '<'))
- $this->_is_old = true;
- break;
- case 'iPhone':
- case 'iPod':
- $this->_is_old = true;
- break;
+ if (stripos($this->_agent, "msnbot") !== false) {
+ $aresult = explode("/", stristr($this->_agent, "msnbot"));
+ $aversion = explode(" ", $aresult[1]);
+ $this->setVersion(str_replace(";", "", $aversion[0]));
+ $this->_browser_name = self::BROWSER_MSNBOT;
+ $this->setRobot(true);
+
+ return true;
+ }
+
+ return false;
}
- }
- /**
- * GET the IP address
- */
- protected function checkIP()
- {
- if (getenv("HTTP_CLIENT_IP"))
- $this->_ip = getenv("HTTP_CLIENT_IP");
- elseif (getenv("HTTP_X_FORWARDED_FOR"))
- $this->_ip = getenv("HTTP_X_FORWARDED_FOR");
- else
- $this->_ip = getenv("REMOTE_ADDR");
- }
+ /**
+ * Determine if the browser is the W3C Validator or not (last updated 1.7)
+ * @return boolean True if the browser is the W3C Validator otherwise false
+ */
+ protected function checkBrowserW3CValidator()
+ {
+ if (stripos($this->_agent, 'W3C-checklink') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'W3C-checklink'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->_browser_name = self::BROWSER_W3CVALIDATOR;
+ return true;
+ } else if (stripos($this->_agent, 'W3C_Validator') !== false) {
+ // Some of the Validator versions do not delineate w/ a slash - add it back in
+ $ua = str_replace("W3C_Validator ", "W3C_Validator/", $this->_agent);
+ $aresult = explode('/', stristr($ua, 'W3C_Validator'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->_browser_name = self::BROWSER_W3CVALIDATOR;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is the Yahoo! Slurp Robot or not (last updated 1.7)
+ * @return boolean True if the browser is the Yahoo! Slurp Robot otherwise false
+ */
+ protected function checkBrowserSlurp()
+ {
+ if (stripos($this->_agent, 'slurp') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Slurp'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->_browser_name = self::BROWSER_SLURP;
+ $this->setRobot(true);
+ $this->setMobile(false);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Internet Explorer or not (last updated 1.7)
+ * @return boolean True if the browser is Internet Explorer otherwise false
+ */
+ protected function checkBrowserInternetExplorer()
+ {
+
+ // Test for v1 - v1.5 IE
+ if (stripos($this->_agent, 'microsoft internet explorer') !== false) {
+ $this->setBrowser(self::BROWSER_IE);
+ $this->setVersion('1.0');
+ $aresult = stristr($this->_agent, '/');
+ if (preg_match('/308|425|426|474|0b1/i', $aresult)) {
+ $this->setVersion('1.5');
+ }
+
+ return true;
+ }
+ // Test for versions > 1.5
+ else if (stripos($this->_agent, 'msie') !== false && stripos($this->_agent, 'opera') === false) {
+ // See if the browser is the odd MSN Explorer
+ if (stripos($this->_agent, 'msnb') !== false) {
+ $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'MSN'));
+ $this->setBrowser(self::BROWSER_MSN);
+ $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
+
+ return true;
+ }
+ $aresult = explode(' ', stristr(str_replace(';', '; ', $this->_agent), 'msie'));
+ $this->setBrowser(self::BROWSER_IE);
+ $this->setVersion(str_replace(array('(', ')', ';'), '', $aresult[1]));
+
+ return true;
+ }
+ // Test for Pocket IE
+ else if (stripos($this->_agent, 'mspie') !== false || stripos($this->_agent, 'pocket') !== false) {
+ $aresult = explode(' ', stristr($this->_agent, 'mspie'));
+ $this->setPlatform(self::PLATFORM_WINDOWS_CE);
+ $this->setBrowser(self::BROWSER_POCKET_IE);
+ $this->setMobile(true);
+
+ if (stripos($this->_agent, 'mspie') !== false) {
+ $this->setVersion($aresult[1]);
+ } else {
+ $aversion = explode('/', $this->_agent);
+ $this->setVersion($aversion[1]);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Opera or not (last updated 1.7)
+ * @return boolean True if the browser is Opera otherwise false
+ */
+ protected function checkBrowserOpera()
+ {
+ if (stripos($this->_agent, 'opera mini') !== false) {
+ $resultant = stristr($this->_agent, 'opera mini');
+ if (preg_match('/\//', $resultant)) {
+ $aresult = explode('/', $resultant);
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $aversion = explode(' ', stristr($resultant, 'opera mini'));
+ $this->setVersion($aversion[1]);
+ }
+ $this->_browser_name = self::BROWSER_OPERA_MINI;
+ $this->setMobile(true);
+
+ return true;
+ } else if (stripos($this->_agent, 'opera') !== false) {
+ $resultant = stristr($this->_agent, 'opera');
+ if (preg_match('/Version\/([0-9]{2}.*)$/', $resultant, $matches)) {
+ $this->setVersion($matches[1]);
+ } else if (preg_match('/\//', $resultant)) {
+ $aresult = explode('/', str_replace("(", " ", $resultant));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $aversion = explode(' ', stristr($resultant, 'opera'));
+ $this->setVersion(isset($aversion[1]) ? $aversion[1] : "");
+ }
+ $this->_browser_name = self::BROWSER_OPERA;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Chrome or not (last updated 1.7)
+ * @return boolean True if the browser is Chrome otherwise false
+ */
+ protected function checkBrowserChrome()
+ {
+ if (stripos($this->_agent, 'Chrome') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Chrome'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_CHROME);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is WebTv or not (last updated 1.7)
+ * @return boolean True if the browser is WebTv otherwise false
+ */
+ protected function checkBrowserWebTv()
+ {
+ if (stripos($this->_agent, 'webtv') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'webtv'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_WEBTV);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is NetPositive or not (last updated 1.7)
+ * @return boolean True if the browser is NetPositive otherwise false
+ */
+ protected function checkBrowserNetPositive()
+ {
+ if (stripos($this->_agent, 'NetPositive') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'NetPositive'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion(str_replace(array('(', ')', ';'), '', $aversion[0]));
+ $this->setBrowser(self::BROWSER_NETPOSITIVE);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Galeon or not (last updated 1.7)
+ * @return boolean True if the browser is Galeon otherwise false
+ */
+ protected function checkBrowserGaleon()
+ {
+ if (stripos($this->_agent, 'galeon') !== false) {
+ $aresult = explode(' ', stristr($this->_agent, 'galeon'));
+ $aversion = explode('/', $aresult[0]);
+ $this->setVersion($aversion[1]);
+ $this->setBrowser(self::BROWSER_GALEON);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Konqueror or not (last updated 1.7)
+ * @return boolean True if the browser is Konqueror otherwise false
+ */
+ protected function checkBrowserKonqueror()
+ {
+ if (stripos($this->_agent, 'Konqueror') !== false) {
+ $aresult = explode(' ', stristr($this->_agent, 'Konqueror'));
+ $aversion = explode('/', $aresult[0]);
+ $this->setVersion($aversion[1]);
+ $this->setBrowser(self::BROWSER_KONQUEROR);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is iCab or not (last updated 1.7)
+ * @return boolean True if the browser is iCab otherwise false
+ */
+ protected function checkBrowserIcab()
+ {
+ if (stripos($this->_agent, 'icab') !== false) {
+ $aversion = explode(' ', stristr(str_replace('/', ' ', $this->_agent), 'icab'));
+ $this->setVersion($aversion[1]);
+ $this->setBrowser(self::BROWSER_ICAB);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is OmniWeb or not (last updated 1.7)
+ * @return boolean True if the browser is OmniWeb otherwise false
+ */
+ protected function checkBrowserOmniWeb()
+ {
+ if (stripos($this->_agent, 'omniweb') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'omniweb'));
+ $aversion = explode(' ', isset($aresult[1]) ? $aresult[1] : "");
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_OMNIWEB);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Phoenix or not (last updated 1.7)
+ * @return boolean True if the browser is Phoenix otherwise false
+ */
+ protected function checkBrowserPhoenix()
+ {
+ if (stripos($this->_agent, 'Phoenix') !== false) {
+ $aversion = explode('/', stristr($this->_agent, 'Phoenix'));
+ $this->setVersion($aversion[1]);
+ $this->setBrowser(self::BROWSER_PHOENIX);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Firebird or not (last updated 1.7)
+ * @return boolean True if the browser is Firebird otherwise false
+ */
+ protected function checkBrowserFirebird()
+ {
+ if (stripos($this->_agent, 'Firebird') !== false) {
+ $aversion = explode('/', stristr($this->_agent, 'Firebird'));
+ $this->setVersion($aversion[1]);
+ $this->setBrowser(self::BROWSER_FIREBIRD);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Netscape Navigator 9+ or not (last updated 1.7)
+ * NOTE: (http://browser.netscape.com/ - Official support ended on March 1st, 2008)
+ * @return boolean True if the browser is Netscape Navigator 9+ otherwise false
+ */
+ protected function checkBrowserNetscapeNavigator9Plus()
+ {
+ if (stripos($this->_agent, 'Firefox') !== false && preg_match('/Navigator\/([^ ]*)/i', $this->_agent, $matches)) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
+
+ return true;
+ } else if (stripos($this->_agent, 'Firefox') === false && preg_match('/Netscape6?\/([^ ]*)/i', $this->_agent, $matches)) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_NETSCAPE_NAVIGATOR);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Shiretoko or not (https://wiki.mozilla.org/Projects/shiretoko) (last updated 1.7)
+ * @return boolean True if the browser is Shiretoko otherwise false
+ */
+ protected function checkBrowserShiretoko()
+ {
+ if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/Shiretoko\/([^ ]*)/i', $this->_agent, $matches)) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_SHIRETOKO);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Ice Cat or not (http://en.wikipedia.org/wiki/GNU_IceCat) (last updated 1.7)
+ * @return boolean True if the browser is Ice Cat otherwise false
+ */
+ protected function checkBrowserIceCat()
+ {
+ if (stripos($this->_agent, 'Mozilla') !== false && preg_match('/IceCat\/([^ ]*)/i', $this->_agent, $matches)) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_ICECAT);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Nokia or not (last updated 1.7)
+ * @return boolean True if the browser is Nokia otherwise false
+ */
+ protected function checkBrowserNokia()
+ {
+ if (preg_match("/Nokia([^\/]+)\/([^ SP]+)/i", $this->_agent, $matches)) {
+ $this->setVersion($matches[2]);
+ if (stripos($this->_agent, 'Series60') !== false || strpos($this->_agent, 'S60') !== false) {
+ $this->setBrowser(self::BROWSER_NOKIA_S60);
+ } else {
+ $this->setBrowser(self::BROWSER_NOKIA);
+ }
+ $this->setMobile(true);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Firefox or not (last updated 1.7)
+ * @return boolean True if the browser is Firefox otherwise false
+ */
+ protected function checkBrowserFirefox()
+ {
+ if (stripos($this->_agent, 'safari') === false) {
+ if (preg_match("/Firefox[\/ \(]([^ ;\)]+)/i", $this->_agent, $matches)) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_FIREFOX);
+
+ return true;
+ } else if (preg_match("/Firefox$/i", $this->_agent, $matches)) {
+ $this->setVersion("");
+ $this->setBrowser(self::BROWSER_FIREFOX);
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Firefox or not (last updated 1.7)
+ * @return boolean True if the browser is Firefox otherwise false
+ */
+ protected function checkBrowserIceweasel()
+ {
+ if (stripos($this->_agent, 'Iceweasel') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Iceweasel'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_ICEWEASEL);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Mozilla or not (last updated 1.7)
+ * @return boolean True if the browser is Mozilla otherwise false
+ */
+ protected function checkBrowserMozilla()
+ {
+ if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) {
+ $aversion = explode(' ', stristr($this->_agent, 'rv:'));
+ preg_match('/rv:[0-9].[0-9][a-b]?/i', $this->_agent, $aversion);
+ $this->setVersion(str_replace('rv:', '', $aversion[0]));
+ $this->setBrowser(self::BROWSER_MOZILLA);
+
+ return true;
+ } else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/rv:[0-9]\.[0-9]/i', $this->_agent) && stripos($this->_agent, 'netscape') === false) {
+ $aversion = explode('', stristr($this->_agent, 'rv:'));
+ $this->setVersion(str_replace('rv:', '', $aversion[0]));
+ $this->setBrowser(self::BROWSER_MOZILLA);
+
+ return true;
+ } else if (stripos($this->_agent, 'mozilla') !== false && preg_match('/mozilla\/([^ ]*)/i', $this->_agent, $matches) && stripos($this->_agent, 'netscape') === false) {
+ $this->setVersion($matches[1]);
+ $this->setBrowser(self::BROWSER_MOZILLA);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Lynx or not (last updated 1.7)
+ * @return boolean True if the browser is Lynx otherwise false
+ */
+ protected function checkBrowserLynx()
+ {
+ if (stripos($this->_agent, 'lynx') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Lynx'));
+ $aversion = explode(' ', (isset($aresult[1]) ? $aresult[1] : ""));
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_LYNX);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Amaya or not (last updated 1.7)
+ * @return boolean True if the browser is Amaya otherwise false
+ */
+ protected function checkBrowserAmaya()
+ {
+ if (stripos($this->_agent, 'amaya') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Amaya'));
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ $this->setBrowser(self::BROWSER_AMAYA);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Safari or not (last updated 1.7)
+ * @return boolean True if the browser is Safari otherwise false
+ */
+ protected function checkBrowserSafari()
+ {
+ if (stripos($this->_agent, 'Safari') !== false && stripos($this->_agent, 'iPhone') === false && stripos($this->_agent, 'iPod') === false) {
+ $aresult = explode('/', stristr($this->_agent, 'Version'));
+ if (isset($aresult[1])) {
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $this->setVersion(self::VERSION_UNKNOWN);
+ }
+ $this->setBrowser(self::BROWSER_SAFARI);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is iPhone or not (last updated 1.7)
+ * @return boolean True if the browser is iPhone otherwise false
+ */
+ protected function checkBrowseriPhone()
+ {
+ if (stripos($this->_agent, 'iPhone') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Version'));
+ if (isset($aresult[1])) {
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $this->setVersion(self::VERSION_UNKNOWN);
+ }
+ $this->setMobile(true);
+ $this->setBrowser(self::BROWSER_IPHONE);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is iPod or not (last updated 1.7)
+ * @return boolean True if the browser is iPod otherwise false
+ */
+ protected function checkBrowseriPad()
+ {
+ if (stripos($this->_agent, 'iPad') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Version'));
+ if (isset($aresult[1])) {
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $this->setVersion(self::VERSION_UNKNOWN);
+ }
+ $this->setTablet(true);
+ $this->setMobile(true);
+ $this->setBrowser(self::BROWSER_IPAD);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is iPod or not (last updated 1.7)
+ * @return boolean True if the browser is iPod otherwise false
+ */
+ protected function checkBrowseriPod()
+ {
+ if (stripos($this->_agent, 'iPod') !== false) {
+ $aresult = explode('/', stristr($this->_agent, 'Version'));
+ if (isset($aresult[1])) {
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $this->setVersion(self::VERSION_UNKNOWN);
+ }
+ $this->setMobile(true);
+ $this->setBrowser(self::BROWSER_IPOD);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine if the browser is Android or not (last updated 1.7)
+ * @return boolean True if the browser is Android otherwise false
+ */
+ protected function checkBrowserAndroid()
+ {
+ if (stripos($this->_agent, 'Android') !== false) {
+ $aresult = explode(' ', stristr($this->_agent, 'Android'));
+ if (isset($aresult[1])) {
+ $aversion = explode(' ', $aresult[1]);
+ $this->setVersion($aversion[0]);
+ } else {
+ $this->setVersion(self::VERSION_UNKNOWN);
+ }
+ $this->setMobile(true);
+ $this->setBrowser(self::BROWSER_ANDROID);
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Determine the user's platform (last updated 1.7)
+ */
+ protected function checkPlatform()
+ {
+ if (stripos($this->_agent, 'windows') !== false) {
+ $this->_platform = self::PLATFORM_WINDOWS;
+ } else if (stripos($this->_agent, 'iPad') !== false) {
+ $this->_platform = self::PLATFORM_IPAD;
+ } else if (stripos($this->_agent, 'iPod') !== false) {
+ $this->_platform = self::PLATFORM_IPOD;
+ } else if (stripos($this->_agent, 'iPhone') !== false) {
+ $this->_platform = self::PLATFORM_IPHONE;
+ } elseif (stripos($this->_agent, 'mac') !== false) {
+ $this->_platform = self::PLATFORM_APPLE;
+ } elseif (stripos($this->_agent, 'android') !== false) {
+ $this->_platform = self::PLATFORM_ANDROID;
+ } elseif (stripos($this->_agent, 'linux') !== false) {
+ $this->_platform = self::PLATFORM_LINUX;
+ } else if (stripos($this->_agent, 'Nokia') !== false) {
+ $this->_platform = self::PLATFORM_NOKIA;
+ } else if (stripos($this->_agent, 'BlackBerry') !== false) {
+ $this->_platform = self::PLATFORM_BLACKBERRY;
+ } elseif (stripos($this->_agent, 'FreeBSD') !== false) {
+ $this->_platform = self::PLATFORM_FREEBSD;
+ } elseif (stripos($this->_agent, 'OpenBSD') !== false) {
+ $this->_platform = self::PLATFORM_OPENBSD;
+ } elseif (stripos($this->_agent, 'NetBSD') !== false) {
+ $this->_platform = self::PLATFORM_NETBSD;
+ } elseif (stripos($this->_agent, 'OpenSolaris') !== false) {
+ $this->_platform = self::PLATFORM_OPENSOLARIS;
+ } elseif (stripos($this->_agent, 'SunOS') !== false) {
+ $this->_platform = self::PLATFORM_SUNOS;
+ } elseif (stripos($this->_agent, 'OS\/2') !== false) {
+ $this->_platform = self::PLATFORM_OS2;
+ } elseif (stripos($this->_agent, 'BeOS') !== false) {
+ $this->_platform = self::PLATFORM_BEOS;
+ } elseif (stripos($this->_agent, 'win') !== false) {
+ $this->_platform = self::PLATFORM_WINDOWS;
+ }
+ }
+
+ /**
+ * Check if is new generation
+ */
+ protected function checkNewGeneration()
+ {
+ $this->_is_new_generation = false;
+
+ if (in_array($this->_browser_name, array('Opera', 'Internet Explorer', 'Firefox', 'Iceweasel', 'Safari', 'Chrome', 'iPhone', 'iPod'))) {
+ switch ($this->_browser_name) {
+ case 'Opera':
+ if ($this->_version >= 10)
+ $this->_is_new_generation = true;
+ break;
+ case 'Internet Explorer':
+ if ($this->_version >= 7)
+ $this->_is_new_generation = true;
+ if ($this->_chrome_frame === true && $this->_chrome_frame_version >= 6)
+ $this->_is_new_generation = true;
+ break;
+ case 'Firefox':
+ case 'Iceweasel':
+ if ($this->_version >= 3)
+ $this->_is_new_generation = true;
+ break;
+ case 'Safari':
+ if ($this->_version >= 4)
+ $this->_is_new_generation = true;
+ break;
+ case 'Chrome':
+ if ($this->_version >= 4)
+ $this->_is_new_generation = true;
+ break;
+ case 'iPhone':
+ case 'iPod':
+ $this->_is_new_generation = true;
+ break;
+ }
+ }
+ }
+
+ /**
+ * Check if is HTML5
+ */
+ protected function checkHTML5()
+ {
+ if (in_array($this->_browser_name, array('Opera', 'Internet Explorer', 'Firefox', 'Iceweasel', 'Safari', 'Chrome', 'iPhone', 'iPod'))) {
+ switch ($this->_browser_name) {
+ case 'Opera':
+ if ($this->_version >= 10)
+ $this->_is_html5 = true;
+ break;
+ case 'Internet Explorer':
+ if ($this->_version >= 9)
+ $this->_is_html5 = true;
+ if ($this->_chrome_frame === true && $this->_chrome_frame_version >= 6)
+ $this->_is_html5 = true;
+ break;
+ case 'Firefox':
+ case 'Iceweasel':
+ if ($this->_version >= 4)
+ $this->_is_html5 = true;
+ break;
+ case 'Safari':
+ if ($this->_version >= 5)
+ $this->_is_html5 = true;
+ break;
+ case 'Chrome':
+ if ($this->_version >= 9)
+ $this->_is_html5 = true;
+ break;
+ case 'iPhone':
+ case 'iPod':
+ $this->_is_html5 = true;
+ break;
+ }
+ }
+ }
+
+ /**
+ * Check the version of browser
+ */
+ protected function checkAge()
+ {
+ $this->_is_old = false;
+
+ switch ($this->_browser_name) {
+ case 'Opera':
+ if ($this->_version < 10)
+ $this->_is_old = true;
+ break;
+ case 'Firefox':
+ case 'Iceweasel':
+ if ($this->_version < 3)
+ $this->_is_old = true;
+ break;
+ case 'Safari':
+ if ($this->_version < 5)
+ $this->_is_old = true;
+ break;
+ case 'Chrome':
+ if (version_compare($this->_version, 5, '<'))
+ $this->_is_old = true;
+ break;
+ case 'iPhone':
+ case 'iPod':
+ $this->_is_old = true;
+ break;
+ }
+ }
+
+ /**
+ * GET the IP address
+ */
+ protected function checkIP()
+ {
+ if (getenv("HTTP_CLIENT_IP"))
+ $this->_ip = getenv("HTTP_CLIENT_IP");
+ elseif (getenv("HTTP_X_FORWARDED_FOR"))
+ $this->_ip = getenv("HTTP_X_FORWARDED_FOR");
+ else
+ $this->_ip = getenv("REMOTE_ADDR");
+ }
}
diff --git a/lib/classes/DailymotionWithoutOauth2.php b/lib/classes/DailymotionWithoutOauth2.php
index 855b481d9b..bbe346074a 100644
--- a/lib/classes/DailymotionWithoutOauth2.php
+++ b/lib/classes/DailymotionWithoutOauth2.php
@@ -15,8 +15,7 @@ require_once __DIR__ . '/../vendor/dailymotion-sdk-php/Dailymotion.php';
class DailymotionWithoutOauth2 extends Dailymotion
{
-
-/**
+ /**
* Call a remote method.
*
* @param $method String the method name to call.
@@ -33,60 +32,43 @@ class DailymotionWithoutOauth2 extends Dailymotion
{
$headers = array('Content-Type: application/json');
$payload = json_encode(array
- (
+ (
'call' => $method,
'args' => $args,
- ));
+ ));
$status_code = null;
- try
- {
+ try {
$result = json_decode($this->oauthRequest($this->apiEndpointUrl, $payload, $access_token, $headers, $status_code), true);
- }
- catch (DailymotionAuthException $e)
- {
+ } catch (DailymotionAuthException $e) {
- if ($e->error === 'invalid_token')
- {
- throw new Bridge_Exception_ActionAuthNeedReconnect();
- }
- else
- {
+ if ($e->error === 'invalid_token') {
+ throw new Bridge_Exception_ActionAuthNeedReconnect();
+ } else {
throw $e;
}
}
- if (!isset($result))
- {
+ if ( ! isset($result)) {
throw new DailymotionApiException('Invalid API server response.');
- }
- elseif ($status_code !== 200)
- {
+ } elseif ($status_code !== 200) {
throw new DailymotionApiException('Unknown error: ' . $status_code, $status_code);
- }
- elseif (is_array($result) && isset($result['error']))
- {
+ } elseif (is_array($result) && isset($result['error'])) {
$message = isset($result['error']['message']) ? $result['error']['message'] : null;
$code = isset($result['error']['code']) ? $result['error']['code'] : null;
- if ($code === 403)
- {
+ if ($code === 403) {
throw new DailymotionAuthRequiredException($message, $code);
- }
- else
- {
+ } else {
throw new DailymotionApiException($message, $code);
}
- }
- elseif (!isset($result['result']))
- {
+ } elseif ( ! isset($result['result'])) {
throw new DailymotionApiException("Invalid API server response: no `result' key found.");
}
return $result['result'];
}
-
- /**
+ /**
* Upload a file on the Dailymotion servers and generate an URL to be used with API methods.
*
* @param $filePath String a path to the file to upload
diff --git a/lib/classes/Exception/Session/MailLocked.class.php b/lib/classes/Exception/Session/MailLocked.class.php
index 4ce40f09da..aa35c2c842 100644
--- a/lib/classes/Exception/Session/MailLocked.class.php
+++ b/lib/classes/Exception/Session/MailLocked.class.php
@@ -17,18 +17,16 @@
*/
class Exception_Session_MailLocked extends Exception
{
+ protected $usr_id;
- protected $usr_id;
-
- public function __construct($usr_id = null, $message = null, $code = null, $previous = null)
- {
- $this->usr_id = $usr_id;
- parent::__construct($message, $code, $previous);
- }
-
- public function get_usr_id()
- {
- return $this->usr_id;
- }
+ public function __construct($usr_id = null, $message = null, $code = null, $previous = null)
+ {
+ $this->usr_id = $usr_id;
+ parent::__construct($message, $code, $previous);
+ }
+ public function get_usr_id()
+ {
+ return $this->usr_id;
+ }
}
diff --git a/lib/classes/Feed/Abstract.class.php b/lib/classes/Feed/Abstract.class.php
index 0c976c98d1..1b65e811fd 100644
--- a/lib/classes/Feed/Abstract.class.php
+++ b/lib/classes/Feed/Abstract.class.php
@@ -17,79 +17,82 @@
*/
abstract class Feed_Abstract
{
- /**
- *
- */
- const FORMAT_RSS = 'rss';
- /**
- *
- */
- const FORMAT_ATOM = 'atom';
- /**
- *
- */
- const FORMAT_COOLIRIS = 'cooliris';
+ /**
+ *
+ */
+ const FORMAT_RSS = 'rss';
+ /**
+ *
+ */
+ const FORMAT_ATOM = 'atom';
+ /**
+ *
+ */
+ const FORMAT_COOLIRIS = 'cooliris';
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var string
- */
- protected $title;
- /**
- *
- * @var string
- */
- protected $subtitle;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->title;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @return string
- */
- public function get_subtitle()
- {
- return $this->subtitle;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $subtitle;
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return $this->updated_on;
- }
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->title;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_subtitle()
+ {
+ return $this->subtitle;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return $this->updated_on;
+ }
}
diff --git a/lib/classes/Feed/Adapter.class.php b/lib/classes/Feed/Adapter.class.php
index 6705feb602..3cb20977e3 100644
--- a/lib/classes/Feed/Adapter.class.php
+++ b/lib/classes/Feed/Adapter.class.php
@@ -17,738 +17,708 @@
*/
class Feed_Adapter extends Feed_Abstract implements Feed_Interface, cache_cacheableInterface
{
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var collection
+ */
+ protected $collection;
- /**
- *
- * @var collection
- */
- protected $collection;
+ /**
+ *
+ * @var array
+ */
+ protected $publishers;
- /**
- *
- * @var array
- */
- protected $publishers;
+ /**
+ *
+ * @var boolean
+ */
+ protected $public;
- /**
- *
- * @var boolean
- */
- protected $public;
+ /**
+ *
+ * @var Feed_Publisher_Adapter
+ */
+ protected $owner;
- /**
- *
- * @var Feed_Publisher_Adapter
- */
- protected $owner;
+ /**
+ *
+ * @var string
+ */
+ protected $icon_url;
- /**
- *
- * @var string
- */
- protected $icon_url;
+ const CACHE_ENTRY_NUMBER = 'entrynumber';
+ const CACHE_USER_TOKEN = 'usr_token';
+ const MAX_ENTRIES = 20;
- const CACHE_ENTRY_NUMBER = 'entrynumber';
- const CACHE_USER_TOKEN = 'usr_token';
- const MAX_ENTRIES = 20;
-
- /**
- *
- * @param appbox $appbox
- * @param int $id
- * @return Feed_Adapter
- */
- public function __construct(appbox &$appbox, $id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $id;
-
- $this->load();
-
- return $this;
- }
-
- protected function load()
- {
- try
+ /**
+ *
+ * @param appbox $appbox
+ * @param int $id
+ * @return Feed_Adapter
+ */
+ public function __construct(appbox &$appbox, $id)
{
- $datas = $this->get_data_from_cache();
+ $this->appbox = $appbox;
+ $this->id = (int) $id;
- $this->title = $datas['title'];
- $this->subtitle = $datas['subtitle'];
- $this->collection = $datas['base_id'] ? collection::get_from_base_id($datas['base_id']) : null;
- $this->created_on = $datas['created_on'];
- $this->updated_on = $datas['updated_on'];
- $this->public = $datas['public'];
-
- return $this;
- }
- catch (Exception $e)
- {
+ $this->load();
+ return $this;
}
- $sql = 'SELECT id, title, subtitle, created_on, updated_on, base_id, public
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+
+ $this->title = $datas['title'];
+ $this->subtitle = $datas['subtitle'];
+ $this->collection = $datas['base_id'] ? collection::get_from_base_id($datas['base_id']) : null;
+ $this->created_on = $datas['created_on'];
+ $this->updated_on = $datas['updated_on'];
+ $this->public = $datas['public'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT id, title, subtitle, created_on, updated_on, base_id, public
FROM feeds WHERE id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_FeedNotFound ();
+ if ( ! $row)
+ throw new Exception_FeedNotFound ();
- $this->title = $row['title'];
- $this->subtitle = $row['subtitle'];
- if (!is_null($row['base_id']))
- $this->collection = collection::get_from_base_id($row['base_id']);
- $this->created_on = new DateTime($row['created_on']);
- $this->updated_on = new DateTime($row['updated_on']);
- $this->public = !!$row['public'];
+ $this->title = $row['title'];
+ $this->subtitle = $row['subtitle'];
+ if ( ! is_null($row['base_id']))
+ $this->collection = collection::get_from_base_id($row['base_id']);
+ $this->created_on = new DateTime($row['created_on']);
+ $this->updated_on = new DateTime($row['updated_on']);
+ $this->public = ! ! $row['public'];
- $base_id = $this->collection instanceof collection ? $this->collection->get_base_id() : null;
+ $base_id = $this->collection instanceof collection ? $this->collection->get_base_id() : null;
- $datas = array(
- 'title' => $this->title
- , 'subtitle' => $this->subtitle
- , 'base_id' => $base_id
- , 'created_on' => $this->created_on
- , 'updated_on' => $this->updated_on
- , 'public' => $this->public
- );
+ $datas = array(
+ 'title' => $this->title
+ , 'subtitle' => $this->subtitle
+ , 'base_id' => $base_id
+ , 'created_on' => $this->created_on
+ , 'updated_on' => $this->updated_on
+ , 'public' => $this->public
+ );
- $this->set_data_to_cache($datas);
+ $this->set_data_to_cache($datas);
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function get_icon_url()
- {
- if ($this->icon_url)
-
- return $this->icon_url;
-
- $url = '/skins/icons/rss32.gif';
-
- $file = $this->appbox->get_registry()->get('GV_RootPath')
- . 'www/custom/feed_' . $this->get_id() . '.jpg';
-
- if (file_exists($file))
- {
- $url = '/custom/feed_' . $this->get_id() . '.jpg';
+ return $this;
}
- $this->icon_url = $url;
+ /**
+ *
+ * @return string
+ */
+ public function get_icon_url()
+ {
+ if ($this->icon_url)
+ return $this->icon_url;
- return $this->icon_url;
- }
+ $url = '/skins/icons/rss32.gif';
- /**
- *
- * @param system_file $file
- * @return Feed_Adapter
- */
- public function set_icon(system_file $file)
- {
- $registry = registry::get_instance();
-
- $config_file = $registry->get('GV_RootPath')
- . 'config/feed_' . $this->get_id() . '.jpg';
- $www_file = $registry->get('GV_RootPath')
+ $file = $this->appbox->get_registry()->get('GV_RootPath')
. 'www/custom/feed_' . $this->get_id() . '.jpg';
- copy($file->getPathname(), $config_file);
- copy($file->getPathname(), $www_file);
- $this->icon_url = null;
+ if (file_exists($file)) {
+ $url = '/custom/feed_' . $this->get_id() . '.jpg';
+ }
- return $this;
- }
+ $this->icon_url = $url;
- public function set_created_on(DateTime $created_on)
- {
- $sql = 'UPDATE feeds SET created_on = :created_on
+ return $this->icon_url;
+ }
+
+ /**
+ *
+ * @param system_file $file
+ * @return Feed_Adapter
+ */
+ public function set_icon(system_file $file)
+ {
+ $registry = registry::get_instance();
+
+ $config_file = $registry->get('GV_RootPath')
+ . 'config/feed_' . $this->get_id() . '.jpg';
+ $www_file = $registry->get('GV_RootPath')
+ . 'www/custom/feed_' . $this->get_id() . '.jpg';
+
+ copy($file->getPathname(), $config_file);
+ copy($file->getPathname(), $www_file);
+ $this->icon_url = null;
+
+ return $this;
+ }
+
+ public function set_created_on(DateTime $created_on)
+ {
+ $sql = 'UPDATE feeds SET created_on = :created_on
WHERE id = :feed_id';
- $params = array(
- ':created_on' => $created_on->format(DATE_ISO8601)
- , ':feed_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->created_on = $created_on;
- $this->delete_data_from_cache();
+ $params = array(
+ ':created_on' => $created_on->format(DATE_ISO8601)
+ , ':feed_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->created_on = $created_on;
+ $this->delete_data_from_cache();
- return $this;
- }
-
- public function reset_icon()
- {
- $registry = registry::get_instance();
- $config_file = $registry->get('GV_RootPath')
- . 'config/feed_' . $this->get_id() . '.jpg';
- $www_file = $registry->get('GV_RootPath')
- . 'www/custom/feed_' . $this->get_id() . '.jpg';
-
- if (is_file($config_file))
- unlink($config_file);
- if (is_file($www_file))
- unlink($www_file);
-
- $this->icon_url = null;
-
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_aggregated()
- {
- return false;
- }
-
- /**
- *
- * @param User_Adapter $user
- * @return boolean
- */
- public function is_owner(User_Adapter $user)
- {
- $this->load_publishers();
-
- return $this->owner->get_user()->get_id() === $user->get_id();
- }
-
- /**
- *
- * @param User_Adapter $user
- * @return boolean
- */
- public function is_publisher(User_Adapter $user)
- {
- return in_array($user->get_id(), array_keys($this->get_publishers()));
- }
-
- /**
- * Tells if a user has access to the feed
- *
- * @param User_Adapter $user
- * @return type
- */
- public function has_access(User_Adapter $user)
- {
- if ($this->get_collection() instanceof collection)
-
- return $user->ACL()->has_access_to_base($this->collection->get_base_id());
- return true;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_public()
- {
- if ($this->get_collection() instanceof collection)
- {
- return false;
+ return $this;
}
- return $this->public;
- }
+ public function reset_icon()
+ {
+ $registry = registry::get_instance();
+ $config_file = $registry->get('GV_RootPath')
+ . 'config/feed_' . $this->get_id() . '.jpg';
+ $www_file = $registry->get('GV_RootPath')
+ . 'www/custom/feed_' . $this->get_id() . '.jpg';
- /**
- *
- * @return array
- */
- public function get_publishers()
- {
- return $this->load_publishers();
- }
+ if (is_file($config_file))
+ unlink($config_file);
+ if (is_file($www_file))
+ unlink($www_file);
- /**
- *
- * @return collection
- */
- public function get_collection()
- {
- return $this->collection;
- }
+ $this->icon_url = null;
- /**
- *
- * @param User_Adapter $user
- * @return Feed_Adapter
- */
- public function add_publisher(User_Adapter $user)
- {
- if (in_array($user->get_id(), array_keys($this->get_publishers())))
+ return $this;
+ }
- return $this;
+ /**
+ *
+ * @return boolean
+ */
+ public function is_aggregated()
+ {
+ return false;
+ }
- Feed_Publisher_Adapter::create($this->appbox, $user, $this, false);
- $this->publishers = null;
+ /**
+ *
+ * @param User_Adapter $user
+ * @return boolean
+ */
+ public function is_owner(User_Adapter $user)
+ {
+ $this->load_publishers();
- return $this;
- }
+ return $this->owner->get_user()->get_id() === $user->get_id();
+ }
- /**
- *
- * @return array
- */
- protected function load_publishers()
- {
- if (is_array($this->publishers))
+ /**
+ *
+ * @param User_Adapter $user
+ * @return boolean
+ */
+ public function is_publisher(User_Adapter $user)
+ {
+ return in_array($user->get_id(), array_keys($this->get_publishers()));
+ }
- return $this->publishers;
+ /**
+ * Tells if a user has access to the feed
+ *
+ * @param User_Adapter $user
+ * @return type
+ */
+ public function has_access(User_Adapter $user)
+ {
+ if ($this->get_collection() instanceof collection)
+ return $user->ACL()->has_access_to_base($this->collection->get_base_id());
+ return true;
+ }
- $sql = 'SELECT id, usr_id, owner FROM feed_publishers
+ /**
+ *
+ * @return boolean
+ */
+ public function is_public()
+ {
+ if ($this->get_collection() instanceof collection) {
+ return false;
+ }
+
+ return $this->public;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ public function get_publishers()
+ {
+ return $this->load_publishers();
+ }
+
+ /**
+ *
+ * @return collection
+ */
+ public function get_collection()
+ {
+ return $this->collection;
+ }
+
+ /**
+ *
+ * @param User_Adapter $user
+ * @return Feed_Adapter
+ */
+ public function add_publisher(User_Adapter $user)
+ {
+ if (in_array($user->get_id(), array_keys($this->get_publishers())))
+ return $this;
+
+ Feed_Publisher_Adapter::create($this->appbox, $user, $this, false);
+ $this->publishers = null;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ protected function load_publishers()
+ {
+ if (is_array($this->publishers))
+ return $this->publishers;
+
+ $sql = 'SELECT id, usr_id, owner FROM feed_publishers
WHERE feed_id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_id' => $this->id));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_id' => $this->id));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $publisher = new Feed_Publisher_Adapter($this->appbox, $row['id']);
- $this->publishers[$row['usr_id']] = $publisher;
- if ($publisher->is_owner())
- $this->owner = $publisher;
+ foreach ($rs as $row) {
+ $publisher = new Feed_Publisher_Adapter($this->appbox, $row['id']);
+ $this->publishers[$row['usr_id']] = $publisher;
+ if ($publisher->is_owner())
+ $this->owner = $publisher;
+ }
+
+ return $this->publishers;
}
- return $this->publishers;
- }
-
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
-
- /**
- *
- * @param collection $collection
- * @return Feed_Adapter
- */
- public function set_collection(collection $collection = null)
- {
- $base_id = null;
- if ($collection instanceof collection)
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
{
- $base_id = $collection->get_base_id();
+ return $this->id;
}
- $sql = 'UPDATE feeds SET base_id = :base_id, updated_on = NOW()
+ /**
+ *
+ * @param collection $collection
+ * @return Feed_Adapter
+ */
+ public function set_collection(collection $collection = null)
+ {
+ $base_id = null;
+ if ($collection instanceof collection) {
+ $base_id = $collection->get_base_id();
+ }
+
+ $sql = 'UPDATE feeds SET base_id = :base_id, updated_on = NOW()
WHERE id = :feed_id';
- $params = array(':base_id' => $base_id, ':feed_id' => $this->get_id());
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->collection = $collection;
- $this->delete_data_from_cache();
+ $params = array(':base_id' => $base_id, ':feed_id' => $this->get_id());
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->collection = $collection;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param boolean $boolean
- * @return Feed_Adapter
- */
- public function set_public($boolean)
- {
- $boolean = !!$boolean;
- $sql = 'UPDATE feeds SET public = :public, updated_on = NOW()
+ /**
+ *
+ * @param boolean $boolean
+ * @return Feed_Adapter
+ */
+ public function set_public($boolean)
+ {
+ $boolean = ! ! $boolean;
+ $sql = 'UPDATE feeds SET public = :public, updated_on = NOW()
WHERE id = :feed_id';
- $params = array(
- ':public' => $boolean ? '1' : '0',
- ':feed_id' => $this->get_id()
- );
+ $params = array(
+ ':public' => $boolean ? '1' : '0',
+ ':feed_id' => $this->get_id()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->public = $boolean;
- $this->delete_data_from_cache();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->public = $boolean;
+ $this->delete_data_from_cache();
- $feed_collection = new Feed_Collection($this->appbox, array());
- $feed_collection->delete_data_from_cache(Feed_Collection::CACHE_PUBLIC);
+ $feed_collection = new Feed_Collection($this->appbox, array());
+ $feed_collection->delete_data_from_cache(Feed_Collection::CACHE_PUBLIC);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $title
- * @return Feed_Adapter
- */
- public function set_title($title)
- {
- $title = trim(strip_tags($title));
+ /**
+ *
+ * @param string $title
+ * @return Feed_Adapter
+ */
+ public function set_title($title)
+ {
+ $title = trim(strip_tags($title));
- if ($title === '')
- throw new Exception_InvalidArgument();
+ if ($title === '')
+ throw new Exception_InvalidArgument();
- $sql = 'UPDATE feeds SET title = :title, updated_on = NOW()
+ $sql = 'UPDATE feeds SET title = :title, updated_on = NOW()
WHERE id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':title' => $title, ':feed_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->title = $title;
- $this->delete_data_from_cache();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':title' => $title, ':feed_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->title = $title;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $subtitle
- * @return Feed_Adapter
- */
- public function set_subtitle($subtitle)
- {
- $subtitle = strip_tags($subtitle);
+ /**
+ *
+ * @param string $subtitle
+ * @return Feed_Adapter
+ */
+ public function set_subtitle($subtitle)
+ {
+ $subtitle = strip_tags($subtitle);
- $sql = 'UPDATE feeds SET subtitle = :subtitle, updated_on = NOW()
+ $sql = 'UPDATE feeds SET subtitle = :subtitle, updated_on = NOW()
WHERE id = :feed_id';
- $params = array(':subtitle' => $subtitle, ':feed_id' => $this->get_id());
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->subtitle = $subtitle;
- $this->delete_data_from_cache();
+ $params = array(':subtitle' => $subtitle, ':feed_id' => $this->get_id());
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->subtitle = $subtitle;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param string $title
- * @param string $subtitle
- * @return Feed_Adapter
- */
- public static function create(appbox &$appbox, User_Adapter $user, $title, $subtitle)
- {
- $sql = 'INSERT INTO feeds (id, title, subtitle, created_on, updated_on)
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param string $title
+ * @param string $subtitle
+ * @return Feed_Adapter
+ */
+ public static function create(appbox &$appbox, User_Adapter $user, $title, $subtitle)
+ {
+ $sql = 'INSERT INTO feeds (id, title, subtitle, created_on, updated_on)
VALUES (null, :title, :subtitle, NOW(), NOW())';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':title' => $title, ':subtitle' => $subtitle));
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':title' => $title, ':subtitle' => $subtitle));
+ $stmt->closeCursor();
- $feed_id = $appbox->get_connection()->lastInsertId();
+ $feed_id = $appbox->get_connection()->lastInsertId();
- $feed = new self($appbox, $feed_id);
+ $feed = new self($appbox, $feed_id);
- Feed_Publisher_Adapter::create($appbox, $user, $feed, true);
+ Feed_Publisher_Adapter::create($appbox, $user, $feed, true);
- return $feed;
- }
+ return $feed;
+ }
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param int $id
- * @return Feed_Adapter
- */
- public static function load_with_user(appbox &$appbox, User_Adapter &$user, $id)
- {
- $feed = new self($appbox, $id);
- $coll = $feed->get_collection();
- if (
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param int $id
+ * @return Feed_Adapter
+ */
+ public static function load_with_user(appbox &$appbox, User_Adapter &$user, $id)
+ {
+ $feed = new self($appbox, $id);
+ $coll = $feed->get_collection();
+ if (
$feed->is_public()
|| $coll === null
|| in_array($coll->get_base_id(), array_keys($user->ACL()->get_granted_base()))
- )
- {
- return $feed;
+ ) {
+ return $feed;
+ }
+
+ throw new Exception_FeedNotFound();
}
- throw new Exception_FeedNotFound();
- }
-
- /**
- *
- * @return int
- */
- public function get_count_total_entries()
- {
- try
- {
- return $this->get_data_from_cache(self::CACHE_ENTRY_NUMBER);
- }
- catch (Exception $e)
+ /**
+ *
+ * @return int
+ */
+ public function get_count_total_entries()
{
+ try {
+ return $this->get_data_from_cache(self::CACHE_ENTRY_NUMBER);
+ } catch (Exception $e) {
- }
+ }
- $sql = 'SELECT count(id) as number
+ $sql = 'SELECT count(id) as number
FROM feed_entries WHERE feed_id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_id' => $this->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $number = $row ? (int) $row['number'] : 0;
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_id' => $this->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $number = $row ? (int) $row['number'] : 0;
+ $stmt->closeCursor();
- $this->set_data_to_cache($number, self::CACHE_ENTRY_NUMBER);
+ $this->set_data_to_cache($number, self::CACHE_ENTRY_NUMBER);
- return $number;
- }
-
- /**
- *
- * @return void
- */
- public function delete()
- {
- $this->reset_icon();
- while ($this->get_count_total_entries() > 0)
- {
- $entries_coll = $this->get_entries(0, 10);
- foreach ($entries_coll->get_entries() as $entry)
- {
- $entry->delete();
- }
- unset($entries_coll);
- $this->delete_data_from_cache(self::CACHE_ENTRY_NUMBER);
+ return $number;
}
- foreach ($this->get_publishers() as $publishers)
- $publishers->delete();
+ /**
+ *
+ * @return void
+ */
+ public function delete()
+ {
+ $this->reset_icon();
+ while ($this->get_count_total_entries() > 0) {
+ $entries_coll = $this->get_entries(0, 10);
+ foreach ($entries_coll->get_entries() as $entry) {
+ $entry->delete();
+ }
+ unset($entries_coll);
+ $this->delete_data_from_cache(self::CACHE_ENTRY_NUMBER);
+ }
- $sql = 'DELETE FROM feed_tokens WHERE feed_id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_id' => $this->get_id()));
- $stmt->closeCursor();
+ foreach ($this->get_publishers() as $publishers)
+ $publishers->delete();
- $sql = 'DELETE FROM feeds WHERE id = :feed_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM feed_tokens WHERE feed_id = :feed_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ $sql = 'DELETE FROM feeds WHERE id = :feed_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_id' => $this->get_id()));
+ $stmt->closeCursor();
- $this->delete_data_from_cache();
+ $this->delete_data_from_cache();
- $feed_coll = new Feed_Collection($this->appbox, array());
- $feed_coll->delete_data_from_cache(Feed_Collection::CACHE_PUBLIC);
+ $feed_coll = new Feed_Collection($this->appbox, array());
+ $feed_coll->delete_data_from_cache(Feed_Collection::CACHE_PUBLIC);
- return;
- }
+ return;
+ }
- /**
- *
- * @param int $offset_start
- * @param int $how_many
- * @return Feed_Entry_Collection
- */
- public function get_entries($offset_start, $how_many)
- {
- $offset_start = (int) $offset_start;
- $how_many = $how_many > self::MAX_ENTRIES ? self::MAX_ENTRIES : (int) $how_many;
+ /**
+ *
+ * @param int $offset_start
+ * @param int $how_many
+ * @return Feed_Entry_Collection
+ */
+ public function get_entries($offset_start, $how_many)
+ {
+ $offset_start = (int) $offset_start;
+ $how_many = $how_many > self::MAX_ENTRIES ? self::MAX_ENTRIES : (int) $how_many;
- $sql = 'SELECT id
+ $sql = 'SELECT id
FROM feed_entries
WHERE feed_id = :feed_id
ORDER BY id DESC
LIMIT ' . $offset_start . ', ' . $how_many;
- $params = array(
- ':feed_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $params = array(
+ ':feed_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $result = new Feed_Entry_Collection();
+ $result = new Feed_Entry_Collection();
- foreach ($rs as $row)
- {
- $entry = new Feed_Entry_Adapter($this->appbox, $this, $row['id']);
- $result->add_entry($entry);
+ foreach ($rs as $row) {
+ $entry = new Feed_Entry_Adapter($this->appbox, $this, $row['id']);
+ $result->add_entry($entry);
+ }
+
+ return $result;
}
- return $result;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param string $format
- * @param int $page
- * @return Feed_Link
- */
- public function get_homepage_link(registryInterface $registry, $format, $page = null)
- {
- if (!$this->is_public())
-
- return null;
- switch ($format)
+ /**
+ *
+ * @param registryInterface $registry
+ * @param string $format
+ * @param int $page
+ * @return Feed_Link
+ */
+ public function get_homepage_link(registryInterface $registry, $format, $page = null)
{
- case self::FORMAT_ATOM:
- return new Feed_Link(
+ if ( ! $this->is_public())
+ return null;
+ switch ($format) {
+ case self::FORMAT_ATOM:
+ return new Feed_Link(
sprintf('%sfeeds/feed/%s/atom/%s'
- , $registry->get('GV_ServerName')
- , $this->get_id()
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_id()
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'Atom')
, 'application/atom+xml'
- );
- break;
- case self::FORMAT_RSS:
- default:
- return new Feed_Link(
+ );
+ break;
+ case self::FORMAT_RSS:
+ default:
+ return new Feed_Link(
sprintf('%sfeeds/feed/%s/rss/%s'
- , $registry->get('GV_ServerName')
- , $this->get_id()
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_id()
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
- );
- break;
+ );
+ break;
+ }
}
- }
- /**
- *
- * @param User_Adapter $user
- * @param boolean $renew
- * @return string
- */
- protected function get_token(User_Adapter $user, $renew = false)
- {
- $cache_key = self::CACHE_USER_TOKEN . '_' . $user->get_id();
- try
+ /**
+ *
+ * @param User_Adapter $user
+ * @param boolean $renew
+ * @return string
+ */
+ protected function get_token(User_Adapter $user, $renew = false)
{
- if (!$renew)
+ $cache_key = self::CACHE_USER_TOKEN . '_' . $user->get_id();
+ try {
+ if ( ! $renew)
+ return $this->get_data_from_cache($cache_key);
+ } catch (Exception $e) {
- return $this->get_data_from_cache($cache_key);
- }
- catch (Exception $e)
- {
+ }
- }
-
- $sql = 'SELECT token FROM feed_tokens
+ $sql = 'SELECT token FROM feed_tokens
WHERE usr_id = :usr_id AND feed_id = :feed_id
AND aggregated IS NULL';
- $params = array(
- ':usr_id' => $user->get_id(),
- ':feed_id' => $this->get_id()
- );
+ $params = array(
+ ':usr_id' => $user->get_id(),
+ ':feed_id' => $this->get_id()
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row || $renew === true)
- {
- $token = random::generatePassword(12, random::LETTERS_AND_NUMBERS);
- $sql = 'REPLACE INTO feed_tokens (id, token, feed_id, usr_id, aggregated)
+ if ( ! $row || $renew === true) {
+ $token = random::generatePassword(12, random::LETTERS_AND_NUMBERS);
+ $sql = 'REPLACE INTO feed_tokens (id, token, feed_id, usr_id, aggregated)
VALUES (null, :token, :feed_id, :usr_id, :aggregated)';
- $params = array(
- ':token' => $token
- , ':feed_id' => $this->get_id()
- , ':usr_id' => $user->get_id()
- , ':aggregated' => null
- );
+ $params = array(
+ ':token' => $token
+ , ':feed_id' => $this->get_id()
+ , ':usr_id' => $user->get_id()
+ , ':aggregated' => null
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $this->delete_data_from_cache($cache_key);
- }
- else
- {
- $token = $row['token'];
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $this->delete_data_from_cache($cache_key);
+ } else {
+ $token = $row['token'];
+ }
+
+ $this->set_data_to_cache($token, $cache_key);
+
+ return $token;
}
- $this->set_data_to_cache($token, $cache_key);
-
- return $token;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param User_Adapter $user
- * @param string $format
- * @param int $page
- * @param boolean $renew_token
- * @return Feed_Link
- */
- public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false)
- {
- switch ($format)
+ /**
+ *
+ * @param registryInterface $registry
+ * @param User_Adapter $user
+ * @param string $format
+ * @param int $page
+ * @param boolean $renew_token
+ * @return Feed_Link
+ */
+ public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false)
{
- case self::FORMAT_ATOM:
- return new Feed_Link(
+ switch ($format) {
+ case self::FORMAT_ATOM:
+ return new Feed_Link(
sprintf('%sfeeds/userfeed/%s/%s/atom/'
- , $registry->get('GV_ServerName')
- , $this->get_token($user, $renew_token)
- , $this->get_id()
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_token($user, $renew_token)
+ , $this->get_id()
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'Atom')
, 'application/atom+xml'
- );
- break;
- case self::FORMAT_RSS:
- return new Feed_Link(
+ );
+ break;
+ case self::FORMAT_RSS:
+ return new Feed_Link(
sprintf('%sfeeds/userfeed/%s/%s/rss/%s'
- , $registry->get('GV_ServerName')
- , $this->get_token($user, $renew_token)
- , $this->get_id()
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_token($user, $renew_token)
+ , $this->get_id()
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
- );
- break;
+ );
+ break;
+ }
}
- }
- public function get_cache_key($option = null)
- {
- return 'feed_adapter_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
- }
+ public function get_cache_key($option = null)
+ {
+ return 'feed_adapter_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
-
- public function delete_data_from_cache($option = null)
- {
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/Feed/Aggregate.class.php b/lib/classes/Feed/Aggregate.class.php
index 6d1c083e5c..1c169fb31c 100644
--- a/lib/classes/Feed/Aggregate.class.php
+++ b/lib/classes/Feed/Aggregate.class.php
@@ -17,259 +17,248 @@
*/
class Feed_Aggregate extends Feed_Abstract implements Feed_Interface
{
+ /**
+ *
+ * @var array
+ */
+ protected $feeds;
- /**
- *
- * @var array
- */
- protected $feeds;
-
- /**
- *
- * @param appbox $appbox
- * @param array $feeds
- * @return Feed_Aggregate
- */
- public function __construct(appbox &$appbox, Array $feeds)
- {
- $this->title = 'AGGREGGATE';
- $this->subtitle = 'AGREGGATE SUBTITLE';
- $this->created_on = new DateTime();
- $this->updated_on = new DateTime();
- $this->appbox = $appbox;
-
- $tmp_feeds = array();
-
- foreach ($feeds as $feed)
+ /**
+ *
+ * @param appbox $appbox
+ * @param array $feeds
+ * @return Feed_Aggregate
+ */
+ public function __construct(appbox &$appbox, Array $feeds)
{
- $tmp_feeds[$feed->get_id()] = $feed;
+ $this->title = 'AGGREGGATE';
+ $this->subtitle = 'AGREGGATE SUBTITLE';
+ $this->created_on = new DateTime();
+ $this->updated_on = new DateTime();
+ $this->appbox = $appbox;
+
+ $tmp_feeds = array();
+
+ foreach ($feeds as $feed) {
+ $tmp_feeds[$feed->get_id()] = $feed;
+ }
+
+ $this->feeds = $tmp_feeds;
+
+ return $this;
}
- $this->feeds = $tmp_feeds;
+ public function get_id()
+ {
+ throw new LogicException('Aggregate feed does not have an id');
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_icon_url()
+ {
+ $url = '/skins/icons/rss32.gif';
- public function get_id()
- {
- throw new LogicException('Aggregate feed does not have an id');
- }
+ return $url;
+ }
- /**
- *
- * @return string
- */
- public function get_icon_url()
- {
- $url = '/skins/icons/rss32.gif';
+ /**
+ *
+ * @return boolean
+ */
+ public function is_aggregated()
+ {
+ return true;
+ }
- return $url;
- }
+ /**
+ *
+ * @param int $offset_start
+ * @param int $how_many
+ * @return Feed_Entry_Collection
+ */
+ public function get_entries($offset_start, $how_many)
+ {
+ $result = new Feed_Entry_Collection();
- /**
- *
- * @return boolean
- */
- public function is_aggregated()
- {
- return true;
- }
+ if (count($this->feeds) === 0)
+ return $result;
- /**
- *
- * @param int $offset_start
- * @param int $how_many
- * @return Feed_Entry_Collection
- */
- public function get_entries($offset_start, $how_many)
- {
- $result = new Feed_Entry_Collection();
+ $offset_start = (int) $offset_start;
+ $how_many = $how_many > 20 ? 20 : (int) $how_many;
- if (count($this->feeds) === 0)
-
- return $result;
-
- $offset_start = (int) $offset_start;
- $how_many = $how_many > 20 ? 20 : (int) $how_many;
-
- $sql = 'SELECT id, feed_id
+ $sql = 'SELECT id, feed_id
FROM feed_entries
WHERE feed_id IN (' . implode(', ', array_keys($this->feeds)) . ')
ORDER BY id DESC
LIMIT ' . $offset_start . ', ' . $how_many;
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $entry = new Feed_Entry_Adapter(
- $this->appbox
- , $this->feeds[$row['feed_id']], $row['id']
- );
- $result->add_entry($entry);
+ foreach ($rs as $row) {
+ $entry = new Feed_Entry_Adapter(
+ $this->appbox
+ , $this->feeds[$row['feed_id']], $row['id']
+ );
+ $result->add_entry($entry);
+ }
+
+ return $result;
}
- return $result;
- }
-
- /**
- *
- * @return int
- */
- public function get_count_total_entries()
- {
- if (count($this->feeds) === 0)
-
- return 0;
- $sql = 'SELECT count(id) as number
+ /**
+ *
+ * @return int
+ */
+ public function get_count_total_entries()
+ {
+ if (count($this->feeds) === 0)
+ return 0;
+ $sql = 'SELECT count(id) as number
FROM feed_entries
WHERE feed_id
IN (' . implode(', ', array_keys($this->feeds)) . ') ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $number = $row ? (int) $row['number'] : 0;
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $number = $row ? (int) $row['number'] : 0;
+ $stmt->closeCursor();
- return $number;
- }
+ return $number;
+ }
- /**
- *
- * @param registryInterface $registry
- * @param string $format
- * @param int $page
- * @return Feed_Link
- */
- public function get_homepage_link(registryInterface $registry, $format, $page = null)
- {
- switch ($format)
+ /**
+ *
+ * @param registryInterface $registry
+ * @param string $format
+ * @param int $page
+ * @return Feed_Link
+ */
+ public function get_homepage_link(registryInterface $registry, $format, $page = null)
{
- case self::FORMAT_ATOM:
- return new Feed_Link(
+ switch ($format) {
+ case self::FORMAT_ATOM:
+ return new Feed_Link(
sprintf('%sfeeds/aggregated/atom/%s'
- , $registry->get('GV_ServerName')
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'Atom')
, 'application/atom+xml'
- );
- break;
- case self::FORMAT_COOLIRIS:
- return new Feed_Link(
+ );
+ break;
+ case self::FORMAT_COOLIRIS:
+ return new Feed_Link(
sprintf('%sfeeds/cooliris/%s'
- , $registry->get('GV_ServerName')
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
- );
- break;
- default:
- case self::FORMAT_RSS:
- return new Feed_Link(
+ );
+ break;
+ default:
+ case self::FORMAT_RSS:
+ return new Feed_Link(
sprintf('%sfeeds/aggregated/rss/%s'
- , $registry->get('GV_ServerName')
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
- );
- break;
+ );
+ break;
+ }
}
- }
- /**
- *
- * @param User_Adapter $user
- * @param boolean $renew
- * @return string
- */
- protected function get_token(User_Adapter $user, $renew = false)
- {
- $sql = 'SELECT token FROM feed_tokens
- WHERE usr_id = :usr_id AND aggregated = "1"';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if (!$row || $renew === true)
+ /**
+ *
+ * @param User_Adapter $user
+ * @param boolean $renew
+ * @return string
+ */
+ protected function get_token(User_Adapter $user, $renew = false)
{
- $token = random::generatePassword(12, random::LETTERS_AND_NUMBERS);
- $sql = 'REPLACE INTO feed_tokens (id, token, feed_id, usr_id, aggregated)
+ $sql = 'SELECT token FROM feed_tokens
+ WHERE usr_id = :usr_id AND aggregated = "1"';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ( ! $row || $renew === true) {
+ $token = random::generatePassword(12, random::LETTERS_AND_NUMBERS);
+ $sql = 'REPLACE INTO feed_tokens (id, token, feed_id, usr_id, aggregated)
VALUES (null, :token, :feed_id, :usr_id, :aggregated)';
- $params = array(
- ':token' => $token
- , ':feed_id' => null
- , ':usr_id' => $user->get_id()
- , ':aggregated' => '1'
- );
+ $params = array(
+ ':token' => $token
+ , ':feed_id' => null
+ , ':usr_id' => $user->get_id()
+ , ':aggregated' => '1'
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- }
- else
- {
- $token = $row['token'];
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ } else {
+ $token = $row['token'];
+ }
+
+ return $token;
}
- return $token;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @return Feed_Aggregate
- */
- public static function load_with_user(appbox &$appbox, User_Adapter &$user)
- {
- $feeds = Feed_Collection::load_all($appbox, $user);
-
- return new self($appbox, $feeds->get_feeds());
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param User_Adapter $user
- * @param string $format
- * @param int $page
- * @param boolean $renew_token
- * @return Feed_Link
- */
- public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false)
- {
- switch ($format)
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @return Feed_Aggregate
+ */
+ public static function load_with_user(appbox &$appbox, User_Adapter &$user)
{
- case self::FORMAT_ATOM:
- return new Feed_Link(
+ $feeds = Feed_Collection::load_all($appbox, $user);
+
+ return new self($appbox, $feeds->get_feeds());
+ }
+
+ /**
+ *
+ * @param registryInterface $registry
+ * @param User_Adapter $user
+ * @param string $format
+ * @param int $page
+ * @param boolean $renew_token
+ * @return Feed_Link
+ */
+ public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false)
+ {
+ switch ($format) {
+ case self::FORMAT_ATOM:
+ return new Feed_Link(
sprintf('%sfeeds/userfeed/aggregated/%s/atom/%s'
- , $registry->get('GV_ServerName')
- , $this->get_token($user, $renew_token)
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_token($user, $renew_token)
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'Atom')
, 'application/atom+xml'
- );
- break;
- case self::FORMAT_RSS:
- return new Feed_Link(
+ );
+ break;
+ case self::FORMAT_RSS:
+ return new Feed_Link(
sprintf('%sfeeds/userfeed/aggregated/%s/rss/%s'
- , $registry->get('GV_ServerName')
- , $this->get_token($user, $renew_token)
- , ($page ? '?page=' . $page : '')
+ , $registry->get('GV_ServerName')
+ , $this->get_token($user, $renew_token)
+ , ($page ? '?page=' . $page : '')
)
, sprintf('%s - %s', $this->get_title(), 'RSS')
, 'application/rss+xml'
- );
- break;
+ );
+ break;
+ }
}
- }
-
}
diff --git a/lib/classes/Feed/Collection.class.php b/lib/classes/Feed/Collection.class.php
index 1c7f628c7d..0dfa97e49d 100644
--- a/lib/classes/Feed/Collection.class.php
+++ b/lib/classes/Feed/Collection.class.php
@@ -17,155 +17,147 @@
*/
class Feed_Collection implements Feed_CollectionInterface, cache_cacheableInterface
{
+ /**
+ *
+ * @var Array
+ */
+ protected $feeds;
- /**
- *
- * @var Array
- */
- protected $feeds;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- const CACHE_PUBLIC = 'public';
+ const CACHE_PUBLIC = 'public';
- /**
- *
- * @param appbox $appbox
- * @param array $feeds
- * @return Feed_Collection
- */
- public function __construct(appbox $appbox, Array $feeds)
- {
- $this->feeds = $feeds;
- $this->appbox = $appbox;
+ /**
+ *
+ * @param appbox $appbox
+ * @param array $feeds
+ * @return Feed_Collection
+ */
+ public function __construct(appbox $appbox, Array $feeds)
+ {
+ $this->feeds = $feeds;
+ $this->appbox = $appbox;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @return Feed_Collection
- */
- public static function load_all(appbox $appbox, User_Adapter $user)
- {
- $base_ids = array_keys($user->ACL()->get_granted_base());
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @return Feed_Collection
+ */
+ public static function load_all(appbox $appbox, User_Adapter $user)
+ {
+ $base_ids = array_keys($user->ACL()->get_granted_base());
- $sql = 'SELECT id FROM feeds
+ $sql = 'SELECT id FROM feeds
WHERE base_id IS NULL ';
- if (count($base_ids) > 0)
- {
- $sql .= ' OR base_id
+ if (count($base_ids) > 0) {
+ $sql .= ' OR base_id
IN (' . implode(', ', $base_ids) . ') ';
- }
+ }
- $sql .= ' OR public = "1"
+ $sql .= ' OR public = "1"
ORDER BY created_on DESC';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $feeds = array();
+ $feeds = array();
- foreach ($rs as $row)
- {
- $feeds[] = new Feed_Adapter($appbox, $row['id']);
+ foreach ($rs as $row) {
+ $feeds[] = new Feed_Adapter($appbox, $row['id']);
+ }
+
+ return new self($appbox, $feeds);
}
- return new self($appbox, $feeds);
- }
-
- /**
- *
- * @return Array
- */
- public function get_feeds()
- {
- return $this->feeds;
- }
-
- /**
- *
- * @return Feed_Aggregate
- */
- public function get_aggregate()
- {
- return new Feed_Aggregate($this->appbox, $this->feeds);
- }
-
- /**
- *
- * @param appbox $appbox
- * @return Feed_Collection
- */
- public static function load_public_feeds(appbox $appbox)
- {
- $rs = self::retrieve_public_feed_ids($appbox);
- $feeds = array();
- foreach ($rs as $feed_id)
+ /**
+ *
+ * @return Array
+ */
+ public function get_feeds()
{
- $feeds[] = new Feed_Adapter($appbox, $feed_id);
+ return $this->feeds;
}
- return new self($appbox, $feeds);
- }
-
- protected static function retrieve_public_feed_ids(appbox &$appbox)
- {
- $key = self::get_cache_key(self::CACHE_PUBLIC);
-
- try
+ /**
+ *
+ * @return Feed_Aggregate
+ */
+ public function get_aggregate()
{
- return $appbox->get_data_from_cache($key);
- }
- catch (Exception $e)
- {
-
+ return new Feed_Aggregate($this->appbox, $this->feeds);
}
- $sql = 'SELECT id FROM feeds WHERE public = "1" ORDER BY created_on DESC';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $feeds = array();
-
- foreach ($rs as $row)
+ /**
+ *
+ * @param appbox $appbox
+ * @return Feed_Collection
+ */
+ public static function load_public_feeds(appbox $appbox)
{
- $feeds[] = $row['id'];
+ $rs = self::retrieve_public_feed_ids($appbox);
+ $feeds = array();
+ foreach ($rs as $feed_id) {
+ $feeds[] = new Feed_Adapter($appbox, $feed_id);
+ }
+
+ return new self($appbox, $feeds);
}
- $appbox->set_data_to_cache($feeds, $key);
+ protected static function retrieve_public_feed_ids(appbox &$appbox)
+ {
+ $key = self::get_cache_key(self::CACHE_PUBLIC);
- return $feeds;
- }
+ try {
+ return $appbox->get_data_from_cache($key);
+ } catch (Exception $e) {
- public function get_cache_key($option = null)
- {
- return 'feedcollection_' . ($option ? '_' . $option : '');
- }
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
+ $sql = 'SELECT id FROM feeds WHERE public = "1" ORDER BY created_on DESC';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ $feeds = array();
- public function delete_data_from_cache($option = null)
- {
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
+ foreach ($rs as $row) {
+ $feeds[] = $row['id'];
+ }
+ $appbox->set_data_to_cache($feeds, $key);
+
+ return $feeds;
+ }
+
+ public function get_cache_key($option = null)
+ {
+ return 'feedcollection_' . ($option ? '_' . $option : '');
+ }
+
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
+
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/Feed/CollectionInterface.class.php b/lib/classes/Feed/CollectionInterface.class.php
index 3467e95690..23f0a77d5c 100644
--- a/lib/classes/Feed/CollectionInterface.class.php
+++ b/lib/classes/Feed/CollectionInterface.class.php
@@ -17,7 +17,8 @@
*/
interface Feed_CollectionInterface
{
- public function get_feeds();
- public function get_aggregate();
+ public function get_feeds();
+
+ public function get_aggregate();
}
diff --git a/lib/classes/Feed/Entry/Adapter.class.php b/lib/classes/Feed/Entry/Adapter.class.php
index 95cdfe8e96..6949cd5830 100644
--- a/lib/classes/Feed/Entry/Adapter.class.php
+++ b/lib/classes/Feed/Entry/Adapter.class.php
@@ -17,568 +17,550 @@
*/
class Feed_Entry_Adapter implements Feed_Entry_Interface, cache_cacheableInterface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @var string
- */
- protected $title;
+ /**
+ *
+ * @var string
+ */
+ protected $subtitle;
- /**
- *
- * @var string
- */
- protected $subtitle;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
+ /**
+ *
+ * @var Feed_Publisher_Adapter
+ */
+ protected $publisher;
- /**
- *
- * @var Feed_Publisher_Adapter
- */
- protected $publisher;
+ /**
+ *
+ * @var int
+ */
+ protected $publisher_id;
- /**
- *
- * @var int
- */
- protected $publisher_id;
+ /**
+ *
+ * @var String
+ */
+ protected $author_name;
- /**
- *
- * @var String
- */
- protected $author_name;
+ /**
+ *
+ * @var String
+ */
+ protected $author_email;
- /**
- *
- * @var String
- */
- protected $author_email;
+ /**
+ *
+ * @var Feed_Adapter
+ */
+ protected $feed;
- /**
- *
- * @var Feed_Adapter
- */
- protected $feed;
+ /**
+ *
+ * @var array
+ */
+ protected $items;
- /**
- *
- * @var array
- */
- protected $items;
+ const CACHE_ELEMENTS = 'elements';
- const CACHE_ELEMENTS = 'elements';
-
- /**
- *
- * @param appbox $appbox
- * @param Feed_Adapter $feed
- * @param int $id
- * @return Feed_Entry_Adapter
- */
- public function __construct(appbox &$appbox, Feed_Adapter &$feed, $id)
- {
- $this->appbox = $appbox;
- $this->feed = $feed;
- $this->id = (int) $id;
- $this->load();
-
- return $this;
- }
-
- /**
- *
- * @return Feed_Entry_Adapter
- */
- protected function load()
- {
- try
- {
- $datas = $this->get_data_from_cache();
-
- $this->title = $datas['title'];
- $this->subtitle = $datas['subtitle'];
- $this->author_name = $datas['author_name'];
- $this->author_email = $datas['author_email'];
- $this->publisher_id = $datas['publisher_id'];
- $this->updated_on = $datas['updated_on'];
- $this->created_on = $datas['created_on'];
-
- return $this;
- }
- catch (Exception $e)
+ /**
+ *
+ * @param appbox $appbox
+ * @param Feed_Adapter $feed
+ * @param int $id
+ * @return Feed_Entry_Adapter
+ */
+ public function __construct(appbox &$appbox, Feed_Adapter &$feed, $id)
{
+ $this->appbox = $appbox;
+ $this->feed = $feed;
+ $this->id = (int) $id;
+ $this->load();
+ return $this;
}
- $sql = 'SELECT publisher, title, description, created_on, updated_on
+ /**
+ *
+ * @return Feed_Entry_Adapter
+ */
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+
+ $this->title = $datas['title'];
+ $this->subtitle = $datas['subtitle'];
+ $this->author_name = $datas['author_name'];
+ $this->author_email = $datas['author_email'];
+ $this->publisher_id = $datas['publisher_id'];
+ $this->updated_on = $datas['updated_on'];
+ $this->created_on = $datas['created_on'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT publisher, title, description, created_on, updated_on
, author_name, author_email
FROM feed_entries
WHERE id = :id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_Feed_EntryNotFound();
+ if ( ! $row)
+ throw new Exception_Feed_EntryNotFound();
- $this->title = $row['title'];
- $this->subtitle = $row['description'];
- $this->author_name = $row['author_name'];
- $this->author_email = $row['author_email'];
- $this->publisher_id = $row['publisher'];
- $this->updated_on = new DateTime($row['updated_on']);
- $this->created_on = new DateTime($row['created_on']);
+ $this->title = $row['title'];
+ $this->subtitle = $row['description'];
+ $this->author_name = $row['author_name'];
+ $this->author_email = $row['author_email'];
+ $this->publisher_id = $row['publisher'];
+ $this->updated_on = new DateTime($row['updated_on']);
+ $this->created_on = new DateTime($row['created_on']);
- $datas = array(
- 'title' => $this->title
- , 'subtitle' => $this->subtitle
- , 'author_name' => $this->author_name
- , 'author_email' => $this->author_email
- , 'publisher_id' => $this->publisher_id
- , 'updated_on' => $this->updated_on
- , 'created_on' => $this->created_on
- );
+ $datas = array(
+ 'title' => $this->title
+ , 'subtitle' => $this->subtitle
+ , 'author_name' => $this->author_name
+ , 'author_email' => $this->author_email
+ , 'publisher_id' => $this->publisher_id
+ , 'updated_on' => $this->updated_on
+ , 'created_on' => $this->created_on
+ );
- $this->set_data_to_cache($datas);
+ $this->set_data_to_cache($datas);
- return $this;
- }
+ return $this;
+ }
- public function get_link()
- {
- $registry = registry::get_instance();
+ public function get_link()
+ {
+ $registry = registry::get_instance();
- $href = sprintf(
- '%slightbox/feeds/entry/%d/'
- , $registry->get('GV_ServerName')
- , $this->get_id()
- );
+ $href = sprintf(
+ '%slightbox/feeds/entry/%d/'
+ , $registry->get('GV_ServerName')
+ , $this->get_id()
+ );
- return new Feed_Link($href, $this->get_title(), 'text/html');
- }
+ return new Feed_Link($href, $this->get_title(), 'text/html');
+ }
- /**
- *
- * @return Feed_Adapter
- */
- public function get_feed()
- {
- return $this->feed;
- }
+ /**
+ *
+ * @return Feed_Adapter
+ */
+ public function get_feed()
+ {
+ return $this->feed;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->title;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->title;
+ }
- /**
- *
- * @return string
- */
- public function get_subtitle()
- {
- return $this->subtitle;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_subtitle()
+ {
+ return $this->subtitle;
+ }
- /**
- *
- * @param string $title
- * @return Feed_Entry_Adapter
- */
- public function set_title($title)
- {
- $title = trim(strip_tags($title));
+ /**
+ *
+ * @param string $title
+ * @return Feed_Entry_Adapter
+ */
+ public function set_title($title)
+ {
+ $title = trim(strip_tags($title));
- if ($title === '')
- throw new Exception_InvalidArgument();
+ if ($title === '')
+ throw new Exception_InvalidArgument();
- $sql = 'UPDATE feed_entries
+ $sql = 'UPDATE feed_entries
SET title = :title, updated_on = NOW() WHERE id = :entry_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':title' => $title, ':entry_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->title = $title;
- $this->delete_data_from_cache();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':title' => $title, ':entry_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->title = $title;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $subtitle
- * @return Feed_Entry_Adapter
- */
- public function set_subtitle($subtitle)
- {
- $subtitle = strip_tags($subtitle);
+ /**
+ *
+ * @param string $subtitle
+ * @return Feed_Entry_Adapter
+ */
+ public function set_subtitle($subtitle)
+ {
+ $subtitle = strip_tags($subtitle);
- $sql = 'UPDATE feed_entries
+ $sql = 'UPDATE feed_entries
SET description = :subtitle, updated_on = NOW()
WHERE id = :entry_id';
- $params = array(':subtitle' => $subtitle, ':entry_id' => $this->get_id());
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->subtitle = $subtitle;
- $this->delete_data_from_cache();
+ $params = array(':subtitle' => $subtitle, ':entry_id' => $this->get_id());
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->subtitle = $subtitle;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $author_name
- * @return Feed_Entry_Adapter
- */
- public function set_author_name($author_name)
- {
- $sql = 'UPDATE feed_entries
+ /**
+ *
+ * @param string $author_name
+ * @return Feed_Entry_Adapter
+ */
+ public function set_author_name($author_name)
+ {
+ $sql = 'UPDATE feed_entries
SET author_name = :author_name, updated_on = NOW()
WHERE id = :entry_id';
- $params = array(
- ':author_name' => $author_name,
- ':entry_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->author_name = $author_name;
- $this->delete_data_from_cache();
+ $params = array(
+ ':author_name' => $author_name,
+ ':entry_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->author_name = $author_name;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $author_email
- * @return Feed_Entry_Adapter
- */
- public function set_author_email($author_email)
- {
- $sql = 'UPDATE feed_entries
+ /**
+ *
+ * @param string $author_email
+ * @return Feed_Entry_Adapter
+ */
+ public function set_author_email($author_email)
+ {
+ $sql = 'UPDATE feed_entries
SET author_email = :author_email, updated_on = NOW()
WHERE id = :entry_id';
- $params = array(
- ':author_email' => $author_email,
- ':entry_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->author_email = $author_email;
- $this->delete_data_from_cache();
+ $params = array(
+ ':author_email' => $author_email,
+ ':entry_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->author_email = $author_email;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- public function set_created_on(DateTime $datetime)
- {
- $sql = 'UPDATE feed_entries
+ public function set_created_on(DateTime $datetime)
+ {
+ $sql = 'UPDATE feed_entries
SET created_on = :created_on
WHERE id = :entry_id';
- $params = array(
- ':created_on' => $datetime->format(DATE_ISO8601),
- ':entry_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->created_on = $datetime;
- $this->delete_data_from_cache();
+ $params = array(
+ ':created_on' => $datetime->format(DATE_ISO8601),
+ ':entry_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->created_on = $datetime;
+ $this->delete_data_from_cache();
- return $this;
- }
+ return $this;
+ }
- public function set_updated_on(DateTime $datetime)
- {
- $sql = 'UPDATE feed_entries
+ public function set_updated_on(DateTime $datetime)
+ {
+ $sql = 'UPDATE feed_entries
SET updated_on = :updated_on
WHERE id = :entry_id';
- $params = array(
- ':updated_on' => $datetime->format(DATE_ISO8601),
- ':entry_id' => $this->get_id()
- );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->updated_on = $datetime;
- $this->delete_data_from_cache();
+ $params = array(
+ ':updated_on' => $datetime->format(DATE_ISO8601),
+ ':entry_id' => $this->get_id()
+ );
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->updated_on = $datetime;
+ $this->delete_data_from_cache();
- return $this;
- }
-
- /**
- *
- * @return Feed_Publisher_Adapter
- */
- public function get_publisher()
- {
- if (!$this->publisher instanceof Feed_Publisher_Adapter)
- $this->publisher = new Feed_Publisher_Adapter($this->appbox, $this->publisher_id);
-
- return $this->publisher;
- }
-
- /**
- *
- * @param User_adapter $user
- * @return boolean
- */
- public function is_publisher(User_adapter $user)
- {
- return $user->get_id() === $this->get_publisher()->get_user()->get_id();
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_updated_on()
- {
- return $this->updated_on;
- }
-
- /**
- *
- * @return string
- */
- public function get_author_name()
- {
- return $this->author_name;
- }
-
- /**
- *
- * @return string
- */
- public function get_author_email()
- {
- return $this->author_email;
- }
-
- /**
- *
- * @return array
- */
- public function get_content()
- {
- if ($this->items)
-
- return $this->items;
-
- $rs = $this->retrieve_elements();
- $items = array();
- foreach ($rs as $item_id)
- {
- try
- {
- $items[] = new Feed_Entry_Item($this->appbox, $this, $item_id);
- }
- catch (Exception_NotFound $e)
- {
-
- }
+ return $this;
}
- $this->items = $items;
-
- return $this->items;
- }
-
- protected function retrieve_elements()
- {
- try
- {
- return $this->get_data_from_cache(self::CACHE_ELEMENTS);
- }
- catch (Exception $e)
+ /**
+ *
+ * @return Feed_Publisher_Adapter
+ */
+ public function get_publisher()
{
+ if ( ! $this->publisher instanceof Feed_Publisher_Adapter)
+ $this->publisher = new Feed_Publisher_Adapter($this->appbox, $this->publisher_id);
+ return $this->publisher;
}
- $sql = 'SELECT id FROM feed_entry_elements
+ /**
+ *
+ * @param User_adapter $user
+ * @return boolean
+ */
+ public function is_publisher(User_adapter $user)
+ {
+ return $user->get_id() === $this->get_publisher()->get_user()->get_id();
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_updated_on()
+ {
+ return $this->updated_on;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_author_name()
+ {
+ return $this->author_name;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_author_email()
+ {
+ return $this->author_email;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ public function get_content()
+ {
+ if ($this->items)
+ return $this->items;
+
+ $rs = $this->retrieve_elements();
+ $items = array();
+ foreach ($rs as $item_id) {
+ try {
+ $items[] = new Feed_Entry_Item($this->appbox, $this, $item_id);
+ } catch (Exception_NotFound $e) {
+
+ }
+ }
+
+ $this->items = $items;
+
+ return $this->items;
+ }
+
+ protected function retrieve_elements()
+ {
+ try {
+ return $this->get_data_from_cache(self::CACHE_ELEMENTS);
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT id FROM feed_entry_elements
WHERE entry_id = :entry_id ORDER BY ord ASC';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':entry_id' => $this->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':entry_id' => $this->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $items = array();
+ $items = array();
- foreach ($rs as $row)
- {
- $items[] = (int) $row['id'];
+ foreach ($rs as $row) {
+ $items[] = (int) $row['id'];
+ }
+
+ $this->set_data_to_cache($items, self::CACHE_ELEMENTS);
+
+ return $items;
}
- $this->set_data_to_cache($items, self::CACHE_ELEMENTS);
-
- return $items;
- }
-
- /**
- *
- * @return void
- */
- public function delete()
- {
- foreach ($this->get_content() as $content)
+ /**
+ *
+ * @return void
+ */
+ public function delete()
{
- $content->delete();
+ foreach ($this->get_content() as $content) {
+ $content->delete();
+ }
+
+ $sql = 'DELETE FROM feed_entries WHERE id = :entry_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':entry_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ return;
}
- $sql = 'DELETE FROM feed_entries WHERE id = :entry_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':entry_id' => $this->get_id()));
- $stmt->closeCursor();
-
- return;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param Feed_Adapter $feed
- * @param Feed_Publisher_Adapter $publisher
- * @param string $title
- * @param string $subtitle
- * @param string $author_name
- * @param string $author_mail
- * @return Feed_Entry_Adapter
- */
- public static function create(appbox &$appbox, Feed_Adapter $feed
- , Feed_Publisher_Adapter $publisher, $title, $subtitle, $author_name, $author_mail)
- {
- if (!$feed->is_publisher($publisher->get_user()))
+ /**
+ *
+ * @param appbox $appbox
+ * @param Feed_Adapter $feed
+ * @param Feed_Publisher_Adapter $publisher
+ * @param string $title
+ * @param string $subtitle
+ * @param string $author_name
+ * @param string $author_mail
+ * @return Feed_Entry_Adapter
+ */
+ public static function create(appbox &$appbox, Feed_Adapter $feed
+ , Feed_Publisher_Adapter $publisher, $title, $subtitle, $author_name, $author_mail)
{
- throw new Exception_Feed_PublisherNotFound("Publisher not found");
- }
+ if ( ! $feed->is_publisher($publisher->get_user())) {
+ throw new Exception_Feed_PublisherNotFound("Publisher not found");
+ }
- if (!$feed->is_public() && $feed->get_collection() instanceof Collection)
- {
- if (!$publisher->get_user()->ACL()->has_access_to_base($feed->get_collection()->get_base_id()))
- {
- throw new Exception_Unauthorized("User has no rights to publish in current feed");
- }
- }
+ if ( ! $feed->is_public() && $feed->get_collection() instanceof Collection) {
+ if ( ! $publisher->get_user()->ACL()->has_access_to_base($feed->get_collection()->get_base_id())) {
+ throw new Exception_Unauthorized("User has no rights to publish in current feed");
+ }
+ }
- $sql = 'INSERT INTO feed_entries (id, feed_id, publisher, title
+ $sql = 'INSERT INTO feed_entries (id, feed_id, publisher, title
, description, created_on, updated_on, author_name, author_email)
VALUES (null, :feed_id, :publisher_id, :title
, :description, NOW(), NOW(), :author_name, :author_email)';
- $params = array(
- ':feed_id' => $feed->get_id()
- , ':publisher_id' => $publisher->get_id()
- , ':title' => trim($title)
- , ':description' => trim($subtitle)
- , ':author_name' => trim($author_name)
- , ':author_email' => trim($author_mail)
- );
+ $params = array(
+ ':feed_id' => $feed->get_id()
+ , ':publisher_id' => $publisher->get_id()
+ , ':title' => trim($title)
+ , ':description' => trim($subtitle)
+ , ':author_name' => trim($author_name)
+ , ':author_email' => trim($author_mail)
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $entry_id = $appbox->get_connection()->lastInsertId();
+ $entry_id = $appbox->get_connection()->lastInsertId();
- $feed->delete_data_from_cache();
+ $feed->delete_data_from_cache();
- $entry = new self($appbox, $feed, $entry_id);
+ $entry = new self($appbox, $feed, $entry_id);
- $eventsmanager = \eventsmanager_broker::getInstance($appbox, \bootstrap::getCore());
- $eventsmanager->trigger('__FEED_ENTRY_CREATE__', array('entry_id' => $entry_id), $entry);
+ $eventsmanager = \eventsmanager_broker::getInstance($appbox, \bootstrap::getCore());
+ $eventsmanager->trigger('__FEED_ENTRY_CREATE__', array('entry_id' => $entry_id), $entry);
- return $entry;
- }
+ return $entry;
+ }
- /**
- *
- * @param appbox $appbox
- * @param type $id
- * @return Feed_Entry_Adapter
- */
- public static function load_from_id(appbox $appbox, $id)
- {
- $sql = 'SELECT feed_id FROM feed_entries WHERE id = :entry_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':entry_id' => $id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ /**
+ *
+ * @param appbox $appbox
+ * @param type $id
+ * @return Feed_Entry_Adapter
+ */
+ public static function load_from_id(appbox $appbox, $id)
+ {
+ $sql = 'SELECT feed_id FROM feed_entries WHERE id = :entry_id';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':entry_id' => $id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_Feed_EntryNotFound();
+ if ( ! $row)
+ throw new Exception_Feed_EntryNotFound();
- $feed = new Feed_Adapter($appbox, $row['feed_id']);
+ $feed = new Feed_Adapter($appbox, $row['feed_id']);
- return new self($appbox, $feed, $id);
- }
+ return new self($appbox, $feed, $id);
+ }
- public function get_cache_key($option = null)
- {
- return 'feedentry_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
- }
+ public function get_cache_key($option = null)
+ {
+ return 'feedentry_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
-
- public function delete_data_from_cache($option = null)
- {
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/Feed/Entry/Collection.class.php b/lib/classes/Feed/Entry/Collection.class.php
index 048c1db153..975d2e11d0 100644
--- a/lib/classes/Feed/Entry/Collection.class.php
+++ b/lib/classes/Feed/Entry/Collection.class.php
@@ -17,56 +17,57 @@
*/
class Feed_Entry_Collection implements Feed_Entry_CollectionInterface
{
+ /**
+ *
+ * @var array
+ */
+ protected $entries = array();
- /**
- *
- * @var array
- */
- protected $entries = array();
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
- /**
- *
- * @var string
- */
- protected $title;
- /**
- *
- * @var string
- */
- protected $subtitle;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- /**
- *
- * @return Feed_Entry_Collection
- */
- public function __construct()
- {
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @param Feed_Entry_Adapter $entry
- * @return Feed_Entry_Collection
- */
- public function add_entry(Feed_Entry_Adapter $entry)
- {
- $this->entries[] = $entry;
+ /**
+ *
+ * @var string
+ */
+ protected $subtitle;
- return $this;
- }
+ /**
+ *
+ * @return Feed_Entry_Collection
+ */
+ public function __construct()
+ {
+ return $this;
+ }
- /**
- *
- * @return Array
- */
- public function get_entries()
- {
- return $this->entries;
- }
+ /**
+ *
+ * @param Feed_Entry_Adapter $entry
+ * @return Feed_Entry_Collection
+ */
+ public function add_entry(Feed_Entry_Adapter $entry)
+ {
+ $this->entries[] = $entry;
+ return $this;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_entries()
+ {
+ return $this->entries;
+ }
}
diff --git a/lib/classes/Feed/Entry/CollectionInterface.class.php b/lib/classes/Feed/Entry/CollectionInterface.class.php
index a2ca2f7d00..62c10464a3 100644
--- a/lib/classes/Feed/Entry/CollectionInterface.class.php
+++ b/lib/classes/Feed/Entry/CollectionInterface.class.php
@@ -17,9 +17,10 @@
*/
interface Feed_Entry_CollectionInterface
{
- public function __construct();
- public function add_entry(Feed_Entry_Adapter $entry);
+ public function __construct();
- public function get_entries();
+ public function add_entry(Feed_Entry_Adapter $entry);
+
+ public function get_entries();
}
diff --git a/lib/classes/Feed/Entry/Interface.class.php b/lib/classes/Feed/Entry/Interface.class.php
index a9a13bbf93..398eab9f4f 100644
--- a/lib/classes/Feed/Entry/Interface.class.php
+++ b/lib/classes/Feed/Entry/Interface.class.php
@@ -17,40 +17,41 @@
*/
interface Feed_Entry_Interface
{
- public function __construct(appbox &$appbox, Feed_Adapter &$feed, $id);
- public function get_feed();
+ public function __construct(appbox &$appbox, Feed_Adapter &$feed, $id);
- public function get_id();
+ public function get_feed();
- public function get_title();
+ public function get_id();
- public function get_subtitle();
+ public function get_title();
- public function set_title($title);
+ public function get_subtitle();
- public function set_subtitle($subtitle);
+ public function set_title($title);
- public function set_author_name($author_name);
+ public function set_subtitle($subtitle);
- public function set_author_email($author_email);
+ public function set_author_name($author_name);
- public function get_publisher();
+ public function set_author_email($author_email);
- public function get_created_on();
+ public function get_publisher();
- public function get_updated_on();
+ public function get_created_on();
- public function get_author_name();
+ public function get_updated_on();
- public function get_author_email();
+ public function get_author_name();
- public function get_content();
+ public function get_author_email();
- public function delete();
+ public function get_content();
- public static function create(appbox &$appbox, Feed_Adapter $feed
- , Feed_Publisher_Adapter $publisher, $title, $subtitle, $author_name, $author_mail);
+ public function delete();
- public static function load_from_id(appbox $appbox, $id);
+ public static function create(appbox &$appbox, Feed_Adapter $feed
+ , Feed_Publisher_Adapter $publisher, $title, $subtitle, $author_name, $author_mail);
+
+ public static function load_from_id(appbox $appbox, $id);
}
diff --git a/lib/classes/Feed/Entry/Item.class.php b/lib/classes/Feed/Entry/Item.class.php
index 5f20e09728..c56fb2225b 100644
--- a/lib/classes/Feed/Entry/Item.class.php
+++ b/lib/classes/Feed/Entry/Item.class.php
@@ -17,218 +17,213 @@
*/
class Feed_Entry_Item implements Feed_Entry_ItemInterface, cache_cacheableInterface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var record_adapter
+ */
+ protected $record;
- /**
- *
- * @var record_adapter
- */
- protected $record;
+ /**
+ *
+ * @var Feed_Entry_Adapter
+ */
+ protected $entry;
- /**
- *
- * @var Feed_Entry_Adapter
- */
- protected $entry;
+ /**
+ *
+ * @var int
+ */
+ protected $ord;
- /**
- *
- * @var int
- */
- protected $ord;
-
- /**
- *
- * @param appbox $appbox
- * @param Feed_Entry_Adapter $entry
- * @param int $id
- * @return Feed_Entry_Item
- */
- public function __construct(appbox &$appbox, Feed_Entry_Adapter &$entry, $id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $id;
- $this->entry = $entry;
- $this->load();
-
- return $this;
- }
-
- public function get_entry()
- {
- return $this->entry;
- }
-
- /**
- *
- * @return Feed_Entry_Item
- */
- protected function load()
- {
- try
- {
- $datas = $this->get_data_from_cache();
- $this->record = $this->appbox->get_databox($datas['sbas_id'])
- ->get_record($datas['record_id'], $datas['ord']);
- $this->ord = $datas['ord'];
-
- return $this;
- }
- catch (Exception $e)
+ /**
+ *
+ * @param appbox $appbox
+ * @param Feed_Entry_Adapter $entry
+ * @param int $id
+ * @return Feed_Entry_Item
+ */
+ public function __construct(appbox &$appbox, Feed_Entry_Adapter &$entry, $id)
{
+ $this->appbox = $appbox;
+ $this->id = (int) $id;
+ $this->entry = $entry;
+ $this->load();
+ return $this;
}
- $sql = 'SELECT id, sbas_id, record_id, ord
+ public function get_entry()
+ {
+ return $this->entry;
+ }
+
+ /**
+ *
+ * @return Feed_Entry_Item
+ */
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+ $this->record = $this->appbox->get_databox($datas['sbas_id'])
+ ->get_record($datas['record_id'], $datas['ord']);
+ $this->ord = $datas['ord'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT id, sbas_id, record_id, ord
FROM feed_entry_elements WHERE id = :id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_Feed_ItemNotFound();
+ if ( ! $row)
+ throw new Exception_Feed_ItemNotFound();
- $this->record = $this->appbox->get_databox($row['sbas_id'])
+ $this->record = $this->appbox->get_databox($row['sbas_id'])
->get_record($row['record_id']);
- $this->ord = (int) $row['ord'];
+ $this->ord = (int) $row['ord'];
- $datas = array(
- 'record_id' => $this->record->get_record_id()
- , 'sbas_id' => $this->record->get_sbas_id()
- , 'ord' => $this->ord
- );
+ $datas = array(
+ 'record_id' => $this->record->get_record_id()
+ , 'sbas_id' => $this->record->get_sbas_id()
+ , 'ord' => $this->ord
+ );
- $this->set_data_to_cache($datas);
+ $this->set_data_to_cache($datas);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return record_adapter
- */
- public function get_record()
- {
- return $this->record;
- }
+ /**
+ *
+ * @return record_adapter
+ */
+ public function get_record()
+ {
+ return $this->record;
+ }
- /**
- *
- * @return int
- */
- public function get_ord()
- {
- return $this->ord;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_ord()
+ {
+ return $this->ord;
+ }
- public function set_ord($order)
- {
- $order = (int) $order;
- $sql = 'UPDATE feed_entry_elements SET ord = :ord WHERE id = :item_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':ord' => $order, ':item_id' => $this->get_id()));
- $stmt->closeCursor();
+ public function set_ord($order)
+ {
+ $order = (int) $order;
+ $sql = 'UPDATE feed_entry_elements SET ord = :ord WHERE id = :item_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':ord' => $order, ':item_id' => $this->get_id()));
+ $stmt->closeCursor();
- $this->ord = $order;
+ $this->ord = $order;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return void
- */
- public function delete()
- {
- $sql = 'DELETE FROM feed_entry_elements WHERE id = :id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->get_id()));
- $stmt->closeCursor();
+ /**
+ *
+ * @return void
+ */
+ public function delete()
+ {
+ $sql = 'DELETE FROM feed_entry_elements WHERE id = :id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->get_id()));
+ $stmt->closeCursor();
- return;
- }
+ return;
+ }
- /**
- *
- * @param appbox $appbox
- * @param Feed_Entry_Adapter $entry
- * @param record_adapter $record
- * @return Feed_Entry_Item
- */
- public static function create(appbox &$appbox, Feed_Entry_Adapter &$entry, record_adapter &$record)
- {
- $sql = 'SELECT (MAX(ord)+1) as sorter FROM feed_entry_elements
+ /**
+ *
+ * @param appbox $appbox
+ * @param Feed_Entry_Adapter $entry
+ * @param record_adapter $record
+ * @return Feed_Entry_Item
+ */
+ public static function create(appbox &$appbox, Feed_Entry_Adapter &$entry, record_adapter &$record)
+ {
+ $sql = 'SELECT (MAX(ord)+1) as sorter FROM feed_entry_elements
WHERE entry_id = :entry_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':entry_id' => $entry->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':entry_id' => $entry->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $sorter = ($row && $row['sorter'] > 0) ? (int) $row['sorter'] : 1;
+ $sorter = ($row && $row['sorter'] > 0) ? (int) $row['sorter'] : 1;
- $sql = 'INSERT INTO feed_entry_elements
+ $sql = 'INSERT INTO feed_entry_elements
(id, entry_id, sbas_id, record_id, ord)
VALUES (null, :entry_id, :sbas_id, :record_id, :ord)';
- $params = array(
- ':entry_id' => $entry->get_id()
- , ':sbas_id' => $record->get_sbas_id()
- , ':record_id' => $record->get_record_id()
- , ':ord' => $sorter
- );
+ $params = array(
+ ':entry_id' => $entry->get_id()
+ , ':sbas_id' => $record->get_sbas_id()
+ , ':record_id' => $record->get_record_id()
+ , ':ord' => $sorter
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $item_id = $appbox->get_connection()->lastInsertId();
+ $item_id = $appbox->get_connection()->lastInsertId();
- $entry->delete_data_from_cache(Feed_Entry_Adapter::CACHE_ELEMENTS);
+ $entry->delete_data_from_cache(Feed_Entry_Adapter::CACHE_ELEMENTS);
- return new self($appbox, $entry, $item_id);
- }
+ return new self($appbox, $entry, $item_id);
+ }
- public function get_cache_key($option = null)
- {
- return 'feedentryitem_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
- }
+ public function get_cache_key($option = null)
+ {
+ return 'feedentryitem_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
-
- public function delete_data_from_cache($option = null)
- {
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/Feed/Entry/ItemInterface.class.php b/lib/classes/Feed/Entry/ItemInterface.class.php
index 8ab54a4e7c..ec5f71d8da 100644
--- a/lib/classes/Feed/Entry/ItemInterface.class.php
+++ b/lib/classes/Feed/Entry/ItemInterface.class.php
@@ -17,15 +17,16 @@
*/
interface Feed_Entry_ItemInterface
{
- public function __construct(appbox &$appbox, Feed_Entry_Adapter &$entry, $id);
- public function get_id();
+ public function __construct(appbox &$appbox, Feed_Entry_Adapter &$entry, $id);
- public function get_record();
+ public function get_id();
- public function get_ord();
+ public function get_record();
- public function delete();
+ public function get_ord();
- public static function create(appbox &$appbox, Feed_Entry_Adapter &$entry, record_adapter &$record);
+ public function delete();
+
+ public static function create(appbox &$appbox, Feed_Entry_Adapter &$entry, record_adapter &$record);
}
diff --git a/lib/classes/Feed/Interface.class.php b/lib/classes/Feed/Interface.class.php
index 954ffed951..64286666ad 100644
--- a/lib/classes/Feed/Interface.class.php
+++ b/lib/classes/Feed/Interface.class.php
@@ -17,24 +17,24 @@
*/
interface Feed_Interface
{
- public function get_title();
- public function get_subtitle();
+ public function get_title();
- public function get_created_on();
+ public function get_subtitle();
- public function get_updated_on();
+ public function get_created_on();
- public function get_entries($offset_start, $how_many);
+ public function get_updated_on();
- public function get_count_total_entries();
+ public function get_entries($offset_start, $how_many);
- public function get_homepage_link(registryInterface $registry, $format, $page = null);
+ public function get_count_total_entries();
- public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false);
+ public function get_homepage_link(registryInterface $registry, $format, $page = null);
- public function get_icon_url();
+ public function get_user_link(registryInterface $registry, User_Adapter $user, $format, $page = null, $renew_token = false);
- public function is_aggregated();
+ public function get_icon_url();
+ public function is_aggregated();
}
diff --git a/lib/classes/Feed/Link.class.php b/lib/classes/Feed/Link.class.php
index 2f8acd13a2..eb60316512 100644
--- a/lib/classes/Feed/Link.class.php
+++ b/lib/classes/Feed/Link.class.php
@@ -17,64 +17,64 @@
*/
class Feed_Link implements Feed_LinkInterface
{
+ /**
+ *
+ * @var string
+ */
+ protected $mimetype;
- /**
- *
- * @var string
- */
- protected $mimetype;
- /**
- *
- * @var string
- */
- protected $title;
- /**
- *
- * @var string
- */
- protected $href;
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @param string $href
- * @param string $title
- * @param string $mimetype
- * @return Feed_Link
- */
- public function __construct($href, $title, $mimetype)
- {
- $this->mimetype = $mimetype;
- $this->href = $href;
- $this->title = $title;
+ /**
+ *
+ * @var string
+ */
+ protected $href;
- return $this;
- }
+ /**
+ *
+ * @param string $href
+ * @param string $title
+ * @param string $mimetype
+ * @return Feed_Link
+ */
+ public function __construct($href, $title, $mimetype)
+ {
+ $this->mimetype = $mimetype;
+ $this->href = $href;
+ $this->title = $title;
- /**
- *
- * @return string
- */
- public function get_mimetype()
- {
- return $this->mimetype;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->title;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_mimetype()
+ {
+ return $this->mimetype;
+ }
- /**
- *
- * @return string
- */
- public function get_href()
- {
- return $this->href;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->title;
+ }
+ /**
+ *
+ * @return string
+ */
+ public function get_href()
+ {
+ return $this->href;
+ }
}
diff --git a/lib/classes/Feed/LinkInterface.class.php b/lib/classes/Feed/LinkInterface.class.php
index f06dfc223d..3a662ec3fb 100644
--- a/lib/classes/Feed/LinkInterface.class.php
+++ b/lib/classes/Feed/LinkInterface.class.php
@@ -17,9 +17,10 @@
*/
interface Feed_LinkInterface
{
- public function get_mimetype();
- public function get_title();
+ public function get_mimetype();
- public function get_href();
+ public function get_title();
+
+ public function get_href();
}
diff --git a/lib/classes/Feed/Publisher/Adapter.class.php b/lib/classes/Feed/Publisher/Adapter.class.php
index ab4b199ade..711e025b6b 100644
--- a/lib/classes/Feed/Publisher/Adapter.class.php
+++ b/lib/classes/Feed/Publisher/Adapter.class.php
@@ -17,223 +17,221 @@
*/
class Feed_Publisher_Adapter implements Feed_Publisher_Interface, cache_cacheableInterface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var int
- */
- protected $id;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
- /**
- *
- * @var boolean
- */
- protected $owner;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
- /**
- *
- * @var User_Adapter
- */
- protected $added_by;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @param appbox $appbox
- * @param int $id
- * @return Feed_Publisher_Adapter
- */
- public function __construct(appbox &$appbox, $id)
- {
- $this->appbox = $appbox;
- $this->id = (int) $id;
- $this->load();
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- return $this;
- }
+ /**
+ *
+ * @var boolean
+ */
+ protected $owner;
- /**
- *
- * @return Feed_Publisher_Adapter
- */
- protected function load()
- {
- try
- {
- $datas = $this->get_data_from_cache();
-
- $this->user = User_Adapter::getInstance($datas['usr_id'], $this->appbox);
- $this->added_by = User_Adapter::getInstance($datas['added_by_usr_id'], $this->appbox);
- $this->created_on = $datas['created_on'];
- $this->owner = $datas['owner'];
-
- return $this;
- }
- catch (Exception $e)
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
+
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $added_by;
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param int $id
+ * @return Feed_Publisher_Adapter
+ */
+ public function __construct(appbox &$appbox, $id)
{
+ $this->appbox = $appbox;
+ $this->id = (int) $id;
+ $this->load();
+ return $this;
}
- $sql = 'SELECT id, usr_id, owner, created_on, added_by
+ /**
+ *
+ * @return Feed_Publisher_Adapter
+ */
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+
+ $this->user = User_Adapter::getInstance($datas['usr_id'], $this->appbox);
+ $this->added_by = User_Adapter::getInstance($datas['added_by_usr_id'], $this->appbox);
+ $this->created_on = $datas['created_on'];
+ $this->owner = $datas['owner'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT id, usr_id, owner, created_on, added_by
FROM feed_publishers WHERE id = :feed_publisher_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_publisher_id' => $this->id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_publisher_id' => $this->id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_Feed_PublisherNotFound();
+ if ( ! $row)
+ throw new Exception_Feed_PublisherNotFound();
- $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
- $this->owner = !!$row['owner'];
- $this->created_on = new DateTime($row['created_on']);
- $this->added_by = User_Adapter::getInstance($row['added_by'], $this->appbox);
+ $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ $this->owner = ! ! $row['owner'];
+ $this->created_on = new DateTime($row['created_on']);
+ $this->added_by = User_Adapter::getInstance($row['added_by'], $this->appbox);
- $datas = array(
- 'usr_id' => $this->user->get_id()
- , 'owner' => $this->owner
- , 'created_on' => $this->created_on
- , 'added_by_usr_id' => $this->added_by->get_id()
- );
+ $datas = array(
+ 'usr_id' => $this->user->get_id()
+ , 'owner' => $this->owner
+ , 'created_on' => $this->created_on
+ , 'added_by_usr_id' => $this->added_by->get_id()
+ );
- $this->set_data_to_cache($datas);
+ $this->set_data_to_cache($datas);
- return $this;
- }
-
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_owner()
- {
- return $this->owner;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
-
- /**
- *
- * @return User_Adapter
- */
- public function get_added_by()
- {
- return $this->added_by;
- }
-
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
-
- /**
- *
- * @return void
- */
- public function delete()
- {
- $sql = 'DELETE FROM feed_publishers WHERE id = :feed_publisher_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':feed_publisher_id' => $this->get_id()));
- $stmt->closeCursor();
-
- return;
- }
-
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param Feed_Adapter $feed
- * @param boolean $owner
- * @return Feed_Publisher_Adapter
- */
- public static function create(appbox &$appbox, User_Adapter &$user, Feed_Adapter &$feed, $owner)
- {
- $sql = 'INSERT INTO feed_publishers (id, usr_id, feed_id, owner, created_on, added_by)
- VALUES (null, :usr_id, :feed_id, :owner, NOW(), :added_by)';
- $stmt = $appbox->get_connection()->prepare($sql);
- $params = array(
- ':usr_id' => $user->get_id()
- , ':feed_id' => $feed->get_id()
- , ':owner' => $owner ? '1' : null
- , ':added_by' => $owner ? $user->get_id() : $appbox->get_session()->get_usr_id()
- );
- $stmt->execute($params);
- $id = $appbox->get_connection()->lastInsertId();
- $stmt->closeCursor();
-
- return new self($appbox, $id);
- }
-
- /**
- *
- * @param appbox $appbox
- * @param Feed_Adapter $feed
- * @param User_Adapter $user
- * @return Feed_Publisher_Adapter
- */
- public static function getPublisher(appbox &$appbox, Feed_Adapter &$feed, User_Adapter &$user)
- {
- foreach ($feed->get_publishers() as $publisher)
- {
- if ($publisher->get_user()->get_id() === $user->get_id())
-
- return $publisher;
+ return $this;
}
- throw new Exception_Feed_PublisherNotFound('Publisher not found');
- }
- public function get_cache_key($option = null)
- {
- return 'feedpublisher_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->appbox->get_data_from_cache($this->get_cache_key($option));
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_owner()
+ {
+ return $this->owner;
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
- public function delete_data_from_cache($option = null)
- {
- return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_added_by()
+ {
+ return $this->added_by;
+ }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
+
+ /**
+ *
+ * @return void
+ */
+ public function delete()
+ {
+ $sql = 'DELETE FROM feed_publishers WHERE id = :feed_publisher_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':feed_publisher_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param Feed_Adapter $feed
+ * @param boolean $owner
+ * @return Feed_Publisher_Adapter
+ */
+ public static function create(appbox &$appbox, User_Adapter &$user, Feed_Adapter &$feed, $owner)
+ {
+ $sql = 'INSERT INTO feed_publishers (id, usr_id, feed_id, owner, created_on, added_by)
+ VALUES (null, :usr_id, :feed_id, :owner, NOW(), :added_by)';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $params = array(
+ ':usr_id' => $user->get_id()
+ , ':feed_id' => $feed->get_id()
+ , ':owner' => $owner ? '1' : null
+ , ':added_by' => $owner ? $user->get_id() : $appbox->get_session()->get_usr_id()
+ );
+ $stmt->execute($params);
+ $id = $appbox->get_connection()->lastInsertId();
+ $stmt->closeCursor();
+
+ return new self($appbox, $id);
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param Feed_Adapter $feed
+ * @param User_Adapter $user
+ * @return Feed_Publisher_Adapter
+ */
+ public static function getPublisher(appbox &$appbox, Feed_Adapter &$feed, User_Adapter &$user)
+ {
+ foreach ($feed->get_publishers() as $publisher) {
+ if ($publisher->get_user()->get_id() === $user->get_id())
+ return $publisher;
+ }
+ throw new Exception_Feed_PublisherNotFound('Publisher not found');
+ }
+
+ public function get_cache_key($option = null)
+ {
+ return 'feedpublisher_' . $this->get_id() . '_' . ($option ? '_' . $option : '');
+ }
+
+ public function get_data_from_cache($option = null)
+ {
+ return $this->appbox->get_data_from_cache($this->get_cache_key($option));
+ }
+
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/Feed/Publisher/Interface.class.php b/lib/classes/Feed/Publisher/Interface.class.php
index 8df827a245..f35cbaad5a 100644
--- a/lib/classes/Feed/Publisher/Interface.class.php
+++ b/lib/classes/Feed/Publisher/Interface.class.php
@@ -17,21 +17,22 @@
*/
interface Feed_Publisher_Interface
{
- public function __construct(appbox &$appbox, $id);
- public function get_user();
+ public function __construct(appbox &$appbox, $id);
- public function is_owner();
+ public function get_user();
- public function get_created_on();
+ public function is_owner();
- public function get_added_by();
+ public function get_created_on();
- public function get_id();
+ public function get_added_by();
- public function delete();
+ public function get_id();
- public static function create(appbox &$appbox, User_Adapter &$user, Feed_Adapter &$feed, $owner);
+ public function delete();
- public static function getPublisher(appbox &$appbox, Feed_Adapter &$feed, User_Adapter &$user);
+ public static function create(appbox &$appbox, User_Adapter &$user, Feed_Adapter &$feed, $owner);
+
+ public static function getPublisher(appbox &$appbox, Feed_Adapter &$feed, User_Adapter &$user);
}
diff --git a/lib/classes/Feed/Token.class.php b/lib/classes/Feed/Token.class.php
index 4601530e17..395cfc62d3 100644
--- a/lib/classes/Feed/Token.class.php
+++ b/lib/classes/Feed/Token.class.php
@@ -17,92 +17,90 @@
*/
class Feed_Token
{
+ /**
+ *
+ * @var int
+ */
+ protected $usr_id;
- /**
- *
- * @var int
- */
- protected $usr_id;
+ /**
+ *
+ * @var int
+ */
+ protected $feed_id;
- /**
- *
- * @var int
- */
- protected $feed_id;
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @var Feed_Adapter
+ */
+ protected $feed;
- /**
- *
- * @var Feed_Adapter
- */
- protected $feed;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
-
- /**
- *
- * @param appbox $appbox
- * @param string $token
- * @param int $feed_id
- * @return Feed_Token
- */
- public function __construct(appbox &$appbox, $token, $feed_id)
- {
- $sql = 'SELECT feed_id, usr_id FROM feed_tokens
+ /**
+ *
+ * @param appbox $appbox
+ * @param string $token
+ * @param int $feed_id
+ * @return Feed_Token
+ */
+ public function __construct(appbox &$appbox, $token, $feed_id)
+ {
+ $sql = 'SELECT feed_id, usr_id FROM feed_tokens
WHERE feed_id = :feed_id
AND aggregated IS NULL AND token = :token';
- $params = array(
- ':feed_id' => $feed_id
- , ':token' => $token
- );
+ $params = array(
+ ':feed_id' => $feed_id
+ , ':token' => $token
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_FeedNotFound($token);
+ if ( ! $row)
+ throw new Exception_FeedNotFound($token);
- $this->feed_id = (int) $row['feed_id'];
- $this->usr_id = (int) $row['usr_id'];
- $this->appbox = $appbox;
+ $this->feed_id = (int) $row['feed_id'];
+ $this->usr_id = (int) $row['usr_id'];
+ $this->appbox = $appbox;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- if (!$this->user)
- $this->user = User_Adapter::getInstance($this->usr_id, $this->appbox);
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ if ( ! $this->user)
+ $this->user = User_Adapter::getInstance($this->usr_id, $this->appbox);
- return $this->user;
- }
+ return $this->user;
+ }
- /**
- *
- * @return Feed_Adapter
- */
- public function get_feed()
- {
- if (!$this->feed)
- $this->feed = Feed_Adapter::load_with_user($this->appbox, $this->get_user(), $this->feed_id);
-
- return $this->feed;
- }
+ /**
+ *
+ * @return Feed_Adapter
+ */
+ public function get_feed()
+ {
+ if ( ! $this->feed)
+ $this->feed = Feed_Adapter::load_with_user($this->appbox, $this->get_user(), $this->feed_id);
+ return $this->feed;
+ }
}
diff --git a/lib/classes/Feed/TokenAggregate.class.php b/lib/classes/Feed/TokenAggregate.class.php
index 7894d188b7..d1e94e594b 100644
--- a/lib/classes/Feed/TokenAggregate.class.php
+++ b/lib/classes/Feed/TokenAggregate.class.php
@@ -18,46 +18,45 @@
class Feed_TokenAggregate extends Feed_Token
{
- /**
- *
- * @param appbox $appbox
- * @param string $token
- * @return Feed_TokenAggregate
- */
- public function __construct(appbox &$appbox, $token)
- {
+ /**
+ *
+ * @param appbox $appbox
+ * @param string $token
+ * @return Feed_TokenAggregate
+ */
+ public function __construct(appbox &$appbox, $token)
+ {
- $sql = 'SELECT usr_id FROM feed_tokens
+ $sql = 'SELECT usr_id FROM feed_tokens
WHERE aggregated = "1" AND token = :token';
- $params = array(
- ':token' => $token
- );
+ $params = array(
+ ':token' => $token
+ );
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_FeedNotFound($token);
+ if ( ! $row)
+ throw new Exception_FeedNotFound($token);
- $this->usr_id = $row['usr_id'];
- $this->appbox = $appbox;
+ $this->usr_id = $row['usr_id'];
+ $this->appbox = $appbox;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Feed_Aggregate
- */
- public function get_feed()
- {
- if (!$this->feed)
- $this->feed = Feed_Aggregate::load_with_user($this->appbox, $this->get_user());
-
- return $this->feed;
- }
+ /**
+ *
+ * @return Feed_Aggregate
+ */
+ public function get_feed()
+ {
+ if ( ! $this->feed)
+ $this->feed = Feed_Aggregate::load_with_user($this->appbox, $this->get_user());
+ return $this->feed;
+ }
}
diff --git a/lib/classes/Feed/XML/Abstract.class.php b/lib/classes/Feed/XML/Abstract.class.php
index d111c70ec2..0519bdbc6c 100644
--- a/lib/classes/Feed/XML/Abstract.class.php
+++ b/lib/classes/Feed/XML/Abstract.class.php
@@ -17,338 +17,332 @@
*/
abstract class Feed_XML_Abstract
{
+ /**
+ *
+ * @var DateTime
+ */
+ protected $updated_on;
- /**
- *
- * @var DateTime
- */
- protected $updated_on;
- /**
- *
- * @var string
- */
- protected $title;
- /**
- *
- * @var string
- */
- protected $subtitle;
- /**
- *
- * @var Array
- */
- protected $items = array();
- /**
- *
- * @var Feed_Link
- */
- protected $next_page;
- /**
- *
- * @var Feed_Link
- */
- protected $previous_page;
- /**
- *
- * @var Feed_Link
- */
- protected $link;
- /**
- *
- * @var string
- */
- protected $generator;
- /**
- *
- * @var string
- */
- protected $mimetype;
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @param string $title
- */
- public function set_title($title)
- {
- $this->title = $title;
+ /**
+ *
+ * @var string
+ */
+ protected $subtitle;
- return $this;
- }
+ /**
+ *
+ * @var Array
+ */
+ protected $items = array();
- /**
- *
- * @param DateTime $datetime
- * @return Feed_XML_Interface
- */
- public function set_updated_on(DateTime $datetime)
- {
- $this->updated_on = $datetime;
+ /**
+ *
+ * @var Feed_Link
+ */
+ protected $next_page;
- return $this;
- }
+ /**
+ *
+ * @var Feed_Link
+ */
+ protected $previous_page;
- /**
- *
- * @param string $subtitle
- * @return Feed_XML_Interface
- */
- public function set_subtitle($subtitle)
- {
- $this->subtitle = $subtitle;
+ /**
+ *
+ * @var Feed_Link
+ */
+ protected $link;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $generator;
- /**
- *
- * @param Feed_Link $link
- * @return Feed_XML_Interface
- */
- public function set_link(Feed_Link $link)
- {
- $this->link = $link;
+ /**
+ *
+ * @var string
+ */
+ protected $mimetype;
- return $this;
- }
-
- /**
- *
- * @param Feed_Link $next_page
- * @return Feed_XML_Interface
- */
- public function set_next_page(Feed_Link $next_page)
- {
- $this->next_page = $next_page;
-
- return $this;
- }
-
- /**
- *
- * @param Feed_Link $previous_page
- * @return Feed_XML_Interface
- */
- public function set_previous_page(Feed_Link $previous_page)
- {
- $this->previous_page = $previous_page;
-
- return $this;
- }
-
- /**
- *
- * @param Feed_Entry_Adapter $entry
- * @return Feed_XML_Interface
- */
- public function set_item(Feed_Entry_Adapter $entry)
- {
- $this->items[] = $entry;
-
- return $this;
- }
-
- /**
- *
- * @param string $generator
- * @return Feed_XML_Interface
- */
- public function set_generator($generator)
- {
- $this->generator = $generator;
-
- return $this;
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $node
- * @param boolean $namespaced
- * @return Feed_XML_Interface
- */
- public function add_navigation(DOMDocument $document, DOMNode $node, $namespaced)
- {
- $prefix = $namespaced ? 'atom:' : '';
-
- if ($this->previous_page instanceof Feed_Link)
+ /**
+ *
+ * @param string $title
+ */
+ public function set_title($title)
{
- $prev_link = $this->addTag($document, $node, $prefix . 'link');
- $prev_link->setAttribute('rel', 'previous');
- $prev_link->setAttribute('href', $this->previous_page->get_href());
+ $this->title = $title;
+
+ return $this;
}
- if ($this->next_page instanceof Feed_Link)
+ /**
+ *
+ * @param DateTime $datetime
+ * @return Feed_XML_Interface
+ */
+ public function set_updated_on(DateTime $datetime)
{
- $next_link = $this->addTag($document, $node, $prefix . 'link');
- $next_link->setAttribute('rel', 'next');
- $next_link->setAttribute('href', $this->next_page->get_href());
+ $this->updated_on = $datetime;
+
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $node
- * @param string $tagname
- * @param string $tagcontent
- * @return DOMElement
- */
- protected function addTag(DOMDocument &$document, DOMNode &$node, $tagname, $tagcontent = null)
- {
- $tag = $document->createElement($tagname);
-
- if (trim($tagcontent) !== '')
- $tag->appendChild($document->createTextNode($tagcontent));
- $node->appendChild($tag);
-
- return $tag;
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $item
- * @param Feed_Entry_Item $content
- * @return Feed_XML_Interface
- */
- protected function addContent(DOMDocument $document, DOMNode $item, Feed_Entry_Item $content)
- {
- $preview_sd = $content->get_record()->get_subdef('preview');
- $preview_permalink = $preview_sd->get_permalink();
- $thumbnail_sd = $content->get_record()->get_thumbnail();
- $thumbnail_permalink = $thumbnail_sd->get_permalink();
-
- $medium = strtolower($content->get_record()->get_type());
-
- if (!in_array($medium, array('image', 'audio', 'video')))
-
- return $this;
-
- if (!$preview_permalink || !$thumbnail_permalink)
-
- return $this;
-
- $group = $this->addTag($document, $item, 'media:group');
-
- $title_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Title);
- if ($title_field)
+ /**
+ *
+ * @param string $subtitle
+ * @return Feed_XML_Interface
+ */
+ public function set_subtitle($subtitle)
{
- $str_title = $title_field->get_serialized_values(' ');
- $title = $this->addTag($document, $group, 'media:title', $str_title);
- $title->setAttribute('type', 'plain');
+ $this->subtitle = $subtitle;
+
+ return $this;
}
- $desc_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Description);
- if ($desc_field)
+ /**
+ *
+ * @param Feed_Link $link
+ * @return Feed_XML_Interface
+ */
+ public function set_link(Feed_Link $link)
{
- $str_desc = $desc_field->get_serialized_values(' ');
- $desc = $this->addTag($document, $group, 'media:description', $str_desc);
- $desc->setAttribute('type', 'plain');
+ $this->link = $link;
+
+ return $this;
}
- $contrib_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Contributor);
- if ($contrib_field)
+ /**
+ *
+ * @param Feed_Link $next_page
+ * @return Feed_XML_Interface
+ */
+ public function set_next_page(Feed_Link $next_page)
{
- $str_contrib = $contrib_field->get_serialized_values(' ');
- $contrib = $this->addTag($document, $group, 'media:credit', $str_contrib);
- $contrib->setAttribute('role', 'contributor');
- $contrib->setAttribute('scheme', 'urn:ebu');
+ $this->next_page = $next_page;
+
+ return $this;
}
- $director_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Creator);
- if ($director_field)
+ /**
+ *
+ * @param Feed_Link $previous_page
+ * @return Feed_XML_Interface
+ */
+ public function set_previous_page(Feed_Link $previous_page)
{
- $str_director = $director_field->get_serialized_values(' ');
- $director = $this->addTag($document, $group, 'media:credit', $str_director);
- $director->setAttribute('role', 'director');
- $director->setAttribute('scheme', 'urn:ebu');
+ $this->previous_page = $previous_page;
+
+ return $this;
}
- $publisher_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Publisher);
- if ($publisher_field)
+ /**
+ *
+ * @param Feed_Entry_Adapter $entry
+ * @return Feed_XML_Interface
+ */
+ public function set_item(Feed_Entry_Adapter $entry)
{
- $str_publisher = $publisher_field->get_serialized_values(' ');
- $publisher = $this->addTag($document, $group, 'media:credit', $str_publisher);
- $publisher->setAttribute('role', 'publisher');
- $publisher->setAttribute('scheme', 'urn:ebu');
+ $this->items[] = $entry;
+
+ return $this;
}
- $rights_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Rights);
- if ($rights_field)
+ /**
+ *
+ * @param string $generator
+ * @return Feed_XML_Interface
+ */
+ public function set_generator($generator)
{
- $str_rights = $rights_field->get_serialized_values(' ');
- $rights = $this->addTag($document, $group, 'media:copyright', $str_rights);
+ $this->generator = $generator;
+
+ return $this;
}
- $keyword_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Subject);
- if ($keyword_field)
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $node
+ * @param boolean $namespaced
+ * @return Feed_XML_Interface
+ */
+ public function add_navigation(DOMDocument $document, DOMNode $node, $namespaced)
{
- $str_keywords = $keyword_field->get_serialized_values(', ');
- $keywords = $this->addTag($document, $group, 'media:keywords', $str_keywords);
+ $prefix = $namespaced ? 'atom:' : '';
+
+ if ($this->previous_page instanceof Feed_Link) {
+ $prev_link = $this->addTag($document, $node, $prefix . 'link');
+ $prev_link->setAttribute('rel', 'previous');
+ $prev_link->setAttribute('href', $this->previous_page->get_href());
+ }
+
+ if ($this->next_page instanceof Feed_Link) {
+ $next_link = $this->addTag($document, $node, $prefix . 'link');
+ $next_link->setAttribute('rel', 'next');
+ $next_link->setAttribute('href', $this->next_page->get_href());
+ }
+
+ return $this;
}
- $duration = $content->get_record()->get_duration();
-
- if ($preview_permalink)
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $node
+ * @param string $tagname
+ * @param string $tagcontent
+ * @return DOMElement
+ */
+ protected function addTag(DOMDocument &$document, DOMNode &$node, $tagname, $tagcontent = null)
{
- $preview = $this->addTag($document, $group, 'media:content');
+ $tag = $document->createElement($tagname);
- $preview->setAttribute('url', $preview_permalink->get_url());
- $preview->setAttribute('fileSize', $preview_sd->get_size());
- $preview->setAttribute('type', $preview_sd->get_mime());
- $preview->setAttribute('medium', $medium);
- $preview->setAttribute('expression', 'full');
- $preview->setAttribute('isDefault', 'true');
+ if (trim($tagcontent) !== '')
+ $tag->appendChild($document->createTextNode($tagcontent));
+ $node->appendChild($tag);
- if ($preview_sd->get_width())
- $preview->setAttribute('width', $preview_sd->get_width());
- if ($preview_sd->get_height())
- $preview->setAttribute('height', $preview_sd->get_height());
- if ($duration)
- $preview->setAttribute('duration', $duration);
+ return $tag;
}
- if ($thumbnail_permalink)
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $item
+ * @param Feed_Entry_Item $content
+ * @return Feed_XML_Interface
+ */
+ protected function addContent(DOMDocument $document, DOMNode $item, Feed_Entry_Item $content)
{
- $thumbnail = $this->addTag($document, $group, 'media:thumbnail');
+ $preview_sd = $content->get_record()->get_subdef('preview');
+ $preview_permalink = $preview_sd->get_permalink();
+ $thumbnail_sd = $content->get_record()->get_thumbnail();
+ $thumbnail_permalink = $thumbnail_sd->get_permalink();
- $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
+ $medium = strtolower($content->get_record()->get_type());
- if ($thumbnail_sd->get_width())
- $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
- if ($thumbnail_sd->get_height())
- $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
+ if ( ! in_array($medium, array('image', 'audio', 'video')))
+ return $this;
+
+ if ( ! $preview_permalink || ! $thumbnail_permalink)
+ return $this;
+
+ $group = $this->addTag($document, $item, 'media:group');
+
+ $title_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Title);
+ if ($title_field) {
+ $str_title = $title_field->get_serialized_values(' ');
+ $title = $this->addTag($document, $group, 'media:title', $str_title);
+ $title->setAttribute('type', 'plain');
+ }
+
+ $desc_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Description);
+ if ($desc_field) {
+ $str_desc = $desc_field->get_serialized_values(' ');
+ $desc = $this->addTag($document, $group, 'media:description', $str_desc);
+ $desc->setAttribute('type', 'plain');
+ }
+
+ $contrib_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Contributor);
+ if ($contrib_field) {
+ $str_contrib = $contrib_field->get_serialized_values(' ');
+ $contrib = $this->addTag($document, $group, 'media:credit', $str_contrib);
+ $contrib->setAttribute('role', 'contributor');
+ $contrib->setAttribute('scheme', 'urn:ebu');
+ }
+
+ $director_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Creator);
+ if ($director_field) {
+ $str_director = $director_field->get_serialized_values(' ');
+ $director = $this->addTag($document, $group, 'media:credit', $str_director);
+ $director->setAttribute('role', 'director');
+ $director->setAttribute('scheme', 'urn:ebu');
+ }
+
+ $publisher_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Publisher);
+ if ($publisher_field) {
+ $str_publisher = $publisher_field->get_serialized_values(' ');
+ $publisher = $this->addTag($document, $group, 'media:credit', $str_publisher);
+ $publisher->setAttribute('role', 'publisher');
+ $publisher->setAttribute('scheme', 'urn:ebu');
+ }
+
+ $rights_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Rights);
+ if ($rights_field) {
+ $str_rights = $rights_field->get_serialized_values(' ');
+ $rights = $this->addTag($document, $group, 'media:copyright', $str_rights);
+ }
+
+ $keyword_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Subject);
+ if ($keyword_field) {
+ $str_keywords = $keyword_field->get_serialized_values(', ');
+ $keywords = $this->addTag($document, $group, 'media:keywords', $str_keywords);
+ }
+
+ $duration = $content->get_record()->get_duration();
+
+ if ($preview_permalink) {
+ $preview = $this->addTag($document, $group, 'media:content');
+
+ $preview->setAttribute('url', $preview_permalink->get_url());
+ $preview->setAttribute('fileSize', $preview_sd->get_size());
+ $preview->setAttribute('type', $preview_sd->get_mime());
+ $preview->setAttribute('medium', $medium);
+ $preview->setAttribute('expression', 'full');
+ $preview->setAttribute('isDefault', 'true');
+
+ if ($preview_sd->get_width())
+ $preview->setAttribute('width', $preview_sd->get_width());
+ if ($preview_sd->get_height())
+ $preview->setAttribute('height', $preview_sd->get_height());
+ if ($duration)
+ $preview->setAttribute('duration', $duration);
+ }
+
+ if ($thumbnail_permalink) {
+ $thumbnail = $this->addTag($document, $group, 'media:thumbnail');
+
+ $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
+
+ if ($thumbnail_sd->get_width())
+ $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
+ if ($thumbnail_sd->get_height())
+ $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
- $thumbnail = $this->addTag($document, $group, 'media:content');
+ $thumbnail = $this->addTag($document, $group, 'media:content');
- $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
- $thumbnail->setAttribute('fileSize', $thumbnail_sd->get_size());
- $thumbnail->setAttribute('type', $thumbnail_sd->get_mime());
- $thumbnail->setAttribute('medium', $medium);
- $thumbnail->setAttribute('isDefault', 'false');
+ $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
+ $thumbnail->setAttribute('fileSize', $thumbnail_sd->get_size());
+ $thumbnail->setAttribute('type', $thumbnail_sd->get_mime());
+ $thumbnail->setAttribute('medium', $medium);
+ $thumbnail->setAttribute('isDefault', 'false');
- if ($thumbnail_sd->get_width())
- $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
- if ($thumbnail_sd->get_height())
- $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
- if ($duration)
- $thumbnail->setAttribute('duration', $duration);
+ if ($thumbnail_sd->get_width())
+ $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
+ if ($thumbnail_sd->get_height())
+ $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
+ if ($duration)
+ $thumbnail->setAttribute('duration', $duration);
+ }
+
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_mimetype()
+ {
+ return $this->mimetype;
+ }
- /**
- *
- * @return string
- */
- public function get_mimetype()
- {
- return $this->mimetype;
- }
-
- abstract public function render();
+ abstract public function render();
}
diff --git a/lib/classes/Feed/XML/Atom.class.php b/lib/classes/Feed/XML/Atom.class.php
index aae53f4683..ff33c03684 100644
--- a/lib/classes/Feed/XML/Atom.class.php
+++ b/lib/classes/Feed/XML/Atom.class.php
@@ -17,178 +17,177 @@
*/
class Feed_XML_Atom extends Feed_XML_Abstract implements Feed_XML_Interface
{
+ /**
+ *
+ * @var string
+ */
+ protected $id;
- /**
- *
- * @var string
- */
- protected $id;
- /**
- *
- * @var string
- */
- protected $author_name;
- /**
- *
- * @var string
- */
- protected $author_email;
- /**
- *
- * @var string
- */
- protected $author_url;
- /**
- *
- * @var boolean
- */
- protected $author = false;
- /**
- *
- * @var string
- */
- protected $icon;
- /**
- *
- * @var string
- */
- protected $mimetype = 'application/atom+xml';
+ /**
+ *
+ * @var string
+ */
+ protected $author_name;
- /**
- *
- * @return string
- */
- public function render()
- {
- $document = new DOMDocument('1.0', 'UTF-8');
- $document->formatOutput = true;
- $document->standalone = true;
+ /**
+ *
+ * @var string
+ */
+ protected $author_email;
- $root = $this->addTag($document, $document, 'feed');
- $root->setAttribute('xmlns', 'http://www.w3.org/2005/Atom');
- $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
+ /**
+ *
+ * @var string
+ */
+ protected $author_url;
- $this->addTag($document, $root, 'title', $this->title);
- if ($this->updated_on instanceof DateTime)
+ /**
+ *
+ * @var boolean
+ */
+ protected $author = false;
+
+ /**
+ *
+ * @var string
+ */
+ protected $icon;
+
+ /**
+ *
+ * @var string
+ */
+ protected $mimetype = 'application/atom+xml';
+
+ /**
+ *
+ * @return string
+ */
+ public function render()
{
- $updated_on = $this->updated_on->format(DATE_ATOM);
- $this->addTag($document, $root, 'updated', $updated_on);
+ $document = new DOMDocument('1.0', 'UTF-8');
+ $document->formatOutput = true;
+ $document->standalone = true;
+
+ $root = $this->addTag($document, $document, 'feed');
+ $root->setAttribute('xmlns', 'http://www.w3.org/2005/Atom');
+ $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
+
+ $this->addTag($document, $root, 'title', $this->title);
+ if ($this->updated_on instanceof DateTime) {
+ $updated_on = $this->updated_on->format(DATE_ATOM);
+ $this->addTag($document, $root, 'updated', $updated_on);
+ }
+
+ if ($this->link instanceof Feed_Link) {
+ $link = $this->addTag($document, $root, 'link');
+ $link->setAttribute('rel', 'self');
+ $link->setAttribute('href', $this->link->get_href());
+ $this->addTag($document, $root, 'id', $this->link->get_href());
+ }
+
+ $this->add_navigation($document, $root, false);
+
+ if ($this->generator)
+ $this->addTag($document, $root, 'generator', $this->generator);
+ if ($this->subtitle)
+ $this->addTag($document, $root, 'subtitle', $this->subtitle);
+ if ($this->icon)
+ $this->addTag($document, $root, 'icon', $this->icon);
+ if ($this->author) {
+ $author = $this->addTag($document, $root, 'author');
+ if ($this->author_email)
+ $this->addTag($document, $author, 'email', $this->author_email);
+ if ($this->author_name)
+ $this->addTag($document, $author, 'name', $this->author_name);
+ if ($this->author_url)
+ $this->addTag($document, $author, 'uri', $this->author_url);
+ }
+
+ foreach ($this->items as $item) {
+ $this->add_item($document, $root, $item);
+ }
+
+ return $document->saveXML();
}
- if ($this->link instanceof Feed_Link)
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMElement $feed
+ * @param Feed_Entry_Adapter $entry
+ * @return DOMElement
+ */
+ protected function add_item(DOMDocument $document, DOMElement $feed, Feed_Entry_Adapter $entry)
{
- $link = $this->addTag($document, $root, 'link');
- $link->setAttribute('rel', 'self');
- $link->setAttribute('href', $this->link->get_href());
- $this->addTag($document, $root, 'id', $this->link->get_href());
+ $entry_node = $this->addTag($document, $feed, 'entry');
+
+ $link = sprintf('%sentry/%d/', $this->link->get_href(), $entry->get_id());
+
+ $this->addTag($document, $entry_node, 'id', $link);
+ $link_tag = $this->addTag($document, $entry_node, 'link');
+ $link_tag->setAttribute('rel', 'self');
+ $link_tag->setAttribute('href', $link);
+
+ $updated_on = $entry->get_updated_on()->format(DATE_ATOM);
+ $created_on = $entry->get_created_on()->format(DATE_ATOM);
+
+ $this->addTag($document, $entry_node, 'updated', $updated_on);
+ $this->addTag($document, $entry_node, 'published', $created_on);
+ $this->addTag($document, $entry_node, 'title', $entry->get_title());
+ $author = $this->addTag($document, $entry_node, 'author');
+
+ if ($entry->get_author_email())
+ $this->addTag($document, $author, 'email', $entry->get_author_email());
+ if ($entry->get_author_name())
+ $this->addTag($document, $author, 'name', $entry->get_author_name());
+
+ $this->addTag($document, $entry_node, 'content', $entry->get_subtitle());
+
+
+ foreach ($entry->get_content() as $content) {
+ $this->addContent($document, $entry_node, $content);
+ }
+
+ return $entry_node;
}
- $this->add_navigation($document, $root, false);
-
- if ($this->generator)
- $this->addTag($document, $root, 'generator', $this->generator);
- if ($this->subtitle)
- $this->addTag($document, $root, 'subtitle', $this->subtitle);
- if ($this->icon)
- $this->addTag($document, $root, 'icon', $this->icon);
- if ($this->author)
+ /**
+ *
+ * @param string $author_name
+ * @return Feed_XML_Atom
+ */
+ public function set_author_name($author_name)
{
- $author = $this->addTag($document, $root, 'author');
- if ($this->author_email)
- $this->addTag($document, $author, 'email', $this->author_email);
- if ($this->author_name)
- $this->addTag($document, $author, 'name', $this->author_name);
- if ($this->author_url)
- $this->addTag($document, $author, 'uri', $this->author_url);
+ $this->author = true;
+ $this->author_name = $author_name;
+
+ return $this;
}
- foreach ($this->items as $item)
+ /**
+ *
+ * @param string $author_name
+ * @return Feed_XML_Atom
+ */
+ public function set_author_email($author_email)
{
- $this->add_item($document, $root, $item);
+ $this->author = true;
+ $this->author_email = $author_email;
+
+ return $this;
}
- return $document->saveXML();
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMElement $feed
- * @param Feed_Entry_Adapter $entry
- * @return DOMElement
- */
- protected function add_item(DOMDocument $document, DOMElement $feed, Feed_Entry_Adapter $entry)
- {
- $entry_node = $this->addTag($document, $feed, 'entry');
-
- $link = sprintf('%sentry/%d/', $this->link->get_href(), $entry->get_id());
-
- $this->addTag($document, $entry_node, 'id', $link);
- $link_tag = $this->addTag($document, $entry_node, 'link');
- $link_tag->setAttribute('rel', 'self');
- $link_tag->setAttribute('href', $link);
-
- $updated_on = $entry->get_updated_on()->format(DATE_ATOM);
- $created_on = $entry->get_created_on()->format(DATE_ATOM);
-
- $this->addTag($document, $entry_node, 'updated', $updated_on);
- $this->addTag($document, $entry_node, 'published', $created_on);
- $this->addTag($document, $entry_node, 'title', $entry->get_title());
- $author = $this->addTag($document, $entry_node, 'author');
-
- if ($entry->get_author_email())
- $this->addTag($document, $author, 'email', $entry->get_author_email());
- if ($entry->get_author_name())
- $this->addTag($document, $author, 'name', $entry->get_author_name());
-
- $this->addTag($document, $entry_node, 'content', $entry->get_subtitle());
-
-
- foreach ($entry->get_content() as $content)
+ /**
+ *
+ * @param string $author_name
+ * @return Feed_XML_Atom
+ */
+ public function set_author_url($author_url)
{
- $this->addContent($document, $entry_node, $content);
+ $this->author = true;
+ $this->author_url = $author_url;
+
+ return $this;
}
-
- return $entry_node;
- }
-
- /**
- *
- * @param string $author_name
- * @return Feed_XML_Atom
- */
- public function set_author_name($author_name)
- {
- $this->author = true;
- $this->author_name = $author_name;
-
- return $this;
- }
-
- /**
- *
- * @param string $author_name
- * @return Feed_XML_Atom
- */
- public function set_author_email($author_email)
- {
- $this->author = true;
- $this->author_email = $author_email;
-
- return $this;
- }
-
- /**
- *
- * @param string $author_name
- * @return Feed_XML_Atom
- */
- public function set_author_url($author_url)
- {
- $this->author = true;
- $this->author_url = $author_url;
-
- return $this;
- }
-
}
diff --git a/lib/classes/Feed/XML/Cooliris.class.php b/lib/classes/Feed/XML/Cooliris.class.php
index 8bf18786f3..d2c133a187 100644
--- a/lib/classes/Feed/XML/Cooliris.class.php
+++ b/lib/classes/Feed/XML/Cooliris.class.php
@@ -17,445 +17,422 @@
*/
class Feed_XML_Cooliris extends Feed_XML_Abstract implements Feed_XML_Interface
{
- /**
- * RSS version
- */
- const VERSION = '2.0';
+ /**
+ * RSS version
+ */
+ const VERSION = '2.0';
- /**
- *
- * @var Array
- */
- protected $required_fields = array('title', 'subtitle', 'link');
+ /**
+ *
+ * @var Array
+ */
+ protected $required_fields = array('title', 'subtitle', 'link');
- /**
- *
- * @var string
- */
- protected $language;
+ /**
+ *
+ * @var string
+ */
+ protected $language;
- /**
- *
- * @var string
- */
- protected $copyright;
+ /**
+ *
+ * @var string
+ */
+ protected $copyright;
- /**
- *
- * @var string
- */
- protected $managingEditor;
+ /**
+ *
+ * @var string
+ */
+ protected $managingEditor;
- /**
- *
- * @var string
- */
- protected $webMaster;
+ /**
+ *
+ * @var string
+ */
+ protected $webMaster;
- /**
- *
- * @var DateTime
- */
- protected $lastBuildDate;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $lastBuildDate;
- /**
- *
- * @var string
- */
- protected $categories;
+ /**
+ *
+ * @var string
+ */
+ protected $categories;
- /**
- *
- * @var string
- */
- protected $docs = 'http://blogs.law.harvard.edu/tech/rss';
+ /**
+ *
+ * @var string
+ */
+ protected $docs = 'http://blogs.law.harvard.edu/tech/rss';
- /**
- *
- * @var int
- */
- protected $ttl;
+ /**
+ *
+ * @var int
+ */
+ protected $ttl;
- /**
- *
- * @var Feed_XML_RSS_Image
- */
- protected $image;
+ /**
+ *
+ * @var Feed_XML_RSS_Image
+ */
+ protected $image;
- /**
- *
- * @var string
- */
- protected $skipHours = array();
+ /**
+ *
+ * @var string
+ */
+ protected $skipHours = array();
- /**
- *
- * @var string
- */
- protected $skipDays = array();
+ /**
+ *
+ * @var string
+ */
+ protected $skipDays = array();
- /**
- *
- * @var string
- */
- protected $mimetype = 'application/rss+xml';
+ /**
+ *
+ * @var string
+ */
+ protected $mimetype = 'application/rss+xml';
- /**
- *
- * @param string $language
- * @return Feed_XML_RSS
- */
- public function set_language($language)
- {
- $this->language = $language;
-
- return $this;
- }
-
- /**
- *
- * @param string $language
- * @return Feed_XML_RSS
- */
- public function set_copyright($copyright)
- {
- $this->copyright = $copyright;
-
- return $this;
- }
-
- /**
- *
- * @param string $managingEditor
- * @return Feed_XML_RSS
- */
- public function set_managingEditor($managingEditor)
- {
- $this->managingEditor = $managingEditor;
-
- return $this;
- }
-
- /**
- *
- * @param string $webMaster
- * @return Feed_XML_RSS
- */
- public function set_webMaster($webMaster)
- {
- $this->webMaster = $webMaster;
-
- return $this;
- }
-
- /**
- *
- * @param DateTime $lastBuildDate
- * @return Feed_XML_RSS
- */
- public function set_lastBuildDate(DateTime $lastBuildDate)
- {
- $this->lastBuildDate = $lastBuildDate;
-
- return $this;
- }
-
- /**
- *
- * @param string $category
- * @return Feed_XML_RSS
- */
- public function set_category($category)
- {
- $this->categories[] = $category;
-
- return $this;
- }
-
- /**
- *
- * @param string $docs
- * @return Feed_XML_RSS
- */
- public function set_docs($docs)
- {
- $this->docs = $docs;
-
- return $this;
- }
-
- /**
- *
- * @param int $ttl
- * @return Feed_XML_RSS
- */
- public function set_ttl($ttl)
- {
- $this->ttl = $ttl;
-
- return $this;
- }
-
- /**
- *
- * @param Feed_XML_RSS_Image $image
- * @return Feed_XML_RSS
- */
- public function set_image(Feed_XML_RSS_Image $image)
- {
- $this->image = $image;
-
- return $this;
- }
-
- /**
- *
- * @param string $skipHours
- * @return Feed_XML_RSS
- */
- public function set_skipHour($hour)
- {
- $this->skipHours[] = (int) $hour;
-
- return $this;
- }
-
- /**
- *
- * @param string $skipDays
- * @return Feed_XML_RSS
- */
- public function set_skipDays($day)
- {
- $this->skipDays[] = $day;
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function render()
- {
- $doc = new DOMDocument('1.0', 'UTF-8');
- $doc->formatOutput = true;
- $doc->standalone = true;
-
-
- $root = $this->addTag($doc, $doc, 'rss');
-
- $root->setAttribute('version', self::VERSION);
- $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
- $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
- $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
-
- $channel = $this->addTag($doc, $root, 'channel');
-
- $this->addTag($doc, $channel, 'title', $this->title);
- $this->addTag($doc, $channel, 'dc:title', $this->title);
- $this->addTag($doc, $channel, 'description', $this->subtitle);
- if ($this->link instanceof Feed_Link)
- $this->addTag($doc, $channel, 'link', $this->link->get_href());
-
- if ($this->language)
- $this->addTag($doc, $channel, 'language', $this->language);
- if ($this->copyright)
- $this->addTag($doc, $channel, 'copyright', $this->copyright);
- if ($this->managingEditor)
- $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor);
- if ($this->webMaster)
- $this->addTag($doc, $channel, 'webMaster', $this->webMaster);
- if ($this->updated_on instanceof DateTime)
+ /**
+ *
+ * @param string $language
+ * @return Feed_XML_RSS
+ */
+ public function set_language($language)
{
- $updated_on = $this->updated_on->format(DATE_RFC2822);
- $this->addTag($doc, $channel, 'pubDate', $updated_on);
- }
- if ($this->lastBuildDate instanceof DateTime)
- {
- $last_build = $this->lastBuildDate->format(DATE_RFC2822);
- $this->addTag($doc, $channel, 'lastBuildDate', $last_build);
- }
- if (count($this->categories) > 0)
- {
- foreach ($this->categories as $category)
- {
- $this->addTag($doc, $channel, 'category', $category);
- }
- }
- if ($this->generator)
- $this->addTag($doc, $channel, 'generator', $this->generator);
- if ($this->docs)
- $this->addTag($doc, $channel, 'docs', $this->docs);
- if ($this->ttl)
- $this->addTag($doc, $channel, 'ttl', $this->ttl);
- if ($this->image instanceof Feed_XML_RSS_Image)
- {
- $image = $this->addTag($doc, $channel, 'image');
- $this->addTag($doc, $image, 'url', $this->image->get_url());
- $this->addTag($doc, $image, 'title', $this->image->get_title());
- $this->addTag($doc, $image, 'link', $this->image->get_link());
- if ($this->image->get_width())
- $this->addTag($doc, $image, 'width', $this->image->get_width());
- if ($this->image->get_height())
- $this->addTag($doc, $image, 'height', $this->image->get_height());
- if ($this->image->get_description())
- $this->addTag($doc, $image, 'description', $this->image->get_description());
- }
- if (count($this->skipHours))
- {
- $skipHours = $this->addTag($doc, $channel, 'skipHours');
- foreach ($this->skipHours as $hour)
- {
- $this->addTag($doc, $skipHours, 'hour', $hour);
- }
- }
- if (count($this->skipDays) > 0)
- {
- $skipDays = $this->addTag($doc, $channel, 'skipDays');
- foreach ($this->skipDays as $day)
- {
- $this->addTag($doc, $skipDays, 'day', $day);
- }
- }
- if ($this->link instanceof Feed_Link)
- {
- $self_link = $this->addTag($doc, $channel, 'atom:link');
- $self_link->setAttribute('rel', 'self');
- $self_link->setAttribute('href', $this->link->get_href());
+ $this->language = $language;
+
+ return $this;
}
- $this->add_navigation($doc, $channel, true);
-
- foreach ($this->items as $item)
+ /**
+ *
+ * @param string $language
+ * @return Feed_XML_RSS
+ */
+ public function set_copyright($copyright)
{
- $this->add_item($doc, $channel, $item);
+ $this->copyright = $copyright;
+
+ return $this;
}
- return $doc->saveXML();
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $node
- * @param Feed_Entry_Adapter $entry
- * @return DOMElement
- */
- protected function add_item(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry)
- {
- foreach ($entry->get_content() as $content)
+ /**
+ *
+ * @param string $managingEditor
+ * @return Feed_XML_RSS
+ */
+ public function set_managingEditor($managingEditor)
{
- $this->addContent($document, $node, $entry, $content);
+ $this->managingEditor = $managingEditor;
+
+ return $this;
}
- return;
- }
-
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $item
- * @param Feed_Entry_Item $content
- * @return Feed_XML_Interface
- */
- protected function addContent(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry, Feed_Entry_Item $content)
- {
-
- $preview_sd = $content->get_record()->get_subdef('preview');
- $preview_permalink = $preview_sd->get_permalink();
- $thumbnail_sd = $content->get_record()->get_thumbnail();
- $thumbnail_permalink = $thumbnail_sd->get_permalink();
-
- $medium = strtolower($content->get_record()->get_type());
-
- if (!in_array($medium, array('image', 'audio', 'video')))
-
- return $this;
-
- if (!$preview_permalink || !$thumbnail_permalink)
-
- return $this;
-
- //add item node to channel node
- $item = $this->addTag($document, $node, 'item');
-
- $title_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Title);
- if ($title_field)
+ /**
+ *
+ * @param string $webMaster
+ * @return Feed_XML_RSS
+ */
+ public function set_webMaster($webMaster)
{
- $str_title = $title_field->get_serialized_values(' ');
- }
- else
- {
- $str_title = $content->get_record()->get_title();
+ $this->webMaster = $webMaster;
+
+ return $this;
}
- //attach tile node to item node
- $title = $this->addTag($document, $item, 'title', $str_title);
+ /**
+ *
+ * @param DateTime $lastBuildDate
+ * @return Feed_XML_RSS
+ */
+ public function set_lastBuildDate(DateTime $lastBuildDate)
+ {
+ $this->lastBuildDate = $lastBuildDate;
- $desc_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Description);
- if ($desc_field)
- {
- $str_desc = $desc_field->get_serialized_values(' ');
- }
- else
- {
- $str_desc = '';
+ return $this;
}
- //attach desc node to item node
- $desc = $this->addTag($document, $item, 'description', $str_desc);
-
- $duration = $content->get_record()->get_duration();
-
- if ($preview_permalink)
+ /**
+ *
+ * @param string $category
+ * @return Feed_XML_RSS
+ */
+ public function set_category($category)
{
- $preview = $this->addTag($document, $item, 'media:content');
+ $this->categories[] = $category;
- $preview->setAttribute('url', $preview_permalink->get_url());
- $preview->setAttribute('fileSize', $preview_sd->get_size());
- $preview->setAttribute('type', $preview_sd->get_mime());
- $preview->setAttribute('medium', $medium);
- $preview->setAttribute('expression', 'full');
- $preview->setAttribute('isDefault', 'true');
-
- if ($preview_sd->get_width())
- $preview->setAttribute('width', $preview_sd->get_width());
- if ($preview_sd->get_height())
- $preview->setAttribute('height', $preview_sd->get_height());
- if ($duration)
- $preview->setAttribute('duration', $duration);
+ return $this;
}
- if ($thumbnail_permalink)
+ /**
+ *
+ * @param string $docs
+ * @return Feed_XML_RSS
+ */
+ public function set_docs($docs)
{
- $thumbnail = $this->addTag($document, $item, 'media:thumbnail');
+ $this->docs = $docs;
- $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
-
- if ($thumbnail_sd->get_width())
- $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
- if ($thumbnail_sd->get_height())
- $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
-
-
- $thumbnail = $this->addTag($document, $item, 'media:content');
-
- $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
- $thumbnail->setAttribute('fileSize', $thumbnail_sd->get_size());
- $thumbnail->setAttribute('type', $thumbnail_sd->get_mime());
- $thumbnail->setAttribute('medium', $medium);
- $thumbnail->setAttribute('isDefault', 'false');
-
- if ($thumbnail_sd->get_width())
- $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
- if ($thumbnail_sd->get_height())
- $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
- if ($duration)
- $thumbnail->setAttribute('duration', $duration);
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @param int $ttl
+ * @return Feed_XML_RSS
+ */
+ public function set_ttl($ttl)
+ {
+ $this->ttl = $ttl;
+ return $this;
+ }
+
+ /**
+ *
+ * @param Feed_XML_RSS_Image $image
+ * @return Feed_XML_RSS
+ */
+ public function set_image(Feed_XML_RSS_Image $image)
+ {
+ $this->image = $image;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $skipHours
+ * @return Feed_XML_RSS
+ */
+ public function set_skipHour($hour)
+ {
+ $this->skipHours[] = (int) $hour;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $skipDays
+ * @return Feed_XML_RSS
+ */
+ public function set_skipDays($day)
+ {
+ $this->skipDays[] = $day;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function render()
+ {
+ $doc = new DOMDocument('1.0', 'UTF-8');
+ $doc->formatOutput = true;
+ $doc->standalone = true;
+
+
+ $root = $this->addTag($doc, $doc, 'rss');
+
+ $root->setAttribute('version', self::VERSION);
+ $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
+ $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
+ $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+
+ $channel = $this->addTag($doc, $root, 'channel');
+
+ $this->addTag($doc, $channel, 'title', $this->title);
+ $this->addTag($doc, $channel, 'dc:title', $this->title);
+ $this->addTag($doc, $channel, 'description', $this->subtitle);
+ if ($this->link instanceof Feed_Link)
+ $this->addTag($doc, $channel, 'link', $this->link->get_href());
+
+ if ($this->language)
+ $this->addTag($doc, $channel, 'language', $this->language);
+ if ($this->copyright)
+ $this->addTag($doc, $channel, 'copyright', $this->copyright);
+ if ($this->managingEditor)
+ $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor);
+ if ($this->webMaster)
+ $this->addTag($doc, $channel, 'webMaster', $this->webMaster);
+ if ($this->updated_on instanceof DateTime) {
+ $updated_on = $this->updated_on->format(DATE_RFC2822);
+ $this->addTag($doc, $channel, 'pubDate', $updated_on);
+ }
+ if ($this->lastBuildDate instanceof DateTime) {
+ $last_build = $this->lastBuildDate->format(DATE_RFC2822);
+ $this->addTag($doc, $channel, 'lastBuildDate', $last_build);
+ }
+ if (count($this->categories) > 0) {
+ foreach ($this->categories as $category) {
+ $this->addTag($doc, $channel, 'category', $category);
+ }
+ }
+ if ($this->generator)
+ $this->addTag($doc, $channel, 'generator', $this->generator);
+ if ($this->docs)
+ $this->addTag($doc, $channel, 'docs', $this->docs);
+ if ($this->ttl)
+ $this->addTag($doc, $channel, 'ttl', $this->ttl);
+ if ($this->image instanceof Feed_XML_RSS_Image) {
+ $image = $this->addTag($doc, $channel, 'image');
+ $this->addTag($doc, $image, 'url', $this->image->get_url());
+ $this->addTag($doc, $image, 'title', $this->image->get_title());
+ $this->addTag($doc, $image, 'link', $this->image->get_link());
+ if ($this->image->get_width())
+ $this->addTag($doc, $image, 'width', $this->image->get_width());
+ if ($this->image->get_height())
+ $this->addTag($doc, $image, 'height', $this->image->get_height());
+ if ($this->image->get_description())
+ $this->addTag($doc, $image, 'description', $this->image->get_description());
+ }
+ if (count($this->skipHours)) {
+ $skipHours = $this->addTag($doc, $channel, 'skipHours');
+ foreach ($this->skipHours as $hour) {
+ $this->addTag($doc, $skipHours, 'hour', $hour);
+ }
+ }
+ if (count($this->skipDays) > 0) {
+ $skipDays = $this->addTag($doc, $channel, 'skipDays');
+ foreach ($this->skipDays as $day) {
+ $this->addTag($doc, $skipDays, 'day', $day);
+ }
+ }
+ if ($this->link instanceof Feed_Link) {
+ $self_link = $this->addTag($doc, $channel, 'atom:link');
+ $self_link->setAttribute('rel', 'self');
+ $self_link->setAttribute('href', $this->link->get_href());
+ }
+
+ $this->add_navigation($doc, $channel, true);
+
+ foreach ($this->items as $item) {
+ $this->add_item($doc, $channel, $item);
+ }
+
+ return $doc->saveXML();
+ }
+
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $node
+ * @param Feed_Entry_Adapter $entry
+ * @return DOMElement
+ */
+ protected function add_item(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry)
+ {
+ foreach ($entry->get_content() as $content) {
+ $this->addContent($document, $node, $entry, $content);
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $item
+ * @param Feed_Entry_Item $content
+ * @return Feed_XML_Interface
+ */
+ protected function addContent(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry, Feed_Entry_Item $content)
+ {
+
+ $preview_sd = $content->get_record()->get_subdef('preview');
+ $preview_permalink = $preview_sd->get_permalink();
+ $thumbnail_sd = $content->get_record()->get_thumbnail();
+ $thumbnail_permalink = $thumbnail_sd->get_permalink();
+
+ $medium = strtolower($content->get_record()->get_type());
+
+ if ( ! in_array($medium, array('image', 'audio', 'video')))
+ return $this;
+
+ if ( ! $preview_permalink || ! $thumbnail_permalink)
+ return $this;
+
+ //add item node to channel node
+ $item = $this->addTag($document, $node, 'item');
+
+ $title_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Title);
+ if ($title_field) {
+ $str_title = $title_field->get_serialized_values(' ');
+ } else {
+ $str_title = $content->get_record()->get_title();
+ }
+
+ //attach tile node to item node
+ $title = $this->addTag($document, $item, 'title', $str_title);
+
+ $desc_field = $content->get_record()->get_caption()->get_dc_field(databox_Field_DCESAbstract::Description);
+ if ($desc_field) {
+ $str_desc = $desc_field->get_serialized_values(' ');
+ } else {
+ $str_desc = '';
+ }
+
+ //attach desc node to item node
+ $desc = $this->addTag($document, $item, 'description', $str_desc);
+
+ $duration = $content->get_record()->get_duration();
+
+ if ($preview_permalink) {
+ $preview = $this->addTag($document, $item, 'media:content');
+
+ $preview->setAttribute('url', $preview_permalink->get_url());
+ $preview->setAttribute('fileSize', $preview_sd->get_size());
+ $preview->setAttribute('type', $preview_sd->get_mime());
+ $preview->setAttribute('medium', $medium);
+ $preview->setAttribute('expression', 'full');
+ $preview->setAttribute('isDefault', 'true');
+
+ if ($preview_sd->get_width())
+ $preview->setAttribute('width', $preview_sd->get_width());
+ if ($preview_sd->get_height())
+ $preview->setAttribute('height', $preview_sd->get_height());
+ if ($duration)
+ $preview->setAttribute('duration', $duration);
+ }
+
+ if ($thumbnail_permalink) {
+ $thumbnail = $this->addTag($document, $item, 'media:thumbnail');
+
+ $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
+
+ if ($thumbnail_sd->get_width())
+ $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
+ if ($thumbnail_sd->get_height())
+ $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
+
+
+ $thumbnail = $this->addTag($document, $item, 'media:content');
+
+ $thumbnail->setAttribute('url', $thumbnail_permalink->get_url());
+ $thumbnail->setAttribute('fileSize', $thumbnail_sd->get_size());
+ $thumbnail->setAttribute('type', $thumbnail_sd->get_mime());
+ $thumbnail->setAttribute('medium', $medium);
+ $thumbnail->setAttribute('isDefault', 'false');
+
+ if ($thumbnail_sd->get_width())
+ $thumbnail->setAttribute('width', $thumbnail_sd->get_width());
+ if ($thumbnail_sd->get_height())
+ $thumbnail->setAttribute('height', $thumbnail_sd->get_height());
+ if ($duration)
+ $thumbnail->setAttribute('duration', $duration);
+ }
+
+ return $this;
+ }
}
diff --git a/lib/classes/Feed/XML/Interface.class.php b/lib/classes/Feed/XML/Interface.class.php
index ab7c31a20e..2fd423318b 100644
--- a/lib/classes/Feed/XML/Interface.class.php
+++ b/lib/classes/Feed/XML/Interface.class.php
@@ -17,23 +17,24 @@
*/
interface Feed_XML_Interface
{
- public function set_title($title);
- public function set_updated_on(DateTime $datetime);
+ public function set_title($title);
- public function set_subtitle($subtitle);
+ public function set_updated_on(DateTime $datetime);
- public function set_link(Feed_Link $link);
+ public function set_subtitle($subtitle);
- public function set_next_page(Feed_Link $next_page);
+ public function set_link(Feed_Link $link);
- public function set_previous_page(Feed_Link $previous_page);
+ public function set_next_page(Feed_Link $next_page);
- public function set_item(Feed_Entry_Adapter $entry);
+ public function set_previous_page(Feed_Link $previous_page);
- public function set_generator($generator);
+ public function set_item(Feed_Entry_Adapter $entry);
- public function add_navigation(DOMDocument $document, DOMNode $node, $namespaced);
+ public function set_generator($generator);
- public function get_mimetype();
+ public function add_navigation(DOMDocument $document, DOMNode $node, $namespaced);
+
+ public function get_mimetype();
}
diff --git a/lib/classes/Feed/XML/RSS.class.php b/lib/classes/Feed/XML/RSS.class.php
index a5bcbebea6..41621077c6 100644
--- a/lib/classes/Feed/XML/RSS.class.php
+++ b/lib/classes/Feed/XML/RSS.class.php
@@ -17,355 +17,354 @@
*/
class Feed_XML_RSS extends Feed_XML_Abstract implements Feed_XML_Interface
{
- /**
- * RSS version
- */
- const VERSION = '2.0';
+ /**
+ * RSS version
+ */
+ const VERSION = '2.0';
- /**
- *
- * @var Array
- */
- protected $required_fields = array('title', 'subtitle', 'link');
- /**
- *
- * @var string
- */
- protected $language;
- /**
- *
- * @var string
- */
- protected $copyright;
- /**
- *
- * @var string
- */
- protected $managingEditor;
- /**
- *
- * @var string
- */
- protected $webMaster;
- /**
- *
- * @var DateTime
- */
- protected $lastBuildDate;
- /**
- *
- * @var string
- */
- protected $categories;
- /**
- *
- * @var string
- */
- protected $docs = 'http://blogs.law.harvard.edu/tech/rss';
- /**
- *
- * @var int
- */
- protected $ttl;
- /**
- *
- * @var Feed_XML_RSS_Image
- */
- protected $image;
- /**
- *
- * @var string
- */
- protected $skipHours = array();
- /**
- *
- * @var string
- */
- protected $skipDays = array();
- /**
- *
- * @var string
- */
- protected $mimetype = 'application/rss+xml';
+ /**
+ *
+ * @var Array
+ */
+ protected $required_fields = array('title', 'subtitle', 'link');
- /**
- *
- * @param string $language
- * @return Feed_XML_RSS
- */
- public function set_language($language)
- {
- $this->language = $language;
+ /**
+ *
+ * @var string
+ */
+ protected $language;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $copyright;
- /**
- *
- * @param string $language
- * @return Feed_XML_RSS
- */
- public function set_copyright($copyright)
- {
- $this->copyright = $copyright;
+ /**
+ *
+ * @var string
+ */
+ protected $managingEditor;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $webMaster;
- /**
- *
- * @param string $managingEditor
- * @return Feed_XML_RSS
- */
- public function set_managingEditor($managingEditor)
- {
- $this->managingEditor = $managingEditor;
+ /**
+ *
+ * @var DateTime
+ */
+ protected $lastBuildDate;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $categories;
- /**
- *
- * @param string $webMaster
- * @return Feed_XML_RSS
- */
- public function set_webMaster($webMaster)
- {
- $this->webMaster = $webMaster;
+ /**
+ *
+ * @var string
+ */
+ protected $docs = 'http://blogs.law.harvard.edu/tech/rss';
- return $this;
- }
+ /**
+ *
+ * @var int
+ */
+ protected $ttl;
- /**
- *
- * @param DateTime $lastBuildDate
- * @return Feed_XML_RSS
- */
- public function set_lastBuildDate(DateTime $lastBuildDate)
- {
- $this->lastBuildDate = $lastBuildDate;
+ /**
+ *
+ * @var Feed_XML_RSS_Image
+ */
+ protected $image;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $skipHours = array();
- /**
- *
- * @param string $category
- * @return Feed_XML_RSS
- */
- public function set_category($category)
- {
- $this->categories[] = $category;
+ /**
+ *
+ * @var string
+ */
+ protected $skipDays = array();
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $mimetype = 'application/rss+xml';
- /**
- *
- * @param string $docs
- * @return Feed_XML_RSS
- */
- public function set_docs($docs)
- {
- $this->docs = $docs;
-
- return $this;
- }
-
- /**
- *
- * @param int $ttl
- * @return Feed_XML_RSS
- */
- public function set_ttl($ttl)
- {
- $this->ttl = $ttl;
-
- return $this;
- }
-
- /**
- *
- * @param Feed_XML_RSS_Image $image
- * @return Feed_XML_RSS
- */
- public function set_image(Feed_XML_RSS_Image $image)
- {
- $this->image = $image;
-
- return $this;
- }
-
- /**
- *
- * @param string $skipHours
- * @return Feed_XML_RSS
- */
- public function set_skipHour($hour)
- {
- $this->skipHours[] = (int) $hour;
-
- return $this;
- }
-
- /**
- *
- * @param string $skipDays
- * @return Feed_XML_RSS
- */
- public function set_skipDays($day)
- {
- $this->skipDays[] = $day;
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function render()
- {
- $doc = new DOMDocument('1.0', 'UTF-8');
- $doc->formatOutput = true;
- $doc->standalone = true;
-
-
- $root = $this->addTag($doc, $doc, 'rss');
-
- $root->setAttribute('version', self::VERSION);
- $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
- $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
- $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
-
- $channel = $this->addTag($doc, $root, 'channel');
-
- $this->addTag($doc, $channel, 'title', $this->title);
- $this->addTag($doc, $channel, 'dc:title', $this->title);
- $this->addTag($doc, $channel, 'description', $this->subtitle);
- if ($this->link instanceof Feed_Link)
- $this->addTag($doc, $channel, 'link', $this->link->get_href());
-
- if ($this->language)
- $this->addTag($doc, $channel, 'language', $this->language);
- if ($this->copyright)
- $this->addTag($doc, $channel, 'copyright', $this->copyright);
- if ($this->managingEditor)
- $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor);
- if ($this->webMaster)
- $this->addTag($doc, $channel, 'webMaster', $this->webMaster);
- if ($this->updated_on instanceof DateTime)
+ /**
+ *
+ * @param string $language
+ * @return Feed_XML_RSS
+ */
+ public function set_language($language)
{
- $updated_on = $this->updated_on->format(DATE_RFC2822);
- $this->addTag($doc, $channel, 'pubDate', $updated_on);
- }
- if ($this->lastBuildDate instanceof DateTime)
- {
- $last_build = $this->lastBuildDate->format(DATE_RFC2822);
- $this->addTag($doc, $channel, 'lastBuildDate', $last_build);
- }
- if (count($this->categories) > 0)
- {
- foreach ($this->categories as $category)
- {
- $this->addTag($doc, $channel, 'category', $category);
- }
- }
- if ($this->generator)
- $this->addTag($doc, $channel, 'generator', $this->generator);
- if ($this->docs)
- $this->addTag($doc, $channel, 'docs', $this->docs);
- if ($this->ttl)
- $this->addTag($doc, $channel, 'ttl', $this->ttl);
- if ($this->image instanceof Feed_XML_RSS_Image)
- {
- $image = $this->addTag($doc, $channel, 'image');
- $this->addTag($doc, $image, 'url', $this->image->get_url());
- $this->addTag($doc, $image, 'title', $this->image->get_title());
- $this->addTag($doc, $image, 'link', $this->image->get_link());
- if ($this->image->get_width())
- $this->addTag($doc, $image, 'width', $this->image->get_width());
- if ($this->image->get_height())
- $this->addTag($doc, $image, 'height', $this->image->get_height());
- if ($this->image->get_description())
- $this->addTag($doc, $image, 'description', $this->image->get_description());
- }
- if (count($this->skipHours))
- {
- $skipHours = $this->addTag($doc, $channel, 'skipHours');
- foreach ($this->skipHours as $hour)
- {
- $this->addTag($doc, $skipHours, 'hour', $hour);
- }
- }
- if (count($this->skipDays) > 0)
- {
- $skipDays = $this->addTag($doc, $channel, 'skipDays');
- foreach ($this->skipDays as $day)
- {
- $this->addTag($doc, $skipDays, 'day', $day);
- }
- }
- if ($this->link instanceof Feed_Link)
- {
- $self_link = $this->addTag($doc, $channel, 'atom:link');
- $self_link->setAttribute('rel', 'self');
- $self_link->setAttribute('href', $this->link->get_href());
+ $this->language = $language;
+
+ return $this;
}
- $this->add_navigation($doc, $channel, true);
-
- foreach ($this->items as $item)
+ /**
+ *
+ * @param string $language
+ * @return Feed_XML_RSS
+ */
+ public function set_copyright($copyright)
{
- $this->add_item($doc, $channel, $item);
+ $this->copyright = $copyright;
+
+ return $this;
}
- return $doc->saveXML();
- }
+ /**
+ *
+ * @param string $managingEditor
+ * @return Feed_XML_RSS
+ */
+ public function set_managingEditor($managingEditor)
+ {
+ $this->managingEditor = $managingEditor;
- /**
- *
- * @param DOMDocument $document
- * @param DOMNode $node
- * @param Feed_Entry_Adapter $entry
- * @return DOMElement
- */
- protected function add_item(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry)
- {
- $item = $this->addTag($document, $node, 'item');
+ return $this;
+ }
- $link = $entry->get_link();
+ /**
+ *
+ * @param string $webMaster
+ * @return Feed_XML_RSS
+ */
+ public function set_webMaster($webMaster)
+ {
+ $this->webMaster = $webMaster;
- $this->addTag($document, $item, 'title', $entry->get_title());
- $this->addTag($document, $item, 'description', $entry->get_subtitle());
+ return $this;
+ }
- $author = sprintf(
+ /**
+ *
+ * @param DateTime $lastBuildDate
+ * @return Feed_XML_RSS
+ */
+ public function set_lastBuildDate(DateTime $lastBuildDate)
+ {
+ $this->lastBuildDate = $lastBuildDate;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $category
+ * @return Feed_XML_RSS
+ */
+ public function set_category($category)
+ {
+ $this->categories[] = $category;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $docs
+ * @return Feed_XML_RSS
+ */
+ public function set_docs($docs)
+ {
+ $this->docs = $docs;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param int $ttl
+ * @return Feed_XML_RSS
+ */
+ public function set_ttl($ttl)
+ {
+ $this->ttl = $ttl;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param Feed_XML_RSS_Image $image
+ * @return Feed_XML_RSS
+ */
+ public function set_image(Feed_XML_RSS_Image $image)
+ {
+ $this->image = $image;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $skipHours
+ * @return Feed_XML_RSS
+ */
+ public function set_skipHour($hour)
+ {
+ $this->skipHours[] = (int) $hour;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $skipDays
+ * @return Feed_XML_RSS
+ */
+ public function set_skipDays($day)
+ {
+ $this->skipDays[] = $day;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function render()
+ {
+ $doc = new DOMDocument('1.0', 'UTF-8');
+ $doc->formatOutput = true;
+ $doc->standalone = true;
+
+
+ $root = $this->addTag($doc, $doc, 'rss');
+
+ $root->setAttribute('version', self::VERSION);
+ $root->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/');
+ $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
+ $root->setAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/');
+
+ $channel = $this->addTag($doc, $root, 'channel');
+
+ $this->addTag($doc, $channel, 'title', $this->title);
+ $this->addTag($doc, $channel, 'dc:title', $this->title);
+ $this->addTag($doc, $channel, 'description', $this->subtitle);
+ if ($this->link instanceof Feed_Link)
+ $this->addTag($doc, $channel, 'link', $this->link->get_href());
+
+ if ($this->language)
+ $this->addTag($doc, $channel, 'language', $this->language);
+ if ($this->copyright)
+ $this->addTag($doc, $channel, 'copyright', $this->copyright);
+ if ($this->managingEditor)
+ $this->addTag($doc, $channel, 'managingEditor', $this->managingEditor);
+ if ($this->webMaster)
+ $this->addTag($doc, $channel, 'webMaster', $this->webMaster);
+ if ($this->updated_on instanceof DateTime) {
+ $updated_on = $this->updated_on->format(DATE_RFC2822);
+ $this->addTag($doc, $channel, 'pubDate', $updated_on);
+ }
+ if ($this->lastBuildDate instanceof DateTime) {
+ $last_build = $this->lastBuildDate->format(DATE_RFC2822);
+ $this->addTag($doc, $channel, 'lastBuildDate', $last_build);
+ }
+ if (count($this->categories) > 0) {
+ foreach ($this->categories as $category) {
+ $this->addTag($doc, $channel, 'category', $category);
+ }
+ }
+ if ($this->generator)
+ $this->addTag($doc, $channel, 'generator', $this->generator);
+ if ($this->docs)
+ $this->addTag($doc, $channel, 'docs', $this->docs);
+ if ($this->ttl)
+ $this->addTag($doc, $channel, 'ttl', $this->ttl);
+ if ($this->image instanceof Feed_XML_RSS_Image) {
+ $image = $this->addTag($doc, $channel, 'image');
+ $this->addTag($doc, $image, 'url', $this->image->get_url());
+ $this->addTag($doc, $image, 'title', $this->image->get_title());
+ $this->addTag($doc, $image, 'link', $this->image->get_link());
+ if ($this->image->get_width())
+ $this->addTag($doc, $image, 'width', $this->image->get_width());
+ if ($this->image->get_height())
+ $this->addTag($doc, $image, 'height', $this->image->get_height());
+ if ($this->image->get_description())
+ $this->addTag($doc, $image, 'description', $this->image->get_description());
+ }
+ if (count($this->skipHours)) {
+ $skipHours = $this->addTag($doc, $channel, 'skipHours');
+ foreach ($this->skipHours as $hour) {
+ $this->addTag($doc, $skipHours, 'hour', $hour);
+ }
+ }
+ if (count($this->skipDays) > 0) {
+ $skipDays = $this->addTag($doc, $channel, 'skipDays');
+ foreach ($this->skipDays as $day) {
+ $this->addTag($doc, $skipDays, 'day', $day);
+ }
+ }
+ if ($this->link instanceof Feed_Link) {
+ $self_link = $this->addTag($doc, $channel, 'atom:link');
+ $self_link->setAttribute('rel', 'self');
+ $self_link->setAttribute('href', $this->link->get_href());
+ }
+
+ $this->add_navigation($doc, $channel, true);
+
+ foreach ($this->items as $item) {
+ $this->add_item($doc, $channel, $item);
+ }
+
+ return $doc->saveXML();
+ }
+
+ /**
+ *
+ * @param DOMDocument $document
+ * @param DOMNode $node
+ * @param Feed_Entry_Adapter $entry
+ * @return DOMElement
+ */
+ protected function add_item(DOMDocument $document, DOMNode $node, Feed_Entry_Adapter $entry)
+ {
+ $item = $this->addTag($document, $node, 'item');
+
+ $link = $entry->get_link();
+
+ $this->addTag($document, $item, 'title', $entry->get_title());
+ $this->addTag($document, $item, 'description', $entry->get_subtitle());
+
+ $author = sprintf(
'%s (%s)'
, $entry->get_author_email()
, $entry->get_author_name()
- );
- $created_on = $entry->get_created_on()->format(DATE_RFC2822);
+ );
+ $created_on = $entry->get_created_on()->format(DATE_RFC2822);
- $this->addTag($document, $item, 'author', $author);
- $this->addTag($document, $item, 'pubDate', $created_on);
- $this->addTag($document, $item, 'guid', $link->get_href());
- $this->addTag($document, $item, 'link', $link->get_href());
+ $this->addTag($document, $item, 'author', $author);
+ $this->addTag($document, $item, 'pubDate', $created_on);
+ $this->addTag($document, $item, 'guid', $link->get_href());
+ $this->addTag($document, $item, 'link', $link->get_href());
- /**
- * Missing :
- *
- * category Includes the item in one or more categories. More.
- * comments URL of a page for comments relating to the item. More.
- * enclosure Describes a media object that is attached to the item. More.
- * source The RSS channel that the item came from. More.
- *
- */
- foreach ($entry->get_content() as $content)
- {
- $this->addContent($document, $item, $content);
+ /**
+ * Missing :
+ *
+ * category Includes the item in one or more categories. More.
+ * comments URL of a page for comments relating to the item. More.
+ * enclosure Describes a media object that is attached to the item. More.
+ * source The RSS channel that the item came from. More.
+ *
+ */
+ foreach ($entry->get_content() as $content) {
+ $this->addContent($document, $item, $content);
+ }
+
+ return $item;
}
-
- return $item;
- }
-
}
diff --git a/lib/classes/Feed/XML/RSS/Image.class.php b/lib/classes/Feed/XML/RSS/Image.class.php
index 093c9a1141..284bfccf2d 100644
--- a/lib/classes/Feed/XML/RSS/Image.class.php
+++ b/lib/classes/Feed/XML/RSS/Image.class.php
@@ -17,142 +17,145 @@
*/
class Feed_XML_RSS_Image implements Feed_XML_RSS_ImageInterface
{
+ /**
+ *
+ * @var string
+ */
+ protected $url;
- /**
- *
- * @var string
- */
- protected $url;
- /**
- *
- * @var string
- */
- protected $title;
- /**
- *
- * @var string
- */
- protected $link;
- /**
- *
- * @var string
- */
- protected $description;
- /**
- *
- * @var int
- */
- protected $width;
- /**
- *
- * @var int
- */
- protected $height;
+ /**
+ *
+ * @var string
+ */
+ protected $title;
- /**
- *
- * @param string $url
- * @param string $title
- * @param string $link
- * @return Feed_XML_RSS_Image
- */
- public function __construct($url, $title, $link)
- {
- $this->url = $url;
- $this->title = $title;
- $this->link = $link;
+ /**
+ *
+ * @var string
+ */
+ protected $link;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $description;
- /**
- *
- * @param type $description
- * @return Feed_XML_RSS_Image
- */
- public function set_description($description)
- {
- $this->description = $description;
+ /**
+ *
+ * @var int
+ */
+ protected $width;
- return $this;
- }
+ /**
+ *
+ * @var int
+ */
+ protected $height;
- /**
- *
- * @param int $width
- * @return Feed_XML_RSS_Image
- */
- public function set_width($width)
- {
- $this->width = (int) $width;
+ /**
+ *
+ * @param string $url
+ * @param string $title
+ * @param string $link
+ * @return Feed_XML_RSS_Image
+ */
+ public function __construct($url, $title, $link)
+ {
+ $this->url = $url;
+ $this->title = $title;
+ $this->link = $link;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param int $height
- * @return Feed_XML_RSS_Image
- */
- public function set_height($height)
- {
- $this->height = (int) $height;
+ /**
+ *
+ * @param type $description
+ * @return Feed_XML_RSS_Image
+ */
+ public function set_description($description)
+ {
+ $this->description = $description;
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return $this->url;
- }
+ /**
+ *
+ * @param int $width
+ * @return Feed_XML_RSS_Image
+ */
+ public function set_width($width)
+ {
+ $this->width = (int) $width;
- /**
- *
- * @return string
- */
- public function get_title()
- {
- return $this->title;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_link()
- {
- return $this->link;
- }
+ /**
+ *
+ * @param int $height
+ * @return Feed_XML_RSS_Image
+ */
+ public function set_height($height)
+ {
+ $this->height = (int) $height;
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return $this->description;
- }
+ return $this;
+ }
- /**
- *
- * @return int
- */
- public function get_width()
- {
- return $this->width;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return $this->url;
+ }
- /**
- *
- * @return int
- */
- public function get_height()
- {
- return $this->height;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_title()
+ {
+ return $this->title;
+ }
+ /**
+ *
+ * @return string
+ */
+ public function get_link()
+ {
+ return $this->link;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return $this->description;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_width()
+ {
+ return $this->width;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_height()
+ {
+ return $this->height;
+ }
}
diff --git a/lib/classes/Feed/XML/RSS/ImageInterface.class.php b/lib/classes/Feed/XML/RSS/ImageInterface.class.php
index 4c4aaf302f..9b9df42407 100644
--- a/lib/classes/Feed/XML/RSS/ImageInterface.class.php
+++ b/lib/classes/Feed/XML/RSS/ImageInterface.class.php
@@ -17,17 +17,18 @@
*/
interface Feed_XML_RSS_ImageInterface
{
- public function __construct($url, $title, $link);
- public function get_url();
+ public function __construct($url, $title, $link);
- public function get_title();
+ public function get_url();
- public function get_link();
+ public function get_title();
- public function get_description();
+ public function get_link();
- public function get_height();
+ public function get_description();
- public function get_width();
+ public function get_height();
+
+ public function get_width();
}
diff --git a/lib/classes/Session/Authentication/Guest.class.php b/lib/classes/Session/Authentication/Guest.class.php
index c62cebec5d..a46396cd10 100644
--- a/lib/classes/Session/Authentication/Guest.class.php
+++ b/lib/classes/Session/Authentication/Guest.class.php
@@ -18,77 +18,76 @@
*/
class Session_Authentication_Guest implements Session_Authentication_Interface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @param appbox $appbox
- * @return Session_Authentication_Guest
- */
- public function __construct(appbox &$appbox)
- {
- $this->appbox = $appbox;
+ /**
+ *
+ * @param appbox $appbox
+ * @return Session_Authentication_Guest
+ */
+ public function __construct(appbox &$appbox)
+ {
+ $this->appbox = $appbox;
- $nonce = random::generatePassword(16);
- $password = random::generatePassword(24);
- $this->user = User_Adapter::create($this->appbox, 'invite', $password, null, false, true);
+ $nonce = random::generatePassword(16);
+ $password = random::generatePassword(24);
+ $this->user = User_Adapter::create($this->appbox, 'invite', $password, null, false, true);
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Session_Authentication_Guest
- */
- public function prelog()
- {
- return $this;
- }
+ /**
+ *
+ * @return Session_Authentication_Guest
+ */
+ public function prelog()
+ {
+ return $this;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function signOn()
- {
- $inviteUsrid = User_Adapter::get_usr_id_from_login('invite');
- $invite_user = User_Adapter::getInstance($inviteUsrid, $this->appbox);
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function signOn()
+ {
+ $inviteUsrid = User_Adapter::get_usr_id_from_login('invite');
+ $invite_user = User_Adapter::getInstance($inviteUsrid, $this->appbox);
- $usr_base_ids = array_keys($this->user->ACL()->get_granted_base());
- $this->user->ACL()->revoke_access_from_bases($usr_base_ids);
+ $usr_base_ids = array_keys($this->user->ACL()->get_granted_base());
+ $this->user->ACL()->revoke_access_from_bases($usr_base_ids);
- $invite_base_ids = array_keys($invite_user->ACL()->get_granted_base());
- $this->user->ACL()->apply_model($invite_user, $invite_base_ids);
+ $invite_base_ids = array_keys($invite_user->ACL()->get_granted_base());
+ $this->user->ACL()->apply_model($invite_user, $invite_base_ids);
- return $this->user;
- }
-
- /**
- *
- * @return Session_Authentication_Guest
- */
- public function postlog()
- {
- return $this;
- }
+ return $this->user;
+ }
+ /**
+ *
+ * @return Session_Authentication_Guest
+ */
+ public function postlog()
+ {
+ return $this;
+ }
}
diff --git a/lib/classes/Session/Authentication/Interface.class.php b/lib/classes/Session/Authentication/Interface.class.php
index 13c9735b16..bea6b93629 100644
--- a/lib/classes/Session/Authentication/Interface.class.php
+++ b/lib/classes/Session/Authentication/Interface.class.php
@@ -18,30 +18,31 @@
interface Session_Authentication_Interface
{
- /**
- * Pre execution after authentication
- *
- * @return Session_Authentication_Interface
- */
- public function prelog();
+ /**
+ * Pre execution after authentication
+ *
+ * @return Session_Authentication_Interface
+ */
+ public function prelog();
- /**
- * Verify the authentication
- *
- * @return User_Adapter
- */
- public function signOn();
- /**
- * Give the user related to the object
- *
- * @return User_Adapter
- */
- public function get_user();
+ /**
+ * Verify the authentication
+ *
+ * @return User_Adapter
+ */
+ public function signOn();
- /**
- * Post execution after authentication
- *
- * @return Session_Authentication_Interface
- */
- public function postlog();
+ /**
+ * Give the user related to the object
+ *
+ * @return User_Adapter
+ */
+ public function get_user();
+
+ /**
+ * Post execution after authentication
+ *
+ * @return Session_Authentication_Interface
+ */
+ public function postlog();
}
diff --git a/lib/classes/Session/Authentication/Native.class.php b/lib/classes/Session/Authentication/Native.class.php
index c3e96cddfe..4293450b99 100644
--- a/lib/classes/Session/Authentication/Native.class.php
+++ b/lib/classes/Session/Authentication/Native.class.php
@@ -18,144 +18,144 @@
*/
class Session_Authentication_Native implements Session_Authentication_Interface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var boolean
- */
- protected $captcha_challenge_result;
- /**
- *
- * @var string
- */
- protected $login;
- /**
- *
- * @var password
- */
- protected $password;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @var boolean
+ */
+ protected $captcha_challenge_result;
- /**
- *
- * @param appbox $appbox
- * @param string $login
- * @param string $password
- * @return Session_Authentication_Native
- */
- public function __construct(appbox &$appbox, $login, $password)
- {
- $this->appbox = $appbox;
- $this->login = $login;
- $this->password = $password;
+ /**
+ *
+ * @var string
+ */
+ protected $login;
- try
+ /**
+ *
+ * @var password
+ */
+ protected $password;
+
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param string $login
+ * @param string $password
+ * @return Session_Authentication_Native
+ */
+ public function __construct(appbox &$appbox, $login, $password)
{
- $usr_id = User_Adapter::get_usr_id_from_login($this->login);
- $this->user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- throw new Exception_Unauthorized('User does not exists anymore');
+ $this->appbox = $appbox;
+ $this->login = $login;
+ $this->password = $password;
+
+ try {
+ $usr_id = User_Adapter::get_usr_id_from_login($this->login);
+ $this->user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ throw new Exception_Unauthorized('User does not exists anymore');
+ }
+
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
+ /**
+ *
+ * @param boolean $captcha_challenge_result
+ * @return Session_Authentication_Native
+ */
+ public function set_captcha_challenge($captcha_challenge_result)
+ {
+ $this->captcha_challenge_result = $captcha_challenge_result;
- /**
- *
- * @param boolean $captcha_challenge_result
- * @return Session_Authentication_Native
- */
- public function set_captcha_challenge($captcha_challenge_result)
- {
- $this->captcha_challenge_result = $captcha_challenge_result;
+ return $this;
+ }
- return $this;
- }
+ public function prelog()
+ {
+ return $this;
+ }
- public function prelog()
- {
- return $this;
- }
-
- /**
- *
- * @return user_Adapter
- */
- public function signOn()
- {
- $browser = Browser::getInstance();
- $this->check_and_revoke_badlogs($browser->getIP());
+ /**
+ *
+ * @return user_Adapter
+ */
+ public function signOn()
+ {
+ $browser = Browser::getInstance();
+ $this->check_and_revoke_badlogs($browser->getIP());
- $this->check_bad_salinity()
+ $this->check_bad_salinity()
->check_mail_locked()
->challenge_password($browser);
- return $this->user;
- }
+ return $this->user;
+ }
- /**
- *
- * @return Session_Authentication_Native
- */
- public function postlog()
- {
- return $this;
- }
+ /**
+ *
+ * @return Session_Authentication_Native
+ */
+ public function postlog()
+ {
+ return $this;
+ }
- /**
- * Verify if the current user has not verified is account by email
- *
- * @return Session_Authentication_Native
- */
- protected function check_mail_locked()
- {
- $conn = $this->appbox->get_connection();
+ /**
+ * Verify if the current user has not verified is account by email
+ *
+ * @return Session_Authentication_Native
+ */
+ protected function check_mail_locked()
+ {
+ $conn = $this->appbox->get_connection();
- $sql = 'SELECT mail_locked, usr_id
+ $sql = 'SELECT mail_locked, usr_id
FROM usr
WHERE usr_id = :usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->user->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->user->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($row && $row['mail_locked'] == "1")
- throw new Exception_Session_MailLocked($this->user->get_id());
+ if ($row && $row['mail_locked'] == "1")
+ throw new Exception_Session_MailLocked($this->user->get_id());
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param Browser $browser
- * @return Session_Authentication_Native
- */
- public function challenge_password(Browser $browser =null)
- {
- $conn = $this->appbox->get_connection();
+ /**
+ *
+ * @param Browser $browser
+ * @return Session_Authentication_Native
+ */
+ public function challenge_password(Browser $browser = null)
+ {
+ $conn = $this->appbox->get_connection();
- $sql = 'SELECT usr_id
+ $sql = 'SELECT usr_id
FROM usr
WHERE usr_login = :login
AND usr.usr_password = :password
@@ -164,135 +164,129 @@ class Session_Authentication_Native implements Session_Authentication_Interface
AND salted_password = 1
AND model_of="0" AND invite="0"';
- $salt = User_Adapter::salt_password($this->password, $this->user->get_nonce());
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(
- ':login' => $this->login,
- ':password' => $salt
- ));
+ $salt = User_Adapter::salt_password($this->password, $this->user->get_nonce());
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(
+ ':login' => $this->login,
+ ':password' => $salt
+ ));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (count($rs) == 0)
- {
- if ($browser instanceof Browser)
- $this->save_badlog($browser);
- throw new Exception_Unauthorized('Bad login/Password');
+ if (count($rs) == 0) {
+ if ($browser instanceof Browser)
+ $this->save_badlog($browser);
+ throw new Exception_Unauthorized('Bad login/Password');
+ }
+
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @param Browser $browser
+ * @return Session_Authentication_Native
+ */
+ protected function save_badlog(Browser $browser)
+ {
+ $conn = $this->appbox->get_connection();
+ $date_obj = new DateTime('-5 month');
- /**
- *
- * @param Browser $browser
- * @return Session_Authentication_Native
- */
- protected function save_badlog(Browser $browser)
- {
- $conn = $this->appbox->get_connection();
- $date_obj = new DateTime('-5 month');
+ $sql = 'DELETE FROM badlog WHERE date < :date';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':date' => phraseadate::format_mysql($date_obj)));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM badlog WHERE date < :date';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':date' => phraseadate::format_mysql($date_obj)));
- $stmt->closeCursor();
-
- $sql = 'INSERT INTO badlog (date,login,pwd,ip,locked)
+ $sql = 'INSERT INTO badlog (date,login,pwd,ip,locked)
VALUES (NOW(), :login, :password, :ip, "1")';
- $params = array(
- ':login' => $this->login
- , ':password' => $this->password
- , ':ip' => $browser->getIP()
- );
+ $params = array(
+ ':login' => $this->login
+ , ':password' => $this->password
+ , ':ip' => $browser->getIP()
+ );
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Session_Authentication_Native
- */
- protected function check_bad_salinity()
- {
- $sql = 'SELECT salted_password
+ /**
+ *
+ * @return Session_Authentication_Native
+ */
+ protected function check_bad_salinity()
+ {
+ $sql = 'SELECT salted_password
FROM usr
WHERE usr_login = :login AND usr_password = :password';
- $params = array(
- ':login' => $this->login,
- ':password' => hash('sha256', $this->password)
- );
+ $params = array(
+ ':login' => $this->login,
+ ':password' => hash('sha256', $this->password)
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($row && $row['salted_password'] === '0')
- throw new Exception_Session_BadSalinity();
+ if ($row && $row['salted_password'] === '0')
+ throw new Exception_Session_BadSalinity();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param string $ip
- * @return Session_Authentication_Native
- */
- protected function check_and_revoke_badlogs($ip)
- {
- $conn = $this->appbox->get_connection();
- $registry = $this->appbox->get_registry();
+ /**
+ *
+ * @param string $ip
+ * @return Session_Authentication_Native
+ */
+ protected function check_and_revoke_badlogs($ip)
+ {
+ $conn = $this->appbox->get_connection();
+ $registry = $this->appbox->get_registry();
- $sql = 'SELECT id FROM badlog
+ $sql = 'SELECT id FROM badlog
WHERE (login = :login OR ip = :ip) AND locked="1"';
- $params = array(':login' => $this->login, ':ip' => $ip);
+ $params = array(':login' => $this->login, ':ip' => $ip);
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $row_count = $stmt->rowCount();
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $row_count = $stmt->rowCount();
+ $stmt->closeCursor();
- if ($row_count == 0)
+ if ($row_count == 0)
+ return $this;
- return $this;
+ if ($this->captcha_challenge_result === true) {
+ $sql = 'UPDATE badlog SET locked="0" WHERE (login=:login OR ip=:ip)';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':login' => $this->login, ':ip' => $ip));
+ $stmt->closeCursor();
+ } elseif ($row_count > 9) {
+ if ($this->is_captcha_activated($registry))
+ throw new Exception_Session_RequireCaptcha();
+ }
- if ($this->captcha_challenge_result === true)
- {
- $sql = 'UPDATE badlog SET locked="0" WHERE (login=:login OR ip=:ip)';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':login' => $this->login, ':ip' => $ip));
- $stmt->closeCursor();
- }
- elseif ($row_count > 9)
- {
- if ($this->is_captcha_activated($registry))
- throw new Exception_Session_RequireCaptcha();
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @return boolean
- */
- protected function is_captcha_activated(registryInterface $registry)
- {
- $registry = $this->appbox->get_registry();
-
- return ($registry->get('GV_captchas')
- && trim($registry->get('GV_captcha_private_key')) !== ''
- && trim($registry->get('GV_captcha_public_key') !== ''));
- }
+ /**
+ *
+ * @param registryInterface $registry
+ * @return boolean
+ */
+ protected function is_captcha_activated(registryInterface $registry)
+ {
+ $registry = $this->appbox->get_registry();
+ return ($registry->get('GV_captchas')
+ && trim($registry->get('GV_captcha_private_key')) !== ''
+ && trim($registry->get('GV_captcha_public_key') !== ''));
+ }
}
diff --git a/lib/classes/Session/Authentication/None.class.php b/lib/classes/Session/Authentication/None.class.php
index c10375be2d..539256a194 100644
--- a/lib/classes/Session/Authentication/None.class.php
+++ b/lib/classes/Session/Authentication/None.class.php
@@ -17,59 +17,57 @@
*/
class Session_Authentication_None implements Session_Authentication_Interface
{
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
+ /**
+ *
+ * @param User_Adapter $user
+ * @return Session_Authentication_None
+ */
+ public function __construct(User_Adapter $user)
+ {
+ $this->user = $user;
- /**
- *
- * @param User_Adapter $user
- * @return Session_Authentication_None
- */
- public function __construct(User_Adapter $user)
- {
- $this->user = $user;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return Session_Authentication_None
+ */
+ public function prelog()
+ {
+ return $this;
+ }
- /**
- *
- * @return Session_Authentication_None
- */
- public function prelog()
- {
- return $this;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
-
- /**
- *
- * @return User_Adapter
- */
- public function signOn()
- {
- return $this->user;
- }
-
- /**
- *
- * @return Session_Authentication_None
- */
- public function postlog()
- {
- return $this;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function signOn()
+ {
+ return $this->user;
+ }
+ /**
+ *
+ * @return Session_Authentication_None
+ */
+ public function postlog()
+ {
+ return $this;
+ }
}
diff --git a/lib/classes/Session/Authentication/PersistentCookie.class.php b/lib/classes/Session/Authentication/PersistentCookie.class.php
index eab3f23919..f2330aa5d8 100644
--- a/lib/classes/Session/Authentication/PersistentCookie.class.php
+++ b/lib/classes/Session/Authentication/PersistentCookie.class.php
@@ -17,101 +17,98 @@
*/
class Session_Authentication_PersistentCookie implements Session_Authentication_Interface
{
+ /**
+ *
+ * @var type
+ */
+ protected $appbox;
- /**
- *
- * @var type
- */
- protected $appbox;
+ /**
+ *
+ * @var type
+ */
+ protected $persistent_cookie;
- /**
- *
- * @var type
- */
- protected $persistent_cookie;
- /**
- *
- * @var int
- */
- protected $ses_id;
+ /**
+ *
+ * @var int
+ */
+ protected $ses_id;
- /**
- *
- * @param appbox $appbox
- * @param type $persistent_cookie
- * @return Session_Authentication_PersistentCookie
- */
- public function __construct(appbox &$appbox, $persistent_cookie)
- {
- $this->appbox = $appbox;
- $this->persistent_cookie = $persistent_cookie;
-
- $browser = Browser::getInstance();
-
- $conn = $this->appbox->get_connection();
- $sql = 'SELECT usr_id, session_id, nonce, token FROM cache WHERE token = :token';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':token' => $this->persistent_cookie));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if (!$row || count($row) == 0)
+ /**
+ *
+ * @param appbox $appbox
+ * @param type $persistent_cookie
+ * @return Session_Authentication_PersistentCookie
+ */
+ public function __construct(appbox &$appbox, $persistent_cookie)
{
- throw new Exception_Session_WrongToken();
+ $this->appbox = $appbox;
+ $this->persistent_cookie = $persistent_cookie;
+
+ $browser = Browser::getInstance();
+
+ $conn = $this->appbox->get_connection();
+ $sql = 'SELECT usr_id, session_id, nonce, token FROM cache WHERE token = :token';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':token' => $this->persistent_cookie));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ( ! $row || count($row) == 0) {
+ throw new Exception_Session_WrongToken();
+ }
+
+ $string = $browser->getBrowser() . '_' . $browser->getPlatform();
+
+ if (User_Adapter::salt_password($string, $row['nonce']) !== $row['token']) {
+ throw new Exception_Session_WrongToken();
+ }
+
+ $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ $this->ses_id = (int) $row['session_id'];
+
+ return $this;
}
- $string = $browser->getBrowser().'_'.$browser->getPlatform();
-
- if (User_Adapter::salt_password($string, $row['nonce']) !== $row['token'])
+ public function prelog()
{
- throw new Exception_Session_WrongToken();
+ return $this;
}
- $this->user = User_Adapter::getInstance($row['usr_id'], $this->appbox);
- $this->ses_id = (int) $row['session_id'];
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
+ return $this->user;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_ses_id()
+ {
+ return $this->ses_id;
+ }
- public function prelog()
- {
- return $this;
- }
-
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
- return $this->user;
- }
-
- /**
- *
- * @return int
- */
- public function get_ses_id()
- {
- return $this->ses_id;
- }
-
- /**
- *
- * @return User_Adapter
- */
- public function signOn()
- {
- return $this->user;
- }
-
- /**
- *
- * @return Session_Authentication_PersistentCookie
- */
- public function postlog()
- {
- return $this;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function signOn()
+ {
+ return $this->user;
+ }
+ /**
+ *
+ * @return Session_Authentication_PersistentCookie
+ */
+ public function postlog()
+ {
+ return $this;
+ }
}
diff --git a/lib/classes/Session/Authentication/Token.class.php b/lib/classes/Session/Authentication/Token.class.php
index 7727bd69dc..bd6dbfdee1 100644
--- a/lib/classes/Session/Authentication/Token.class.php
+++ b/lib/classes/Session/Authentication/Token.class.php
@@ -17,79 +17,76 @@
*/
class Session_Authentication_Token implements Session_Authentication_Interface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var string
- */
- protected $token;
- protected $user;
+ /**
+ *
+ * @var string
+ */
+ protected $token;
+ protected $user;
- /**
- *
- * @param appbox $appbox
- * @param type $token
- * @return Session_Authentication_Token
- */
- public function __construct(appbox &$appbox, $token)
- {
- $this->appbox = $appbox;
- $this->token = $token;
-
- try
+ /**
+ *
+ * @param appbox $appbox
+ * @param type $token
+ * @return Session_Authentication_Token
+ */
+ public function __construct(appbox &$appbox, $token)
{
- $datas = random::helloToken($token);
- $usr_id = $datas['usr_id'];
- $this->user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception_NotFound $e)
- {
- throw new Exception_Session_WrongToken();
+ $this->appbox = $appbox;
+ $this->token = $token;
+
+ try {
+ $datas = random::helloToken($token);
+ $usr_id = $datas['usr_id'];
+ $this->user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception_NotFound $e) {
+ throw new Exception_Session_WrongToken();
+ }
+
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @return Session_Authentication_Token
+ */
+ public function prelog()
+ {
+ return $this;
+ }
- /**
- *
- * @return Session_Authentication_Token
- */
- public function prelog()
- {
- return $this;
- }
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function signOn()
+ {
- /**
- *
- * @return User_Adapter
- */
- public function signOn()
- {
+ return $this->user;
+ }
- return $this->user;
- }
- /**
- *
- * @return User_Adapter
- */
- public function get_user()
- {
+ /**
+ *
+ * @return User_Adapter
+ */
+ public function get_user()
+ {
- return $this->user;
- }
-
- /**
- *
- * @return Session_Authentication_Token
- */
- public function postlog()
- {
- return $this;
- }
+ return $this->user;
+ }
+ /**
+ *
+ * @return Session_Authentication_Token
+ */
+ public function postlog()
+ {
+ return $this;
+ }
}
diff --git a/lib/classes/Session/Handler.class.php b/lib/classes/Session/Handler.class.php
index f14c99d0c4..34e7ffa1dc 100644
--- a/lib/classes/Session/Handler.class.php
+++ b/lib/classes/Session/Handler.class.php
@@ -17,587 +17,556 @@
*/
class Session_Handler
{
+ /**
+ *
+ * @var Session_Handler
+ */
+ protected static $_instance;
- /**
- *
- * @var Session_Handler
- */
- protected static $_instance;
+ /**
+ *
+ * @var Session_Storage_Interface
+ */
+ protected $session_storage;
- /**
- *
- * @var Session_Storage_Interface
- */
- protected $session_storage;
+ /**
+ *
+ * @var Session_Phrasea
+ */
+ protected $phrasea_session;
+ protected $appbox;
+ protected static $_cookie;
- /**
- *
- * @var Session_Phrasea
- */
- protected $phrasea_session;
- protected $appbox;
- protected static $_cookie;
-
- /**
- * Constructor
- *
- * @return Session_Handler
- */
- protected function __construct(appbox &$appbox)
- {
- $this->appbox = $appbox;
- $this->init_session_storage();
-
- if ($this->is_authenticated())
+ /**
+ * Constructor
+ *
+ * @return Session_Handler
+ */
+ protected function __construct(appbox &$appbox)
{
- try
- {
- $user = User_Adapter::getInstance($this->get_usr_id(), $appbox);
- $this->restore($user, $this->get_ses_id());
- }
- catch (Exception $e)
- {
- $this->close_phrasea_session();
- }
+ $this->appbox = $appbox;
+ $this->init_session_storage();
+
+ if ($this->is_authenticated()) {
+ try {
+ $user = User_Adapter::getInstance($this->get_usr_id(), $appbox);
+ $this->restore($user, $this->get_ses_id());
+ } catch (Exception $e) {
+ $this->close_phrasea_session();
+ }
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @return Session_Handler
- */
- public static function getInstance(appbox &$appbox)
- {
- if (!self::$_instance)
+ /**
+ *
+ * @return Session_Handler
+ */
+ public static function getInstance(appbox &$appbox)
{
- self::$_instance = new self($appbox);
+ if ( ! self::$_instance) {
+ self::$_instance = new self($appbox);
+ }
+
+ return self::$_instance;
}
- return self::$_instance;
- }
-
- /**
- *
- * @return Void
- */
- public function logout()
- {
+ /**
+ *
+ * @return Void
+ */
+ public function logout()
+ {
// $this->remove_cookies();
- if (!$this->is_authenticated())
+ if ( ! $this->is_authenticated())
+ return;
- return;
+ $this->storage()->reset();
+ $this->close_phrasea_session();
- $this->storage()->reset();
- $this->close_phrasea_session();
+ return;
+ }
- return;
- }
+ /**
+ *
+ * @return Session_Storage_Interface
+ */
+ public function storage()
+ {
+ return $this->session_storage;
+ }
- /**
- *
- * @return Session_Storage_Interface
- */
- public function storage()
- {
- return $this->session_storage;
- }
+ /**
+ * Close the session storage. It can't be re-opened after that
+ *
+ * @return Session_Handler
+ */
+ public function close_storage()
+ {
+ $this->storage()->close();
- /**
- * Close the session storage. It can't be re-opened after that
- *
- * @return Session_Handler
- */
- public function close_storage()
- {
- $this->storage()->close();
+ return $this;
+ }
- return $this;
- }
+ /**
+ * Get the current locale used in this session
+ *
+ * @return string
+ */
+ public static function get_locale()
+ {
+ return self::get_cookie('locale');
+ }
- /**
- * Get the current locale used in this session
- *
- * @return string
- */
- public static function get_locale()
- {
- return self::get_cookie('locale');
- }
+ /**
+ * Set the locale used in this session
+ *
+ * @param string $value under the form i18n_l10n (de_DE, en_US...)
+ * @return Session_Handler;
+ */
+ public static function set_locale($value)
+ {
+ if ((self::isset_cookie('locale') && self::get_cookie('locale') != $value) || ! self::isset_cookie('locale'))
+ self::set_cookie("locale", $value, 0, false);
+ }
- /**
- * Set the locale used in this session
- *
- * @param string $value under the form i18n_l10n (de_DE, en_US...)
- * @return Session_Handler;
- */
- public static function set_locale($value)
- {
- if ((self::isset_cookie('locale') && self::get_cookie('locale') != $value) || !self::isset_cookie('locale'))
- self::set_cookie("locale", $value, 0, false);
- }
+ /**
+ * Get the localization code
+ *
+ * @return string
+ */
+ public function get_l10n()
+ {
+ return array_pop(explode('_', self::get_locale()));
+ }
- /**
- * Get the localization code
- *
- * @return string
- */
- public function get_l10n()
- {
- return array_pop(explode('_', self::get_locale()));
- }
+ /**
+ * Gets the internationalization code
+ *
+ * @return string
+ */
+ public function get_I18n()
+ {
+ return array_shift(explode('_', self::get_locale()));
+ }
- /**
- * Gets the internationalization code
- *
- * @return string
- */
- public function get_I18n()
- {
- return array_shift(explode('_', self::get_locale()));
- }
-
- /**
- * Returns wheter or not it's authenticated
- *
- * @return boolean
- */
- public function is_authenticated()
- {
- return ($this->storage()->has('ses_id') === true &&
+ /**
+ * Returns wheter or not it's authenticated
+ *
+ * @return boolean
+ */
+ public function is_authenticated()
+ {
+ return ($this->storage()->has('ses_id') === true &&
$this->storage()->has('usr_id') === true);
- }
-
- /**
- * Get the usr_id of the owner
- *
- * @deprecated
- * @return int
- */
- public function get_usr_id()
- {
- return $this->storage()->get('usr_id', null);
- }
-
- /**
- * Get the ses_id of the owner
- *
- * @return type
- */
- public function get_ses_id()
- {
- return $this->storage()->get('ses_id', null);
- }
-
- public function isset_postlog()
- {
- return $this->storage()->has('postlog');
- }
-
- public function set_postlog($boolean)
- {
- return $this->storage()->set('postlog', $boolean);
- }
-
- public function get_postlog()
- {
- return $this->storage()->get('postlog');
- }
-
- public function delete_postlog()
- {
- return $this->storage()->remove('postlog');
- }
-
- /**
- * Set temporary preference (till the session ends)
- *
- * @param string $key
- * @param mixed $value
- * @return Session_Handler
- */
- public function set_session_prefs($key, $value)
- {
- $datas = $this->storage()->get('temp_prefs');
- $datas[$key] = $value;
- $this->storage()->set('temp_prefs', $datas);
-
- return $this;
- }
-
- /**
- *
- * @param string $key
- * @return mixed
- */
- public function get_session_prefs($key)
- {
- $datas = $this->storage()->get('temp_prefs');
- if (isset($datas[$key]))
-
- return $datas[$key];
- return null;
- }
-
- /**
- *
- * @param string $name
- * @param mixed $default_value
- * @return mixed
- */
- public static function get_cookie($name, $default_value = null)
- {
- if (http_request::is_command_line() && isset(self::$_cookie[$name]))
-
- return self::$_cookie[$name];
- elseif (!http_request::is_command_line() && isset($_COOKIE[$name]))
-
- return $_COOKIE[$name];
- elseif ($default_value !== null)
-
- return $default_value;
- return null;
- }
-
- /**
- *
- * @param string $name
- * @param mixed $value
- * @param int $avalaibility
- * @param boolean $http_only
- * @return boolean
- */
- public static function set_cookie($name, $value, $avalaibility, $http_only)
- {
- $https = false;
- if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'])
- $https = true;
-
- $expire = $avalaibility === 0 ? 0 : time() + (int) $avalaibility;
-
- $http_only = !!$http_only;
-
- if ($avalaibility >= 0)
- {
- if (http_request::is_command_line())
- self::$_cookie[$name] = $value;
- else
- $_COOKIE[$name] = $value;
}
- else
+
+ /**
+ * Get the usr_id of the owner
+ *
+ * @deprecated
+ * @return int
+ */
+ public function get_usr_id()
{
- if (http_request::is_command_line() && isset(self::$_cookie[$name]))
- unset(self::$_cookie[$name]);
- else
- unset($_COOKIE[$name]);
+ return $this->storage()->get('usr_id', null);
}
- if (!http_request::is_command_line())
- return setcookie($name, $value, $expire, '/', '', $https, $http_only);
- else
+ /**
+ * Get the ses_id of the owner
+ *
+ * @return type
+ */
+ public function get_ses_id()
+ {
+ return $this->storage()->get('ses_id', null);
+ }
- return true;
- }
+ public function isset_postlog()
+ {
+ return $this->storage()->has('postlog');
+ }
- /**
- *
- * @param string $name
- * @return boolean
- */
- public static function isset_cookie($name)
- {
- if (http_request::is_command_line())
+ public function set_postlog($boolean)
+ {
+ return $this->storage()->set('postlog', $boolean);
+ }
- return isset(self::$_cookie[$name]);
- else
+ public function get_postlog()
+ {
+ return $this->storage()->get('postlog');
+ }
- return isset($_COOKIE[$name]);
- }
+ public function delete_postlog()
+ {
+ return $this->storage()->remove('postlog');
+ }
- public function renew_phrasea_session()
- {
- if (!$this->phrasea_session instanceof Session_Phrasea)
- throw new \Exception('No phrasea session available');
+ /**
+ * Set temporary preference (till the session ends)
+ *
+ * @param string $key
+ * @param mixed $value
+ * @return Session_Handler
+ */
+ public function set_session_prefs($key, $value)
+ {
+ $datas = $this->storage()->get('temp_prefs');
+ $datas[$key] = $value;
+ $this->storage()->set('temp_prefs', $datas);
- $this->phrasea_session->close();
+ return $this;
+ }
- $user = \User_Adapter::getInstance($this->get_usr_id(), $this->appbox);
+ /**
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function get_session_prefs($key)
+ {
+ $datas = $this->storage()->get('temp_prefs');
+ if (isset($datas[$key]))
+ return $datas[$key];
+ return null;
+ }
- $this->phrasea_session = new Session_Phrasea($this->appbox, $user);
- $this->phrasea_session->create(\Browser::getInstance());
+ /**
+ *
+ * @param string $name
+ * @param mixed $default_value
+ * @return mixed
+ */
+ public static function get_cookie($name, $default_value = null)
+ {
+ if (http_request::is_command_line() && isset(self::$_cookie[$name]))
+ return self::$_cookie[$name];
+ elseif ( ! http_request::is_command_line() && isset($_COOKIE[$name]))
+ return $_COOKIE[$name];
+ elseif ($default_value !== null)
+ return $default_value;
+ return null;
+ }
- $this->phrasea_session->open();
- $ses_id = $this->phrasea_session->get_id();
+ /**
+ *
+ * @param string $name
+ * @param mixed $value
+ * @param int $avalaibility
+ * @param boolean $http_only
+ * @return boolean
+ */
+ public static function set_cookie($name, $value, $avalaibility, $http_only)
+ {
+ $https = false;
+ if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'])
+ $https = true;
- $this->storage()->set('usr_id', $user->get_id());
- $this->storage()->set('ses_id', $ses_id);
- }
+ $expire = $avalaibility === 0 ? 0 : time() + (int) $avalaibility;
- /**
- * Open the phrasea session
- *
- * @return Session_Handler
- */
- public function open_phrasea_session()
- {
- if (!$this->phrasea_session instanceof Session_Phrasea)
- throw new \Exception('No phrasea session available');
+ $http_only = ! ! $http_only;
- $this->phrasea_session->open();
+ if ($avalaibility >= 0) {
+ if (http_request::is_command_line())
+ self::$_cookie[$name] = $value;
+ else
+ $_COOKIE[$name] = $value;
+ }
+ else {
+ if (http_request::is_command_line() && isset(self::$_cookie[$name]))
+ unset(self::$_cookie[$name]);
+ else
+ unset($_COOKIE[$name]);
+ }
+ if ( ! http_request::is_command_line())
+ return setcookie($name, $value, $expire, '/', '', $https, $http_only);
+ else
+ return true;
+ }
- return $this;
- }
+ /**
+ *
+ * @param string $name
+ * @return boolean
+ */
+ public static function isset_cookie($name)
+ {
+ if (http_request::is_command_line())
+ return isset(self::$_cookie[$name]);
+ else
+ return isset($_COOKIE[$name]);
+ }
- /**
- *
- * @param User_Adapter $user
- * @param type $ses_id
- */
- public function restore(User_Adapter $user, $ses_id)
- {
+ public function renew_phrasea_session()
+ {
+ if ( ! $this->phrasea_session instanceof Session_Phrasea)
+ throw new \Exception('No phrasea session available');
+
+ $this->phrasea_session->close();
+
+ $user = \User_Adapter::getInstance($this->get_usr_id(), $this->appbox);
+
+ $this->phrasea_session = new Session_Phrasea($this->appbox, $user);
+ $this->phrasea_session->create(\Browser::getInstance());
+
+ $this->phrasea_session->open();
+ $ses_id = $this->phrasea_session->get_id();
+
+ $this->storage()->set('usr_id', $user->get_id());
+ $this->storage()->set('ses_id', $ses_id);
+ }
+
+ /**
+ * Open the phrasea session
+ *
+ * @return Session_Handler
+ */
+ public function open_phrasea_session()
+ {
+ if ( ! $this->phrasea_session instanceof Session_Phrasea)
+ throw new \Exception('No phrasea session available');
+
+ $this->phrasea_session->open();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param User_Adapter $user
+ * @param type $ses_id
+ */
+ public function restore(User_Adapter $user, $ses_id)
+ {
// if ($this->is_authenticated())
// $this->close_phrasea_session();
- $this->phrasea_session = new Session_Phrasea($this->appbox, $user, $ses_id);
- $this->phrasea_session->open();
- $ses_id = $this->phrasea_session->get_id();
- $this->storage()->set('usr_id', $user->get_id());
- $this->storage()->set('ses_id', $ses_id);
- }
-
- /**
- * Process the authentication
- *
- * @param Session_Authentication_Interface $auth
- * @return Session_Handler
- */
- public function authenticate(Session_Authentication_Interface $auth)
- {
- if ($this->appbox->get_registry()->get('GV_maintenance'))
- {
- throw new Exception_ServiceUnavailable();
+ $this->phrasea_session = new Session_Phrasea($this->appbox, $user, $ses_id);
+ $this->phrasea_session->open();
+ $ses_id = $this->phrasea_session->get_id();
+ $this->storage()->set('usr_id', $user->get_id());
+ $this->storage()->set('ses_id', $ses_id);
}
- $registry = $this->appbox->get_registry();
-
- $conn = $this->appbox->get_connection();
- $browser = Browser::getInstance();
-
- $sbases = array();
-
- $this->send_reminders();
-
- $auth->prelog();
- if ($this->is_authenticated() && $this->get_usr_id() == $auth->get_user()->get_id())
+ /**
+ * Process the authentication
+ *
+ * @param Session_Authentication_Interface $auth
+ * @return Session_Handler
+ */
+ public function authenticate(Session_Authentication_Interface $auth)
{
- return $this;
- }
- if ($this->is_authenticated() && $this->get_usr_id() != $auth->get_user()->get_id())
- {
- $this->close_phrasea_session();
- }
+ if ($this->appbox->get_registry()->get('GV_maintenance')) {
+ throw new Exception_ServiceUnavailable();
+ }
- $user = $auth->signOn();
- $usr_id = $user->get_id();
+ $registry = $this->appbox->get_registry();
- $this->phrasea_session = new Session_Phrasea($this->appbox, $user);
- $this->phrasea_session->create($browser);
- $ses_id = $this->phrasea_session->get_id();
- $this->storage()->set('usr_id', $usr_id);
- $this->storage()->set('ses_id', $ses_id);
+ $conn = $this->appbox->get_connection();
+ $browser = Browser::getInstance();
- $locale = $this->storage()->get('locale', $user->get_locale($usr_id));
- $this->storage()->set('locale', $locale);
- $user->ACL()->inject_rights();
+ $sbases = array();
- foreach ($user->ACL()->get_granted_sbas() as $databox)
- {
- Session_Logger::create($databox, $browser, $this, $user);
- \cache_databox::insertClient($databox);
- }
+ $this->send_reminders();
- $this->set_usr_lastconn($conn, $user->get_id());
- $this->delete_postlog();
+ $auth->prelog();
+ if ($this->is_authenticated() && $this->get_usr_id() == $auth->get_user()->get_id()) {
+ return $this;
+ }
+ if ($this->is_authenticated() && $this->get_usr_id() != $auth->get_user()->get_id()) {
+ $this->close_phrasea_session();
+ }
- $auth->postlog();
- $this->add_persistent_cookie();
- self::set_cookie('last_act', '', -400000, true);
+ $user = $auth->signOn();
+ $usr_id = $user->get_id();
- return $this;
- }
+ $this->phrasea_session = new Session_Phrasea($this->appbox, $user);
+ $this->phrasea_session->create($browser);
+ $ses_id = $this->phrasea_session->get_id();
+ $this->storage()->set('usr_id', $usr_id);
+ $this->storage()->set('ses_id', $ses_id);
- protected function transfer_baskets()
- {
- $conn = $this->appbox->get_connection();
- $transferBasks = ($this->isset_postlog() && $this->get_postlog() === true);
+ $locale = $this->storage()->get('locale', $user->get_locale($usr_id));
+ $this->storage()->set('locale', $locale);
+ $user->ACL()->inject_rights();
- if (!$transferBasks)
- self::set_cookie('last_act', '', -400000, true);
- if ($transferBasks && Session_Handler::isset_cookie('invite-usr_id'))
- {
- $basks = array();
- $oldusr = self::get_cookie('invite-usr_id');
+ foreach ($user->ACL()->get_granted_sbas() as $databox) {
+ Session_Logger::create($databox, $browser, $this, $user);
+ \cache_databox::insertClient($databox);
+ }
- if ($oldusr == $this->get_usr_id())
+ $this->set_usr_lastconn($conn, $user->get_id());
+ $this->delete_postlog();
+
+ $auth->postlog();
+ $this->add_persistent_cookie();
+ self::set_cookie('last_act', '', -400000, true);
return $this;
+ }
- $sql = 'SELECT sselcont_id, s.ssel_id
+ protected function transfer_baskets()
+ {
+ $conn = $this->appbox->get_connection();
+ $transferBasks = ($this->isset_postlog() && $this->get_postlog() === true);
+
+ if ( ! $transferBasks)
+ self::set_cookie('last_act', '', -400000, true);
+ if ($transferBasks && Session_Handler::isset_cookie('invite-usr_id')) {
+ $basks = array();
+ $oldusr = self::get_cookie('invite-usr_id');
+
+ if ($oldusr == $this->get_usr_id())
+ return $this;
+
+ $sql = 'SELECT sselcont_id, s.ssel_id
FROM sselcont c, ssel s
WHERE s.usr_id = :usr_id
AND s.ssel_id = c.ssel_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_usr_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_usr_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $sql = 'UPDATE ssel set usr_id = :usr_id WHERE ssel_id = :ssel_id AND usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
+ $sql = 'UPDATE ssel set usr_id = :usr_id WHERE ssel_id = :ssel_id AND usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
- foreach ($rs as $row)
- {
- $stmt->execute(array(':usr_id' => $this->get_usr_id(), ':ssel_id' => $row['ssel_id'], ':old_usr_id' => $oldusr));
- }
- $stmt->closeCursor();
+ foreach ($rs as $row) {
+ $stmt->execute(array(':usr_id' => $this->get_usr_id(), ':ssel_id' => $row['ssel_id'], ':old_usr_id' => $oldusr));
+ }
+ $stmt->closeCursor();
- $sql = 'DELETE FROM ssel WHERE usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':old_usr_id' => $oldusr));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM ssel WHERE usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':old_usr_id' => $oldusr));
+ $stmt->closeCursor();
- $sql = 'UPDATE dsel SET usr_id = :usr_id WHERE usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_usr_id(), ':old_usr_id' => $oldusr));
- $stmt->closeCursor();
+ $sql = 'UPDATE dsel SET usr_id = :usr_id WHERE usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_usr_id(), ':old_usr_id' => $oldusr));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM usr WHERE usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':old_usr_id' => $oldusr));
- $stmt->closeCursor();
- $sql = 'DELETE FROM basusr WHERE usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':old_usr_id' => $oldusr));
- $stmt->closeCursor();
- $sql = 'DELETE FROM sbasusr WHERE usr_id = :old_usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':old_usr_id' => $oldusr));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM usr WHERE usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':old_usr_id' => $oldusr));
+ $stmt->closeCursor();
+ $sql = 'DELETE FROM basusr WHERE usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':old_usr_id' => $oldusr));
+ $stmt->closeCursor();
+ $sql = 'DELETE FROM sbasusr WHERE usr_id = :old_usr_id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':old_usr_id' => $oldusr));
+ $stmt->closeCursor();
+ }
+
+ return $this;
}
- return $this;
- }
-
- protected function set_usr_lastconn(connection_pdo &$conn, $usr_id)
- {
- $sql = 'UPDATE usr SET last_conn=now(), locale = :locale
+ protected function set_usr_lastconn(connection_pdo &$conn, $usr_id)
+ {
+ $sql = 'UPDATE usr SET last_conn=now(), locale = :locale
WHERE usr_id = :usr_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(
- ':locale' => self::get_locale(),
- ':usr_id' => $usr_id
- ));
- $stmt->closeCursor();
- }
-
- public function add_persistent_cookie()
- {
- $theclient = Browser::getInstance();
- $nonce = random::generatePassword(16);
-
- $string = $theclient->getBrowser() . '_' . $theclient->getPlatform();
-
- $token = User_Adapter::salt_password($string, $nonce);
-
- $sql = 'UPDATE cache SET nonce = :nonce, token = :token WHERE session_id = :ses_id';
-
- $params = array(
- ':nonce' => $nonce,
- ':ses_id' => $this->get_ses_id(),
- ':token' => $token
- );
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- self::set_cookie('persistent', $token, (30 * 24 * 3600), true);
-
- return $this;
- }
-
- protected function init_session_storage()
- {
- $session_name = 'system';
- if (http_request::is_command_line())
- {
- $this->session_storage = Session_Storage_CommandLine::getInstance($session_name);
- }
- else
- {
- $this->session_storage = Session_Storage_PHPSession::getInstance($session_name);
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(
+ ':locale' => self::get_locale(),
+ ':usr_id' => $usr_id
+ ));
+ $stmt->closeCursor();
}
- return $this;
- }
-
- protected function close_phrasea_session()
- {
- if ($this->phrasea_session instanceof Session_Phrasea)
- $this->phrasea_session->close();
- $this->storage()->reset();
-
- return $this;
- }
-
- public function remove_cookies()
- {
- self::set_cookie($this->storage()->getName(), '', -420000, false);
- self::set_cookie('last_act', '{}', -420000, true);
- self::set_cookie('persistent', '', -420000, true);
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @return Session_Logger
- */
- public function get_logger(databox $databox)
- {
- try
+ public function add_persistent_cookie()
{
- return Session_Logger::load($databox, $this);
- }
- catch(Exception_Session_LoggerNotFound $e)
- {
- $user = null;
- $browser = Browser::getInstance();
+ $theclient = Browser::getInstance();
+ $nonce = random::generatePassword(16);
- if($this->is_authenticated())
- $user = User_Adapter::getInstance ($this->get_usr_id (), appbox::get_instance (\bootstrap::getCore()));
+ $string = $theclient->getBrowser() . '_' . $theclient->getPlatform();
- return Session_Logger::create($databox, $browser, $this, $user);
- }
- }
+ $token = User_Adapter::salt_password($string, $nonce);
- protected function send_reminders()
- {
- if (!class_exists('eventsmanager_broker'))
- {
- return $this;
+ $sql = 'UPDATE cache SET nonce = :nonce, token = :token WHERE session_id = :ses_id';
+
+ $params = array(
+ ':nonce' => $nonce,
+ ':ses_id' => $this->get_ses_id(),
+ ':token' => $token
+ );
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ self::set_cookie('persistent', $token, (30 * 24 * 3600), true);
+
+ return $this;
}
- $Core = bootstrap::getCore();
+ protected function init_session_storage()
+ {
+ $session_name = 'system';
+ if (http_request::is_command_line()) {
+ $this->session_storage = Session_Storage_CommandLine::getInstance($session_name);
+ } else {
+ $this->session_storage = Session_Storage_PHPSession::getInstance($session_name);
+ }
- $registry = $Core->getRegistry();
- $date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days');
+ return $this;
+ }
- $events_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
+ protected function close_phrasea_session()
+ {
+ if ($this->phrasea_session instanceof Session_Phrasea)
+ $this->phrasea_session->close();
+ $this->storage()->reset();
- $sql = 'SELECT v.id as validate_id, v.usr_id, v.ssel_id
+ return $this;
+ }
+
+ public function remove_cookies()
+ {
+ self::set_cookie($this->storage()->getName(), '', -420000, false);
+ self::set_cookie('last_act', '{}', -420000, true);
+ self::set_cookie('persistent', '', -420000, true);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param databox $databox
+ * @return Session_Logger
+ */
+ public function get_logger(databox $databox)
+ {
+ try {
+ return Session_Logger::load($databox, $this);
+ } catch (Exception_Session_LoggerNotFound $e) {
+ $user = null;
+ $browser = Browser::getInstance();
+
+ if ($this->is_authenticated())
+ $user = User_Adapter::getInstance($this->get_usr_id(), appbox::get_instance(\bootstrap::getCore()));
+
+ return Session_Logger::create($databox, $browser, $this, $user);
+ }
+ }
+
+ protected function send_reminders()
+ {
+ if ( ! class_exists('eventsmanager_broker')) {
+ return $this;
+ }
+
+ $Core = bootstrap::getCore();
+
+ $registry = $Core->getRegistry();
+ $date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days');
+
+ $events_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
+
+ $sql = 'SELECT v.id as validate_id, v.usr_id, v.ssel_id
, s.usr_id as owner, t.value
FROM (validate v, ssel s)
INNER JOIN tokens t
@@ -606,155 +575,134 @@ class Session_Handler
WHERE expires_on < :expires_on
AND ISNULL(last_reminder) AND confirmed="0" AND s.ssel_id = v.ssel_id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':expires_on' => phraseadate::format_mysql($date_two_day)));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':expires_on' => phraseadate::format_mysql($date_two_day)));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $params = array(
- 'to' => $row['usr_id'],
- 'ssel_id' => $row['ssel_id'],
- 'from' => $row['owner'],
- 'validate_id' => $row['validate_id'],
- 'url' => $registry->get('GV_ServerName')
- . 'lightbox/validate/'.$row['ssel_id'].'/?LOG=' . $row['value']
- );
+ foreach ($rs as $row) {
+ $params = array(
+ 'to' => $row['usr_id'],
+ 'ssel_id' => $row['ssel_id'],
+ 'from' => $row['owner'],
+ 'validate_id' => $row['validate_id'],
+ 'url' => $registry->get('GV_ServerName')
+ . 'lightbox/validate/' . $row['ssel_id'] . '/?LOG=' . $row['value']
+ );
- $events_mngr->trigger('__VALIDATION_REMINDER__', $params);
+ $events_mngr->trigger('__VALIDATION_REMINDER__', $params);
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function get_my_sessions()
- {
- $sql = 'SELECT session_id, lastaccess, ip, platform, browser, screen
+ public function get_my_sessions()
+ {
+ $sql = 'SELECT session_id, lastaccess, ip, platform, browser, screen
, created_on, browser_version, token
FROM cache WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_usr_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_usr_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $geonames = new geonames();
+ $geonames = new geonames();
- foreach ($rs as $k => $row)
- {
- $datas = $geonames->find_geoname_from_ip($row['ip']);
+ foreach ($rs as $k => $row) {
+ $datas = $geonames->find_geoname_from_ip($row['ip']);
- if ($datas['city'])
- {
- $infos = $datas['city'] . ' (' . $datas['country'] . ')';
- }
- elseif ($datas['fips'])
- {
- $infos = $datas['fips'] . ' (' . $datas['country'] . ')';
- }
- elseif ($datas['country'])
- {
- $infos = $datas['country'];
- }
- else
- {
- $infos = '';
- }
- $rs[$k]['session_id'] = (int) $rs[$k]['session_id'];
- $rs[$k]['ip_infos'] = $infos;
+ if ($datas['city']) {
+ $infos = $datas['city'] . ' (' . $datas['country'] . ')';
+ } elseif ($datas['fips']) {
+ $infos = $datas['fips'] . ' (' . $datas['country'] . ')';
+ } elseif ($datas['country']) {
+ $infos = $datas['country'];
+ } else {
+ $infos = '';
+ }
+ $rs[$k]['session_id'] = (int) $rs[$k]['session_id'];
+ $rs[$k]['ip_infos'] = $infos;
+ }
+
+ return $rs;
}
- return $rs;
- }
-
- public function set_event_module($app, $enter)
- {
- $sql = "SELECT app FROM cache WHERE session_id = :ses_id AND usr_id = :usr_id";
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':ses_id' => $this->get_ses_id(), ':usr_id' => $this->get_usr_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $apps = false;
-
- if ($row)
+ public function set_event_module($app, $enter)
{
- $apps = unserialize($row['app']);
- }
- if (!is_array($apps))
- $apps = array();
+ $sql = "SELECT app FROM cache WHERE session_id = :ses_id AND usr_id = :usr_id";
- if ($enter)
- {
- if ($app && !in_array($app, $apps))
- $apps[] = $app;
- }
- elseif (in_array($app, $apps))
- {
- unset($apps[$app]);
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':ses_id' => $this->get_ses_id(), ':usr_id' => $this->get_usr_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $apps = false;
+
+ if ($row) {
+ $apps = unserialize($row['app']);
+ }
+ if ( ! is_array($apps))
+ $apps = array();
+
+ if ($enter) {
+ if ($app && ! in_array($app, $apps))
+ $apps[] = $app;
+ }
+ elseif (in_array($app, $apps)) {
+ unset($apps[$app]);
+ }
+
+ $ret['apps'] = count($apps);
+
+ $sql = "UPDATE cache SET lastaccess=now(),app = :apps WHERE session_id = :ses_id AND usr_id = :usr_id";
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':ses_id' => $this->get_ses_id(), ':usr_id' => $this->get_usr_id(), ':apps' => serialize($apps)));
+ $stmt->closeCursor();
+
+ return $this;
}
- $ret['apps'] = count($apps);
+ public static function get_active_sessions()
+ {
- $sql = "UPDATE cache SET lastaccess=now(),app = :apps WHERE session_id = :ses_id AND usr_id = :usr_id";
+ $conn = connection::getPDOConnection();
+ $date_obj = new DateTime('-5 min');
+ $time = date("Y-m-d H:i:s", $date_obj->format('U'));
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':ses_id' => $this->get_ses_id(), ':usr_id' => $this->get_usr_id(), ':apps' => serialize($apps)));
- $stmt->closeCursor();
-
- return $this;
- }
-
- public static function get_active_sessions()
- {
-
- $conn = connection::getPDOConnection();
- $date_obj = new DateTime('-5 min');
- $time = date("Y-m-d H:i:s", $date_obj->format('U'));
-
- $sql = "SELECT session_id,app, usr_id, user_agent, ip, lastaccess,
+ $sql = "SELECT session_id,app, usr_id, user_agent, ip, lastaccess,
platform, browser, screen, created_on, browser_version, token
FROM cache WHERE lastaccess > :time";
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':time' => $time));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':time' => $time));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $geonames = new geonames();
+ $geonames = new geonames();
- foreach ($rs as $k => $row)
- {
- $rs[$k]['created_on'] = new DateTime($row['created_on']);
- $rs[$k]['lastaccess'] = new DateTime($row['lastaccess']);
- $rs[$k]['token'] = !!$row['token'];
- $rs[$k]['usr_id'] = User_Adapter::getInstance($row['usr_id'], appbox::get_instance(\bootstrap::getCore()));
+ foreach ($rs as $k => $row) {
+ $rs[$k]['created_on'] = new DateTime($row['created_on']);
+ $rs[$k]['lastaccess'] = new DateTime($row['lastaccess']);
+ $rs[$k]['token'] = ! ! $row['token'];
+ $rs[$k]['usr_id'] = User_Adapter::getInstance($row['usr_id'], appbox::get_instance(\bootstrap::getCore()));
- $datas = $geonames->find_geoname_from_ip($row['ip']);
+ $datas = $geonames->find_geoname_from_ip($row['ip']);
- if ($datas['city'])
- {
- $infos = $datas['city'] . ' (' . $datas['country'] . ')';
- }
- elseif ($datas['fips'])
- {
- $infos = $datas['fips'] . ' (' . $datas['country'] . ')';
- }
- elseif ($datas['country'])
- {
- $infos = $datas['country'];
- }
- else
- {
- $infos = '';
- }
+ if ($datas['city']) {
+ $infos = $datas['city'] . ' (' . $datas['country'] . ')';
+ } elseif ($datas['fips']) {
+ $infos = $datas['fips'] . ' (' . $datas['country'] . ')';
+ } elseif ($datas['country']) {
+ $infos = $datas['country'];
+ } else {
+ $infos = '';
+ }
- $rs[$k]['ip_infos'] = $infos;
+ $rs[$k]['ip_infos'] = $infos;
+ }
+
+ return $rs;
}
-
- return $rs;
- }
-
}
diff --git a/lib/classes/Session/Logger.class.php b/lib/classes/Session/Logger.class.php
index 078c9651a3..87ee9c319a 100644
--- a/lib/classes/Session/Logger.class.php
+++ b/lib/classes/Session/Logger.class.php
@@ -17,99 +17,96 @@
*/
class Session_Logger
{
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var databox
+ */
+ protected $databox;
- /**
- *
- * @var databox
- */
- protected $databox;
+ const EVENT_DELETE = 'delete';
+ const EVENT_EDIT = 'edit';
+ const EVENT_EXPORTDOWNLOAD = 'download';
+ const EVENT_EXPORTFTP = 'ftp';
+ const EVENT_EXPORTMAIL = 'mail';
+ const EVENT_MOVE = 'collection';
+ const EVENT_PRINT = 'print';
+ const EVENT_PUSH = 'push';
+ const EVENT_STATUS = 'status';
+ const EVENT_SUBSTITUTE = 'substit';
+ const EVENT_VALIDATE = 'validate';
- const EVENT_DELETE = 'delete';
- const EVENT_EDIT = 'edit';
- const EVENT_EXPORTDOWNLOAD = 'download';
- const EVENT_EXPORTFTP = 'ftp';
- const EVENT_EXPORTMAIL = 'mail';
- const EVENT_MOVE = 'collection';
- const EVENT_PRINT = 'print';
- const EVENT_PUSH = 'push';
- const EVENT_STATUS = 'status';
- const EVENT_SUBSTITUTE = 'substit';
- const EVENT_VALIDATE = 'validate';
+ /**
+ *
+ * @param databox $databox
+ * @param int $log_id
+ * @return Session_Logger
+ */
+ public function __construct(databox &$databox, $log_id)
+ {
+ $this->databox = $databox;
+ $this->id = (int) $log_id;
- /**
- *
- * @param databox $databox
- * @param int $log_id
- * @return Session_Logger
- */
- public function __construct(databox &$databox, $log_id)
- {
- $this->databox = $databox;
- $this->id = (int) $log_id;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
-
- public function log(record_adapter $record, $action, $final, $comment)
- {
- $sql = 'INSERT INTO log_docs
+ public function log(record_adapter $record, $action, $final, $comment)
+ {
+ $sql = 'INSERT INTO log_docs
(id, log_id, date, record_id, action, final, comment)
VALUES (null, :log_id, NOW(), :record_id, :action, :final, :comm)';
- $stmt = $this->databox->get_connection()->prepare($sql);
+ $stmt = $this->databox->get_connection()->prepare($sql);
- $params = array(
- ':log_id' => $this->get_id()
- , ':record_id' => $record->get_record_id()
- , ':action' => $action
- , ':final' => $final
- , ':comm' => $comment
- );
+ $params = array(
+ ':log_id' => $this->get_id()
+ , ':record_id' => $record->get_record_id()
+ , ':action' => $action
+ , ':final' => $final
+ , ':comm' => $comment
+ );
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt->execute($params);
+ $stmt->closeCursor();
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @param Session_Phrasea $session
- * @param User_Adapter $user
- * @param Browser $browser
- * @return Session_Logger
- */
- public static function create(databox &$databox, Browser &$browser, Session_Handler $session, User_Adapter &$user = null)
- {
- $colls = array();
- $registry = registry::get_instance();
-
- if($user)
- {
- $bases = $user->ACL()->get_granted_base(array(), array($databox->get_sbas_id()));
- foreach ($bases as $collection)
- {
- $colls[] = $collection->get_coll_id();
- }
+ return $this;
}
- $sql = "INSERT INTO log
+ /**
+ *
+ * @param databox $databox
+ * @param Session_Phrasea $session
+ * @param User_Adapter $user
+ * @param Browser $browser
+ * @return Session_Logger
+ */
+ public static function create(databox &$databox, Browser &$browser, Session_Handler $session, User_Adapter &$user = null)
+ {
+ $colls = array();
+ $registry = registry::get_instance();
+
+ if ($user) {
+ $bases = $user->ACL()->get_granted_base(array(), array($databox->get_sbas_id()));
+ foreach ($bases as $collection) {
+ $colls[] = $collection->get_coll_id();
+ }
+ }
+
+ $sql = "INSERT INTO log
(id, date,sit_session, user, site, usrid,coll_list, nav,
version, os, res, ip, user_agent,appli, fonction,
societe, activite, pays)
@@ -118,58 +115,56 @@ class Session_Logger
, :browser, :browser_version, :platform, :screen, :ip
, :user_agent, :appli, :fonction, :company, :activity, :country)";
- $params = array(
- ':ses_id' => $session->get_ses_id(),
- ':usr_login' => $user ? $user->get_login() : null,
- ':site_id' => $registry->get('GV_sit'),
- ':usr_id' => $user ? $user->get_id() : null,
- ':coll_list' => implode(',', $colls),
- ':browser' => $browser->getBrowser(),
- ':browser_version' => $browser->getExtendedVersion(),
- ':platform' => $browser->getPlatform(),
- ':screen' => $browser->getScreenSize(),
- ':ip' => $browser->getIP(),
- ':user_agent' => $browser->getUserAgent(),
- ':appli' => serialize(array()),
- ':fonction' => $user ? $user->get_job() : null,
- ':company' => $user ? $user->get_company() : null,
- ':activity' => $user ? $user->get_position() : null,
- ':country' => $user ? $user->get_country() : null
- );
+ $params = array(
+ ':ses_id' => $session->get_ses_id(),
+ ':usr_login' => $user ? $user->get_login() : null,
+ ':site_id' => $registry->get('GV_sit'),
+ ':usr_id' => $user ? $user->get_id() : null,
+ ':coll_list' => implode(',', $colls),
+ ':browser' => $browser->getBrowser(),
+ ':browser_version' => $browser->getExtendedVersion(),
+ ':platform' => $browser->getPlatform(),
+ ':screen' => $browser->getScreenSize(),
+ ':ip' => $browser->getIP(),
+ ':user_agent' => $browser->getUserAgent(),
+ ':appli' => serialize(array()),
+ ':fonction' => $user ? $user->get_job() : null,
+ ':company' => $user ? $user->get_company() : null,
+ ':activity' => $user ? $user->get_position() : null,
+ ':country' => $user ? $user->get_country() : null
+ );
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute($params);
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute($params);
- $log_id = $databox->get_connection()->lastInsertId();
- $stmt->closeCursor();
+ $log_id = $databox->get_connection()->lastInsertId();
+ $stmt->closeCursor();
- return new Session_Logger($databox, $log_id);
- }
-
- public static function load(databox $databox, Session_Handler $session)
- {
- if(!$session->is_authenticated())
- {
- throw new Exception_Session_LoggerNotFound ('Not authenticated');
+ return new Session_Logger($databox, $log_id);
}
- $sql = 'SELECT id FROM log
+ public static function load(databox $databox, Session_Handler $session)
+ {
+ if ( ! $session->is_authenticated()) {
+ throw new Exception_Session_LoggerNotFound('Not authenticated');
+ }
+
+ $sql = 'SELECT id FROM log
WHERE site = :site AND sit_session = :ses_id';
- $params = array(
- ':site' => $databox->get_registry()->get('GV_sit')
- , ':ses_id' => $session->get_ses_id()
- );
+ $params = array(
+ ':site' => $databox->get_registry()->get('GV_sit')
+ , ':ses_id' => $session->get_ses_id()
+ );
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if(!$row)
- throw new Exception_Session_LoggerNotFound ('Logger not found');
-
- return new self($databox, $row['id']);
- }
+ if ( ! $row)
+ throw new Exception_Session_LoggerNotFound('Logger not found');
+ return new self($databox, $row['id']);
+ }
}
diff --git a/lib/classes/Session/Phrasea.class.php b/lib/classes/Session/Phrasea.class.php
index dd5890f51e..ac890e4736 100644
--- a/lib/classes/Session/Phrasea.class.php
+++ b/lib/classes/Session/Phrasea.class.php
@@ -17,126 +17,126 @@
*/
class Session_Phrasea
{
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $user;
- /**
- *
- * @var User_Adapter
- */
- protected $user;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var int
- */
- protected $ses_id;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @param appbox $appbox
- * @param User_Adapter $user
- * @param int $ses_id
- * @return Session_Phrasea
- */
- public function __construct(appbox &$appbox, User_Adapter &$user, $ses_id = null)
- {
- $this->clear_sessions();
- $this->appbox = $appbox;
- $this->user = $user;
- $this->ses_id = $ses_id;
+ /**
+ *
+ * @var int
+ */
+ protected $ses_id;
- return $this;
- }
+ /**
+ *
+ * @param appbox $appbox
+ * @param User_Adapter $user
+ * @param int $ses_id
+ * @return Session_Phrasea
+ */
+ public function __construct(appbox &$appbox, User_Adapter &$user, $ses_id = null)
+ {
+ $this->clear_sessions();
+ $this->appbox = $appbox;
+ $this->user = $user;
+ $this->ses_id = $ses_id;
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->ses_id;
- }
+ return $this;
+ }
- /**
- *
- * @param Browser $browser
- * @return Session_Phrasea
- */
- public function create(Browser &$browser)
- {
- if ($this->ses_id)
- throw new Exception_Session_AlreadyCreated();
- if (!$this->user)
- throw new Exception_Session_Closed('You have to create a new Phrasea session with the new user');
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->ses_id;
+ }
- if (($ses_id = phrasea_create_session($this->user->get_id())) === false)
- throw new Exception_InternalServerError();
+ /**
+ *
+ * @param Browser $browser
+ * @return Session_Phrasea
+ */
+ public function create(Browser &$browser)
+ {
+ if ($this->ses_id)
+ throw new Exception_Session_AlreadyCreated();
+ if ( ! $this->user)
+ throw new Exception_Session_Closed('You have to create a new Phrasea session with the new user');
- $this->ses_id = $ses_id;
+ if (($ses_id = phrasea_create_session($this->user->get_id())) === false)
+ throw new Exception_InternalServerError();
- $this->update_informations($this->appbox, $browser);
+ $this->ses_id = $ses_id;
- return $this;
- }
+ $this->update_informations($this->appbox, $browser);
- /**
- *
- * @param appbox $appbox
- * @param Browser $browser
- * @param Array $logs
- */
- protected function update_informations(appbox &$appbox, Browser &$browser)
- {
- $sql = "UPDATE cache SET
+ return $this;
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ * @param Browser $browser
+ * @param Array $logs
+ */
+ protected function update_informations(appbox &$appbox, Browser &$browser)
+ {
+ $sql = "UPDATE cache SET
user_agent = :user_agent, ip = :ip, platform = :platform,
browser = :browser,
screen = :screen, browser_version = :browser_version
WHERE session_id = :ses_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(
array(
- ':user_agent' => $browser->getUserAgent(),
- ':ip' => $browser->getIP(),
- ':platform' => $browser->getPlatform(),
- ':browser' => $browser->getBrowser(),
- ':screen' => $browser->getScreenSize(),
+ ':user_agent' => $browser->getUserAgent(),
+ ':ip' => $browser->getIP(),
+ ':platform' => $browser->getPlatform(),
+ ':browser' => $browser->getBrowser(),
+ ':screen' => $browser->getScreenSize(),
':browser_version' => $browser->getExtendedVersion(),
- ':ses_id' => $this->ses_id
+ ':ses_id' => $this->ses_id
)
- );
- $stmt->closeCursor();
- }
+ );
+ $stmt->closeCursor();
+ }
- /**
- *
- * @return Session_Phrasea
- */
- public function open()
- {
- if (!$this->user instanceof User_Adapter)
- throw new Exception_Session_Closed();
- if (!phrasea_open_session($this->ses_id, $this->user->get_id()))
- throw new Exception_Session_Closed();
+ /**
+ *
+ * @return Session_Phrasea
+ */
+ public function open()
+ {
+ if ( ! $this->user instanceof User_Adapter)
+ throw new Exception_Session_Closed();
+ if ( ! phrasea_open_session($this->ses_id, $this->user->get_id()))
+ throw new Exception_Session_Closed();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Session_Phrasea
- */
- public function close()
- {
- phrasea_close_session($this->ses_id);
- $this->ses_id = null;
- $this->user = null;
-
- return $this;
- }
+ /**
+ *
+ * @return Session_Phrasea
+ */
+ public function close()
+ {
+ phrasea_close_session($this->ses_id);
+ $this->ses_id = null;
+ $this->user = null;
+ return $this;
+ }
// /**
// *
// * @param type $usr_id
@@ -151,33 +151,31 @@ class Session_Phrasea
//
// }
- /**
- *
- * @return Session_Phrasea
- */
- protected function clear_sessions()
- {
+ /**
+ *
+ * @return Session_Phrasea
+ */
+ protected function clear_sessions()
+ {
- $conn = connection::getPDOConnection();
- $registry = registry::get_instance();
+ $conn = connection::getPDOConnection();
+ $registry = registry::get_instance();
- $sql = "SELECT session_id FROM cache
+ $sql = "SELECT session_id FROM cache
WHERE (lastaccess < DATE_SUB(NOW(), INTERVAL 1 MONTH) AND token IS NOT NULL)
OR (lastaccess < DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND token IS NULL)";
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- phrasea_close_session($row['session_id']);
+ foreach ($rs as $row) {
+ phrasea_close_session($row['session_id']);
+ }
+
+ $date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days');
+
+ return $this;
}
-
- $date_two_day = new DateTime('+' . (int) $registry->get('GV_validation_reminder') . ' days');
-
- return $this;
- }
-
}
diff --git a/lib/classes/Session/Storage/Abstract.class.php b/lib/classes/Session/Storage/Abstract.class.php
index c65a4e6532..9f25de1ec6 100644
--- a/lib/classes/Session/Storage/Abstract.class.php
+++ b/lib/classes/Session/Storage/Abstract.class.php
@@ -17,34 +17,32 @@
*/
abstract class Session_Storage_Abstract
{
+ /**
+ *
+ * @var boolean
+ */
+ protected $open = true;
- /**
- *
- * @var boolean
- */
- protected $open = true;
+ /**
+ *
+ * @return Session_Storage_Abstract
+ */
+ public function close()
+ {
+ $this->open = false;
- /**
- *
- * @return Session_Storage_Abstract
- */
- public function close()
- {
- $this->open = false;
+ return $this;
+ }
- return $this;
- }
-
- /**
- *
- * @return Session_Storage_Abstract
- */
- protected function require_open_storage()
- {
- if (!$this->open)
- throw new Exception_Session_StorageClosed ();
-
- return $this;
- }
+ /**
+ *
+ * @return Session_Storage_Abstract
+ */
+ protected function require_open_storage()
+ {
+ if ( ! $this->open)
+ throw new Exception_Session_StorageClosed ();
+ return $this;
+ }
}
diff --git a/lib/classes/Session/Storage/CommandLine.class.php b/lib/classes/Session/Storage/CommandLine.class.php
index b1f58ce581..61102eab20 100644
--- a/lib/classes/Session/Storage/CommandLine.class.php
+++ b/lib/classes/Session/Storage/CommandLine.class.php
@@ -17,137 +17,134 @@
*/
class Session_Storage_CommandLine extends Session_Storage_Abstract implements Session_Storage_Interface
{
+ /**
+ *
+ * @var Session_Storage_CommandLine
+ */
+ protected static $_instance;
- /**
- *
- * @var Session_Storage_CommandLine
- */
- protected static $_instance;
- /**
- *
- * @var string
- */
- private static $_name = '';
- /**
- *
- * @var Array
- */
- private static $_cli_storage = array();
+ /**
+ *
+ * @var string
+ */
+ private static $_name = '';
- /**
- *
- * @param string $session_name
- * @return Session_Storage_CommandLine
- */
- public static function getInstance($session_name)
- {
- if (!self::$_instance)
+ /**
+ *
+ * @var Array
+ */
+ private static $_cli_storage = array();
+
+ /**
+ *
+ * @param string $session_name
+ * @return Session_Storage_CommandLine
+ */
+ public static function getInstance($session_name)
{
- self::$_instance = new self($session_name);
+ if ( ! self::$_instance) {
+ self::$_instance = new self($session_name);
+ }
+
+ return self::$_instance;
}
- return self::$_instance;
- }
-
- /**
- *
- * @param string $name
- * @return Session_Storage_CommandLine
- */
- protected function __construct($name)
- {
- return $this;
- }
-
- /**
- *
- * @param string $key
- * @return mixed
- */
- public function get($key, $default_value = null)
- {
- return isset(self::$_cli_storage[self::$_name][$key]) ? self::$_cli_storage[self::$_name][$key] : $default_value;
- }
-
- /**
- *
- * @param string $key
- * @return mixed
- */
- public function has($key)
- {
- return isset(self::$_cli_storage[self::$_name][$key]);
- }
-
- /**
- *
- * @param string $key
- * @param mixed $value
- * @return boolean
- */
- public function set($key, $value)
- {
- $this->require_open_storage();
-
- return self::$_cli_storage[self::$_name][$key] = $value;
- }
-
- /**
- *
- * @param string $key
- * @return boolean
- */
- public function remove($key)
- {
- $retval = null;
- $this->require_open_storage();
-
- if (isset(self::$_cli_storage[self::$_name][$key]))
+ /**
+ *
+ * @param string $name
+ * @return Session_Storage_CommandLine
+ */
+ protected function __construct($name)
{
- $retval = self::$_cli_storage[self::$_name][$key];
- unset(self::$_cli_storage[self::$_name][$key]);
+ return $this;
}
- return $retval;
- }
+ /**
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function get($key, $default_value = null)
+ {
+ return isset(self::$_cli_storage[self::$_name][$key]) ? self::$_cli_storage[self::$_name][$key] : $default_value;
+ }
- /**
- * Return PHP session name
- *
- * @return string
- */
- public function getName()
- {
- return 'commandLine';
- }
+ /**
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function has($key)
+ {
+ return isset(self::$_cli_storage[self::$_name][$key]);
+ }
- /**
- * Return PHP session Id
- *
- * @return string
- */
- public function getId()
- {
- return 'commandLine';
- }
+ /**
+ *
+ * @param string $key
+ * @param mixed $value
+ * @return boolean
+ */
+ public function set($key, $value)
+ {
+ $this->require_open_storage();
+ return self::$_cli_storage[self::$_name][$key] = $value;
+ }
- public function reset()
- {
- self::$_cli_storage[self::$_name] = array();
+ /**
+ *
+ * @param string $key
+ * @return boolean
+ */
+ public function remove($key)
+ {
+ $retval = null;
+ $this->require_open_storage();
- return;
- }
+ if (isset(self::$_cli_storage[self::$_name][$key])) {
+ $retval = self::$_cli_storage[self::$_name][$key];
+ unset(self::$_cli_storage[self::$_name][$key]);
+ }
- /**
- *
- * @return Void
- */
- public function destroy()
- {
- unset(self::$_cli_storage[self::$_name]);
+ return $retval;
+ }
- return;
- }
+ /**
+ * Return PHP session name
+ *
+ * @return string
+ */
+ public function getName()
+ {
+ return 'commandLine';
+ }
+ /**
+ * Return PHP session Id
+ *
+ * @return string
+ */
+ public function getId()
+ {
+ return 'commandLine';
+ }
+
+ public function reset()
+ {
+ self::$_cli_storage[self::$_name] = array();
+
+ return;
+ }
+
+ /**
+ *
+ * @return Void
+ */
+ public function destroy()
+ {
+ unset(self::$_cli_storage[self::$_name]);
+
+ return;
+ }
}
diff --git a/lib/classes/Session/Storage/Interface.class.php b/lib/classes/Session/Storage/Interface.class.php
index 24557e0f5d..fd15673b3e 100644
--- a/lib/classes/Session/Storage/Interface.class.php
+++ b/lib/classes/Session/Storage/Interface.class.php
@@ -17,38 +17,39 @@
*/
interface Session_Storage_Interface
{
- /**
- * Close the session storage
- *
- * @return Void
- */
- public function close();
- /**
- * Return true if the storage contains the key
- *
- * @param string $key
- * @return boolean
- */
- public function has($key);
+ /**
+ * Close the session storage
+ *
+ * @return Void
+ */
+ public function close();
- /**
- * Set a key in the storage
- *
- * @param string $key
- * @param mixed $default_value
- */
- public function get($key, $default_value = null);
+ /**
+ * Return true if the storage contains the key
+ *
+ * @param string $key
+ * @return boolean
+ */
+ public function has($key);
- public function set($key, $value);
+ /**
+ * Set a key in the storage
+ *
+ * @param string $key
+ * @param mixed $default_value
+ */
+ public function get($key, $default_value = null);
- public function remove($key);
+ public function set($key, $value);
- public function getName();
+ public function remove($key);
- public function getId();
+ public function getName();
- public function reset();
+ public function getId();
- public function destroy();
+ public function reset();
+
+ public function destroy();
}
diff --git a/lib/classes/Session/Storage/PHPSession.class.php b/lib/classes/Session/Storage/PHPSession.class.php
index 7843b1b393..eb63d3ed9a 100644
--- a/lib/classes/Session/Storage/PHPSession.class.php
+++ b/lib/classes/Session/Storage/PHPSession.class.php
@@ -17,148 +17,145 @@
*/
class Session_Storage_PHPSession extends Session_Storage_Abstract implements Session_Storage_Interface
{
+ /**
+ *
+ * @var Session_Storage_PHPSession
+ */
+ protected static $_instance;
- /**
- *
- * @var Session_Storage_PHPSession
- */
- protected static $_instance;
- /**
- *
- * @var string
- */
- protected $name = 'PHPSESSID';
+ /**
+ *
+ * @var string
+ */
+ protected $name = 'PHPSESSID';
- /**
- *
- * @param string $session_name
- * @return Session_Storage_PHPSession
- */
- public static function getInstance($session_name)
- {
- if (!self::$_instance)
+ /**
+ *
+ * @param string $session_name
+ * @return Session_Storage_PHPSession
+ */
+ public static function getInstance($session_name)
{
- self::$_instance = new self($session_name);
+ if ( ! self::$_instance) {
+ self::$_instance = new self($session_name);
+ }
+
+ return self::$_instance;
}
- return self::$_instance;
- }
-
- /**
- *
- * @param string $session_name
- * @return Session_Storage_PHPSession
- */
- protected function __construct($session_name)
- {
- $this->name = $session_name;
- $this->start();
-
- return $this;
- }
-
- /**
- *
- * @return Session_Storage_PHPSession
- */
- protected function start()
- {
- session_name($this->name);
- session_start();
- $this->open = true;
-
- return $this;
- }
-
- /**
- *
- * @return Session_Storage_PHPSession
- */
- public function close()
- {
- if ($this->open)
+ /**
+ *
+ * @param string $session_name
+ * @return Session_Storage_PHPSession
+ */
+ protected function __construct($session_name)
{
- session_write_close();
+ $this->name = $session_name;
+ $this->start();
+
+ return $this;
}
- parent::close();
- return $this;
- }
+ /**
+ *
+ * @return Session_Storage_PHPSession
+ */
+ protected function start()
+ {
+ session_name($this->name);
+ session_start();
+ $this->open = true;
- /**
- *
- * @param string $key
- * @return mixed
- */
- public function has($key)
- {
- return isset($_SESSION[$key]);
- }
+ return $this;
+ }
- /**
- *
- * @param string $key
- * @return mixed
- */
- public function get($key, $default_value = null)
- {
- return isset($_SESSION[$key]) ? $_SESSION[$key] : $default_value;
- }
+ /**
+ *
+ * @return Session_Storage_PHPSession
+ */
+ public function close()
+ {
+ if ($this->open) {
+ session_write_close();
+ }
+ parent::close();
- public function set($key, $value)
- {
- $this->require_open_storage();
- $_SESSION[$key] = $value;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function has($key)
+ {
+ return isset($_SESSION[$key]);
+ }
- public function remove($key)
- {
- $this->require_open_storage();
- if (isset($_SESSION[$key]))
- unset($_SESSION[$key]);
+ /**
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public function get($key, $default_value = null)
+ {
+ return isset($_SESSION[$key]) ? $_SESSION[$key] : $default_value;
+ }
- return $this;
- }
+ public function set($key, $value)
+ {
+ $this->require_open_storage();
+ $_SESSION[$key] = $value;
- /**
- * Return PHP session name
- *
- * @return string
- */
- function getName()
- {
- return session_name();
- }
+ return $this;
+ }
- /**
- * Return PHP session Id
- *
- * @return
- */
- function getId()
- {
- return session_id();
- }
+ public function remove($key)
+ {
+ $this->require_open_storage();
+ if (isset($_SESSION[$key]))
+ unset($_SESSION[$key]);
- public function reset()
- {
- $_SESSION = array();
+ return $this;
+ }
- return $this;
- }
+ /**
+ * Return PHP session name
+ *
+ * @return string
+ */
+ function getName()
+ {
+ return session_name();
+ }
- /**
- *
- * @return Void
- */
- public function destroy()
- {
- session_destroy();
- $this->open = false;
+ /**
+ * Return PHP session Id
+ *
+ * @return
+ */
+ function getId()
+ {
+ return session_id();
+ }
- return;
- }
+ public function reset()
+ {
+ $_SESSION = array();
+ return $this;
+ }
+
+ /**
+ *
+ * @return Void
+ */
+ public function destroy()
+ {
+ session_destroy();
+ $this->open = false;
+
+ return;
+ }
}
diff --git a/lib/classes/Setup/Constraint.class.php b/lib/classes/Setup/Constraint.class.php
index 6f033d84df..ab48c08435 100644
--- a/lib/classes/Setup/Constraint.class.php
+++ b/lib/classes/Setup/Constraint.class.php
@@ -17,56 +17,54 @@
*/
class Setup_Constraint
{
+ protected $name;
+ protected $success;
+ protected $message;
+ protected $blocker;
- protected $name;
- protected $success;
- protected $message;
- protected $blocker;
+ public function __construct($name, $success, $message, $blocker = false)
+ {
+ $this->name = $name;
+ $this->success = ! ! $success;
+ $this->message = $message;
+ $this->blocker = ! ! $blocker;
- public function __construct($name, $success, $message, $blocker = false)
- {
- $this->name = $name;
- $this->success = !!$success;
- $this->message = $message;
- $this->blocker = !!$blocker;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_ok()
+ {
+ return $this->success;
+ }
- /**
- *
- * @return boolean
- */
- public function is_ok()
- {
- return $this->success;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_blocker()
- {
- return $this->blocker;
- }
-
- /**
- *
- * @return string
- */
- public function get_message()
- {
- return $this->message;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_blocker()
+ {
+ return $this->blocker;
+ }
+ /**
+ *
+ * @return string
+ */
+ public function get_message()
+ {
+ return $this->message;
+ }
}
diff --git a/lib/classes/Setup/ConstraintsIterator.class.php b/lib/classes/Setup/ConstraintsIterator.class.php
index f76158a621..fc5173f86a 100644
--- a/lib/classes/Setup/ConstraintsIterator.class.php
+++ b/lib/classes/Setup/ConstraintsIterator.class.php
@@ -17,22 +17,20 @@
*/
class Setup_ConstraintsIterator implements IteratorAggregate
{
+ protected $constraints = array();
- protected $constraints = array();
+ public function __construct(Array $constraints)
+ {
+ $this->constraints = $constraints;
+ }
- public function __construct(Array $constraints)
- {
- $this->constraints = $constraints;
- }
-
- public function add(Setup_Constraint $constraint)
- {
- $this->constraints[] = $constraint;
- }
-
- public function getIterator()
- {
- return new ArrayIterator($this->constraints);
- }
+ public function add(Setup_Constraint $constraint)
+ {
+ $this->constraints[] = $constraint;
+ }
+ public function getIterator()
+ {
+ return new ArrayIterator($this->constraints);
+ }
}
diff --git a/lib/classes/Setup/Registry.class.php b/lib/classes/Setup/Registry.class.php
index a7117f7c20..6fbc43dbef 100644
--- a/lib/classes/Setup/Registry.class.php
+++ b/lib/classes/Setup/Registry.class.php
@@ -18,30 +18,28 @@
*/
class Setup_Registry implements registryInterface
{
+ protected $datas = array();
- protected $datas = array();
+ public function get($key, $defaultvalue = null)
+ {
+ return isset($this->datas[$key]) ? $this->datas[$key] : $defaultvalue;
+ }
- public function get($key, $defaultvalue = null)
- {
- return isset($this->datas[$key]) ? $this->datas[$key] : $defaultvalue;
- }
+ public function set($key, $value, $type)
+ {
+ $this->datas[$key] = $value;
+ }
- public function set($key, $value, $type)
- {
- $this->datas[$key] = $value;
- }
+ public function is_set($key)
+ {
+ return isset($this->datas[$key]);
+ }
- public function is_set($key)
- {
- return isset($this->datas[$key]);
- }
-
- public function un_set($key)
- {
- if (isset($this->datas[$key]))
- unset($datas[$key]);
-
- return $this;
- }
+ public function un_set($key)
+ {
+ if (isset($this->datas[$key]))
+ unset($datas[$key]);
+ return $this;
+ }
}
diff --git a/lib/classes/Setup/Upgrade.class.php b/lib/classes/Setup/Upgrade.class.php
index 8d17fafc32..d694a6ac29 100644
--- a/lib/classes/Setup/Upgrade.class.php
+++ b/lib/classes/Setup/Upgrade.class.php
@@ -1,4 +1,5 @@
appbox = $appbox;
+
+ if (count(User_Adapter::get_wrong_email_users($appbox)) > 0) {
+ throw new Exception_Setup_FixBadEmailAddresses('Please fix the database before starting');
+ }
+
+ $this->write_lock();
+
+ return $this;
}
- $this->appbox = $appbox;
-
- if(count(User_Adapter::get_wrong_email_users($appbox)) > 0)
+ /**
+ *
+ * @return Void
+ */
+ public function __destruct()
{
- throw new Exception_Setup_FixBadEmailAddresses('Please fix the database before starting');
+ self::remove_lock_file();
+
+ return;
}
- $this->write_lock();
+ /**
+ * Add steps to do to the counter
+ *
+ * @param int $how_many
+ * @return Setup_Upgrade
+ */
+ public function add_steps($how_many)
+ {
+ $this->total_steps += (int) $how_many;
+ $this->write_lock();
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @return Void
- */
- public function __destruct()
- {
- self::remove_lock_file();
+ /**
+ * Add completed steps to the counter
+ *
+ * @param int $how_many
+ * @return Setup_Upgrade
+ */
+ public function add_steps_complete($how_many)
+ {
+ $this->completed_steps += (int) $how_many;
+ $this->write_lock();
- return;
- }
+ return $this;
+ }
- /**
- * Add steps to do to the counter
- *
- * @param int $how_many
- * @return Setup_Upgrade
- */
- public function add_steps($how_many)
- {
- $this->total_steps += (int) $how_many;
- $this->write_lock();
+ /**
+ * Set the current message
+ *
+ * @param string $message
+ * @return Setup_Upgrade
+ */
+ public function set_current_message($message)
+ {
+ $this->message = $message;
+ $this->write_lock();
- return $this;
- }
+ return $this;
+ }
- /**
- * Add completed steps to the counter
- *
- * @param int $how_many
- * @return Setup_Upgrade
- */
- public function add_steps_complete($how_many)
- {
- $this->completed_steps += (int) $how_many;
- $this->write_lock();
+ /**
+ *
+ * @return float
+ */
+ protected function get_percentage()
+ {
+ if ($this->total_steps === 0)
+ return 1;
+ return round(max(min(($this->completed_steps / $this->total_steps), 1), 0), 2);
+ }
- return $this;
- }
-
- /**
- * Set the current message
- *
- * @param string $message
- * @return Setup_Upgrade
- */
- public function set_current_message($message)
- {
- $this->message = $message;
- $this->write_lock();
-
- return $this;
- }
-
- /**
- *
- * @return float
- */
- protected function get_percentage()
- {
- if ($this->total_steps === 0)
-
- return 1;
- return round(max(min(($this->completed_steps / $this->total_steps), 1), 0), 2);
- }
-
- /**
- *
- *
- * @return Setup_Upgrade
- */
- protected function write_lock()
- {
- $date_obj = new DateTime();
- $dumper = new Symfony\Component\Yaml\Dumper();
- $datas = $dumper->dump(
+ /**
+ *
+ *
+ * @return Setup_Upgrade
+ */
+ protected function write_lock()
+ {
+ $date_obj = new DateTime();
+ $dumper = new Symfony\Component\Yaml\Dumper();
+ $datas = $dumper->dump(
array(
- 'percentage' => $this->get_percentage()
- , 'total_steps' => $this->total_steps
- , 'completed_steps' => $this->completed_steps
- , 'message' => $this->message
- , 'last_update' => $date_obj->format(DATE_ATOM)
- ),1
- );
+ 'percentage' => $this->get_percentage()
+ , 'total_steps' => $this->total_steps
+ , 'completed_steps' => $this->completed_steps
+ , 'message' => $this->message
+ , 'last_update' => $date_obj->format(DATE_ATOM)
+ ), 1
+ );
- if (!file_put_contents(self::get_lock_file(), $datas))
- throw new Exception_Setup_CannotWriteLockFile(
- sprintf('Cannot write lock file to %s', self::get_lock_file())
- );
+ if ( ! file_put_contents(self::get_lock_file(), $datas))
+ throw new Exception_Setup_CannotWriteLockFile(
+ sprintf('Cannot write lock file to %s', self::get_lock_file())
+ );
- return $this;
- }
-
- /**
- * Returns true if the file exists
- *
- * @return boolean
- */
- protected static function lock_exists()
- {
- clearstatcache();
-
- return file_exists(self::get_lock_file());
- }
-
- /**
- * Return the path fil to the lock file
- *
- * @return string
- */
- public static function get_lock_file()
- {
- return __DIR__ . '/../../../tmp/upgrade.lock';
- }
-
- /**
- *
- * @return Void
- */
- protected static function remove_lock_file()
- {
- if (self::lock_exists())
- unlink(self::get_lock_file());
-
- return;
- }
-
- /**
- *
- * Returns an array containing datas about the Upgrade Status.
- * Contains the following keys :
- * - active : (booolean) tells if there's a current upgrade
- * - percentage : (float) a number between 0 and 1 of the current progress
- * - total_steps : (int) total steps
- * - completed_steps : (int) current complete steps
- * - message : (string) a message
- * - last_update : (string) last update in ATOM format
- *
- *
- * @return Array
- */
- public static function get_status()
- {
- $active = self::lock_exists();
-
- $datas = array(
- 'active' => $active
- , 'percentage' => 1
- , 'total_steps' => 0
- , 'completed_steps' => 0
- , 'message' => null
- , 'last_update' => null
- );
-
- if ($active)
- {
- $parser = new Symfony\Component\Yaml\Parser();
- $datas = array_merge(
- $datas
- , $parser->parse(file_get_contents(self::get_lock_file()))
- );
+ return $this;
}
- return $datas;
- }
+ /**
+ * Returns true if the file exists
+ *
+ * @return boolean
+ */
+ protected static function lock_exists()
+ {
+ clearstatcache();
+ return file_exists(self::get_lock_file());
+ }
+
+ /**
+ * Return the path fil to the lock file
+ *
+ * @return string
+ */
+ public static function get_lock_file()
+ {
+ return __DIR__ . '/../../../tmp/upgrade.lock';
+ }
+
+ /**
+ *
+ * @return Void
+ */
+ protected static function remove_lock_file()
+ {
+ if (self::lock_exists())
+ unlink(self::get_lock_file());
+
+ return;
+ }
+
+ /**
+ *
+ * Returns an array containing datas about the Upgrade Status.
+ * Contains the following keys :
+ * - active : (booolean) tells if there's a current upgrade
+ * - percentage : (float) a number between 0 and 1 of the current progress
+ * - total_steps : (int) total steps
+ * - completed_steps : (int) current complete steps
+ * - message : (string) a message
+ * - last_update : (string) last update in ATOM format
+ *
+ *
+ * @return Array
+ */
+ public static function get_status()
+ {
+ $active = self::lock_exists();
+
+ $datas = array(
+ 'active' => $active
+ , 'percentage' => 1
+ , 'total_steps' => 0
+ , 'completed_steps' => 0
+ , 'message' => null
+ , 'last_update' => null
+ );
+
+ if ($active) {
+ $parser = new Symfony\Component\Yaml\Parser();
+ $datas = array_merge(
+ $datas
+ , $parser->parse(file_get_contents(self::get_lock_file()))
+ );
+ }
+
+ return $datas;
+ }
}
diff --git a/lib/classes/User/Adapter.class.php b/lib/classes/User/Adapter.class.php
index 91839ce4e4..866a05bb30 100644
--- a/lib/classes/User/Adapter.class.php
+++ b/lib/classes/User/Adapter.class.php
@@ -17,1812 +17,1749 @@
*/
class User_Adapter implements User_Interface, cache_cacheableInterface
{
-
- /**
- *
- * @var ACL
- */
- protected $ACL;
-
- /**
- *
- * @var Array
- */
- public static $locales = array(
- 'ar_SA' => 'العربية'
- , 'de_DE' => 'Deutsch'
- , 'en_GB' => 'English'
- , 'es_ES' => 'Español'
- , 'fr_FR' => 'Français'
- );
-
- /**
- *
- * @var array
- */
- protected static $_instance = array();
-
- /**
- *
- * @var array
- */
- protected $_prefs = array();
-
- /**
- *
- * @var array
- */
- protected static $_users = array();
-
- /**
- *
- * @var array
- */
- protected $_updated_prefs = array();
-
- /**
- *
- * @var array
- */
- protected static $def_values = array(
- 'view' => 'thumbs',
- 'images_per_page' => 20,
- 'images_size' => 120,
- 'editing_images_size' => 134,
- 'editing_top_box' => '180px',
- 'editing_right_box' => '400px',
- 'editing_left_box' => '710px',
- 'basket_sort_field' => 'name',
- 'basket_sort_order' => 'ASC',
- 'warning_on_delete_story' => 'true',
- 'client_basket_status' => '1',
- 'css' => '000000',
- 'start_page_query' => 'last',
- 'start_page' => 'QUERY',
- 'rollover_thumbnail' => 'caption',
- 'technical_display' => '1',
- 'doctype_display' => '1',
- 'bask_val_order' => 'nat',
- 'basket_caption_display' => '0',
- 'basket_status_display' => '0',
- 'basket_title_display' => '0'
- );
-
- /**
- *
- * @var array
- */
- protected static $available_values = array(
- 'view' => array('thumbs', 'list'),
- 'basket_sort_field' => array('name', 'date'),
- 'basket_sort_order' => array('ASC', 'DESC'),
- 'start_page' => array('PUBLI', 'QUERY', 'LAST_QUERY', 'HELP'),
- 'technical_display' => array('0', '1', 'group'),
- 'rollover_thumbnail' => array('caption', 'preview'),
- 'bask_val_order' => array('nat', 'asc', 'desc')
- );
-
- /**
- *
- * @var appbox
- */
- protected $appbox;
-
- /**
- *
- * @var int
- */
- protected $id;
-
- /**
- *
- * @var string
- */
- protected $email;
-
- /**
- *
- * @var string
- */
- protected $login;
-
- /**
- *
- * @var string
- */
- protected $firstname;
-
- /**
- *
- * @var string
- */
- protected $lastname;
-
- /**
- *
- * @var string
- */
- protected $address;
-
- /**
- *
- * @var string
- */
- protected $city;
-
- /**
- *
- * @var int
- */
- protected $geonameid;
-
- /**
- *
- * @var string
- */
- protected $zip;
-
- /**
- *
- * @var int
- */
- protected $gender;
-
- /**
- *
- * @var string
- */
- protected $tel;
-
- /**
- *
- * @var int
- */
- protected $lastModel;
-
- /**
- *
- * @var DateTime
- */
- protected $creationdate;
-
- /**
- *
- * @var DateTime
- */
- protected $modificationdate;
-
- /**
- *
- * @var string
- */
- protected $fax;
-
- /**
- *
- * @var string
- */
- protected $job;
-
- /**
- *
- * @var string
- */
- protected $position;
-
- /**
- *
- * @var string
- */
- protected $company;
-
- /**
- *
- * @var boolean
- */
- protected $is_admin;
-
- /**
- *
- * @var boolean
- */
- protected $ldap_created;
-
- /**
- *
- * @var boolean
- */
- protected $is_guest;
-
- /**
- *
- * @var boolean
- */
- protected $mail_locked;
-
- /**
- *
- * @var string
- */
- protected $defaultftpdatas;
-
- /**
- *
- * @var string
- */
- protected $mail_notifications;
-
- /**
- *
- * @var string
- */
- protected $activeftp;
-
- /**
- *
- * @var string
- */
- protected $ftp_address;
-
- /**
- *
- * @var string
- */
- protected $ftp_login;
-
- /**
- *
- * @var string
- */
- protected $ftp_password;
-
- /**
- *
- * @var string
- */
- protected $ftp_passif;
-
- /**
- *
- * @var string
- */
- protected $ftp_dir;
-
- /**
- *
- * @var string
- */
- protected $ftp_dir_prefix;
-
- /**
- *
- * @var string
- */
- protected $country;
-
- /**
- *
- * @var boolean
- */
- protected $is_template;
-
- /**
- *
- * @var User_Adapter
- */
- protected $template_owner;
-
- /**
- *
- * @param type $id
- * @param appbox $appbox
- * @return User_Adapter
- */
- public function __construct($id, appbox &$appbox)
- {
- $this->appbox = $appbox;
- $this->load($id);
-
- return $this;
- }
-
- /**
- *
- * @param type $id
- * @param appbox $appbox
- * @return User_Adapter
- */
- public static function getInstance($id, appbox &$appbox)
- {
- if (is_int((int) $id) && (int) $id > 0)
- {
- $id = (int) $id;
- }
- else
- throw new Exception('Invalid usr_id');
-
- if (!isset(self::$_instance[$id]))
- {
- try
- {
- self::$_instance[$id] = $appbox->get_data_from_cache('_user_' . $id);
- self::$_instance[$id]->set_appbox($appbox);
- }
- catch (Exception $e)
- {
- self::$_instance[$id] = new self($id, $appbox);
- $appbox->set_data_to_cache(self::$_instance[$id], '_user_' . $id);
- }
- }
-
- return array_key_exists($id, self::$_instance) ? self::$_instance[$id] : false;
- }
-
- /**
- * Return Access Control List object for the user
- *
- * @return ACL
- */
- public function ACL()
- {
- return $this->get_ACL();
- }
-
- /**
- *
- * @param appbox $appbox
- */
- protected function set_appbox(appbox &$appbox)
- {
- $this->appbox = $appbox;
- }
-
- /**
- *
- * @param type $pasword
- * @return User_Adapter
- */
- public function set_password($pasword)
- {
- $sql = 'UPDATE usr SET usr_password = :password, salted_password = "1"
- WHERE usr_id = :usr_id';
-
- $password = self::salt_password($pasword, $this->get_nonce());
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':password' => $password, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
-
- return $this;
- }
-
- /**
- *
- * @param string $email
- * @return User_Adapter
- */
- public function set_email($email)
- {
- if (trim($email) == '')
- $email = null;
-
- $test_user = User_Adapter::get_usr_id_from_email($email);
-
- if ($test_user && $test_user != $this->get_id())
- {
- throw new Exception_InvalidArgument(sprintf(_('A user already exists with email addres %s'), $email));
- }
-
- $sql = 'UPDATE usr SET usr_mail = :new_email WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':new_email' => $email, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->email = $email;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- * Load if needed of the ACL for the current user
- *
- * @return ACL
- */
- protected function get_ACL()
- {
- if (!$this->ACL instanceof ACL)
- $this->ACL = new ACL($this, $this->appbox);
-
- return $this->ACL;
- }
-
- /**
- *
- * @param boolean $renew
- * @return system_url
- */
- public function get_protected_rss_url($renew = false)
- {
- $session = $this->appbox->get_session();
- $registry = $this->appbox->get_registry();
-
- $token = $title = false;
-
- if (!$renew)
- {
- $sql = 'SELECT value FROM tokens WHERE usr_id = :usr_id AND type="rss"';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- $token = $row['value'];
- }
- else
- {
- $sql = 'DELETE FROM tokens WHERE usr_id = :usr_id AND type="rss"';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- }
- if ($token === false)
- {
- $token = random::getUrlToken(\random::TYPE_RSS, $this->id);
- }
-
- return new system_url($registry->get('GV_ServerName') . 'atom/' . $token);
- }
-
- /**
- * Query in the cache
- *
- * @param unknown_type $query
- * @return boolean
- */
- public static function saveQuery($query)
- {
- try
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- $sql = "INSERT INTO dsel (id, name, usr_id, query)
- VALUES (null, :name, :usr_id, :query)";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(
- ':name' => $query,
- ':usr_id' => $session->get_usr_id(),
- ':query' => $query
- ));
- $stmt->closeCursor();
-
- if ($user->getPrefs('start_page') == 'LAST_QUERY')
- $user->setPrefs('start_page_query', $query);
- }
- catch (Exception $e)
- {
- return false;
- }
-
- return true;
- }
-
- /**
- *
- * @return string
- */
- public function get_country()
- {
- if ($this->geonameid)
- {
- $geonames = new geonames();
-
- return $geonames->get_country($this->geonameid);
- }
-
- return '';
- }
-
- /**
- *
- * @param string $login
- * @return int
- */
- public static function get_usr_id_from_login($login)
- {
- $conn = connection::getPDOConnection();
- $sql = 'SELECT usr_id FROM usr WHERE usr_login = :login';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':login' => trim($login)));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $usr_id = $row ? (int) $row['usr_id'] : false;
-
- return $usr_id;
- }
-
- /**
- *
- * @param int $datas
- * @return User_Adapter
- */
- public function set_defaultftpdatas($datas)
- {
- $sql = 'UPDATE usr SET defaultftpdatasent = :defaultftpdatas WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':defaultftpdatas' => $datas, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->defaultftpdatas = $datas;
-
- return $this;
- }
-
- /**
- *
- * @param bollean $boolean
- * @return User_Adapter
- */
- public function set_mail_notifications($boolean)
- {
- $value = $boolean ? '1' : '0';
- $sql = 'UPDATE usr SET mail_notifications = :mail_notifications WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':mail_notifications' => $value, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->mail_notifications = !!$boolean;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- *
- * @param boolean $boolean
- * @return User_Adapter
- */
- public function set_activeftp($boolean)
- {
- $value = $boolean ? '1' : '0';
- $sql = 'UPDATE usr SET activeftp = :activeftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':activeftp' => $value, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->activeftp = $boolean;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $boolean
- * @return User_Adapter
- */
- public function set_ldap_created($boolean)
- {
- $value = $boolean ? '1' : '0';
- $sql = 'UPDATE usr SET ldap_created = :ldap_created WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':ldap_created' => $value, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ldap_created = $boolean;
-
- return $this;
- }
-
- /**
- *
- * @param string $address
- * @return User_Adapter
- */
- public function set_ftp_address($address)
- {
- $sql = 'UPDATE usr SET addrftp = :addrftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':addrftp' => $address, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_address = $address;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- *
- * @param string $login
- * @return User_Adapter
- */
- public function set_ftp_login($login)
- {
- $sql = 'UPDATE usr SET loginftp = :loginftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':loginftp' => $login, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_login = $login;
-
- return $this;
- }
-
- /**
- *
- * @param type $password
- * @return User_Adapter
- */
- public function set_ftp_password($password)
- {
- $sql = 'UPDATE usr SET pwdFTP = :passwordftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':passwordftp' => $password, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_password = $password;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_ftp_passif($boolean)
- {
- $value = $boolean ? '1' : '0';
- $sql = 'UPDATE usr SET passifftp = :passifftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':passifftp' => $value, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_passif = !!$boolean;
-
- return $this;
- }
-
- public function set_ftp_dir($ftp_dir)
- {
- $sql = 'UPDATE usr SET destftp = :destftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':destftp' => $ftp_dir, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_dir = $ftp_dir;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_ftp_dir_prefix($ftp_dir_prefix)
- {
- $sql = 'UPDATE usr SET prefixFTPfolder = :prefixftp WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':prefixftp' => $ftp_dir_prefix, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->ftp_dir_prefix = $ftp_dir_prefix;
-
- return $this;
- }
-
- public function set_firstname($firstname)
- {
- $sql = 'UPDATE usr SET usr_prenom = :usr_prenom WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_prenom' => $firstname, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->firstname = $firstname;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_lastname($lastname)
- {
- $sql = 'UPDATE usr SET usr_nom = :usr_nom WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_nom' => $lastname, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->lastname = $lastname;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_address($address)
- {
- $sql = 'UPDATE usr SET adresse = :adresse WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':adresse' => $address, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->address = $address;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_city($city)
- {
- $sql = 'UPDATE usr SET ville = :city WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':city' => $city, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->city = $city;
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_geonameid($geonameid)
- {
- $geonames = new geonames();
- $country_code = $geonames->get_country_code($geonameid);
- $sql = 'UPDATE usr SET geonameid = :geonameid, pays=:country_code WHERE usr_id = :usr_id';
-
- $datas = array(
- ':geonameid' => $geonameid,
- ':usr_id' => $this->get_id(),
- ':country_code' => $country_code
+ /**
+ *
+ * @var ACL
+ */
+ protected $ACL;
+
+ /**
+ *
+ * @var Array
+ */
+ public static $locales = array(
+ 'ar_SA' => 'العربية'
+ , 'de_DE' => 'Deutsch'
+ , 'en_GB' => 'English'
+ , 'es_ES' => 'Español'
+ , 'fr_FR' => 'Français'
);
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($datas);
- $stmt->closeCursor();
- $this->geonameid = $geonameid;
- $this->country = $country_code;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var array
+ */
+ protected static $_instance = array();
- return $this;
- }
+ /**
+ *
+ * @var array
+ */
+ protected $_prefs = array();
- public function set_zip($zip)
- {
- $sql = 'UPDATE usr SET cpostal = :cpostal WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':cpostal' => $zip, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->zip = $zip;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var array
+ */
+ protected static $_users = array();
- return $this;
- }
+ /**
+ *
+ * @var array
+ */
+ protected $_updated_prefs = array();
- public function set_gender($gender)
- {
- $sql = 'UPDATE usr SET usr_sexe = :usr_sexe WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_sexe' => $gender, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->gender = $gender;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var array
+ */
+ protected static $def_values = array(
+ 'view' => 'thumbs',
+ 'images_per_page' => 20,
+ 'images_size' => 120,
+ 'editing_images_size' => 134,
+ 'editing_top_box' => '180px',
+ 'editing_right_box' => '400px',
+ 'editing_left_box' => '710px',
+ 'basket_sort_field' => 'name',
+ 'basket_sort_order' => 'ASC',
+ 'warning_on_delete_story' => 'true',
+ 'client_basket_status' => '1',
+ 'css' => '000000',
+ 'start_page_query' => 'last',
+ 'start_page' => 'QUERY',
+ 'rollover_thumbnail' => 'caption',
+ 'technical_display' => '1',
+ 'doctype_display' => '1',
+ 'bask_val_order' => 'nat',
+ 'basket_caption_display' => '0',
+ 'basket_status_display' => '0',
+ 'basket_title_display' => '0'
+ );
- return $this;
- }
+ /**
+ *
+ * @var array
+ */
+ protected static $available_values = array(
+ 'view' => array('thumbs', 'list'),
+ 'basket_sort_field' => array('name', 'date'),
+ 'basket_sort_order' => array('ASC', 'DESC'),
+ 'start_page' => array('PUBLI', 'QUERY', 'LAST_QUERY', 'HELP'),
+ 'technical_display' => array('0', '1', 'group'),
+ 'rollover_thumbnail' => array('caption', 'preview'),
+ 'bask_val_order' => array('nat', 'asc', 'desc')
+ );
- public function set_tel($tel)
- {
- $sql = 'UPDATE usr SET tel = :tel WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':tel' => $tel, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->tel = $tel;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- return $this;
- }
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- public function set_fax($fax)
- {
- $sql = 'UPDATE usr SET fax = :fax WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':fax' => $fax, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->fax = $fax;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var string
+ */
+ protected $email;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $login;
- public function set_job($job)
- {
- $sql = 'UPDATE usr SET fonction = :fonction WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':fonction' => $job, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->job = $job;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var string
+ */
+ protected $firstname;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $lastname;
- public function set_position($position)
- {
- $sql = 'UPDATE usr SET activite = :activite WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':activite' => $position, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->position = $position;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var string
+ */
+ protected $address;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $city;
- public function set_company($company)
- {
- $sql = 'UPDATE usr SET societe = :company WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':company' => $company, ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
- $this->company = $company;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var int
+ */
+ protected $geonameid;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $zip;
- public function set_template(User_Adapter $owner)
- {
- $this->is_template = true;
- $this->template_owner = $owner;
+ /**
+ *
+ * @var int
+ */
+ protected $gender;
- if ($owner->get_id() == $this->get_id())
- throw new Exception_InvalidArgument ();
+ /**
+ *
+ * @var string
+ */
+ protected $tel;
- $sql = 'UPDATE usr SET model_of = :owner_id WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':owner_id' => $owner->get_id(), ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ /**
+ *
+ * @var int
+ */
+ protected $lastModel;
- $this->set_ftp_address('')
- ->set_activeftp(false)
- ->set_city('')
- ->set_company('')
- ->set_email(null)
- ->set_fax('')
- ->set_firstname('')
- ->set_ftp_dir('')
- ->set_ftp_dir_prefix('')
- ->set_ftp_login('')
- ->set_ftp_passif('')
- ->set_ftp_password('')
- ->set_gender('')
- ->set_geonameid('')
- ->set_job('')
- ->set_lastname('')
- ->set_mail_locked(false)
- ->set_mail_notifications(true)
- ->set_position('')
- ->set_zip('')
- ->set_tel('');
+ /**
+ *
+ * @var DateTime
+ */
+ protected $creationdate;
- $this->delete_data_from_cache();
+ /**
+ *
+ * @var DateTime
+ */
+ protected $modificationdate;
- return $this;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $fax;
- public function is_template()
- {
- return $this->is_template;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $job;
- public function is_special()
- {
- return in_array($this->login, array('invite', 'autoregister'));
- }
+ /**
+ *
+ * @var string
+ */
+ protected $position;
- public function get_template_owner()
- {
- return $this->template_owner;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $company;
- public static function get_usr_id_from_email($email)
- {
- if (is_null($email))
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_admin;
- return false;
+ /**
+ *
+ * @var boolean
+ */
+ protected $ldap_created;
- $conn = connection::getPDOConnection();
- $sql = 'SELECT usr_id FROM usr
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_guest;
+
+ /**
+ *
+ * @var boolean
+ */
+ protected $mail_locked;
+
+ /**
+ *
+ * @var string
+ */
+ protected $defaultftpdatas;
+
+ /**
+ *
+ * @var string
+ */
+ protected $mail_notifications;
+
+ /**
+ *
+ * @var string
+ */
+ protected $activeftp;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_address;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_login;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_password;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_passif;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_dir;
+
+ /**
+ *
+ * @var string
+ */
+ protected $ftp_dir_prefix;
+
+ /**
+ *
+ * @var string
+ */
+ protected $country;
+
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_template;
+
+ /**
+ *
+ * @var User_Adapter
+ */
+ protected $template_owner;
+
+ /**
+ *
+ * @param type $id
+ * @param appbox $appbox
+ * @return User_Adapter
+ */
+ public function __construct($id, appbox &$appbox)
+ {
+ $this->appbox = $appbox;
+ $this->load($id);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param type $id
+ * @param appbox $appbox
+ * @return User_Adapter
+ */
+ public static function getInstance($id, appbox &$appbox)
+ {
+ if (is_int((int) $id) && (int) $id > 0) {
+ $id = (int) $id;
+ }
+ else
+ throw new Exception('Invalid usr_id');
+
+ if ( ! isset(self::$_instance[$id])) {
+ try {
+ self::$_instance[$id] = $appbox->get_data_from_cache('_user_' . $id);
+ self::$_instance[$id]->set_appbox($appbox);
+ } catch (Exception $e) {
+ self::$_instance[$id] = new self($id, $appbox);
+ $appbox->set_data_to_cache(self::$_instance[$id], '_user_' . $id);
+ }
+ }
+
+ return array_key_exists($id, self::$_instance) ? self::$_instance[$id] : false;
+ }
+
+ /**
+ * Return Access Control List object for the user
+ *
+ * @return ACL
+ */
+ public function ACL()
+ {
+ return $this->get_ACL();
+ }
+
+ /**
+ *
+ * @param appbox $appbox
+ */
+ protected function set_appbox(appbox &$appbox)
+ {
+ $this->appbox = $appbox;
+ }
+
+ /**
+ *
+ * @param type $pasword
+ * @return User_Adapter
+ */
+ public function set_password($pasword)
+ {
+ $sql = 'UPDATE usr SET usr_password = :password, salted_password = "1"
+ WHERE usr_id = :usr_id';
+
+ $password = self::salt_password($pasword, $this->get_nonce());
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':password' => $password, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $email
+ * @return User_Adapter
+ */
+ public function set_email($email)
+ {
+ if (trim($email) == '')
+ $email = null;
+
+ $test_user = User_Adapter::get_usr_id_from_email($email);
+
+ if ($test_user && $test_user != $this->get_id()) {
+ throw new Exception_InvalidArgument(sprintf(_('A user already exists with email addres %s'), $email));
+ }
+
+ $sql = 'UPDATE usr SET usr_mail = :new_email WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':new_email' => $email, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->email = $email;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ * Load if needed of the ACL for the current user
+ *
+ * @return ACL
+ */
+ protected function get_ACL()
+ {
+ if ( ! $this->ACL instanceof ACL)
+ $this->ACL = new ACL($this, $this->appbox);
+
+ return $this->ACL;
+ }
+
+ /**
+ *
+ * @param boolean $renew
+ * @return system_url
+ */
+ public function get_protected_rss_url($renew = false)
+ {
+ $session = $this->appbox->get_session();
+ $registry = $this->appbox->get_registry();
+
+ $token = $title = false;
+
+ if ( ! $renew) {
+ $sql = 'SELECT value FROM tokens WHERE usr_id = :usr_id AND type="rss"';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ $token = $row['value'];
+ } else {
+ $sql = 'DELETE FROM tokens WHERE usr_id = :usr_id AND type="rss"';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ }
+ if ($token === false) {
+ $token = random::getUrlToken(\random::TYPE_RSS, $this->id);
+ }
+
+ return new system_url($registry->get('GV_ServerName') . 'atom/' . $token);
+ }
+
+ /**
+ * Query in the cache
+ *
+ * @param unknown_type $query
+ * @return boolean
+ */
+ public static function saveQuery($query)
+ {
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ $sql = "INSERT INTO dsel (id, name, usr_id, query)
+ VALUES (null, :name, :usr_id, :query)";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(
+ ':name' => $query,
+ ':usr_id' => $session->get_usr_id(),
+ ':query' => $query
+ ));
+ $stmt->closeCursor();
+
+ if ($user->getPrefs('start_page') == 'LAST_QUERY')
+ $user->setPrefs('start_page_query', $query);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_country()
+ {
+ if ($this->geonameid) {
+ $geonames = new geonames();
+
+ return $geonames->get_country($this->geonameid);
+ }
+
+ return '';
+ }
+
+ /**
+ *
+ * @param string $login
+ * @return int
+ */
+ public static function get_usr_id_from_login($login)
+ {
+ $conn = connection::getPDOConnection();
+ $sql = 'SELECT usr_id FROM usr WHERE usr_login = :login';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':login' => trim($login)));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $usr_id = $row ? (int) $row['usr_id'] : false;
+
+ return $usr_id;
+ }
+
+ /**
+ *
+ * @param int $datas
+ * @return User_Adapter
+ */
+ public function set_defaultftpdatas($datas)
+ {
+ $sql = 'UPDATE usr SET defaultftpdatasent = :defaultftpdatas WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':defaultftpdatas' => $datas, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->defaultftpdatas = $datas;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param bollean $boolean
+ * @return User_Adapter
+ */
+ public function set_mail_notifications($boolean)
+ {
+ $value = $boolean ? '1' : '0';
+ $sql = 'UPDATE usr SET mail_notifications = :mail_notifications WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':mail_notifications' => $value, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->mail_notifications = ! ! $boolean;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param boolean $boolean
+ * @return User_Adapter
+ */
+ public function set_activeftp($boolean)
+ {
+ $value = $boolean ? '1' : '0';
+ $sql = 'UPDATE usr SET activeftp = :activeftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':activeftp' => $value, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->activeftp = $boolean;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param boolean $boolean
+ * @return User_Adapter
+ */
+ public function set_ldap_created($boolean)
+ {
+ $value = $boolean ? '1' : '0';
+ $sql = 'UPDATE usr SET ldap_created = :ldap_created WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':ldap_created' => $value, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ldap_created = $boolean;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $address
+ * @return User_Adapter
+ */
+ public function set_ftp_address($address)
+ {
+ $sql = 'UPDATE usr SET addrftp = :addrftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':addrftp' => $address, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_address = $address;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $login
+ * @return User_Adapter
+ */
+ public function set_ftp_login($login)
+ {
+ $sql = 'UPDATE usr SET loginftp = :loginftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':loginftp' => $login, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_login = $login;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param type $password
+ * @return User_Adapter
+ */
+ public function set_ftp_password($password)
+ {
+ $sql = 'UPDATE usr SET pwdFTP = :passwordftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':passwordftp' => $password, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_password = $password;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_ftp_passif($boolean)
+ {
+ $value = $boolean ? '1' : '0';
+ $sql = 'UPDATE usr SET passifftp = :passifftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':passifftp' => $value, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_passif = ! ! $boolean;
+
+ return $this;
+ }
+
+ public function set_ftp_dir($ftp_dir)
+ {
+ $sql = 'UPDATE usr SET destftp = :destftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':destftp' => $ftp_dir, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_dir = $ftp_dir;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_ftp_dir_prefix($ftp_dir_prefix)
+ {
+ $sql = 'UPDATE usr SET prefixFTPfolder = :prefixftp WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':prefixftp' => $ftp_dir_prefix, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->ftp_dir_prefix = $ftp_dir_prefix;
+
+ return $this;
+ }
+
+ public function set_firstname($firstname)
+ {
+ $sql = 'UPDATE usr SET usr_prenom = :usr_prenom WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_prenom' => $firstname, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->firstname = $firstname;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_lastname($lastname)
+ {
+ $sql = 'UPDATE usr SET usr_nom = :usr_nom WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_nom' => $lastname, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->lastname = $lastname;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_address($address)
+ {
+ $sql = 'UPDATE usr SET adresse = :adresse WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':adresse' => $address, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->address = $address;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_city($city)
+ {
+ $sql = 'UPDATE usr SET ville = :city WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':city' => $city, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->city = $city;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_geonameid($geonameid)
+ {
+ $geonames = new geonames();
+ $country_code = $geonames->get_country_code($geonameid);
+ $sql = 'UPDATE usr SET geonameid = :geonameid, pays=:country_code WHERE usr_id = :usr_id';
+
+ $datas = array(
+ ':geonameid' => $geonameid,
+ ':usr_id' => $this->get_id(),
+ ':country_code' => $country_code
+ );
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($datas);
+ $stmt->closeCursor();
+ $this->geonameid = $geonameid;
+ $this->country = $country_code;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_zip($zip)
+ {
+ $sql = 'UPDATE usr SET cpostal = :cpostal WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':cpostal' => $zip, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->zip = $zip;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_gender($gender)
+ {
+ $sql = 'UPDATE usr SET usr_sexe = :usr_sexe WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_sexe' => $gender, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->gender = $gender;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_tel($tel)
+ {
+ $sql = 'UPDATE usr SET tel = :tel WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':tel' => $tel, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->tel = $tel;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_fax($fax)
+ {
+ $sql = 'UPDATE usr SET fax = :fax WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':fax' => $fax, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->fax = $fax;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_job($job)
+ {
+ $sql = 'UPDATE usr SET fonction = :fonction WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':fonction' => $job, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->job = $job;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_position($position)
+ {
+ $sql = 'UPDATE usr SET activite = :activite WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':activite' => $position, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->position = $position;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_company($company)
+ {
+ $sql = 'UPDATE usr SET societe = :company WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':company' => $company, ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+ $this->company = $company;
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function set_template(User_Adapter $owner)
+ {
+ $this->is_template = true;
+ $this->template_owner = $owner;
+
+ if ($owner->get_id() == $this->get_id())
+ throw new Exception_InvalidArgument ();
+
+ $sql = 'UPDATE usr SET model_of = :owner_id WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':owner_id' => $owner->get_id(), ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ $this->set_ftp_address('')
+ ->set_activeftp(false)
+ ->set_city('')
+ ->set_company('')
+ ->set_email(null)
+ ->set_fax('')
+ ->set_firstname('')
+ ->set_ftp_dir('')
+ ->set_ftp_dir_prefix('')
+ ->set_ftp_login('')
+ ->set_ftp_passif('')
+ ->set_ftp_password('')
+ ->set_gender('')
+ ->set_geonameid('')
+ ->set_job('')
+ ->set_lastname('')
+ ->set_mail_locked(false)
+ ->set_mail_notifications(true)
+ ->set_position('')
+ ->set_zip('')
+ ->set_tel('');
+
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ public function is_template()
+ {
+ return $this->is_template;
+ }
+
+ public function is_special()
+ {
+ return in_array($this->login, array('invite', 'autoregister'));
+ }
+
+ public function get_template_owner()
+ {
+ return $this->template_owner;
+ }
+
+ public static function get_usr_id_from_email($email)
+ {
+ if (is_null($email))
+ return false;
+
+ $conn = connection::getPDOConnection();
+ $sql = 'SELECT usr_id FROM usr
WHERE usr_mail = :email
AND usr_login NOT LIKE "(#deleted_%"
AND invite="0" AND usr_login != "autoregister"';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':email' => trim($email)));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':email' => trim($email)));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $usr_id = $row ? $row['usr_id'] : false;
+ $usr_id = $row ? $row['usr_id'] : false;
- return $usr_id;
- }
+ return $usr_id;
+ }
- /**
- * @todo close all open session
- * @return type
- */
- public function delete()
- {
- $sql = 'UPDATE usr SET usr_login = :usr_login , usr_mail = null
+ /**
+ * @todo close all open session
+ * @return type
+ */
+ public function delete()
+ {
+ $sql = 'UPDATE usr SET usr_login = :usr_login , usr_mail = null
WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_login' => '(#deleted_' . $this->get_login() . '_' . $this->get_id(), ':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_login' => '(#deleted_' . $this->get_login() . '_' . $this->get_id(), ':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM basusr WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM basusr WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM sbasusr WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM sbasusr WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM dsel WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM dsel WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM edit_presets WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM edit_presets WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM ftp_export WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM ftp_export WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM `order` WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM `order` WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM sselnew WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM sselnew WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM tokens WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM tokens WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM usrlist WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM usrlist WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM usr_settings WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM usr_settings WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM usrlistusers WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM usrlistusers WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- $sql = 'DELETE FROM ssel WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $stmt->closeCursor();
+ $sql = 'DELETE FROM ssel WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $stmt->closeCursor();
- unset(self::$_instance[$this->get_id()]);
+ unset(self::$_instance[$this->get_id()]);
- return;
- }
+ return;
+ }
- public function get_defaultftpdatas()
- {
- return $this->defaultftpdatas;
- }
+ public function get_defaultftpdatas()
+ {
+ return $this->defaultftpdatas;
+ }
- public function get_mail_notifications()
- {
- return $this->mail_notifications;
- }
+ public function get_mail_notifications()
+ {
+ return $this->mail_notifications;
+ }
- public function get_activeftp()
- {
- return $this->activeftp;
- }
+ public function get_activeftp()
+ {
+ return $this->activeftp;
+ }
- public function get_ftp_address()
- {
- return $this->ftp_address;
- }
+ public function get_ftp_address()
+ {
+ return $this->ftp_address;
+ }
- public function get_ftp_login()
- {
- return $this->ftp_login;
- }
+ public function get_ftp_login()
+ {
+ return $this->ftp_login;
+ }
- public function get_ftp_password()
- {
- return $this->ftp_password;
- }
+ public function get_ftp_password()
+ {
+ return $this->ftp_password;
+ }
- public function get_ftp_passif()
- {
- return $this->ftp_passif;
- }
+ public function get_ftp_passif()
+ {
+ return $this->ftp_passif;
+ }
- public function get_ftp_dir()
- {
- return $this->ftp_dir;
- }
+ public function get_ftp_dir()
+ {
+ return $this->ftp_dir;
+ }
- public function get_ftp_dir_prefix()
- {
- return $this->ftp_dir_prefix;
- }
+ public function get_ftp_dir_prefix()
+ {
+ return $this->ftp_dir_prefix;
+ }
- /**
- *
- * @param $id
- * @return user
- */
- public function load($id)
- {
- $sql = 'SELECT usr_id, ldap_created, create_db, usr_login, usr_nom, activite,
+ /**
+ *
+ * @param $id
+ * @return user
+ */
+ public function load($id)
+ {
+ $sql = 'SELECT usr_id, ldap_created, create_db, usr_login, usr_nom, activite,
usr_prenom, usr_sexe as gender, usr_mail, adresse, usr_creationdate, usr_modificationdate,
ville, cpostal, tel, fax, fonction, societe, geonameid, lastModel, invite,
defaultftpdatasent, mail_notifications, activeftp, addrftp, loginftp,
pwdFTP, passifftp, destftp, prefixFTPfolder, mail_locked, model_of
FROM usr WHERE usr_id= :id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $id));
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->id = (int) $row['usr_id'];
- $this->email = $row['usr_mail'];
- $this->login = $row['usr_login'];
+ $this->id = (int) $row['usr_id'];
+ $this->email = $row['usr_mail'];
+ $this->login = $row['usr_login'];
- $this->ldap_created = $row['ldap_created'];
+ $this->ldap_created = $row['ldap_created'];
- $this->defaultftpdatas = $row['defaultftpdatasent'];
- $this->mail_notifications = $row['mail_notifications'];
- $this->activeftp = $row['activeftp'];
- $this->ftp_address = $row['addrftp'];
- $this->ftp_login = $row['loginftp'];
- $this->ftp_password = $row['pwdFTP'];
- $this->ftp_passif = $row['passifftp'];
- $this->ftp_dir = $row['destftp'];
- $this->ftp_dir_prefix = $row['prefixFTPfolder'];
+ $this->defaultftpdatas = $row['defaultftpdatasent'];
+ $this->mail_notifications = $row['mail_notifications'];
+ $this->activeftp = $row['activeftp'];
+ $this->ftp_address = $row['addrftp'];
+ $this->ftp_login = $row['loginftp'];
+ $this->ftp_password = $row['pwdFTP'];
+ $this->ftp_passif = $row['passifftp'];
+ $this->ftp_dir = $row['destftp'];
+ $this->ftp_dir_prefix = $row['prefixFTPfolder'];
- $this->mail_locked = !!$row['mail_locked'];
+ $this->mail_locked = ! ! $row['mail_locked'];
- $this->firstname = $row['usr_prenom'];
- $this->lastname = $row['usr_nom'];
- $this->address = $row['adresse'];
- $this->city = $row['ville'];
- $this->geonameid = $row['geonameid'];
- $this->zip = $row['cpostal'];
- $this->gender = $row['gender'];
- $this->tel = $row['tel'];
- $this->fax = $row['fax'];
- $this->job = $row['fonction'];
- $this->position = $row['activite'];
- $this->company = $row['societe'];
- $this->creationdate = new DateTime($row['usr_creationdate']);
- $this->modificationdate = new DateTime($row['usr_modificationdate']);
- $this->applied_template = $row['lastModel'];
+ $this->firstname = $row['usr_prenom'];
+ $this->lastname = $row['usr_nom'];
+ $this->address = $row['adresse'];
+ $this->city = $row['ville'];
+ $this->geonameid = $row['geonameid'];
+ $this->zip = $row['cpostal'];
+ $this->gender = $row['gender'];
+ $this->tel = $row['tel'];
+ $this->fax = $row['fax'];
+ $this->job = $row['fonction'];
+ $this->position = $row['activite'];
+ $this->company = $row['societe'];
+ $this->creationdate = new DateTime($row['usr_creationdate']);
+ $this->modificationdate = new DateTime($row['usr_modificationdate']);
+ $this->applied_template = $row['lastModel'];
- $this->country = geonames::get_country($row['geonameid']);
+ $this->country = geonames::get_country($row['geonameid']);
- $this->is_admin = ($row['create_db'] == '1');
- $this->is_guest = ($row['invite'] == '1');
+ $this->is_admin = ($row['create_db'] == '1');
+ $this->is_guest = ($row['invite'] == '1');
- if ($row['model_of'] > 0)
- {
- $this->is_template = true;
- $this->template_owner = self::getInstance($row['model_of'], $this->appbox);
- }
-
- return $this;
- }
-
- public function set_last_template(User_Interface $template)
- {
- $sql = 'UPDATE usr SET lastModel = :template_id WHERE usr_id = :usr_id';
-
- $params = array(
- ':usr_id' => $this->get_id()
- , ':template_id' => $template->get_login()
- );
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- public function set_mail_locked($boolean)
- {
- $sql = 'UPDATE usr SET mail_locked = :mail_locked WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id(), ':mail_locked' => ($boolean ? '1' : '0')));
- $stmt->closeCursor();
- $this->mail_locked = !!$boolean;
-
- return $this;
- }
-
- public function get_mail_locked()
- {
- return $this->mail_locked;
- }
-
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
-
- public function get_ldap_created()
- {
- return $this->ldap_created;
- }
-
- public function is_guest()
- {
- return $this->is_guest;
- }
-
- public function get_login()
- {
- return $this->login;
- }
-
- public function get_email()
- {
- return $this->email;
- }
-
- public function get_firstname()
- {
- return $this->firstname;
- }
-
- public function get_lastname()
- {
- return $this->lastname;
- }
-
- public function get_company()
- {
- return $this->company;
- }
-
- public function get_tel()
- {
- return $this->tel;
- }
-
- public function get_fax()
- {
- return $this->fax;
- }
-
- public function get_job()
- {
- return $this->job;
- }
-
- public function get_position()
- {
- return $this->position;
- }
-
- public function get_zipcode()
- {
- return $this->zip;
- }
-
- public function get_city()
- {
- return $this->city;
- }
-
- public function get_address()
- {
- return $this->address;
- }
-
- public function get_gender()
- {
- return $this->gender;
- }
-
- public function get_geonameid()
- {
- return $this->geonameid;
- }
-
- public function get_last_connection()
- {
- $sql = 'SELECT last_conn FROM usr WHERE usr_id = :usr_id';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
-
- $stmt->execute(array(':usr_id' => $this->get_id()));
-
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
-
- $stmt->closeCursor();
-
- $date_obj = new DateTime($row['last_conn']);
-
- return $date_obj;
- }
-
- public function get_applied_template()
- {
-
- return $this->applied_template;
- }
-
- public function get_creation_date()
- {
- return $this->creationdate;
- }
-
- public function get_modification_date()
- {
- return $this->modificationdate;
- }
-
- public function is_admin()
- {
- return $this->is_admin;
- }
-
- protected function load_preferences()
- {
- if ($this->_prefs)
-
- return $this;
-
- $registry = \registry::get_instance();
-
- $sql = 'SELECT prop, value FROM usr_settings WHERE usr_id= :id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs as $row)
- {
- $this->_prefs[$row['prop']] = $row['value'];
- }
-
- foreach (self::$def_values as $k => $v)
- {
- if (!isset($this->_prefs[$k]))
- {
- if ($k == 'start_page_query' && $registry->get('GV_defaultQuery'))
- {
- $v = $registry->get('GV_defaultQuery');
+ if ($row['model_of'] > 0) {
+ $this->is_template = true;
+ $this->template_owner = self::getInstance($row['model_of'], $this->appbox);
}
- $this->_prefs[$k] = $v;
- $this->update_pref($k, $v);
- }
+ return $this;
}
- return $this;
- }
-
- protected function load_notifications_preferences()
- {
- $Core = bootstrap::getCore();
- $evt_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
- $notifications = $evt_mngr->list_notifications_available($this->id);
-
- foreach ($notifications as $notification_group => $nots)
+ public function set_last_template(User_Interface $template)
{
- foreach ($nots as $notification)
- {
- if (!isset($this->_prefs['notification_' . $notification['id']]))
- {
- $this->_prefs['notification_' . $notification['id']] = '1';
+ $sql = 'UPDATE usr SET lastModel = :template_id WHERE usr_id = :usr_id';
- $this->update_pref('notification_' . $notification['id'], '1');
- }
- }
- }
- $this->notification_preferences_loaded = true;
- }
-
- protected $notifications_preferences_loaded = false;
-
- public function get_notifications_preference($notification_id)
- {
- if (!$this->notifications_preferences_loaded)
- $this->load_notifications_preferences();
-
- return $this->_prefs['notification_' . $notification_id];
- }
-
- public function set_notification_preference($notification_id, $value)
- {
- if (!$this->notifications_preferences_loaded)
- $this->load_notifications_preferences();
-
- return $this->_prefs['notification_' . $notification_id] = $value ? '1' : '0';
- }
-
- public function get_display_name()
- {
- if ($this->is_template())
- $display_name = sprintf(_('modele %s'), $this->get_login());
- elseif (trim($this->lastname) !== '' || trim($this->firstname) !== '')
- $display_name = $this->firstname . ' ' . $this->lastname;
- elseif (trim($this->email) !== '')
- $display_name = $this->email;
- else
- $display_name = _('phraseanet::utilisateur inconnu');
-
- return $display_name;
- }
-
- protected function update_pref($prop, $value)
- {
- try
- {
- $sql = 'REPLACE INTO usr_settings (usr_id, prop, value)
- VALUES (:usr_id, :prop, :value)';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(
- ':usr_id' => $this->id,
- ':prop' => $prop,
- ':value' => $value
- ));
- $this->delete_data_from_cache();
- }
- catch (Exception $e)
- {
-
- }
-
- return $this;
- }
-
- public function get_cache_key($option = null)
- {
- return '_user_' . $this->get_id() . ($option ? '_' . $option : '');
- }
-
- public function delete_data_from_cache($option = null)
- {
- $this->appbox->delete_data_from_cache($this->get_cache_key($option));
-
- return $this;
- }
-
- public function get_data_from_cache($option = null)
- {
- $this->appbox->get_data_from_cache($this->get_cache_key($option));
-
- return $this;
- }
-
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
-
- return $this;
- }
-
- public static function avLanguages()
- {
- $lngs = array();
-
- $path = __DIR__ . "/../../../locale";
- if ($hdir = opendir($path))
- {
- while (false !== ($file = readdir($hdir)))
- {
- if (substr($file, 0, 1) == "." || strtolower($file) == "cvs")
- continue;
- if (is_dir($path . "/" . $file) && strpos($file, '_') == 2 && strlen($file) == 5)
- {
- if (!array_key_exists($file, self::$locales))
- continue;
- $supFile = explode('_', $file);
- if (!isset($lngs[$supFile[0]]))
- $lngs[$supFile[0]] = array();
- $lngs[$supFile[0]][$file] = array('name' => self::$locales[$file], 'selected' => false);
- }
- }
- }
-
- return $lngs;
- }
-
- public static function get_wrong_email_users(appbox $appbox)
- {
-
- $sql = 'SELECT usr_mail, usr_id FROM usr WHERE usr_mail IS NOT NULL';
-
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
-
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
-
- $stmt->closeCursor();
-
- $users = array();
-
- foreach ($rs as $row)
- {
- if (!isset($users[$row['usr_mail']]))
- {
- $users[$row['usr_mail']] = array();
- }
-
- $users[$row['usr_mail']][] = $row['usr_id'];
- }
-
- $bad_users = array();
-
- foreach ($users as $email => $usrs)
- {
- if (count($usrs) > 1)
- {
- $bad_users[$email] = array();
- foreach ($usrs as $usr_id)
- {
- $user = User_Adapter::getInstance($usr_id, $appbox);
- $bad_users[$email][$user->get_id()] = $user;
- }
- }
- }
-
- unset($users);
-
- return $bad_users;
- }
-
- public function setPrefs($prop, $value)
- {
- $this->load_preferences();
- if (isset($this->_prefs[$prop]) && $this->_prefs[$prop] === $value)
- {
- return $this->_prefs[$prop];
- }
-
- $ok = true;
-
- if (isset(self::$available_values[$prop]))
- {
- $ok = false;
- if (in_array($value, self::$available_values[$prop]))
- $ok = true;
- }
-
- if ($ok)
- {
- $this->_prefs[$prop] = $value;
- $this->update_pref($prop, $value);
- }
-
- return $this->_prefs[$prop];
- }
-
- public function getPrefs($prop)
- {
- $this->load_preferences();
- if (!isset($this->_prefs[$prop]))
- {
- $this->_prefs[$prop] = null;
- $this->update_pref($prop, null);
- }
-
- return $this->_prefs[$prop];
- }
-
- public static function updateClientInfos($app_id)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- if (!$session->is_authenticated())
-
- return;
-
- $ses_id = $session->get_ses_id();
- $usr_id = $session->get_usr_id();
-
- $user = User_Adapter::getInstance($usr_id, $appbox);
-
- $appName = array(
- '1' => 'Prod',
- '2' => 'Client',
- '3' => 'Admin',
- '4' => 'Report',
- '5' => 'Thesaurus',
- '6' => 'Compare',
- '7' => 'Validate',
- '8' => 'Upload',
- '9' => 'API'
- );
-
- if (isset($appName[$app_id]))
- {
- $sbas_ids = array_keys($user->ACL()->get_granted_sbas());
-
- foreach ($sbas_ids as $sbas_id)
- {
- try
- {
- $logger = $session->get_logger(databox::get_instance($sbas_id));
-
- $connbas = connection::getPDOConnection($sbas_id);
- $sql = 'SELECT appli FROM log WHERE id = :log_id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':log_id' => $logger->get_id()));
- $row3 = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if (!$row3)
- throw new Exception('no log');
- $applis = unserialize($row3['appli']);
-
- if (!in_array($app_id, $applis))
- {
- $applis[] = $app_id;
- }
-
- $sql = 'UPDATE log SET appli = :applis WHERE id = :log_id';
-
- $params = array(
- ':applis' => serialize($applis)
- , ':log_id' => $logger->get_id()
- );
-
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- }
- catch (Exception $e)
- {
-
- }
- }
- }
-
- $sql = 'SELECT app FROM cache WHERE session_id = :ses_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':ses_id' => $ses_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $apps = array();
- if ($row)
- $apps = unserialize($row['app']);
-
- if (!in_array($app_id, $apps))
- $apps[] = $app_id;
-
- $sql = "UPDATE cache SET app = :applis WHERE session_id = :ses_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':applis' => serialize($apps), ':ses_id' => $ses_id));
- $stmt->closeCursor();
-
- return;
- }
-
- public static function get_sys_admins()
- {
- $sql = 'SELECT usr_id, usr_login FROM usr WHERE create_db="1"';
- $conn = connection::getPDOConnection();
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $users = array();
-
- foreach ($rs as $row)
- $users[$row['usr_id']] = $row['usr_login'];
-
- return $users;
- }
-
- public static function set_sys_admins($admins)
- {
- try
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $sql = "UPDATE usr SET create_db='0' WHERE create_db='1' AND usr_id != :usr_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $stmt->closeCursor();
-
- $sql = "UPDATE usr SET create_db='1' WHERE usr_id IN (" . implode(',', $admins) . ")";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
-
- return true;
- }
- catch (Exception $e)
- {
-
- }
-
- return false;
- }
-
- public static function reset_sys_admins_rights()
- {
- $users = self::get_sys_admins();
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $conn = $appbox->get_connection();
-
- foreach ($appbox->get_databoxes() as $databox)
- {
- foreach ($users as $usr_id => $value)
- {
- $user = User_Adapter::getInstance($usr_id, $appbox);
- $user->ACL()->give_access_to_sbas(array($databox->get_sbas_id()));
-
- $rights = array(
- 'bas_manage' => '1'
- , 'bas_modify_struct' => '1'
- , 'bas_modif_th' => '1'
- , 'bas_chupub' => '1'
+ $params = array(
+ ':usr_id' => $this->get_id()
+ , ':template_id' => $template->get_login()
);
- $user->ACL()->update_rights_to_sbas($databox->get_sbas_id(), $rights);
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->delete_data_from_cache();
- foreach ($databox->get_collections() as $collection)
- {
- $user->ACL()->give_access_to_base(array($collection->get_base_id()));
+ return $this;
+ }
- $rights = array(
- 'canputinalbum' => '1'
- , 'candwnldhd' => '1'
- , 'candwnldsubdef' => '1'
- , 'nowatermark' => '1'
- , 'candwnldpreview' => '1'
- , 'cancmd' => '1'
- , 'canadmin' => '1'
- , 'canreport' => '1'
- , 'canpush' => '1'
- , 'creationdate' => '1'
- , 'canaddrecord' => '1'
- , 'canmodifrecord' => '1'
- , 'candeleterecord' => '1'
- , 'chgstatus' => '1'
- , 'imgtools' => '1'
- , 'manage' => '1'
- , 'modify_struct' => '1'
- , 'bas_modify_struct' => '1'
- );
+ public function set_mail_locked($boolean)
+ {
+ $sql = 'UPDATE usr SET mail_locked = :mail_locked WHERE usr_id = :usr_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id(), ':mail_locked' => ($boolean ? '1' : '0')));
+ $stmt->closeCursor();
+ $this->mail_locked = ! ! $boolean;
- $user->ACL()->update_rights_to_base($collection->get_base_id(), $rights);
- $user->ACL()->set_limits($collection->get_base_id(), false);
+ return $this;
+ }
+
+ public function get_mail_locked()
+ {
+ return $this->mail_locked;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
+
+ public function get_ldap_created()
+ {
+ return $this->ldap_created;
+ }
+
+ public function is_guest()
+ {
+ return $this->is_guest;
+ }
+
+ public function get_login()
+ {
+ return $this->login;
+ }
+
+ public function get_email()
+ {
+ return $this->email;
+ }
+
+ public function get_firstname()
+ {
+ return $this->firstname;
+ }
+
+ public function get_lastname()
+ {
+ return $this->lastname;
+ }
+
+ public function get_company()
+ {
+ return $this->company;
+ }
+
+ public function get_tel()
+ {
+ return $this->tel;
+ }
+
+ public function get_fax()
+ {
+ return $this->fax;
+ }
+
+ public function get_job()
+ {
+ return $this->job;
+ }
+
+ public function get_position()
+ {
+ return $this->position;
+ }
+
+ public function get_zipcode()
+ {
+ return $this->zip;
+ }
+
+ public function get_city()
+ {
+ return $this->city;
+ }
+
+ public function get_address()
+ {
+ return $this->address;
+ }
+
+ public function get_gender()
+ {
+ return $this->gender;
+ }
+
+ public function get_geonameid()
+ {
+ return $this->geonameid;
+ }
+
+ public function get_last_connection()
+ {
+ $sql = 'SELECT last_conn FROM usr WHERE usr_id = :usr_id';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+
+ $stmt->closeCursor();
+
+ $date_obj = new DateTime($row['last_conn']);
+
+ return $date_obj;
+ }
+
+ public function get_applied_template()
+ {
+
+ return $this->applied_template;
+ }
+
+ public function get_creation_date()
+ {
+ return $this->creationdate;
+ }
+
+ public function get_modification_date()
+ {
+ return $this->modificationdate;
+ }
+
+ public function is_admin()
+ {
+ return $this->is_admin;
+ }
+
+ protected function load_preferences()
+ {
+ if ($this->_prefs)
+ return $this;
+
+ $registry = \registry::get_instance();
+
+ $sql = 'SELECT prop, value FROM usr_settings WHERE usr_id= :id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs as $row) {
+ $this->_prefs[$row['prop']] = $row['value'];
}
- }
+
+ foreach (self::$def_values as $k => $v) {
+ if ( ! isset($this->_prefs[$k])) {
+ if ($k == 'start_page_query' && $registry->get('GV_defaultQuery')) {
+ $v = $registry->get('GV_defaultQuery');
+ }
+
+ $this->_prefs[$k] = $v;
+ $this->update_pref($k, $v);
+ }
+ }
+
+ return $this;
}
- return;
- }
-
- public static function get_locale($usr_id)
- {
- $locale = 'en_GB';
- try
+ protected function load_notifications_preferences()
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $registry = $appbox->get_registry();
- $locale = $registry->get('GV_default_lng');
+ $Core = bootstrap::getCore();
+ $evt_mngr = eventsmanager_broker::getInstance($this->appbox, $Core);
+ $notifications = $evt_mngr->list_notifications_available($this->id);
- $sql = "SELECT locale FROM usr WHERE usr_id = :usr_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ foreach ($notifications as $notification_group => $nots) {
+ foreach ($nots as $notification) {
+ if ( ! isset($this->_prefs['notification_' . $notification['id']])) {
+ $this->_prefs['notification_' . $notification['id']] = '1';
- if ($row)
- {
- $locale = $row['locale'];
- }
+ $this->update_pref('notification_' . $notification['id'], '1');
+ }
+ }
+ }
+ $this->notification_preferences_loaded = true;
}
- catch (Exception $e)
+ protected $notifications_preferences_loaded = false;
+
+ public function get_notifications_preference($notification_id)
+ {
+ if ( ! $this->notifications_preferences_loaded)
+ $this->load_notifications_preferences();
+
+ return $this->_prefs['notification_' . $notification_id];
+ }
+
+ public function set_notification_preference($notification_id, $value)
+ {
+ if ( ! $this->notifications_preferences_loaded)
+ $this->load_notifications_preferences();
+
+ return $this->_prefs['notification_' . $notification_id] = $value ? '1' : '0';
+ }
+
+ public function get_display_name()
+ {
+ if ($this->is_template())
+ $display_name = sprintf(_('modele %s'), $this->get_login());
+ elseif (trim($this->lastname) !== '' || trim($this->firstname) !== '')
+ $display_name = $this->firstname . ' ' . $this->lastname;
+ elseif (trim($this->email) !== '')
+ $display_name = $this->email;
+ else
+ $display_name = _('phraseanet::utilisateur inconnu');
+
+ return $display_name;
+ }
+
+ protected function update_pref($prop, $value)
+ {
+ try {
+ $sql = 'REPLACE INTO usr_settings (usr_id, prop, value)
+ VALUES (:usr_id, :prop, :value)';
+
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(
+ ':usr_id' => $this->id,
+ ':prop' => $prop,
+ ':value' => $value
+ ));
+ $this->delete_data_from_cache();
+ } catch (Exception $e) {
+
+ }
+
+ return $this;
+ }
+
+ public function get_cache_key($option = null)
+ {
+ return '_user_' . $this->get_id() . ($option ? '_' . $option : '');
+ }
+
+ public function delete_data_from_cache($option = null)
+ {
+ $this->appbox->delete_data_from_cache($this->get_cache_key($option));
+
+ return $this;
+ }
+
+ public function get_data_from_cache($option = null)
+ {
+ $this->appbox->get_data_from_cache($this->get_cache_key($option));
+
+ return $this;
+ }
+
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ $this->appbox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+
+ return $this;
+ }
+
+ public static function avLanguages()
+ {
+ $lngs = array();
+
+ $path = __DIR__ . "/../../../locale";
+ if ($hdir = opendir($path)) {
+ while (false !== ($file = readdir($hdir))) {
+ if (substr($file, 0, 1) == "." || strtolower($file) == "cvs")
+ continue;
+ if (is_dir($path . "/" . $file) && strpos($file, '_') == 2 && strlen($file) == 5) {
+ if ( ! array_key_exists($file, self::$locales))
+ continue;
+ $supFile = explode('_', $file);
+ if ( ! isset($lngs[$supFile[0]]))
+ $lngs[$supFile[0]] = array();
+ $lngs[$supFile[0]][$file] = array('name' => self::$locales[$file], 'selected' => false);
+ }
+ }
+ }
+
+ return $lngs;
+ }
+
+ public static function get_wrong_email_users(appbox $appbox)
{
+ $sql = 'SELECT usr_mail, usr_id FROM usr WHERE usr_mail IS NOT NULL';
+
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+
+ $stmt->closeCursor();
+
+ $users = array();
+
+ foreach ($rs as $row) {
+ if ( ! isset($users[$row['usr_mail']])) {
+ $users[$row['usr_mail']] = array();
+ }
+
+ $users[$row['usr_mail']][] = $row['usr_id'];
+ }
+
+ $bad_users = array();
+
+ foreach ($users as $email => $usrs) {
+ if (count($usrs) > 1) {
+ $bad_users[$email] = array();
+ foreach ($usrs as $usr_id) {
+ $user = User_Adapter::getInstance($usr_id, $appbox);
+ $bad_users[$email][$user->get_id()] = $user;
+ }
+ }
+ }
+
+ unset($users);
+
+ return $bad_users;
}
- return $locale;
- }
+ public function setPrefs($prop, $value)
+ {
+ $this->load_preferences();
+ if (isset($this->_prefs[$prop]) && $this->_prefs[$prop] === $value) {
+ return $this->_prefs[$prop];
+ }
- public static function create(appbox &$appbox, $login, $password, $email, $admin, $invite = false)
- {
- $conn = $appbox->get_connection();
+ $ok = true;
- if (trim($login) == '')
- throw new Exception('Invalid username');
- if (trim($password) == '')
- throw new Exception('Invalid password');
+ if (isset(self::$available_values[$prop])) {
+ $ok = false;
+ if (in_array($value, self::$available_values[$prop]))
+ $ok = true;
+ }
- $login = $invite ? 'invite' . random::generatePassword(16) : $login;
+ if ($ok) {
+ $this->_prefs[$prop] = $value;
+ $this->update_pref($prop, $value);
+ }
- $nonce = random::generatePassword(16);
+ return $this->_prefs[$prop];
+ }
- $sql = 'INSERT INTO usr
+ public function getPrefs($prop)
+ {
+ $this->load_preferences();
+ if ( ! isset($this->_prefs[$prop])) {
+ $this->_prefs[$prop] = null;
+ $this->update_pref($prop, null);
+ }
+
+ return $this->_prefs[$prop];
+ }
+
+ public static function updateClientInfos($app_id)
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ if ( ! $session->is_authenticated())
+ return;
+
+ $ses_id = $session->get_ses_id();
+ $usr_id = $session->get_usr_id();
+
+ $user = User_Adapter::getInstance($usr_id, $appbox);
+
+ $appName = array(
+ '1' => 'Prod',
+ '2' => 'Client',
+ '3' => 'Admin',
+ '4' => 'Report',
+ '5' => 'Thesaurus',
+ '6' => 'Compare',
+ '7' => 'Validate',
+ '8' => 'Upload',
+ '9' => 'API'
+ );
+
+ if (isset($appName[$app_id])) {
+ $sbas_ids = array_keys($user->ACL()->get_granted_sbas());
+
+ foreach ($sbas_ids as $sbas_id) {
+ try {
+ $logger = $session->get_logger(databox::get_instance($sbas_id));
+
+ $connbas = connection::getPDOConnection($sbas_id);
+ $sql = 'SELECT appli FROM log WHERE id = :log_id';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':log_id' => $logger->get_id()));
+ $row3 = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ( ! $row3)
+ throw new Exception('no log');
+ $applis = unserialize($row3['appli']);
+
+ if ( ! in_array($app_id, $applis)) {
+ $applis[] = $app_id;
+ }
+
+ $sql = 'UPDATE log SET appli = :applis WHERE id = :log_id';
+
+ $params = array(
+ ':applis' => serialize($applis)
+ , ':log_id' => $logger->get_id()
+ );
+
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+
+ }
+ }
+ }
+
+ $sql = 'SELECT app FROM cache WHERE session_id = :ses_id';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':ses_id' => $ses_id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $apps = array();
+ if ($row)
+ $apps = unserialize($row['app']);
+
+ if ( ! in_array($app_id, $apps))
+ $apps[] = $app_id;
+
+ $sql = "UPDATE cache SET app = :applis WHERE session_id = :ses_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':applis' => serialize($apps), ':ses_id' => $ses_id));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ public static function get_sys_admins()
+ {
+ $sql = 'SELECT usr_id, usr_login FROM usr WHERE create_db="1"';
+ $conn = connection::getPDOConnection();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $users = array();
+
+ foreach ($rs as $row)
+ $users[$row['usr_id']] = $row['usr_login'];
+
+ return $users;
+ }
+
+ public static function set_sys_admins($admins)
+ {
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+
+ $sql = "UPDATE usr SET create_db='0' WHERE create_db='1' AND usr_id != :usr_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $stmt->closeCursor();
+
+ $sql = "UPDATE usr SET create_db='1' WHERE usr_id IN (" . implode(',', $admins) . ")";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+
+ return true;
+ } catch (Exception $e) {
+
+ }
+
+ return false;
+ }
+
+ public static function reset_sys_admins_rights()
+ {
+ $users = self::get_sys_admins();
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $conn = $appbox->get_connection();
+
+ foreach ($appbox->get_databoxes() as $databox) {
+ foreach ($users as $usr_id => $value) {
+ $user = User_Adapter::getInstance($usr_id, $appbox);
+ $user->ACL()->give_access_to_sbas(array($databox->get_sbas_id()));
+
+ $rights = array(
+ 'bas_manage' => '1'
+ , 'bas_modify_struct' => '1'
+ , 'bas_modif_th' => '1'
+ , 'bas_chupub' => '1'
+ );
+
+ $user->ACL()->update_rights_to_sbas($databox->get_sbas_id(), $rights);
+
+ foreach ($databox->get_collections() as $collection) {
+ $user->ACL()->give_access_to_base(array($collection->get_base_id()));
+
+ $rights = array(
+ 'canputinalbum' => '1'
+ , 'candwnldhd' => '1'
+ , 'candwnldsubdef' => '1'
+ , 'nowatermark' => '1'
+ , 'candwnldpreview' => '1'
+ , 'cancmd' => '1'
+ , 'canadmin' => '1'
+ , 'canreport' => '1'
+ , 'canpush' => '1'
+ , 'creationdate' => '1'
+ , 'canaddrecord' => '1'
+ , 'canmodifrecord' => '1'
+ , 'candeleterecord' => '1'
+ , 'chgstatus' => '1'
+ , 'imgtools' => '1'
+ , 'manage' => '1'
+ , 'modify_struct' => '1'
+ , 'bas_modify_struct' => '1'
+ );
+
+ $user->ACL()->update_rights_to_base($collection->get_base_id(), $rights);
+ $user->ACL()->set_limits($collection->get_base_id(), false);
+ }
+ }
+ }
+
+ return;
+ }
+
+ public static function get_locale($usr_id)
+ {
+ $locale = 'en_GB';
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $registry = $appbox->get_registry();
+ $locale = $registry->get('GV_default_lng');
+
+ $sql = "SELECT locale FROM usr WHERE usr_id = :usr_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ($row) {
+ $locale = $row['locale'];
+ }
+ } catch (Exception $e) {
+
+ }
+
+ return $locale;
+ }
+
+ public static function create(appbox &$appbox, $login, $password, $email, $admin, $invite = false)
+ {
+ $conn = $appbox->get_connection();
+
+ if (trim($login) == '')
+ throw new Exception('Invalid username');
+ if (trim($password) == '')
+ throw new Exception('Invalid password');
+
+ $login = $invite ? 'invite' . random::generatePassword(16) : $login;
+
+ $nonce = random::generatePassword(16);
+
+ $sql = 'INSERT INTO usr
(usr_id, usr_login, usr_password, usr_creationdate, usr_mail, create_db, nonce, salted_password, invite)
VALUES (null, :login, :password, NOW(), :email, :admin, :nonce, 1, :invite)';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(
- ':login' => $login,
- ':nonce' => $nonce,
- ':password' => self::salt_password($password, $nonce),
- ':email' => ($email ? $email : null),
- ':admin' => ($admin ? '1' : '0'),
- ':invite' => ($invite ? '1' : '0')
- ));
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(
+ ':login' => $login,
+ ':nonce' => $nonce,
+ ':password' => self::salt_password($password, $nonce),
+ ':email' => ($email ? $email : null),
+ ':admin' => ($admin ? '1' : '0'),
+ ':invite' => ($invite ? '1' : '0')
+ ));
+ $stmt->closeCursor();
- $usr_id = $conn->lastInsertId();
+ $usr_id = $conn->lastInsertId();
- if ($invite)
- {
- $sql = 'UPDATE usr SET usr_login = "invite' . $usr_id . '" WHERE usr_id="' . $usr_id . '"';
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
+ if ($invite) {
+ $sql = 'UPDATE usr SET usr_login = "invite' . $usr_id . '" WHERE usr_id="' . $usr_id . '"';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+ }
+
+ return self::getInstance($usr_id, $appbox);
}
- return self::getInstance($usr_id, $appbox);
- }
-
- public static function salt_password($password, $nonce)
- {
- $registry = registry::get_instance();
-
- return hash_hmac('sha512', $password . $nonce, $registry->get('GV_sit'));
- }
-
- protected $nonce;
-
- public function get_nonce()
- {
- if ($this->nonce)
-
- return $this->nonce;
- $nonce = false;
-
- $sql = 'SELECT nonce FROM usr WHERE usr_id = :usr_id ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $this->get_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
-
- $nonce = $row['nonce'];
-
- $this->nonce = $nonce;
-
- return $this->nonce;
- }
-
- public function __sleep()
- {
- $vars = array();
- foreach ($this as $key => $value)
+ public static function salt_password($password, $nonce)
{
- if (in_array($key, array('ACL', 'appbox')))
- continue;
- $vars[] = $key;
+ $registry = registry::get_instance();
+
+ return hash_hmac('sha512', $password . $nonce, $registry->get('GV_sit'));
+ }
+ protected $nonce;
+
+ public function get_nonce()
+ {
+ if ($this->nonce)
+ return $this->nonce;
+ $nonce = false;
+
+ $sql = 'SELECT nonce FROM usr WHERE usr_id = :usr_id ';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $this->get_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
+
+ $nonce = $row['nonce'];
+
+ $this->nonce = $nonce;
+
+ return $this->nonce;
}
- return $vars;
- }
+ public function __sleep()
+ {
+ $vars = array();
+ foreach ($this as $key => $value) {
+ if (in_array($key, array('ACL', 'appbox')))
+ continue;
+ $vars[] = $key;
+ }
+ return $vars;
+ }
}
diff --git a/lib/classes/User/Interface.class.php b/lib/classes/User/Interface.class.php
index d44f1c7b60..338dd01970 100644
--- a/lib/classes/User/Interface.class.php
+++ b/lib/classes/User/Interface.class.php
@@ -17,159 +17,160 @@
*/
interface User_Interface
{
- public function get_id();
- public function is_admin();
+ public function get_id();
- public function __construct($id, appbox &$appbox);
+ public function is_admin();
- public function ACL();
+ public function __construct($id, appbox &$appbox);
- public function set_password($pasword);
+ public function ACL();
- public function set_email($email);
+ public function set_password($pasword);
- public function get_protected_rss_url($renew = false);
+ public function set_email($email);
- public function get_country();
+ public function get_protected_rss_url($renew = false);
- public function set_defaultftpdatas($datas);
+ public function get_country();
- public function set_mail_notifications($boolean);
+ public function set_defaultftpdatas($datas);
- public function set_activeftp($boolean);
+ public function set_mail_notifications($boolean);
- public function set_ftp_address($address);
+ public function set_activeftp($boolean);
- public function set_ftp_login($login);
+ public function set_ftp_address($address);
- public function set_ftp_password($password);
+ public function set_ftp_login($login);
- public function set_ftp_passif($boolean);
+ public function set_ftp_password($password);
- public function set_ftp_dir($ftp_dir);
+ public function set_ftp_passif($boolean);
- public function set_ftp_dir_prefix($ftp_dir_prefix);
+ public function set_ftp_dir($ftp_dir);
- public function set_firstname($firstname);
+ public function set_ftp_dir_prefix($ftp_dir_prefix);
- public function set_lastname($lastname);
+ public function set_firstname($firstname);
- public function set_address($address);
+ public function set_lastname($lastname);
- public function set_city($city);
+ public function set_address($address);
- public function set_geonameid($geonameid);
+ public function set_city($city);
- public function set_zip($zip);
+ public function set_geonameid($geonameid);
- public function set_gender($gender);
+ public function set_zip($zip);
- public function set_tel($tel);
+ public function set_gender($gender);
- public function set_fax($fax);
+ public function set_tel($tel);
- public function set_job($job);
+ public function set_fax($fax);
- public function set_position($position);
+ public function set_job($job);
- public function set_company($company);
+ public function set_position($position);
- public function delete();
+ public function set_company($company);
- public function get_defaultftpdatas();
+ public function delete();
- public function get_mail_notifications();
+ public function get_defaultftpdatas();
- public function get_activeftp();
+ public function get_mail_notifications();
- public function get_ftp_address();
+ public function get_activeftp();
- public function get_ftp_login();
+ public function get_ftp_address();
- public function get_ftp_password();
+ public function get_ftp_login();
- public function get_ftp_passif();
+ public function get_ftp_password();
- public function get_ftp_dir();
+ public function get_ftp_passif();
- public function get_ftp_dir_prefix();
+ public function get_ftp_dir();
- public function load($id);
+ public function get_ftp_dir_prefix();
- public function set_last_template(User_Interface $template);
+ public function load($id);
- public function set_mail_locked($boolean);
+ public function set_last_template(User_Interface $template);
- public function get_mail_locked();
+ public function set_mail_locked($boolean);
- public function is_guest();
+ public function get_mail_locked();
- public function get_login();
+ public function is_guest();
- public function get_email();
+ public function get_login();
- public function get_firstname();
+ public function get_email();
- public function get_lastname();
+ public function get_firstname();
- public function get_company();
+ public function get_lastname();
- public function get_tel();
+ public function get_company();
- public function get_fax();
+ public function get_tel();
- public function get_job();
+ public function get_fax();
- public function get_position();
+ public function get_job();
- public function get_zipcode();
+ public function get_position();
- public function get_city();
+ public function get_zipcode();
- public function get_address();
+ public function get_city();
- public function get_gender();
+ public function get_address();
- public function get_geonameid();
+ public function get_gender();
- public function get_applied_template();
+ public function get_geonameid();
- public function get_creation_date();
+ public function get_applied_template();
- public function get_notifications_preference($notification_id);
+ public function get_creation_date();
- public function set_notification_preference($notification_id, $value);
+ public function get_notifications_preference($notification_id);
- public function get_display_name();
+ public function set_notification_preference($notification_id, $value);
- public function get_nonce();
+ public function get_display_name();
- public static function avLanguages();
+ public function get_nonce();
- public function setPrefs($prop, $value);
+ public static function avLanguages();
- public function getPrefs($prop);
+ public function setPrefs($prop, $value);
- public static function updateClientInfos($app_id);
+ public function getPrefs($prop);
- public static function get_sys_admins();
+ public static function updateClientInfos($app_id);
- public static function set_sys_admins($admins);
+ public static function get_sys_admins();
- public static function reset_sys_admins_rights();
+ public static function set_sys_admins($admins);
- public static function get_locale($usr_id);
+ public static function reset_sys_admins_rights();
- public static function create(appbox &$appbox, $login, $password, $email, $admin, $invite = false);
+ public static function get_locale($usr_id);
- public static function salt_password($password, $nonce);
+ public static function create(appbox &$appbox, $login, $password, $email, $admin, $invite = false);
- public static function getInstance($id, appbox &$appbox);
+ public static function salt_password($password, $nonce);
- public static function saveQuery($query);
+ public static function getInstance($id, appbox &$appbox);
- public static function get_usr_id_from_login($login);
+ public static function saveQuery($query);
- public static function get_usr_id_from_email($email);
+ public static function get_usr_id_from_login($login);
+
+ public static function get_usr_id_from_email($email);
}
diff --git a/lib/classes/User/Query.class.php b/lib/classes/User/Query.class.php
index d377b6491e..dbec3bf45d 100644
--- a/lib/classes/User/Query.class.php
+++ b/lib/classes/User/Query.class.php
@@ -19,683 +19,640 @@ use Doctrine\Common\Collections\ArrayCollection;
*/
class User_Query implements User_QueryInterface
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
+ /**
+ *
+ * @var Array
+ */
+ protected $results = array();
- /**
- *
- * @var Array
- */
- protected $results = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $sort = array();
- /**
- *
- * @var Array
- */
- protected $sort = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $like_field = array();
- /**
- *
- * @var Array
- */
- protected $like_field = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $have_rights;
- /**
- *
- * @var Array
- */
- protected $have_rights;
+ /**
+ *
+ * @var Array
+ */
+ protected $have_not_rights;
- /**
- *
- * @var Array
- */
- protected $have_not_rights;
+ /**
+ *
+ * @var string
+ */
+ protected $like_match = 'OR';
- /**
- *
- * @var string
- */
- protected $like_match = 'OR';
+ /**
+ *
+ * @var string
+ */
+ protected $get_inactives = '';
- /**
- *
- * @var string
- */
- protected $get_inactives = '';
+ /**
+ *
+ * @var int
+ */
+ protected $total = 0;
- /**
- *
- * @var int
- */
- protected $total = 0;
+ /**
+ *
+ * @var Array
+ */
+ protected $active_bases = array();
- /**
- *
- * @var Array
- */
- protected $active_bases = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $active_sbas = array();
- /**
- *
- * @var Array
- */
- protected $active_sbas = array();
+ /**
+ *
+ * @var boolean
+ */
+ protected $bases_restrictions = false;
- /**
- *
- * @var boolean
- */
- protected $bases_restrictions = false;
+ /**
+ *
+ * @var boolean
+ */
+ protected $sbas_restrictions = false;
- /**
- *
- * @var boolean
- */
- protected $sbas_restrictions = false;
+ /**
+ *
+ * @var boolean
+ */
+ protected $include_templates = false;
- /**
- *
- * @var boolean
- */
- protected $include_templates = false;
+ /**
+ *
+ * @var boolean
+ */
+ protected $only_templates = false;
- /**
- *
- * @var boolean
- */
- protected $only_templates = false;
+ /**
+ *
+ * @var Array
+ */
+ protected $base_ids = array();
- /**
- *
- * @var Array
- */
- protected $base_ids = array();
+ /**
+ *
+ * @var Array
+ */
+ protected $sbas_ids = array();
- /**
- *
- * @var Array
- */
- protected $sbas_ids = array();
+ /**
+ *
+ * @var int
+ */
+ protected $page;
- /**
- *
- * @var int
- */
- protected $page;
+ /**
+ *
+ * @var int
+ */
+ protected $offset_start;
- /**
- *
- * @var int
- */
- protected $offset_start;
+ /**
+ *
+ * @var int
+ */
+ protected $results_quantity;
+ protected $include_phantoms = true;
+ protected $include_special_users = false;
+ protected $include_invite = false;
+ protected $activities;
+ protected $templates;
+ protected $companies;
+ protected $countries;
+ protected $positions;
+ protected $in_ids;
- /**
- *
- * @var int
- */
- protected $results_quantity;
- protected $include_phantoms = true;
- protected $include_special_users = false;
- protected $include_invite = false;
- protected $activities;
- protected $templates;
- protected $companies;
- protected $countries;
- protected $positions;
- protected $in_ids;
+ const ORD_ASC = 'asc';
+ const ORD_DESC = 'desc';
+ const SORT_FIRSTNAME = 'usr_prenom';
+ const SORT_LASTNAME = 'usr_nom';
+ const SORT_COMPANY = 'societe';
+ const SORT_LOGIN = 'usr_login';
+ const SORT_EMAIL = 'usr_mail';
+ const SORT_ID = 'usr_id';
+ const SORT_CREATIONDATE = 'usr_creationdate';
+ const SORT_COUNTRY = 'pays';
+ const SORT_LASTMODEL = 'lastModel';
+ const LIKE_FIRSTNAME = 'usr_prenom';
+ const LIKE_LASTNAME = 'usr_nom';
+ const LIKE_NAME = 'name';
+ const LIKE_COMPANY = 'societe';
+ const LIKE_LOGIN = 'usr_login';
+ const LIKE_EMAIL = 'usr_mail';
+ const LIKE_COUNTRY = 'pays';
+ const LIKE_MATCH_AND = 'AND';
+ const LIKE_MATCH_OR = 'OR';
- const ORD_ASC = 'asc';
- const ORD_DESC = 'desc';
- const SORT_FIRSTNAME = 'usr_prenom';
- const SORT_LASTNAME = 'usr_nom';
- const SORT_COMPANY = 'societe';
- const SORT_LOGIN = 'usr_login';
- const SORT_EMAIL = 'usr_mail';
- const SORT_ID = 'usr_id';
- const SORT_CREATIONDATE = 'usr_creationdate';
- const SORT_COUNTRY = 'pays';
- const SORT_LASTMODEL = 'lastModel';
- const LIKE_FIRSTNAME = 'usr_prenom';
- const LIKE_LASTNAME = 'usr_nom';
- const LIKE_NAME = 'name';
- const LIKE_COMPANY = 'societe';
- const LIKE_LOGIN = 'usr_login';
- const LIKE_EMAIL = 'usr_mail';
- const LIKE_COUNTRY = 'pays';
- const LIKE_MATCH_AND = 'AND';
- const LIKE_MATCH_OR = 'OR';
-
- /**
- *
- * @return User_Query
- */
- public function __construct(appbox &$appbox)
- {
- $this->appbox = $appbox;
-
- foreach ($appbox->get_databoxes() as $databox)
+ /**
+ *
+ * @return User_Query
+ */
+ public function __construct(appbox &$appbox)
{
- $this->active_sbas[] = $databox->get_sbas_id();
- foreach ($databox->get_collections() as $collection)
- {
- $this->active_bases[] = $collection->get_base_id();
- }
+ $this->appbox = $appbox;
+
+ foreach ($appbox->get_databoxes() as $databox) {
+ $this->active_sbas[] = $databox->get_sbas_id();
+ foreach ($databox->get_collections() as $collection) {
+ $this->active_bases[] = $collection->get_base_id();
+ }
+ }
+
+ return $this;
+ }
+ protected $sql_params;
+
+ /**
+ *
+ * @return \Doctrine\Common\Collections\ArrayCollection
+ */
+ public function get_results()
+ {
+ return $this->results;
}
- return $this;
- }
+ /**
+ *
+ * @return string
+ */
+ protected function generate_sql_constraints()
+ {
+ $this->sql_params = array();
- protected $sql_params;
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- /**
- *
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function get_results()
- {
- return $this->results;
- }
-
- /**
- *
- * @return string
- */
- protected function generate_sql_constraints()
- {
- $this->sql_params = array();
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $sql = '
+ $sql = '
FROM usr LEFT JOIN basusr ON (usr.usr_id = basusr.usr_id)
LEFT JOIN sbasusr ON (usr.usr_id = sbasusr.usr_id)
WHERE 1 ';
- if (!$this->include_special_users)
- {
- $sql .= ' AND usr_login != "autoregister"
+ if ( ! $this->include_special_users) {
+ $sql .= ' AND usr_login != "autoregister"
AND usr_login != "invite" ';
- }
+ }
- $sql .= ' AND usr_login NOT LIKE "(#deleted_%" ';
+ $sql .= ' AND usr_login NOT LIKE "(#deleted_%" ';
- if (!$this->include_invite)
- {
- $sql .= ' AND usr.invite=0 ';
- }
+ if ( ! $this->include_invite) {
+ $sql .= ' AND usr.invite=0 ';
+ }
- if ($this->only_templates === true)
- {
- $sql .= ' AND model_of = ' . $session->get_usr_id();
- }
- elseif ($this->include_templates === false)
- {
- $sql .= ' AND model_of=0';
- }
- else
- {
- $sql .= ' AND (model_of=0 OR model_of = ' . $session->get_usr_id() . ' ) ';
- }
+ if ($this->only_templates === true) {
+ $sql .= ' AND model_of = ' . $session->get_usr_id();
+ } elseif ($this->include_templates === false) {
+ $sql .= ' AND model_of=0';
+ } else {
+ $sql .= ' AND (model_of=0 OR model_of = ' . $session->get_usr_id() . ' ) ';
+ }
- if ($this->activities)
- {
- $sql .= $this->generate_field_constraints('activite', $this->activities);
- }
+ if ($this->activities) {
+ $sql .= $this->generate_field_constraints('activite', $this->activities);
+ }
- if ($this->positions)
- {
- $sql .= $this->generate_field_constraints('fonction', $this->positions);
- }
+ if ($this->positions) {
+ $sql .= $this->generate_field_constraints('fonction', $this->positions);
+ }
- if ($this->countries)
- {
- $sql .= $this->generate_field_constraints('pays', $this->countries);
- }
+ if ($this->countries) {
+ $sql .= $this->generate_field_constraints('pays', $this->countries);
+ }
- if ($this->companies)
- {
- $sql .= $this->generate_field_constraints('societe', $this->companies);
- }
+ if ($this->companies) {
+ $sql .= $this->generate_field_constraints('societe', $this->companies);
+ }
- if ($this->templates)
- {
- $sql .= $this->generate_field_constraints('lastModel', $this->templates);
- }
+ if ($this->templates) {
+ $sql .= $this->generate_field_constraints('lastModel', $this->templates);
+ }
- $baslist = array();
+ $baslist = array();
- if (count($this->base_ids) == 0)
- {
- if ($this->bases_restrictions)
- throw new Exception('No base available for you, not enough rights');
- }
- else
- {
- $extra = $this->include_phantoms ? ' OR base_id IS NULL ' : '';
+ if (count($this->base_ids) == 0) {
+ if ($this->bases_restrictions)
+ throw new Exception('No base available for you, not enough rights');
+ }
+ else {
+ $extra = $this->include_phantoms ? ' OR base_id IS NULL ' : '';
- $not_base_id = array_diff($this->active_bases, $this->base_ids);
+ $not_base_id = array_diff($this->active_bases, $this->base_ids);
- if (count($not_base_id) > 0 && count($not_base_id) < count($this->base_ids))
- {
- $sql .= sprintf(' AND ((base_id != %s ) ' . $extra . ')'
- , implode(' AND base_id != ', $not_base_id)
- );
- }
- else
- {
- $sql .= sprintf(' AND (base_id = %s ' . $extra . ') '
- , implode(' OR base_id = ', $this->base_ids)
- );
- }
- }
+ if (count($not_base_id) > 0 && count($not_base_id) < count($this->base_ids)) {
+ $sql .= sprintf(' AND ((base_id != %s ) ' . $extra . ')'
+ , implode(' AND base_id != ', $not_base_id)
+ );
+ } else {
+ $sql .= sprintf(' AND (base_id = %s ' . $extra . ') '
+ , implode(' OR base_id = ', $this->base_ids)
+ );
+ }
+ }
- if (count($this->sbas_ids) == 0)
- {
- if ($this->sbas_restrictions)
- throw new Exception('No base available for you, not enough rights');
- }
- else
- {
- $extra = $this->include_phantoms ? ' OR sbas_id IS NULL ' : '';
+ if (count($this->sbas_ids) == 0) {
+ if ($this->sbas_restrictions)
+ throw new Exception('No base available for you, not enough rights');
+ }
+ else {
+ $extra = $this->include_phantoms ? ' OR sbas_id IS NULL ' : '';
- $not_sbas_id = array_diff($this->active_sbas, $this->sbas_ids);
+ $not_sbas_id = array_diff($this->active_sbas, $this->sbas_ids);
- if (count($not_sbas_id) > 0 && count($not_sbas_id) < count($this->sbas_ids))
- {
- $sql .= sprintf(' AND ((sbas_id != %s ) ' . $extra . ')'
- , implode(' AND sbas_id != ', $not_sbas_id)
- );
- }
- else
- {
- $sql .= sprintf(' AND (sbas_id = %s ' . $extra . ') '
- , implode(' OR sbas_id = ', $this->sbas_ids)
- );
- }
- }
+ if (count($not_sbas_id) > 0 && count($not_sbas_id) < count($this->sbas_ids)) {
+ $sql .= sprintf(' AND ((sbas_id != %s ) ' . $extra . ')'
+ , implode(' AND sbas_id != ', $not_sbas_id)
+ );
+ } else {
+ $sql .= sprintf(' AND (sbas_id = %s ' . $extra . ') '
+ , implode(' OR sbas_id = ', $this->sbas_ids)
+ );
+ }
+ }
- if ($this->in_ids)
- {
- $sql .= 'AND (usr.usr_id = ' . implode(' OR usr.usr_id = ', $this->in_ids) . ')';
- }
+ if ($this->in_ids) {
+ $sql .= 'AND (usr.usr_id = ' . implode(' OR usr.usr_id = ', $this->in_ids) . ')';
+ }
- if ($this->have_rights)
- {
- foreach ($this->have_rights as $right)
- {
- $sql .= ' AND basusr.`' . $right . '` = 1 ';
- }
- }
+ if ($this->have_rights) {
+ foreach ($this->have_rights as $right) {
+ $sql .= ' AND basusr.`' . $right . '` = 1 ';
+ }
+ }
- if ($this->have_not_rights)
- {
- foreach ($this->have_not_rights as $right)
- {
- $sql .= ' AND basusr.`' . $right . '` = 0 ';
- }
- }
+ if ($this->have_not_rights) {
+ foreach ($this->have_not_rights as $right) {
+ $sql .= ' AND basusr.`' . $right . '` = 0 ';
+ }
+ }
- $sql_like = array();
+ $sql_like = array();
- foreach ($this->like_field as $like_field => $like_value)
- {
- switch ($like_field)
- {
- case self::LIKE_NAME:
- $qrys = array();
- foreach (explode(' ', $like_value) as $like_val)
- {
- if (trim($like_val) === '')
- continue;
+ foreach ($this->like_field as $like_field => $like_value) {
+ switch ($like_field) {
+ case self::LIKE_NAME:
+ $qrys = array();
+ foreach (explode(' ', $like_value) as $like_val) {
+ if (trim($like_val) === '')
+ continue;
- $qrys[] = sprintf(
- ' (usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci
+ $qrys[] = sprintf(
+ ' (usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci
OR usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci) '
- , self::LIKE_FIRSTNAME
- , str_replace(array('"', '%'), array('\"', '\%'), $like_val)
- , self::LIKE_LASTNAME
- , str_replace(array('"', '%'), array('\"', '\%'), $like_val)
+ , self::LIKE_FIRSTNAME
+ , str_replace(array('"', '%'), array('\"', '\%'), $like_val)
+ , self::LIKE_LASTNAME
+ , str_replace(array('"', '%'), array('\"', '\%'), $like_val)
+ );
+ }
+
+ if (count($qrys) > 0)
+ $sql_like[] = ' (' . implode(' AND ', $qrys) . ') ';
+
+ break;
+ case self::LIKE_FIRSTNAME:
+ case self::LIKE_LASTNAME:
+ case self::LIKE_COMPANY:
+ case self::LIKE_EMAIL:
+ case self::LIKE_LOGIN:
+ case self::LIKE_COUNTRY:
+ $sql_like[] = sprintf(
+ ' usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci '
+ , $like_field
+ , str_replace(array('"', '%'), array('\"', '\%'), $like_value)
+ );
+ break;
+ default;
+ break;
+ }
+ }
+
+
+ if (count($sql_like) > 0)
+ $sql .= sprintf(' AND (%s) ', implode($this->like_match, $sql_like));
+
+ return $sql;
+ }
+
+ protected function generate_field_constraints($fieldName, ArrayCollection $fields)
+ {
+ $n = 0;
+ $constraints = array();
+
+ foreach ($fields as $field) {
+ $constraints[':' . $fieldName . $n ++] = $field;
+ }
+ $sql = ' AND (' . $fieldName . ' = '
+ . implode(' OR ' . $fieldName . ' = ', array_keys($constraints)) . ') ';
+
+ $this->sql_params = array_merge($this->sql_params, $constraints);
+
+ return $sql;
+ }
+
+ public function in(array $usr_ids)
+ {
+ $tmp_usr_ids = array();
+
+ foreach ($usr_ids as $usr_id) {
+ $tmp_usr_ids[] = (int) $usr_id;
+ }
+
+ $this->in_ids = array_unique($tmp_usr_ids);
+
+ return $this;
+ }
+
+ public function include_phantoms($boolean = true)
+ {
+ $this->include_phantoms = ! ! $boolean;
+
+ return $this;
+ }
+
+ public function include_special_users($boolean = false)
+ {
+ $this->include_special_users = ! ! $boolean;
+
+ return $this;
+ }
+
+ public function include_invite($boolean = false)
+ {
+ $this->include_invite = ! ! $boolean;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param array $rights
+ * @return User_Query
+ */
+ public function who_have_right(Array $rights)
+ {
+ $this->have_rights = $rights;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param boolean $boolean
+ * @return User_Query
+ */
+ public function include_templates($boolean)
+ {
+ $this->include_templates = ! ! $boolean;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param boolean $boolean
+ * @return User_Query
+ */
+ public function only_templates($boolean)
+ {
+ $this->only_templates = ! ! $boolean;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param array $rights
+ * @return User_Query
+ */
+ public function who_have_not_right(Array $rights)
+ {
+ $this->have_not_rights = $rights;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return User_Query
+ */
+ public function execute()
+ {
+ $conn = $this->appbox->get_connection();
+
+ $sorter = array();
+
+ foreach ($this->sort as $sort => $ord) {
+
+ $k = count($sorter);
+
+ switch ($sort) {
+ case self::SORT_FIRSTNAME:
+ case self::SORT_LASTNAME:
+ case self::SORT_COMPANY:
+ case self::SORT_LOGIN:
+ case self::SORT_EMAIL:
+ $sorter[$k] = ' usr.`' . $sort . '` COLLATE utf8_unicode_ci ';
+ break;
+ case self::SORT_ID:
+ case self::SORT_CREATIONDATE:
+ case self::SORT_COUNTRY:
+ case self::SORT_LASTMODEL:
+ $sorter[$k] = ' usr.`' . $sort . '` ';
+ break;
+ default:
+ break;
+ }
+
+ if ( ! isset($sorter[$k]))
+ continue;
+
+ switch ($ord) {
+ case self::ORD_ASC:
+ default:
+ $sorter[$k] .= ' ASC ';
+ break;
+ case self::ORD_DESC:
+ $sorter[$k] .= ' DESC ';
+ break;
+ }
+ }
+
+ $sql = 'SELECT DISTINCT usr.usr_id ' . $this->generate_sql_constraints();
+
+ $sorter = implode(', ', $sorter);
+
+ if (trim($sorter) != '')
+ $sql .= ' ORDER BY ' . $sorter;
+
+ if (is_int($this->offset_start) && is_int($this->results_quantity)) {
+ $sql .= sprintf(
+ ' LIMIT %d, %d'
+ , $this->offset_start
+ , $this->results_quantity
);
- }
+ }
- if (count($qrys) > 0)
- $sql_like[] = ' (' . implode(' AND ', $qrys) . ') ';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- break;
- case self::LIKE_FIRSTNAME:
- case self::LIKE_LASTNAME:
- case self::LIKE_COMPANY:
- case self::LIKE_EMAIL:
- case self::LIKE_LOGIN:
- case self::LIKE_COUNTRY:
- $sql_like[] = sprintf(
- ' usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci '
- , $like_field
- , str_replace(array('"', '%'), array('\"', '\%'), $like_value)
- );
- break;
- default;
- break;
- }
+ $users = new ArrayCollection();
+
+ foreach ($rs as $row) {
+ $users[] = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ }
+
+ $this->results = $users;
+
+ return $this;
}
-
- if (count($sql_like) > 0)
- $sql .= sprintf(' AND (%s) ', implode($this->like_match, $sql_like));
-
- return $sql;
- }
-
- protected function generate_field_constraints($fieldName, ArrayCollection $fields)
- {
- $n = 0;
- $constraints = array();
-
- foreach ($fields as $field)
+ /**
+ *
+ * @return int
+ */
+ public function get_total()
{
- $constraints[':' . $fieldName . $n++] = $field;
+ if ($this->total)
+ return $this->total;
+
+ $conn = $this->appbox->get_connection();
+
+ $sql_count = 'SELECT COUNT(DISTINCT usr.usr_id) as total '
+ . $this->generate_sql_constraints();
+
+ $stmt = $conn->prepare($sql_count);
+ $stmt->execute($this->sql_params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+
+ $this->total = $row['total'];
+
+ $this->page = 1;
+ if ($this->total > 0 && is_int($this->offset_start) && is_int($this->results_quantity)) {
+ $this->page = floor($this->offset_start / $this->results_quantity) + 1;
+ $this->total_page = floor($this->total / $this->results_quantity) + 1;
+ }
+
+ return $this->total;
}
- $sql = ' AND (' . $fieldName . ' = '
- . implode(' OR ' . $fieldName . ' = ', array_keys($constraints)) . ') ';
- $this->sql_params = array_merge($this->sql_params, $constraints);
-
- return $sql;
- }
-
- public function in(array $usr_ids)
- {
- $tmp_usr_ids = array();
-
- foreach ($usr_ids as $usr_id)
+ /**
+ *
+ * @return int
+ */
+ public function get_page()
{
- $tmp_usr_ids[] = (int) $usr_id;
+ $this->get_total();
+
+ return $this->page;
}
- $this->in_ids = array_unique($tmp_usr_ids);
-
- return $this;
- }
-
- public function include_phantoms($boolean = true)
- {
- $this->include_phantoms = !!$boolean;
-
- return $this;
- }
-
- public function include_special_users($boolean = false)
- {
- $this->include_special_users = !!$boolean;
-
- return $this;
- }
-
- public function include_invite($boolean = false)
- {
- $this->include_invite = !!$boolean;
-
- return $this;
- }
-
- /**
- *
- * @param array $rights
- * @return User_Query
- */
- public function who_have_right(Array $rights)
- {
- $this->have_rights = $rights;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $boolean
- * @return User_Query
- */
- public function include_templates($boolean)
- {
- $this->include_templates = !!$boolean;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $boolean
- * @return User_Query
- */
- public function only_templates($boolean)
- {
- $this->only_templates = !!$boolean;
-
- return $this;
- }
-
- /**
- *
- * @param array $rights
- * @return User_Query
- */
- public function who_have_not_right(Array $rights)
- {
- $this->have_not_rights = $rights;
-
- return $this;
- }
-
- /**
- *
- * @return User_Query
- */
- public function execute()
- {
- $conn = $this->appbox->get_connection();
-
- $sorter = array();
-
- foreach ($this->sort as $sort => $ord)
+ /**
+ *
+ * @return int
+ */
+ public function get_total_page()
{
+ $this->get_total();
- $k = count($sorter);
-
- switch ($sort)
- {
- case self::SORT_FIRSTNAME:
- case self::SORT_LASTNAME:
- case self::SORT_COMPANY:
- case self::SORT_LOGIN:
- case self::SORT_EMAIL:
- $sorter[$k] = ' usr.`' . $sort . '` COLLATE utf8_unicode_ci ';
- break;
- case self::SORT_ID:
- case self::SORT_CREATIONDATE:
- case self::SORT_COUNTRY:
- case self::SORT_LASTMODEL:
- $sorter[$k] = ' usr.`' . $sort . '` ';
- break;
- default:
- break;
- }
-
- if (!isset($sorter[$k]))
- continue;
-
- switch ($ord)
- {
- case self::ORD_ASC:
- default:
- $sorter[$k] .= ' ASC ';
- break;
- case self::ORD_DESC:
- $sorter[$k] .= ' DESC ';
- break;
- }
+ return $this->total_page;
}
- $sql = 'SELECT DISTINCT usr.usr_id ' . $this->generate_sql_constraints();
-
- $sorter = implode(', ', $sorter);
-
- if (trim($sorter) != '')
- $sql .= ' ORDER BY ' . $sorter;
-
- if (is_int($this->offset_start) && is_int($this->results_quantity))
+ /**
+ *
+ * @param ACL $ACL User's ACLs
+ * @param array $rights An array of base rights you need
+ * @return User_Query
+ */
+ public function on_bases_where_i_am(ACL $ACL, Array $rights)
{
- $sql .= sprintf(
- ' LIMIT %d, %d'
- , $this->offset_start
- , $this->results_quantity
- );
+ $this->bases_restrictions = true;
+ $baslist = array_keys($ACL->get_granted_base($rights));
+
+ if (count($this->base_ids) > 0)
+ $this->base_ids = array_intersect($this->base_ids, $baslist);
+ else
+ $this->base_ids = $baslist;
+
+ $this->total = $this->page = $this->total_page = null;
+
+ return $this;
}
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $users = new ArrayCollection();
-
- foreach ($rs as $row)
+ /**
+ *
+ * @param ACL $ACL
+ * @param array $rights An array of sbas rights you need
+ * @return User_Query
+ */
+ public function on_sbas_where_i_am(ACL $ACL, Array $rights)
{
- $users[] = User_Adapter::getInstance($row['usr_id'], $this->appbox);
+ $this->sbas_restrictions = true;
+ $sbaslist = array_keys($ACL->get_granted_sbas($rights));
+
+ if (count($this->sbas_ids) > 0)
+ $this->sbas_ids = array_intersect($this->sbas_ids, $sbaslist);
+ else
+ $this->sbas_ids = $sbaslist;
+
+ $this->total = $this->page = $this->total_page = null;
+
+ return $this;
}
- $this->results = $users;
-
- return $this;
- }
-
- /**
- *
- * @return int
- */
- public function get_total()
- {
- if ($this->total)
-
- return $this->total;
-
- $conn = $this->appbox->get_connection();
-
- $sql_count = 'SELECT COUNT(DISTINCT usr.usr_id) as total '
- . $this->generate_sql_constraints();
-
- $stmt = $conn->prepare($sql_count);
- $stmt->execute($this->sql_params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
-
- $this->total = $row['total'];
-
- $this->page = 1;
- if ($this->total > 0 && is_int($this->offset_start) && is_int($this->results_quantity))
+ /**
+ *
+ * @param int $offset_start
+ * @param int $results_quantity
+ * @return User_Query
+ */
+ public function limit($offset_start, $results_quantity)
{
- $this->page = floor($this->offset_start / $this->results_quantity) + 1;
- $this->total_page = floor($this->total / $this->results_quantity) + 1;
+ $this->offset_start = (int) $offset_start;
+ $this->results_quantity = (int) $results_quantity;
+
+ return $this;
}
- return $this->total;
- }
-
- /**
- *
- * @return int
- */
- public function get_page()
- {
- $this->get_total();
-
- return $this->page;
- }
-
- /**
- *
- * @return int
- */
- public function get_total_page()
- {
- $this->get_total();
-
- return $this->total_page;
- }
-
- /**
- *
- * @param ACL $ACL User's ACLs
- * @param array $rights An array of base rights you need
- * @return User_Query
- */
- public function on_bases_where_i_am(ACL $ACL, Array $rights)
- {
- $this->bases_restrictions = true;
- $baslist = array_keys($ACL->get_granted_base($rights));
-
- if (count($this->base_ids) > 0)
- $this->base_ids = array_intersect($this->base_ids, $baslist);
- else
- $this->base_ids = $baslist;
-
- $this->total = $this->page = $this->total_page = null;
-
- return $this;
- }
-
- /**
- *
- * @param ACL $ACL
- * @param array $rights An array of sbas rights you need
- * @return User_Query
- */
- public function on_sbas_where_i_am(ACL $ACL, Array $rights)
- {
- $this->sbas_restrictions = true;
- $sbaslist = array_keys($ACL->get_granted_sbas($rights));
-
- if (count($this->sbas_ids) > 0)
- $this->sbas_ids = array_intersect($this->sbas_ids, $sbaslist);
- else
- $this->sbas_ids = $sbaslist;
-
- $this->total = $this->page = $this->total_page = null;
-
- return $this;
- }
-
- /**
- *
- * @param int $offset_start
- * @param int $results_quantity
- * @return User_Query
- */
- public function limit($offset_start, $results_quantity)
- {
- $this->offset_start = (int) $offset_start;
- $this->results_quantity = (int) $results_quantity;
-
- return $this;
- }
-
- /**
- * Query width a like field
- * like fields are defined as constants of the object
- *
- * @param const $like_field
- * @param string $like_value
- * @return User_Query
- */
- public function like($like_field, $like_value)
- {
+ /**
+ * Query width a like field
+ * like fields are defined as constants of the object
+ *
+ * @param const $like_field
+ * @param string $like_value
+ * @return User_Query
+ */
+ public function like($like_field, $like_value)
+ {
// if ($like_field == self::LIKE_NAME)
// {
@@ -704,374 +661,355 @@ class User_Query implements User_QueryInterface
// }
// else
// {
- $this->like_field[trim($like_field)] = trim($like_value);
+ $this->like_field[trim($like_field)] = trim($like_value);
// }
- $this->total = $this->page = $this->total_page = null;
+ $this->total = $this->page = $this->total_page = null;
- return $this;
- }
-
- /**
- * Choose whether multiple like will be treated as AND or OR
- *
- * @param type $like_match
- * @return User_Query
- */
- public function like_match($like_match)
- {
- switch ($like_match)
- {
- case self::LIKE_MATCH_AND:
- case self::LIKE_MATCH_OR:
- $this->like_match = $like_match;
- break;
- default:
- break;
- }
- $this->total = $this->page = $this->total_page = null;
-
- return $this;
- }
-
- /**
- * Restrict User search on base_ids
- *
- * @param array $base_ids
- * @return User_Query
- */
- public function on_base_ids(Array $base_ids = null)
- {
- if (!$base_ids)
-
- return $this;
-
- $this->bases_restrictions = true;
-
- $this->include_phantoms(false);
-
- if (count($this->base_ids) > 0)
- $this->base_ids = array_intersect($this->base_ids, $base_ids);
- else
- $this->base_ids = $base_ids;
-
- $this->total = $this->page = $this->total_page = null;
-
- return $this;
- }
-
- /**
- *
- * @param array $sbas_ids
- * @return User_Query
- */
- public function on_sbas_ids(Array $sbas_ids = null)
- {
- if (!$sbas_ids)
-
- return $this;
-
- $this->sbas_restrictions = true;
-
- $this->include_phantoms(false);
-
- if (count($this->sbas_ids) > 0)
- $this->sbas_ids = array_intersect($this->sbas_ids, $sbas_ids);
- else
- $this->sbas_ids = $sbas_ids;
-
- $this->total = $this->page = $this->total_page = null;
-
- return $this;
- }
-
- /**
- * Sort results. Sort field and sort order are defined as constants
- * of this object
- *
- * @param const $sort
- * @param const $ord
- * @return User_Query
- */
- public function sort_by($sort, $ord = 'asc')
- {
- $this->sort[$sort] = $ord;
-
- return $this;
- }
-
- public function haveActivities(array $req_activities)
- {
- $Activities = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($req_activities as $activity)
- {
- $activity = trim($activity);
-
- if ($activity === '')
- continue;
-
- if ($Activities->contains($activity))
- continue;
-
- $Activities->add($activity);
+ return $this;
}
- if (!$Activities->isEmpty())
+ /**
+ * Choose whether multiple like will be treated as AND or OR
+ *
+ * @param type $like_match
+ * @return User_Query
+ */
+ public function like_match($like_match)
{
- $this->activities = $Activities;
+ switch ($like_match) {
+ case self::LIKE_MATCH_AND:
+ case self::LIKE_MATCH_OR:
+ $this->like_match = $like_match;
+ break;
+ default:
+ break;
+ }
+ $this->total = $this->page = $this->total_page = null;
+
+ return $this;
}
- return $this;
- }
-
- public function havePositions(array $req_positions)
- {
- $Positions = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($req_positions as $Position)
+ /**
+ * Restrict User search on base_ids
+ *
+ * @param array $base_ids
+ * @return User_Query
+ */
+ public function on_base_ids(Array $base_ids = null)
{
- $Position = trim($Position);
+ if ( ! $base_ids)
+ return $this;
- if ($Position === '')
- continue;
+ $this->bases_restrictions = true;
- if ($Positions->contains($Position))
- continue;
+ $this->include_phantoms(false);
- $Positions->add($Position);
+ if (count($this->base_ids) > 0)
+ $this->base_ids = array_intersect($this->base_ids, $base_ids);
+ else
+ $this->base_ids = $base_ids;
+
+ $this->total = $this->page = $this->total_page = null;
+
+ return $this;
}
- if (!$Positions->isEmpty())
+ /**
+ *
+ * @param array $sbas_ids
+ * @return User_Query
+ */
+ public function on_sbas_ids(Array $sbas_ids = null)
{
- $this->positions = $Positions;
+ if ( ! $sbas_ids)
+ return $this;
+
+ $this->sbas_restrictions = true;
+
+ $this->include_phantoms(false);
+
+ if (count($this->sbas_ids) > 0)
+ $this->sbas_ids = array_intersect($this->sbas_ids, $sbas_ids);
+ else
+ $this->sbas_ids = $sbas_ids;
+
+ $this->total = $this->page = $this->total_page = null;
+
+ return $this;
}
- return $this;
- }
-
- public function inCountries(array $req_countries)
- {
- $Countries = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($req_countries as $Country)
+ /**
+ * Sort results. Sort field and sort order are defined as constants
+ * of this object
+ *
+ * @param const $sort
+ * @param const $ord
+ * @return User_Query
+ */
+ public function sort_by($sort, $ord = 'asc')
{
- $Country = trim($Country);
+ $this->sort[$sort] = $ord;
- if ($Country === '')
- continue;
-
- if ($Countries->contains($Country))
- continue;
-
- $Countries->add($Country);
+ return $this;
}
- if (!$Countries->isEmpty())
+ public function haveActivities(array $req_activities)
{
- $this->countries = $Countries;
+ $Activities = new \Doctrine\Common\Collections\ArrayCollection();
+
+ foreach ($req_activities as $activity) {
+ $activity = trim($activity);
+
+ if ($activity === '')
+ continue;
+
+ if ($Activities->contains($activity))
+ continue;
+
+ $Activities->add($activity);
+ }
+
+ if ( ! $Activities->isEmpty()) {
+ $this->activities = $Activities;
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function inCompanies(array $req_companies)
- {
- $Companies = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($req_companies as $Company)
+ public function havePositions(array $req_positions)
{
- $Company = trim($Company);
+ $Positions = new \Doctrine\Common\Collections\ArrayCollection();
- if ($Company === '')
- continue;
+ foreach ($req_positions as $Position) {
+ $Position = trim($Position);
- if ($Companies->contains($Company))
- continue;
+ if ($Position === '')
+ continue;
- $Companies->add($Company);
+ if ($Positions->contains($Position))
+ continue;
+
+ $Positions->add($Position);
+ }
+
+ if ( ! $Positions->isEmpty()) {
+ $this->positions = $Positions;
+ }
+
+ return $this;
}
- if (!$Companies->isEmpty())
+ public function inCountries(array $req_countries)
{
- $this->companies = $Companies;
+ $Countries = new \Doctrine\Common\Collections\ArrayCollection();
+
+ foreach ($req_countries as $Country) {
+ $Country = trim($Country);
+
+ if ($Country === '')
+ continue;
+
+ if ($Countries->contains($Country))
+ continue;
+
+ $Countries->add($Country);
+ }
+
+ if ( ! $Countries->isEmpty()) {
+ $this->countries = $Countries;
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function haveTemplate(array $req_templates)
- {
- $Templates = new \Doctrine\Common\Collections\ArrayCollection();
-
- foreach ($req_templates as $Template)
+ public function inCompanies(array $req_companies)
{
- $Template = trim($Template);
+ $Companies = new \Doctrine\Common\Collections\ArrayCollection();
- if ($Template === '')
- continue;
+ foreach ($req_companies as $Company) {
+ $Company = trim($Company);
- if ($Templates->contains($Template))
- continue;
+ if ($Company === '')
+ continue;
- $Templates->add($Template);
+ if ($Companies->contains($Company))
+ continue;
+
+ $Companies->add($Company);
+ }
+
+ if ( ! $Companies->isEmpty()) {
+ $this->companies = $Companies;
+ }
+
+ return $this;
}
- if (!$Templates->isEmpty())
+ public function haveTemplate(array $req_templates)
{
- $this->templates = $Templates;
+ $Templates = new \Doctrine\Common\Collections\ArrayCollection();
+
+ foreach ($req_templates as $Template) {
+ $Template = trim($Template);
+
+ if ($Template === '')
+ continue;
+
+ if ($Templates->contains($Template))
+ continue;
+
+ $Templates->add($Template);
+ }
+
+ if ( ! $Templates->isEmpty()) {
+ $this->templates = $Templates;
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- * Wheter or not retrieve inactive users
- * (inactive users do not have the "access" right)
- *
- * @param boolean $boolean
- * @return User_Query
- */
- public function get_inactives($boolean = true)
- {
- $this->get_inactives = !!$boolean;
-
- return $this;
- }
-
- public function getRelatedActivities()
- {
- $conn = $this->appbox->get_connection();
-
- $sql = 'SELECT DISTINCT usr.activite ' . $this->generate_sql_constraints();
-
- $sql .= ' ORDER BY usr.activite';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $activities = array();
-
- foreach ($rs as $row)
+ /**
+ * Wheter or not retrieve inactive users
+ * (inactive users do not have the "access" right)
+ *
+ * @param boolean $boolean
+ * @return User_Query
+ */
+ public function get_inactives($boolean = true)
{
- if (trim($row['activite']) === '')
- continue;
+ $this->get_inactives = ! ! $boolean;
- $activities[] = $row['activite'];
+ return $this;
}
- return $activities;
- }
-
- public function getRelatedPositions()
- {
- $conn = $this->appbox->get_connection();
-
- $sql = 'SELECT DISTINCT usr.fonction ' . $this->generate_sql_constraints();
-
- $sql .= ' ORDER BY usr.fonction';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $fonction = array();
-
- foreach ($rs as $row)
+ public function getRelatedActivities()
{
- if (trim($row['fonction']) === '')
- continue;
+ $conn = $this->appbox->get_connection();
- $fonction[] = $row['fonction'];
+ $sql = 'SELECT DISTINCT usr.activite ' . $this->generate_sql_constraints();
+
+ $sql .= ' ORDER BY usr.activite';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $activities = array();
+
+ foreach ($rs as $row) {
+ if (trim($row['activite']) === '')
+ continue;
+
+ $activities[] = $row['activite'];
+ }
+
+ return $activities;
}
- return $fonction;
- }
-
- public function getRelatedCountries()
- {
- require_once __DIR__ . '/../../classes/deprecated/countries.php';
-
- $conn = $this->appbox->get_connection();
-
- $sql = 'SELECT DISTINCT usr.pays ' . $this->generate_sql_constraints();
-
- $sql .= ' ORDER BY usr.pays';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $pays = array();
-
- $ctry = \getCountries(\Session_Handler::get_locale());
-
- foreach ($rs as $row)
+ public function getRelatedPositions()
{
- if (trim($row['pays']) === '')
- continue;
+ $conn = $this->appbox->get_connection();
- if (isset($ctry[$row['pays']]))
- $pays[$row['pays']] = $ctry[$row['pays']];
+ $sql = 'SELECT DISTINCT usr.fonction ' . $this->generate_sql_constraints();
+
+ $sql .= ' ORDER BY usr.fonction';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $fonction = array();
+
+ foreach ($rs as $row) {
+ if (trim($row['fonction']) === '')
+ continue;
+
+ $fonction[] = $row['fonction'];
+ }
+
+ return $fonction;
}
- return $pays;
- }
-
- public function getRelatedCompanies()
- {
- $conn = $this->appbox->get_connection();
-
- $sql = 'SELECT DISTINCT usr.societe ' . $this->generate_sql_constraints();
-
- $sql .= ' ORDER BY usr.societe';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $societe = array();
-
- foreach ($rs as $row)
+ public function getRelatedCountries()
{
- if (trim($row['societe']) === '')
- continue;
+ require_once __DIR__ . '/../../classes/deprecated/countries.php';
- $societe[] = $row['societe'];
+ $conn = $this->appbox->get_connection();
+
+ $sql = 'SELECT DISTINCT usr.pays ' . $this->generate_sql_constraints();
+
+ $sql .= ' ORDER BY usr.pays';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $pays = array();
+
+ $ctry = \getCountries(\Session_Handler::get_locale());
+
+ foreach ($rs as $row) {
+ if (trim($row['pays']) === '')
+ continue;
+
+ if (isset($ctry[$row['pays']]))
+ $pays[$row['pays']] = $ctry[$row['pays']];
+ }
+
+ return $pays;
}
- return $societe;
- }
-
- public function getRelatedTemplates()
- {
- $conn = $this->appbox->get_connection();
-
- $sql = 'SELECT DISTINCT usr.lastModel ' . $this->generate_sql_constraints();
-
- $sql .= ' ORDER BY usr.lastModel';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute($this->sql_params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $lastModel = array();
-
- foreach ($rs as $row)
+ public function getRelatedCompanies()
{
- if (trim($row['lastModel']) === '')
- continue;
+ $conn = $this->appbox->get_connection();
- $lastModel[] = $row['lastModel'];
+ $sql = 'SELECT DISTINCT usr.societe ' . $this->generate_sql_constraints();
+
+ $sql .= ' ORDER BY usr.societe';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $societe = array();
+
+ foreach ($rs as $row) {
+ if (trim($row['societe']) === '')
+ continue;
+
+ $societe[] = $row['societe'];
+ }
+
+ return $societe;
}
- return $lastModel;
- }
+ public function getRelatedTemplates()
+ {
+ $conn = $this->appbox->get_connection();
+ $sql = 'SELECT DISTINCT usr.lastModel ' . $this->generate_sql_constraints();
+
+ $sql .= ' ORDER BY usr.lastModel';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($this->sql_params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $lastModel = array();
+
+ foreach ($rs as $row) {
+ if (trim($row['lastModel']) === '')
+ continue;
+
+ $lastModel[] = $row['lastModel'];
+ }
+
+ return $lastModel;
+ }
}
diff --git a/lib/classes/User/QueryInterface.class.php b/lib/classes/User/QueryInterface.class.php
index 293c0df5ac..3ce84a5065 100644
--- a/lib/classes/User/QueryInterface.class.php
+++ b/lib/classes/User/QueryInterface.class.php
@@ -17,35 +17,36 @@
*/
interface User_QueryInterface
{
- public function __construct(appbox &$appbox);
- public function get_results();
+ public function __construct(appbox &$appbox);
- public function who_have_right(Array $rights);
+ public function get_results();
- public function who_have_not_right(Array $rights);
+ public function who_have_right(Array $rights);
- public function execute();
+ public function who_have_not_right(Array $rights);
- public function get_total();
+ public function execute();
- public function get_page();
+ public function get_total();
- public function on_bases_where_i_am(ACL $ACL, Array $rights);
+ public function get_page();
- public function on_sbas_where_i_am(ACL $ACL, Array $rights);
+ public function on_bases_where_i_am(ACL $ACL, Array $rights);
- public function limit($offset_start, $results_quantity);
+ public function on_sbas_where_i_am(ACL $ACL, Array $rights);
- public function like($like_field, $like_value);
+ public function limit($offset_start, $results_quantity);
- public function like_match($like_match);
+ public function like($like_field, $like_value);
- public function on_sbas_ids(Array $sbas_ids);
+ public function like_match($like_match);
- public function on_base_ids(Array $base_ids);
+ public function on_sbas_ids(Array $sbas_ids);
- public function sort_by($sort, $ord = 'asc');
+ public function on_base_ids(Array $base_ids);
- public function get_inactives($boolean = true);
+ public function sort_by($sort, $ord = 'asc');
+
+ public function get_inactives($boolean = true);
}
diff --git a/lib/classes/ZipArchiveImproved.class.php b/lib/classes/ZipArchiveImproved.class.php
index 5d2a92f7f4..5de73cb115 100644
--- a/lib/classes/ZipArchiveImproved.class.php
+++ b/lib/classes/ZipArchiveImproved.class.php
@@ -11,129 +11,121 @@
*/
class ZipArchiveImproved extends ZipArchive
{
+ protected $_archiveFileName = null;
+ protected $_newAddedFilesCounter = 0;
+ protected $_newAddedFilesSize = 100;
- protected $_archiveFileName = null;
- protected $_newAddedFilesCounter = 0;
- protected $_newAddedFilesSize = 100;
-
- /**
- * returns the name of the archive file.
- *
- * @return string
- */
- public function getArchiveFileName()
- {
- return $this->_archiveFileName;
- }
-
- /**
- * returns the number of files that are going to be added to ZIP
- * without reopenning the stream to file.
- *
- * @return int
- */
- public function getNewAddedFilesSize()
- {
- return $this->_newAddedFilesSize;
- }
-
- /**
- * sets the number of files that are going to be added to ZIP
- * without reopenning the stream to file. if no size is specified, default is 100.
- *
- * @param int
- * @return ZipArchiveImproved self reference
- */
- public function setNewlAddedFilesSize($size=100)
- {
- if (empty($size) || !is_int($size) || $size < 1)
+ /**
+ * returns the name of the archive file.
+ *
+ * @return string
+ */
+ public function getArchiveFileName()
{
- $size = 100;
- }
- $this->_newAddedFilesSize = $size;
-
- return $this;
- }
-
- /**
- * opens a stream to a ZIP archive file. calls the ZipArchive::open() internally.
- * overwrites ZipArchive::open() to add the archiveFileName functionality.
- *
- * @param string $fileName
- * @param int $flags
- * return mixed
- */
- public function open($fileName, $flags)
- {
- $this->_archiveFileName = $fileName;
- $this->_newAddedFilesCounter = 0;
-
- return parent::open($fileName, $flags);
- }
-
- /**
- * closes the stream to ZIP archive file. calls the ZipArchive::close() internally.
- * overwrites ZipArchive::close() to add the archiveFileName functionality.
- *
- * @return bool
- */
- public function close()
- {
- $this->_archiveFileName = null;
- $this->_newAddedFilesCounter = 0;
-
- return parent::close();
- }
-
- /**
- * closes the connection to ZIP file and openes the connection again.
- *
- * @return bool
- */
- public function reopen()
- {
- $archiveFileName = $this->_archiveFileName;
- if (!$this->close())
- {
- return false;
+ return $this->_archiveFileName;
}
- return $this->open($archiveFileName, self::CREATE);
- }
-
- /**
- * adds a file to a ZIP archive from the given path. calls the ZipArchive::addFile() internally.
- * overwrites ZipArchive::addFile() to handle maximum file connections in operating systems.
- *
- * @param string $fileName the path to file to be added to archive
- * @param string [optional] $localname the name of the file in the ZIP archive
- * @return bool
- */
- public function addFile($fileName)
- {
- if ($this->_newAddedFilesCounter >= $this->_newAddedFilesSize)
+ /**
+ * returns the number of files that are going to be added to ZIP
+ * without reopenning the stream to file.
+ *
+ * @return int
+ */
+ public function getNewAddedFilesSize()
{
- $this->reopen();
- }
- if (func_num_args() > 1)
- {
- $flags = func_get_arg(1);
- $added = parent::addFile($fileName, $flags);
- if ($added)
- {
- $this->_newAddedFilesCounter++;
- }
-
- return $added;
- }
- $added = parent::addFile($fileName);
- if ($added)
- {
- $this->_newAddedFilesCounter++;
+ return $this->_newAddedFilesSize;
}
- return $added;
- }
+ /**
+ * sets the number of files that are going to be added to ZIP
+ * without reopenning the stream to file. if no size is specified, default is 100.
+ *
+ * @param int
+ * @return ZipArchiveImproved self reference
+ */
+ public function setNewlAddedFilesSize($size = 100)
+ {
+ if (empty($size) || ! is_int($size) || $size < 1) {
+ $size = 100;
+ }
+ $this->_newAddedFilesSize = $size;
+ return $this;
+ }
+
+ /**
+ * opens a stream to a ZIP archive file. calls the ZipArchive::open() internally.
+ * overwrites ZipArchive::open() to add the archiveFileName functionality.
+ *
+ * @param string $fileName
+ * @param int $flags
+ * return mixed
+ */
+ public function open($fileName, $flags)
+ {
+ $this->_archiveFileName = $fileName;
+ $this->_newAddedFilesCounter = 0;
+
+ return parent::open($fileName, $flags);
+ }
+
+ /**
+ * closes the stream to ZIP archive file. calls the ZipArchive::close() internally.
+ * overwrites ZipArchive::close() to add the archiveFileName functionality.
+ *
+ * @return bool
+ */
+ public function close()
+ {
+ $this->_archiveFileName = null;
+ $this->_newAddedFilesCounter = 0;
+
+ return parent::close();
+ }
+
+ /**
+ * closes the connection to ZIP file and openes the connection again.
+ *
+ * @return bool
+ */
+ public function reopen()
+ {
+ $archiveFileName = $this->_archiveFileName;
+ if ( ! $this->close()) {
+ return false;
+ }
+
+ return $this->open($archiveFileName, self::CREATE);
+ }
+
+ /**
+ * adds a file to a ZIP archive from the given path. calls the ZipArchive::addFile() internally.
+ * overwrites ZipArchive::addFile() to handle maximum file connections in operating systems.
+ *
+ * @param string $fileName the path to file to be added to archive
+ * @param string [optional] $localname the name of the file in the ZIP archive
+ * @return bool
+ */
+ public function addFile($fileName)
+ {
+ if ($this->_newAddedFilesCounter >= $this->_newAddedFilesSize) {
+ $this->reopen();
+ }
+ if (func_num_args() > 1) {
+ $flags = func_get_arg(1);
+ $added = parent::addFile($fileName, $flags);
+ if ($added) {
+ $this->_newAddedFilesCounter ++;
+ }
+
+ return $added;
+ }
+ $added = parent::addFile($fileName);
+ if ($added) {
+ $this->_newAddedFilesCounter ++;
+ }
+
+ return $added;
+ }
// public function addFile()
}
diff --git a/lib/classes/appbox.class.php b/lib/classes/appbox.class.php
index 68847c269f..8f6faee102 100644
--- a/lib/classes/appbox.class.php
+++ b/lib/classes/appbox.class.php
@@ -17,638 +17,584 @@
*/
class appbox extends base
{
-
- /**
- *
- * @var int
- */
- protected $id;
-
- /**
- *
- * @var appbox
- */
- protected static $_instance;
-
- /**
- *
- * constant defining the app type
- */
-
- const BASE_TYPE = self::APPLICATION_BOX;
-
- /**
- *
- * @var
- */
- protected $session;
- protected $cache;
- protected $connection;
- protected $registry;
- protected $Core;
-
- const CACHE_LIST_BASES = 'list_bases';
- const CACHE_SBAS_IDS = 'sbas_ids';
-
- /**
- * Singleton pattern
- *
- * @return appbox
- */
- public static function get_instance(\Alchemy\Phrasea\Core $Core, registryInterface &$registry = null)
- {
- if (!self::$_instance instanceof self)
- {
- self::$_instance = new self($Core, $registry);
- }
-
- return self::$_instance;
- }
-
- /**
- * Constructor
- *
- * @return appbox
- */
- protected function __construct(\Alchemy\Phrasea\Core $Core, registryInterface $registry = null)
- {
- $this->Core = $Core;
- if (!$registry)
- $registry = registry::get_instance($Core);
- $this->connection = connection::getPDOConnection(null, $registry);
- $this->registry = $registry;
- $this->session = Session_Handler::getInstance($this);
-
- $configuration = $Core->getConfiguration();
-
- $choosenConnexion = $configuration->getPhraseanet()->get('database');
-
- $connexion = $configuration->getConnexion($choosenConnexion);
-
- $this->host = $connexion->get('host');
- $this->port = $connexion->get('port');
- $this->user = $connexion->get('user');
- $this->passwd = $connexion->get('password');
- $this->dbname = $connexion->get('dbname');
-
- return $this;
- }
-
- /**
- *
- * @param collection $collection
- * @param system_file $pathfile
- * @param string $pic_type
- * @return appbox
- */
- public function write_collection_pic(collection $collection, system_file $pathfile = null, $pic_type)
- {
- if ($pathfile instanceof system_file)
- {
- $mime = $pathfile->get_mime();
-
- if (!in_array(mb_strtolower($mime), array('image/gif', 'image/png', 'image/jpeg', 'image/jpg', 'image/pjpeg')))
- {
- throw new Exception('Invalid file format');
- }
- }
-
- switch($pic_type)
- {
- case collection::PIC_WM;
- $collection->reset_watermark();
- break;
- case collection::PIC_LOGO:
- case collection::PIC_PRESENTATION:
- break;
- case collection::PIC_STAMP:
- $collection->reset_stamp();
- break;
- default:
- throw new Exception('unknown pic_type');
- break;
- }
-
- if ($pic_type == collection::PIC_LOGO)
- $collection->update_logo($pathfile);
-
- $registry = registry::get_instance();
- $file = $registry->get('GV_RootPath') . 'config/' . $pic_type . '/' . $collection->get_base_id();
- if (is_file($file))
- {
- unlink($file);
- }
- $custom_path = $registry->get('GV_RootPath') . 'www/custom/' . $pic_type . '/';
- if (is_file($custom_path))
- {
- unlink($custom_path);
- }
- if (!is_dir($custom_path))
- {
- system_file::mkdir($custom_path);
- }
- $custom_path.= $collection->get_base_id();
-
- if (is_null($pathfile))
-
- return $this;
-
- $datas = file_get_contents($pathfile->getPathname());
- if (is_null($datas))
-
- return $this;
-
- file_put_contents($file, $datas);
- file_put_contents($custom_path, $datas);
- $system_file = new system_file($file);
- $system_file->chmod();
- $system_file = new system_file($custom_path);
- $system_file->chmod();
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @param system_file $pathfile
- * @param $pic_type
- * @return appbox
- */
- public function write_databox_pic(databox $databox, system_file $pathfile = null, $pic_type)
- {
-
- if ($pathfile instanceof system_file)
- {
- $mime = $pathfile->get_mime();
-
- if (!in_array(mb_strtolower($mime), array('image/jpeg', 'image/jpg', 'image/pjpeg')))
- {
- throw new Exception('Invalid file format');
- }
- }
- if (!in_array($pic_type, array(databox::PIC_PDF)))
- throw new Exception('unknown pic_type');
- $registry = $databox->get_registry();
- $file = $registry->get('GV_RootPath') . 'config/minilogos/' . $pic_type . '_' . $databox->get_sbas_id();
- if (is_file($file))
- {
- unlink($file);
- }
- $custom_path = $registry->get('GV_RootPath') . 'www/custom/minilogos/';
- if (is_file($custom_path))
- {
- unlink($custom_path);
- }
- if (!is_dir($custom_path))
- {
- system_file::mkdir($custom_path);
- }
- $custom_path.= $pic_type . '_' . $databox->get_sbas_id();
-
- if (is_null($pathfile))
-
- return $this;
-
- $datas = file_get_contents($pathfile->getPathname());
- if (is_null($datas))
-
- return $this;
-
- file_put_contents($file, $datas);
- file_put_contents($custom_path, $datas);
- $system_file = new system_file($file);
- $system_file->chmod();
- $system_file = new system_file($custom_path);
- $system_file->chmod();
- $databox->delete_data_from_cache('printLogo');
-
- return $this;
- }
-
- /**
- *
- * @param collection $collection
- * @param $ordre
- * @return appbox
- */
- public function set_collection_order(collection $collection, $ordre)
- {
- $sqlupd = "UPDATE bas SET ord = :ordre WHERE base_id = :base_id";
- $stmt = $this->get_connection()->prepare($sqlupd);
- $stmt->execute(array(':ordre' => $ordre, ':base_id' => $collection->get_base_id()));
- $stmt->closeCursor();
-
- $collection->get_databox()->delete_data_from_cache(\databox::CACHE_COLLECTIONS);
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @param $boolean
- * @return appbox
- */
- public function set_databox_indexable(databox $databox, $boolean)
- {
- $boolean = !!$boolean;
- $sql = 'UPDATE sbas SET indexable = :indexable WHERE sbas_id = :sbas_id';
-
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(
- ':indexable' => ($boolean ? '1' : '0'),
- ':sbas_id' => $databox->get_sbas_id()
- ));
- $stmt->closeCursor();
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @return
- */
- public function is_databox_indexable(databox $databox)
- {
- $sql = 'SELECT indexable FROM sbas WHERE sbas_id = :sbas_id';
-
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':sbas_id' => $databox->get_sbas_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $indexable = $row ? $row['indexable'] : null;
-
- return $indexable;
- }
-
- /**
- *
- * @param databox $databox
- * @param $viewname
- * @return appbox
- */
- public function set_databox_viewname(databox $databox, $viewname)
- {
- $viewname = strip_tags($viewname);
- $sql = 'UPDATE sbas SET viewname = :viewname WHERE sbas_id = :sbas_id';
-
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':viewname' => $viewname, ':sbas_id' => $databox->get_sbas_id()));
- $stmt->closeCursor();
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
- cache_databox::update($databox->get_sbas_id(), 'structure');
-
- return $this;
- }
-
- /**
- *
- * @return const
- */
- public function get_base_type()
- {
- return self::BASE_TYPE;
- }
-
- public function forceUpgrade(Setup_Upgrade &$upgrader)
- {
- $upgrader->add_steps(8 + count($this->get_databoxes()));
-
- $registry = $this->get_registry();
+ /**
+ *
+ * @var int
+ */
+ protected $id;
/**
- * Step 1
+ *
+ * @var appbox
*/
- $upgrader->set_current_message(_('Flushing cache'));
+ protected static $_instance;
- $this->Core['CacheService']->flushAll();
+ /**
+ *
+ * constant defining the app type
+ */
+ const BASE_TYPE = self::APPLICATION_BOX;
- $upgrader->add_steps_complete(1);
+ /**
+ *
+ * @var
+ */
+ protected $session;
+ protected $cache;
+ protected $connection;
+ protected $registry;
+ protected $Core;
+ const CACHE_LIST_BASES = 'list_bases';
+ const CACHE_SBAS_IDS = 'sbas_ids';
- $upgrader->set_current_message(_('Creating new tables'));
- $core = bootstrap::getCore();
- $em = $core->getEntityManager();
- //create schema
-
- if ($em->getConnection()->getDatabasePlatform()->supportsAlterTable())
+ /**
+ * Singleton pattern
+ *
+ * @return appbox
+ */
+ public static function get_instance(\Alchemy\Phrasea\Core $Core, registryInterface &$registry = null)
{
- $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
- $metas = $em->getMetadataFactory()->getAllMetadata();
- $tool->updateSchema($metas, true);
- }
+ if ( ! self::$_instance instanceof self) {
+ self::$_instance = new self($Core, $registry);
+ }
- $upgrader->add_steps_complete(1);
-
- /**
- * Step 2
- */
- $upgrader->set_current_message(_('Purging directories'));
- $system_file = new system_file($registry->get('GV_RootPath') . 'tmp/cache_minify/');
- $system_file->empty_directory();
- $upgrader->add_steps_complete(1);
-
- /**
- * Step 3
- */
- $upgrader->set_current_message(_('Purging directories'));
- $system_file = new system_file($registry->get('GV_RootPath') . 'tmp/cache_twig/');
- $system_file->empty_directory();
- $upgrader->add_steps_complete(1);
-
- /**
- * Step 5
- */
- $upgrader->set_current_message(_('Copying files'));
- phrasea::copy_custom_files();
- $upgrader->add_steps_complete(1);
-
- $advices = array();
-
- /**
- * Step 6
- */
- $upgrader->set_current_message(_('Upgrading appbox'));
- $advices = $this->upgradeDB(true, $upgrader);
- $upgrader->add_steps_complete(1);
-
- /**
- * Step 7
- */
- foreach ($this->get_databoxes() as $s)
- {
- $upgrader->set_current_message(sprintf(_('Upgrading %s'), $s->get_viewname()));
- $advices = array_merge($advices, $s->upgradeDB(true, $upgrader));
- $upgrader->add_steps_complete(1);
+ return self::$_instance;
}
/**
- * Step 8
+ * Constructor
+ *
+ * @return appbox
*/
- $upgrader->set_current_message(_('Post upgrade'));
- $this->post_upgrade($upgrader);
- $upgrader->add_steps_complete(1);
+ protected function __construct(\Alchemy\Phrasea\Core $Core, registryInterface $registry = null)
+ {
+ $this->Core = $Core;
+ if ( ! $registry)
+ $registry = registry::get_instance($Core);
+ $this->connection = connection::getPDOConnection(null, $registry);
+ $this->registry = $registry;
+ $this->session = Session_Handler::getInstance($this);
+ $configuration = $Core->getConfiguration();
+
+ $choosenConnexion = $configuration->getPhraseanet()->get('database');
+
+ $connexion = $configuration->getConnexion($choosenConnexion);
+
+ $this->host = $connexion->get('host');
+ $this->port = $connexion->get('port');
+ $this->user = $connexion->get('user');
+ $this->passwd = $connexion->get('password');
+ $this->dbname = $connexion->get('dbname');
+
+ return $this;
+ }
/**
- * Step 9
+ *
+ * @param collection $collection
+ * @param system_file $pathfile
+ * @param string $pic_type
+ * @return appbox
*/
- $upgrader->set_current_message(_('Flushing cache'));
-
- $this->Core['CacheService']->flushAll();
-
- $upgrader->add_steps_complete(1);
-
- return $advices;
- }
-
- protected function post_upgrade(Setup_Upgrade &$upgrader)
- {
- $Core = bootstrap::getCore();
-
- $upgrader->add_steps(1 + count($this->get_databoxes()));
- $this->apply_patches($this->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
- $this->setVersion($Core->getVersion()->getNumber());
- $upgrader->add_steps_complete(1);
-
- foreach ($this->get_databoxes() as $databox)
+ public function write_collection_pic(collection $collection, system_file $pathfile = null, $pic_type)
{
- $databox->apply_patches($databox->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
- $databox->setVersion($Core->getVersion()->getNumber());
- $upgrader->add_steps_complete(1);
+ if ($pathfile instanceof system_file) {
+ $mime = $pathfile->get_mime();
+
+ if ( ! in_array(mb_strtolower($mime), array('image/gif', 'image/png', 'image/jpeg', 'image/jpg', 'image/pjpeg'))) {
+ throw new Exception('Invalid file format');
+ }
+ }
+
+ switch ($pic_type) {
+ case collection::PIC_WM;
+ $collection->reset_watermark();
+ break;
+ case collection::PIC_LOGO:
+ case collection::PIC_PRESENTATION:
+ break;
+ case collection::PIC_STAMP:
+ $collection->reset_stamp();
+ break;
+ default:
+ throw new Exception('unknown pic_type');
+ break;
+ }
+
+ if ($pic_type == collection::PIC_LOGO)
+ $collection->update_logo($pathfile);
+
+ $registry = registry::get_instance();
+ $file = $registry->get('GV_RootPath') . 'config/' . $pic_type . '/' . $collection->get_base_id();
+ if (is_file($file)) {
+ unlink($file);
+ }
+ $custom_path = $registry->get('GV_RootPath') . 'www/custom/' . $pic_type . '/';
+ if (is_file($custom_path)) {
+ unlink($custom_path);
+ }
+ if ( ! is_dir($custom_path)) {
+ system_file::mkdir($custom_path);
+ }
+ $custom_path.= $collection->get_base_id();
+
+ if (is_null($pathfile))
+ return $this;
+
+ $datas = file_get_contents($pathfile->getPathname());
+ if (is_null($datas))
+ return $this;
+
+ file_put_contents($file, $datas);
+ file_put_contents($custom_path, $datas);
+ $system_file = new system_file($file);
+ $system_file->chmod();
+ $system_file = new system_file($custom_path);
+ $system_file->chmod();
+
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param type $conn
- * @param type $dbname
- * @param type $write_file
- * @return type
- */
- public static function create(\Alchemy\Phrasea\Core $Core, registryInterface &$registry, connection_interface $conn, $dbname, $write_file = false)
- {
- $credentials = $conn->get_credentials();
-
- if ($conn->is_multi_db() && trim($dbname) === '')
+ /**
+ *
+ * @param databox $databox
+ * @param system_file $pathfile
+ * @param $pic_type
+ * @return appbox
+ */
+ public function write_databox_pic(databox $databox, system_file $pathfile = null, $pic_type)
{
- throw new \Exception(_('Nom de base de donnee incorrect'));
+
+ if ($pathfile instanceof system_file) {
+ $mime = $pathfile->get_mime();
+
+ if ( ! in_array(mb_strtolower($mime), array('image/jpeg', 'image/jpg', 'image/pjpeg'))) {
+ throw new Exception('Invalid file format');
+ }
+ }
+ if ( ! in_array($pic_type, array(databox::PIC_PDF)))
+ throw new Exception('unknown pic_type');
+ $registry = $databox->get_registry();
+ $file = $registry->get('GV_RootPath') . 'config/minilogos/' . $pic_type . '_' . $databox->get_sbas_id();
+ if (is_file($file)) {
+ unlink($file);
+ }
+ $custom_path = $registry->get('GV_RootPath') . 'www/custom/minilogos/';
+ if (is_file($custom_path)) {
+ unlink($custom_path);
+ }
+ if ( ! is_dir($custom_path)) {
+ system_file::mkdir($custom_path);
+ }
+ $custom_path.= $pic_type . '_' . $databox->get_sbas_id();
+
+ if (is_null($pathfile))
+ return $this;
+
+ $datas = file_get_contents($pathfile->getPathname());
+ if (is_null($datas))
+ return $this;
+
+ file_put_contents($file, $datas);
+ file_put_contents($custom_path, $datas);
+ $system_file = new system_file($file);
+ $system_file->chmod();
+ $system_file = new system_file($custom_path);
+ $system_file->chmod();
+ $databox->delete_data_from_cache('printLogo');
+
+ return $this;
}
- if ($write_file)
+ /**
+ *
+ * @param collection $collection
+ * @param $ordre
+ * @return appbox
+ */
+ public function set_collection_order(collection $collection, $ordre)
{
- if ($conn->is_multi_db() && !isset($credentials['dbname']))
- {
- $credentials['dbname'] = $dbname;
- }
+ $sqlupd = "UPDATE bas SET ord = :ordre WHERE base_id = :base_id";
+ $stmt = $this->get_connection()->prepare($sqlupd);
+ $stmt->execute(array(':ordre' => $ordre, ':base_id' => $collection->get_base_id()));
+ $stmt->closeCursor();
- foreach ($credentials as $key => $value)
- {
- $key = $key == 'hostname' ? 'host' : $key;
- $connexionINI[$key] = (string) $value;
- }
+ $collection->get_databox()->delete_data_from_cache(\databox::CACHE_COLLECTIONS);
- $Core->getConfiguration()->initialize();
- $connexionINI['driver'] = 'pdo_mysql';
- $connexionINI['charset'] = 'UTF8';
+ return $this;
+ }
- $serverName = $registry->get('GV_ServerName');
+ /**
+ *
+ * @param databox $databox
+ * @param $boolean
+ * @return appbox
+ */
+ public function set_databox_indexable(databox $databox, $boolean)
+ {
+ $boolean = ! ! $boolean;
+ $sql = 'UPDATE sbas SET indexable = :indexable WHERE sbas_id = :sbas_id';
- $root = __DIR__ . '/../../';
-
- $connexion = array(
- 'main_connexion' => $connexionINI,
- 'test_connexion' => array(
- 'driver' => 'pdo_sqlite',
- 'path' => realpath($root . 'tests') . '/tests.sqlite',
- 'charset' => 'UTF8'
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(
+ ':indexable' => ($boolean ? '1' : '0'),
+ ':sbas_id' => $databox->get_sbas_id()
));
+ $stmt->closeCursor();
- $cacheService = "array_cache";
-
- $Core->getConfiguration()->setConnexions($connexion);
-
- $services = $Core->getConfiguration()->getConfigurations();
-
- foreach ($services as $serviceName => $service)
- {
- if ($serviceName === "doctrine_prod")
- {
-
- $services["doctrine_prod"]["options"]["cache"] = array(
- "query" => $cacheService,
- "result" => $cacheService,
- "metadata" => $cacheService
- );
- }
- }
- $Core->getConfiguration()->setConfigurations($services);
-
- $arrayConf = $Core->getConfiguration()->getConfigurations();
-
- foreach ($arrayConf as $key => $value)
- {
- if (is_array($value) && array_key_exists('phraseanet', $value))
- {
- $arrayConf[$key]["phraseanet"]["servername"] = $serverName;
- }
-
- if (is_array($value) && $key === 'prod')
- {
- $arrayConf[$key]["cache"] = $cacheService;
- }
- }
-
- $Core->getConfiguration()->setConfigurations($arrayConf);
-
- $Core->getConfiguration()->setEnvironnement('prod');
+ return $this;
}
- try
+
+ /**
+ *
+ * @param databox $databox
+ * @return
+ */
+ public function is_databox_indexable(databox $databox)
{
- if ($conn->is_multi_db())
- {
- $conn->query('CREATE DATABASE `' . $dbname . '`
+ $sql = 'SELECT indexable FROM sbas WHERE sbas_id = :sbas_id';
+
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':sbas_id' => $databox->get_sbas_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $indexable = $row ? $row['indexable'] : null;
+
+ return $indexable;
+ }
+
+ /**
+ *
+ * @param databox $databox
+ * @param $viewname
+ * @return appbox
+ */
+ public function set_databox_viewname(databox $databox, $viewname)
+ {
+ $viewname = strip_tags($viewname);
+ $sql = 'UPDATE sbas SET viewname = :viewname WHERE sbas_id = :sbas_id';
+
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':viewname' => $viewname, ':sbas_id' => $databox->get_sbas_id()));
+ $stmt->closeCursor();
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
+ cache_databox::update($databox->get_sbas_id(), 'structure');
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return const
+ */
+ public function get_base_type()
+ {
+ return self::BASE_TYPE;
+ }
+
+ public function forceUpgrade(Setup_Upgrade &$upgrader)
+ {
+ $upgrader->add_steps(8 + count($this->get_databoxes()));
+
+ $registry = $this->get_registry();
+
+ /**
+ * Step 1
+ */
+ $upgrader->set_current_message(_('Flushing cache'));
+
+ $this->Core['CacheService']->flushAll();
+
+ $upgrader->add_steps_complete(1);
+
+
+ $upgrader->set_current_message(_('Creating new tables'));
+ $core = bootstrap::getCore();
+ $em = $core->getEntityManager();
+ //create schema
+
+ if ($em->getConnection()->getDatabasePlatform()->supportsAlterTable()) {
+ $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
+ $metas = $em->getMetadataFactory()->getAllMetadata();
+ $tool->updateSchema($metas, true);
+ }
+
+ $upgrader->add_steps_complete(1);
+
+ /**
+ * Step 2
+ */
+ $upgrader->set_current_message(_('Purging directories'));
+ $system_file = new system_file($registry->get('GV_RootPath') . 'tmp/cache_minify/');
+ $system_file->empty_directory();
+ $upgrader->add_steps_complete(1);
+
+ /**
+ * Step 3
+ */
+ $upgrader->set_current_message(_('Purging directories'));
+ $system_file = new system_file($registry->get('GV_RootPath') . 'tmp/cache_twig/');
+ $system_file->empty_directory();
+ $upgrader->add_steps_complete(1);
+
+ /**
+ * Step 5
+ */
+ $upgrader->set_current_message(_('Copying files'));
+ phrasea::copy_custom_files();
+ $upgrader->add_steps_complete(1);
+
+ $advices = array();
+
+ /**
+ * Step 6
+ */
+ $upgrader->set_current_message(_('Upgrading appbox'));
+ $advices = $this->upgradeDB(true, $upgrader);
+ $upgrader->add_steps_complete(1);
+
+ /**
+ * Step 7
+ */
+ foreach ($this->get_databoxes() as $s) {
+ $upgrader->set_current_message(sprintf(_('Upgrading %s'), $s->get_viewname()));
+ $advices = array_merge($advices, $s->upgradeDB(true, $upgrader));
+ $upgrader->add_steps_complete(1);
+ }
+
+ /**
+ * Step 8
+ */
+ $upgrader->set_current_message(_('Post upgrade'));
+ $this->post_upgrade($upgrader);
+ $upgrader->add_steps_complete(1);
+
+
+ /**
+ * Step 9
+ */
+ $upgrader->set_current_message(_('Flushing cache'));
+
+ $this->Core['CacheService']->flushAll();
+
+ $upgrader->add_steps_complete(1);
+
+ return $advices;
+ }
+
+ protected function post_upgrade(Setup_Upgrade &$upgrader)
+ {
+ $Core = bootstrap::getCore();
+
+ $upgrader->add_steps(1 + count($this->get_databoxes()));
+ $this->apply_patches($this->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
+ $this->setVersion($Core->getVersion()->getNumber());
+ $upgrader->add_steps_complete(1);
+
+ foreach ($this->get_databoxes() as $databox) {
+ $databox->apply_patches($databox->get_version(), $Core->getVersion()->getNumber(), true, $upgrader);
+ $databox->setVersion($Core->getVersion()->getNumber());
+ $upgrader->add_steps_complete(1);
+ }
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param registryInterface $registry
+ * @param type $conn
+ * @param type $dbname
+ * @param type $write_file
+ * @return type
+ */
+ public static function create(\Alchemy\Phrasea\Core $Core, registryInterface &$registry, connection_interface $conn, $dbname, $write_file = false)
+ {
+ $credentials = $conn->get_credentials();
+
+ if ($conn->is_multi_db() && trim($dbname) === '') {
+ throw new \Exception(_('Nom de base de donnee incorrect'));
+ }
+
+ if ($write_file) {
+ if ($conn->is_multi_db() && ! isset($credentials['dbname'])) {
+ $credentials['dbname'] = $dbname;
+ }
+
+ foreach ($credentials as $key => $value) {
+ $key = $key == 'hostname' ? 'host' : $key;
+ $connexionINI[$key] = (string) $value;
+ }
+
+ $Core->getConfiguration()->initialize();
+ $connexionINI['driver'] = 'pdo_mysql';
+ $connexionINI['charset'] = 'UTF8';
+
+ $serverName = $registry->get('GV_ServerName');
+
+ $root = __DIR__ . '/../../';
+
+ $connexion = array(
+ 'main_connexion' => $connexionINI,
+ 'test_connexion' => array(
+ 'driver' => 'pdo_sqlite',
+ 'path' => realpath($root . 'tests') . '/tests.sqlite',
+ 'charset' => 'UTF8'
+ ));
+
+ $cacheService = "array_cache";
+
+ $Core->getConfiguration()->setConnexions($connexion);
+
+ $services = $Core->getConfiguration()->getConfigurations();
+
+ foreach ($services as $serviceName => $service) {
+ if ($serviceName === "doctrine_prod") {
+
+ $services["doctrine_prod"]["options"]["cache"] = array(
+ "query" => $cacheService,
+ "result" => $cacheService,
+ "metadata" => $cacheService
+ );
+ }
+ }
+ $Core->getConfiguration()->setConfigurations($services);
+
+ $arrayConf = $Core->getConfiguration()->getConfigurations();
+
+ foreach ($arrayConf as $key => $value) {
+ if (is_array($value) && array_key_exists('phraseanet', $value)) {
+ $arrayConf[$key]["phraseanet"]["servername"] = $serverName;
+ }
+
+ if (is_array($value) && $key === 'prod') {
+ $arrayConf[$key]["cache"] = $cacheService;
+ }
+ }
+
+ $Core->getConfiguration()->setConfigurations($arrayConf);
+
+ $Core->getConfiguration()->setEnvironnement('prod');
+ }
+ try {
+ if ($conn->is_multi_db()) {
+ $conn->query('CREATE DATABASE `' . $dbname . '`
CHARACTER SET utf8 COLLATE utf8_unicode_ci');
- }
+ }
+ } catch (Exception $e) {
+
+ }
+
+ try {
+ if ($conn->is_multi_db()) {
+ $conn->query('USE `' . $dbname . '`');
+ }
+ } catch (Exception $e) {
+ throw new Exception(_('setup::la base de donnees existe deja et vous n\'avez pas les droits ou vous n\'avez pas les droits de la creer') . $e->getMessage());
+ }
+
+ try {
+ $appbox = self::get_instance($Core, $registry);
+ $appbox->insert_datas();
+ } catch (Exception $e) {
+ throw new Exception('Error while installing ' . $e->getMessage());
+ }
+
+ return $appbox;
}
- catch (Exception $e)
+ protected $databoxes;
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_databoxes()
{
+ if ($this->databoxes)
+ return $this->databoxes;
+ $ret = array();
+ foreach ($this->retrieve_sbas_ids() as $sbas_id) {
+ try {
+ $ret[$sbas_id] = databox::get_instance($sbas_id);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ $this->databoxes = $ret;
+
+ return $this->databoxes;
}
- try
+ protected function retrieve_sbas_ids()
{
- if ($conn->is_multi_db())
- {
- $conn->query('USE `' . $dbname . '`');
- }
+ try {
+ return $this->get_data_from_cache(self::CACHE_SBAS_IDS);
+ } catch (Exception $e) {
+
+ }
+ $sql = 'SELECT sbas_id FROM sbas';
+
+ $ret = array();
+
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs as $row) {
+ $ret[] = (int) $row['sbas_id'];
+ }
+
+ $this->set_data_to_cache($ret, self::CACHE_SBAS_IDS);
+
+ return $ret;
}
- catch (Exception $e)
+
+ public function get_databox($sbas_id)
{
- throw new Exception(_('setup::la base de donnees existe deja et vous n\'avez pas les droits ou vous n\'avez pas les droits de la creer') . $e->getMessage());
+ $databoxes = $this->get_databoxes();
+ if ( ! array_key_exists($sbas_id, $databoxes))
+ throw new Exception_DataboxNotFound('Databox `' . $sbas_id . '` not found');
+
+ return $databoxes[$sbas_id];
}
- try
+ /**
+ *
+ * @return Session_Handler
+ */
+ public function get_session()
{
- $appbox = self::get_instance($Core, $registry);
- $appbox->insert_datas();
+ return $this->session;
}
- catch (Exception $e)
+
+ public static function list_databox_templates()
{
- throw new Exception('Error while installing ' . $e->getMessage());
+ $files = array();
+ $dir = new DirectoryIterator(__DIR__ . '/../conf.d/data_templates/');
+ foreach ($dir as $fileinfo) {
+ if ($fileinfo->isFile()) {
+ $files[] = substr($fileinfo->getFilename(), 0, (strlen($fileinfo->getFilename()) - 4));
+ }
+ }
+
+ return $files;
}
- return $appbox;
- }
-
- protected $databoxes;
-
- /**
- *
- * @return Array
- */
- public function get_databoxes()
- {
- if ($this->databoxes)
-
- return $this->databoxes;
-
- $ret = array();
- foreach ($this->retrieve_sbas_ids() as $sbas_id)
+ /**
+ *
+ * @param $option
+ * @return string
+ */
+ public function get_cache_key($option = null)
{
- try
- {
- $ret[$sbas_id] = databox::get_instance($sbas_id);
- }
- catch (Exception $e)
- {
-
- }
+ return 'appbox_' . ($option ? $option . '_' : '');
}
-
- $this->databoxes = $ret;
-
- return $this->databoxes;
- }
-
- protected function retrieve_sbas_ids()
- {
- try
- {
- return $this->get_data_from_cache(self::CACHE_SBAS_IDS);
- }
- catch (Exception $e)
- {
-
- }
- $sql = 'SELECT sbas_id FROM sbas';
-
- $ret = array();
-
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs as $row)
- {
- $ret[] = (int) $row['sbas_id'];
- }
-
- $this->set_data_to_cache($ret, self::CACHE_SBAS_IDS);
-
- return $ret;
- }
-
- public function get_databox($sbas_id)
- {
- $databoxes = $this->get_databoxes();
- if (!array_key_exists($sbas_id, $databoxes))
- throw new Exception_DataboxNotFound('Databox `' . $sbas_id . '` not found');
-
- return $databoxes[$sbas_id];
- }
-
- /**
- *
- * @return Session_Handler
- */
- public function get_session()
- {
- return $this->session;
- }
-
- public static function list_databox_templates()
- {
- $files = array();
- $dir = new DirectoryIterator(__DIR__ . '/../conf.d/data_templates/');
- foreach ($dir as $fileinfo)
- {
- if ($fileinfo->isFile())
- {
- $files[] = substr($fileinfo->getFilename(), 0, (strlen($fileinfo->getFilename()) - 4));
- }
- }
-
- return $files;
- }
-
- /**
- *
- * @param $option
- * @return string
- */
- public function get_cache_key($option = null)
- {
- return 'appbox_' . ($option ? $option . '_' : '');
- }
-
}
diff --git a/lib/classes/appbox/register.class.php b/lib/classes/appbox/register.class.php
index 3a20aebb96..b5e71a57cc 100644
--- a/lib/classes/appbox/register.class.php
+++ b/lib/classes/appbox/register.class.php
@@ -17,83 +17,80 @@
*/
class appbox_register
{
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- /**
- *
- * @var appbox
- */
- protected $appbox;
-
- /**
- * Construct an Appbox_Register object which will give use infos
- * about the current registrations on the provided appbox
- *
- * @param appbox $appbox
- * @return appbox_register
- */
- public function __construct(appbox &$appbox)
- {
- $this->appbox = $appbox;
-
- return $this;
- }
-
- /**
- * Add a registration request for a user on a collection
- *
- * @param User_Interface $user
- * @param collection $collection
- * @return appbox_register
- */
- public function add_request(User_Interface $user, collection $collection)
- {
- $sql = "INSERT INTO demand (date_modif, usr_id, base_id, en_cours, refuser)
- VALUES (now(), :usr_id , :base_id, 1, 0)";
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id(), ':base_id' => $collection->get_base_id()));
- $stmt->closeCursor();
-
- return $this;
- }
-
- /**
- * Return an array of collection objects where provided
- * user is waiting for approbation
- *
- * @param User_Interface $user
- * @return array
- */
- public function get_collection_awaiting_for_user(User_Interface $user)
- {
- $sql = 'SELECT base_id FROM demand WHERE usr_id = :usr_id AND en_cours="1" ';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $user->get_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- $ret = array();
- foreach ($rs as $row)
+ /**
+ * Construct an Appbox_Register object which will give use infos
+ * about the current registrations on the provided appbox
+ *
+ * @param appbox $appbox
+ * @return appbox_register
+ */
+ public function __construct(appbox &$appbox)
{
- $ret[] = collection::get_from_base_id($row['base_id']);
+ $this->appbox = $appbox;
+
+ return $this;
}
- return $ret;
- }
+ /**
+ * Add a registration request for a user on a collection
+ *
+ * @param User_Interface $user
+ * @param collection $collection
+ * @return appbox_register
+ */
+ public function add_request(User_Interface $user, collection $collection)
+ {
+ $sql = "INSERT INTO demand (date_modif, usr_id, base_id, en_cours, refuser)
+ VALUES (now(), :usr_id , :base_id, 1, 0)";
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id(), ':base_id' => $collection->get_base_id()));
+ $stmt->closeCursor();
- /**
- * Remove all registration older than a month
- *
- * @param appbox $appbox
- * @return appbox_register
- */
- public static function clean_old_requests(appbox $appbox)
- {
- $lastMonth = new DateTime('-1 month');
- $sql = "delete from demand where date_modif < :lastMonth";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':lastMonth' => phraseadate::format_mysql($lastMonth)));
- $stmt->closeCursor();
+ return $this;
+ }
- return;
- }
+ /**
+ * Return an array of collection objects where provided
+ * user is waiting for approbation
+ *
+ * @param User_Interface $user
+ * @return array
+ */
+ public function get_collection_awaiting_for_user(User_Interface $user)
+ {
+ $sql = 'SELECT base_id FROM demand WHERE usr_id = :usr_id AND en_cours="1" ';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $user->get_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ $ret = array();
+ foreach ($rs as $row) {
+ $ret[] = collection::get_from_base_id($row['base_id']);
+ }
+ return $ret;
+ }
+
+ /**
+ * Remove all registration older than a month
+ *
+ * @param appbox $appbox
+ * @return appbox_register
+ */
+ public static function clean_old_requests(appbox $appbox)
+ {
+ $lastMonth = new DateTime('-1 month');
+ $sql = "delete from demand where date_modif < :lastMonth";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':lastMonth' => phraseadate::format_mysql($lastMonth)));
+ $stmt->closeCursor();
+
+ return;
+ }
}
diff --git a/lib/classes/base.class.php b/lib/classes/base.class.php
index f5d87a5270..fbc26cc165 100644
--- a/lib/classes/base.class.php
+++ b/lib/classes/base.class.php
@@ -11,905 +11,821 @@
abstract class base implements cache_cacheableInterface
{
+ protected $version;
- protected $version;
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- /**
- *
- * @var int
- */
- protected $id;
+ /**
+ *
+ * @var string
+ */
+ protected $schema;
- /**
- *
- * @var string
- */
- protected $schema;
+ /**
+ *
+ * @var
+ */
+ protected $dbname;
- /**
- *
- * @var
- */
- protected $dbname;
+ /**
+ *
+ * @var
+ */
+ protected $passwd;
- /**
- *
- * @var
- */
- protected $passwd;
+ /**
+ * Database Username
+ *
+ * @var
+ */
+ protected $user;
- /**
- * Database Username
- *
- * @var
- */
- protected $user;
+ /**
+ *
+ * @var
+ */
+ protected $port;
- /**
- *
- * @var
- */
- protected $port;
+ /**
+ *
+ * @var
+ */
+ protected $host;
- /**
- *
- * @var
- */
- protected $host;
+ /**
+ *
+ */
+ const APPLICATION_BOX = 'APPLICATION_BOX';
+ /**
+ *
+ */
+ const DATA_BOX = 'DATA_BOX';
- /**
- *
- */
+ /**
+ *
+ */
+ abstract function get_base_type();
- const APPLICATION_BOX = 'APPLICATION_BOX';
- /**
- *
- */
- const DATA_BOX = 'DATA_BOX';
-
- /**
- *
- */
- abstract function get_base_type();
-
- /**
- *
- * @return
- */
- public function get_schema()
- {
- if ($this->schema)
-
- return $this->schema;
-
- $this->load_schema();
-
- return $this->schema;
- }
-
- /**
- *
- * @return
- */
- public function get_dbname()
- {
- return $this->dbname;
- }
-
- /**
- *
- * @return
- */
- public function get_passwd()
- {
- return $this->passwd;
- }
-
- /**
- *
- * @return
- */
- public function get_user()
- {
- return $this->user;
- }
-
- /**
- *
- * @return
- */
- public function get_port()
- {
- return $this->port;
- }
-
- /**
- *
- * @return
- */
- public function get_host()
- {
- return $this->host;
- }
-
- /**
- *
- * @return registry
- */
- public function get_registry()
- {
- return $this->registry;
- }
-
- /**
- *
- * @param registryInterface $registry
- * @return base
- */
- public function set_registry(registryInterface $registry)
- {
- $this->registry = $registry;
-
- return $this;
- }
-
- /**
- *
- * @return connection_pdo
- */
- public function get_connection()
- {
- return $this->connection;
- }
-
- public function get_cache()
- {
- if (!$this->cache)
+ /**
+ *
+ * @return
+ */
+ public function get_schema()
{
- $this->cache = $this->Core->getCache();
+ if ($this->schema)
+ return $this->schema;
+
+ $this->load_schema();
+
+ return $this->schema;
}
- return $this->cache;
- }
-
- /**
- *
- * @param $option
- * @return
- */
- public function get_data_from_cache($option = null)
- {
-
- if ($this->get_base_type() == self::DATA_BOX)
+ /**
+ *
+ * @return
+ */
+ public function get_dbname()
{
- \cache_databox::refresh($this->id);
+ return $this->dbname;
}
- return $this->get_cache()->get($this->get_cache_key($option));
- }
-
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->get_cache()->save($this->get_cache_key($option), $value, $duration);
- }
-
- public function delete_data_from_cache($option = null)
- {
-
- if ($option === appbox::CACHE_LIST_BASES)
+ /**
+ *
+ * @return
+ */
+ public function get_passwd()
{
- $keys = array($this->get_cache_key(appbox::CACHE_LIST_BASES));
- phrasea::reset_sbasDatas();
- phrasea::reset_baseDatas();
- phrasea::clear_sbas_params();
- $keys[] = $this->get_cache_key(appbox::CACHE_SBAS_IDS);
-
- return $this->get_cache()->deleteMulti($keys);
+ return $this->passwd;
}
- if (is_array($option))
+ /**
+ *
+ * @return
+ */
+ public function get_user()
{
- foreach ($option as $key => $value)
- $option[$key] = $this->get_cache_key($value);
-
- return $this->get_cache()->deleteMulti($option);
- }
- else
- {
- return $this->get_cache()->delete($this->get_cache_key($option));
- }
- }
-
- public function get_cache_key($option = null)
- {
- throw new Exception(__METHOD__ . ' must be defined in extended class');
- }
-
- public function need_major_upgrade()
- {
- return (version_compare($this->get_version(), '3.2.0.0a1', '<') === true);
- }
-
- public function get_version()
- {
-
- if ($this->version)
-
- return $this->version;
-
- $version = '0.0.0';
-
- $sql = '';
- if ($this->get_base_type() == self::APPLICATION_BOX)
- $sql = 'SELECT version FROM sitepreff';
- if ($this->get_base_type() == self::DATA_BOX)
- $sql = 'SELECT value AS version FROM pref WHERE prop="version" LIMIT 1;';
-
- if ($sql !== '')
- {
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- if ($row)
- $version = $row['version'];
+ return $this->user;
}
- $this->version = $version;
-
- return $this->version;
- }
-
- public function upgradeavailable()
- {
- if ($this->get_version())
-
- return version_compare(\Alchemy\Phrasea\Core\Version::getNumber(), $this->get_version(), '>');
- else
-
- return true;
- }
-
- protected function upgradeDb($apply_patches, Setup_Upgrade &$upgrader)
- {
- $recommends = array();
-
- $allTables = array();
-
- $schema = $this->get_schema();
-
- foreach ($schema->tables->table as $table)
- $allTables[(string) $table['name']] = $table;
-
- $upgrader->add_steps(count($allTables) + 1);
-
- $sql = "SHOW TABLE STATUS";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
-
- $ORMTables = array(
- 'BasketElements',
- 'Baskets',
- 'StoryWZ',
- 'UsrListOwners',
- 'UsrLists',
- 'UsrListsContent',
- 'ValidationDatas',
- 'ValidationParticipants',
- 'ValidationSessions',
- );
-
- foreach ($rs as $row)
+ /**
+ *
+ * @return
+ */
+ public function get_port()
{
- $tname = $row["Name"];
+ return $this->port;
+ }
- if (isset($allTables[$tname]))
- {
- $upgrader->set_current_message(sprintf(_('Updating table %s'), $tname));
+ /**
+ *
+ * @return
+ */
+ public function get_host()
+ {
+ return $this->host;
+ }
- $engine = strtolower(trim($allTables[$tname]->engine));
- $ref_engine = strtolower($row['Engine']);
+ /**
+ *
+ * @return registry
+ */
+ public function get_registry()
+ {
+ return $this->registry;
+ }
- if ($engine != $ref_engine && in_array($engine, array('innodb', 'myisam')))
- {
- $sql = 'ALTER TABLE `' . $tname . '` ENGINE = ' . $engine;
- try
- {
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
- }
- catch (Exception $e)
- {
- $recommends[] = array(
- 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
- 'sql' => $sql
- );
- }
+ /**
+ *
+ * @param registryInterface $registry
+ * @return base
+ */
+ public function set_registry(registryInterface $registry)
+ {
+ $this->registry = $registry;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return connection_pdo
+ */
+ public function get_connection()
+ {
+ return $this->connection;
+ }
+
+ public function get_cache()
+ {
+ if ( ! $this->cache) {
+ $this->cache = $this->Core->getCache();
}
- $ret = self::upgradeTable($allTables[$tname]);
- $recommends = array_merge($recommends, $ret);
- unset($allTables[$tname]);
- $upgrader->add_steps_complete(1);
- }
- elseif (!in_array($tname, $ORMTables))
- {
- $recommends[] = array(
- 'message' => 'Une table pourrait etre supprime',
- 'sql' => 'DROP TABLE ' . $this->dbname . '.`' . $tname . '`;'
- );
- }
+ return $this->cache;
}
- foreach ($allTables as $tname => $table)
+ /**
+ *
+ * @param $option
+ * @return
+ */
+ public function get_data_from_cache($option = null)
{
- $upgrader->set_current_message(sprintf(_('Creating table %s'), $table));
- $this->createTable($table);
- $upgrader->add_steps_complete(1);
+
+ if ($this->get_base_type() == self::DATA_BOX) {
+ \cache_databox::refresh($this->id);
+ }
+
+ return $this->get_cache()->get($this->get_cache_key($option));
}
- $current_version = $this->get_version();
- $Core = bootstrap::getCore();
-
- $upgrader->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname()));
- if ($apply_patches)
+ public function set_data_to_cache($value, $option = null, $duration = 0)
{
- $this->apply_patches($current_version, $Core->getVersion()->getNumber(), false, $upgrader);
+ return $this->get_cache()->save($this->get_cache_key($option), $value, $duration);
}
- $upgrader->add_steps_complete(1);
- return $recommends;
- }
-
- protected function setVersion($version)
- {
- try
+ public function delete_data_from_cache($option = null)
{
- $sql = '';
- if ($this->get_base_type() === self::APPLICATION_BOX)
- $sql = 'UPDATE sitepreff SET version = "' . $version . '"';
- if ($this->get_base_type() === self::DATA_BOX)
- {
- $sql = 'DELETE FROM pref WHERE prop="version" AND locale IS NULL';
- $this->get_connection()->query($sql);
- $sql = 'REPLACE INTO pref (id, prop, value,locale, updated_on) VALUES (null, "version", :version,"", NOW())';
- }
- if ($sql !== '')
- {
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':version' => $version));
- $stmt->closeCursor();
+
+ if ($option === appbox::CACHE_LIST_BASES) {
+ $keys = array($this->get_cache_key(appbox::CACHE_LIST_BASES));
+ phrasea::reset_sbasDatas();
+ phrasea::reset_baseDatas();
+ phrasea::clear_sbas_params();
+ $keys[] = $this->get_cache_key(appbox::CACHE_SBAS_IDS);
+
+ return $this->get_cache()->deleteMulti($keys);
+ }
+
+ if (is_array($option)) {
+ foreach ($option as $key => $value)
+ $option[$key] = $this->get_cache_key($value);
+
+ return $this->get_cache()->deleteMulti($option);
+ } else {
+ return $this->get_cache()->delete($this->get_cache_key($option));
+ }
+ }
+
+ public function get_cache_key($option = null)
+ {
+ throw new Exception(__METHOD__ . ' must be defined in extended class');
+ }
+
+ public function need_major_upgrade()
+ {
+ return (version_compare($this->get_version(), '3.2.0.0a1', '<') === true);
+ }
+
+ public function get_version()
+ {
+
+ if ($this->version)
+ return $this->version;
+
+ $version = '0.0.0';
+
+ $sql = '';
+ if ($this->get_base_type() == self::APPLICATION_BOX)
+ $sql = 'SELECT version FROM sitepreff';
+ if ($this->get_base_type() == self::DATA_BOX)
+ $sql = 'SELECT value AS version FROM pref WHERE prop="version" LIMIT 1;';
+
+ if ($sql !== '') {
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ if ($row)
+ $version = $row['version'];
+ }
$this->version = $version;
- return true;
- }
- }
- catch (Exception $e)
- {
- throw new Exception('Unable to set the database version');
+ return $this->version;
}
- return;
- }
-
- /**
- *
- * @return base
- */
- protected function load_schema()
- {
- if ($this->schema)
-
- return $this;
-
- $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml");
-
- if (!$structure)
- throw new Exception('Unable to load schema');
-
- if ($this->get_base_type() === self::APPLICATION_BOX)
- $this->schema = $structure->appbox;
- elseif ($this->get_base_type() === self::DATA_BOX)
- $this->schema = $structure->databox;
- else
- throw new Exception('Unknown schema type');
-
- return $this;
- }
-
- /**
- *
- * @return base
- */
- protected function insert_datas()
- {
- $this->load_schema();
-
- foreach ($this->get_schema()->tables->table as $table)
+ public function upgradeavailable()
{
- $this->createTable($table);
+ if ($this->get_version())
+ return version_compare(\Alchemy\Phrasea\Core\Version::getNumber(), $this->get_version(), '>');
+ else
+ return true;
}
- $Core = bootstrap::getCore();
- $this->setVersion($Core->getVersion()->getNumber());
-
- return $this;
- }
-
- /**
- *
- * @param SimpleXMLElement $table
- * @return base
- */
- protected function createTable(SimpleXMLElement $table)
- {
- $field_stmt = $defaults_stmt = array();
-
- $create_stmt = "CREATE TABLE `" . $table['name'] . "` (";
-
- foreach ($table->fields->field as $field)
+ protected function upgradeDb($apply_patches, Setup_Upgrade &$upgrader)
{
- $isnull = trim($field->null) == "" ? "NOT NULL" : "NULL";
+ $recommends = array();
- if (trim($field->default) != "" && trim($field->default) != "CURRENT_TIMESTAMP")
- $is_default = " default '" . $field->default . "'";
- elseif (trim($field->default) == "CURRENT_TIMESTAMP")
- $is_default = " default " . $field->default;
- else
- $is_default = '';
+ $allTables = array();
- $character_set = '';
- if (in_array(strtolower((string) $field->type), array('text', 'longtext', 'mediumtext', 'tinytext'))
- || substr(strtolower((string) $field->type), 0, 7) == 'varchar'
- || in_array(substr(strtolower((string) $field->type), 0, 4), array('char', 'enum')))
- {
+ $schema = $this->get_schema();
- $collation = trim((string) $field->collation) != '' ? trim((string) $field->collation) : 'utf8_unicode_ci';
+ foreach ($schema->tables->table as $table)
+ $allTables[(string) $table['name']] = $table;
- $code = array_pop(array_reverse(explode('_', $collation)));
+ $upgrader->add_steps(count($allTables) + 1);
- $character_set = ' CHARACTER SET ' . $code . ' COLLATE ' . $collation;
- }
-
- $field_stmt[] = " `" . $field->name . "` " . $field->type . " "
- . $field->extra . " " . $character_set . " "
- . $is_default . " " . $isnull . "";
- }
+ $sql = "SHOW TABLE STATUS";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($table->indexes)
- {
- foreach ($table->indexes->index as $index)
- {
- switch ($index->type)
- {
- case "PRIMARY":
- $primary_fields = array();
+ $ORMTables = array(
+ 'BasketElements',
+ 'Baskets',
+ 'StoryWZ',
+ 'UsrListOwners',
+ 'UsrLists',
+ 'UsrListsContent',
+ 'ValidationDatas',
+ 'ValidationParticipants',
+ 'ValidationSessions',
+ );
- foreach ($index->fields->field as $field)
- {
- $primary_fields[] = "`" . $field . "`";
+ foreach ($rs as $row) {
+ $tname = $row["Name"];
+
+ if (isset($allTables[$tname])) {
+ $upgrader->set_current_message(sprintf(_('Updating table %s'), $tname));
+
+ $engine = strtolower(trim($allTables[$tname]->engine));
+ $ref_engine = strtolower($row['Engine']);
+
+ if ($engine != $ref_engine && in_array($engine, array('innodb', 'myisam'))) {
+ $sql = 'ALTER TABLE `' . $tname . '` ENGINE = ' . $engine;
+ try {
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+ $recommends[] = array(
+ 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
+ 'sql' => $sql
+ );
+ }
+ }
+
+ $ret = self::upgradeTable($allTables[$tname]);
+ $recommends = array_merge($recommends, $ret);
+ unset($allTables[$tname]);
+ $upgrader->add_steps_complete(1);
+ } elseif ( ! in_array($tname, $ORMTables)) {
+ $recommends[] = array(
+ 'message' => 'Une table pourrait etre supprime',
+ 'sql' => 'DROP TABLE ' . $this->dbname . '.`' . $tname . '`;'
+ );
}
-
- $field_stmt[] = 'PRIMARY KEY (' . implode(',', $primary_fields) . ')';
- break;
- case "UNIQUE":
- $unique_fields = array();
-
- foreach ($index->fields->field as $field)
- {
- $unique_fields[] = "`" . $field . "`";
- }
-
- $field_stmt[] = 'UNIQUE KEY `' . $index->name . '` (' . implode(',', $unique_fields) . ')';
- break;
- case "INDEX":
- $index_fields = array();
-
- foreach ($index->fields->field as $field)
- {
- $index_fields[] = "`" . $field . "`";
- }
-
- $field_stmt[] = 'KEY `' . $index->name . '` (' . implode(',', $index_fields) . ')';
- break;
- }
- }
- }
- if ($table->defaults)
- {
- foreach ($table->defaults->default as $default)
- {
- $k = $v = $params = $dates_values = array();
- $nonce = random::generatePassword(16);
- foreach ($default->data as $data)
- {
- $k = trim($data['key']);
- if ($k === 'usr_password')
- $data = User_Adapter::salt_password($data, $nonce);
- if ($k === 'nonce')
- $data = $nonce;
- $v = trim(str_replace(array("\r\n", "\r", "\n", "\t"), '', $data));
-
- if (trim(mb_strtolower($v)) == 'now()')
- $dates_values [$k] = 'NOW()';
- else
- $params[$k] = (trim(mb_strtolower($v)) == 'null' ? null : $v);
}
- $separator = ((count($params) > 0 && count($dates_values) > 0) ? ', ' : '');
+ foreach ($allTables as $tname => $table) {
+ $upgrader->set_current_message(sprintf(_('Creating table %s'), $table));
+ $this->createTable($table);
+ $upgrader->add_steps_complete(1);
+ }
+ $current_version = $this->get_version();
- $defaults_stmt[] = array(
- 'sql' =>
- 'INSERT INTO `' . $table['name'] . '` (' . implode(', ', array_keys($params))
- . $separator . implode(', ', array_keys($dates_values)) . ')
+ $Core = bootstrap::getCore();
+
+ $upgrader->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname()));
+ if ($apply_patches) {
+ $this->apply_patches($current_version, $Core->getVersion()->getNumber(), false, $upgrader);
+ }
+ $upgrader->add_steps_complete(1);
+
+ return $recommends;
+ }
+
+ protected function setVersion($version)
+ {
+ try {
+ $sql = '';
+ if ($this->get_base_type() === self::APPLICATION_BOX)
+ $sql = 'UPDATE sitepreff SET version = "' . $version . '"';
+ if ($this->get_base_type() === self::DATA_BOX) {
+ $sql = 'DELETE FROM pref WHERE prop="version" AND locale IS NULL';
+ $this->get_connection()->query($sql);
+ $sql = 'REPLACE INTO pref (id, prop, value,locale, updated_on) VALUES (null, "version", :version,"", NOW())';
+ }
+ if ($sql !== '') {
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':version' => $version));
+ $stmt->closeCursor();
+
+ $this->version = $version;
+
+ return true;
+ }
+ } catch (Exception $e) {
+ throw new Exception('Unable to set the database version');
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @return base
+ */
+ protected function load_schema()
+ {
+ if ($this->schema)
+ return $this;
+
+ $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml");
+
+ if ( ! $structure)
+ throw new Exception('Unable to load schema');
+
+ if ($this->get_base_type() === self::APPLICATION_BOX)
+ $this->schema = $structure->appbox;
+ elseif ($this->get_base_type() === self::DATA_BOX)
+ $this->schema = $structure->databox;
+ else
+ throw new Exception('Unknown schema type');
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return base
+ */
+ protected function insert_datas()
+ {
+ $this->load_schema();
+
+ foreach ($this->get_schema()->tables->table as $table) {
+ $this->createTable($table);
+ }
+
+ $Core = bootstrap::getCore();
+ $this->setVersion($Core->getVersion()->getNumber());
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param SimpleXMLElement $table
+ * @return base
+ */
+ protected function createTable(SimpleXMLElement $table)
+ {
+ $field_stmt = $defaults_stmt = array();
+
+ $create_stmt = "CREATE TABLE `" . $table['name'] . "` (";
+
+ foreach ($table->fields->field as $field) {
+ $isnull = trim($field->null) == "" ? "NOT NULL" : "NULL";
+
+ if (trim($field->default) != "" && trim($field->default) != "CURRENT_TIMESTAMP")
+ $is_default = " default '" . $field->default . "'";
+ elseif (trim($field->default) == "CURRENT_TIMESTAMP")
+ $is_default = " default " . $field->default;
+ else
+ $is_default = '';
+
+ $character_set = '';
+ if (in_array(strtolower((string) $field->type), array('text', 'longtext', 'mediumtext', 'tinytext'))
+ || substr(strtolower((string) $field->type), 0, 7) == 'varchar'
+ || in_array(substr(strtolower((string) $field->type), 0, 4), array('char', 'enum'))) {
+
+ $collation = trim((string) $field->collation) != '' ? trim((string) $field->collation) : 'utf8_unicode_ci';
+
+ $code = array_pop(array_reverse(explode('_', $collation)));
+
+ $character_set = ' CHARACTER SET ' . $code . ' COLLATE ' . $collation;
+ }
+
+ $field_stmt[] = " `" . $field->name . "` " . $field->type . " "
+ . $field->extra . " " . $character_set . " "
+ . $is_default . " " . $isnull . "";
+ }
+
+
+ if ($table->indexes) {
+ foreach ($table->indexes->index as $index) {
+ switch ($index->type) {
+ case "PRIMARY":
+ $primary_fields = array();
+
+ foreach ($index->fields->field as $field) {
+ $primary_fields[] = "`" . $field . "`";
+ }
+
+ $field_stmt[] = 'PRIMARY KEY (' . implode(',', $primary_fields) . ')';
+ break;
+ case "UNIQUE":
+ $unique_fields = array();
+
+ foreach ($index->fields->field as $field) {
+ $unique_fields[] = "`" . $field . "`";
+ }
+
+ $field_stmt[] = 'UNIQUE KEY `' . $index->name . '` (' . implode(',', $unique_fields) . ')';
+ break;
+ case "INDEX":
+ $index_fields = array();
+
+ foreach ($index->fields->field as $field) {
+ $index_fields[] = "`" . $field . "`";
+ }
+
+ $field_stmt[] = 'KEY `' . $index->name . '` (' . implode(',', $index_fields) . ')';
+ break;
+ }
+ }
+ }
+ if ($table->defaults) {
+ foreach ($table->defaults->default as $default) {
+ $k = $v = $params = $dates_values = array();
+ $nonce = random::generatePassword(16);
+ foreach ($default->data as $data) {
+ $k = trim($data['key']);
+ if ($k === 'usr_password')
+ $data = User_Adapter::salt_password($data, $nonce);
+ if ($k === 'nonce')
+ $data = $nonce;
+ $v = trim(str_replace(array("\r\n", "\r", "\n", "\t"), '', $data));
+
+ if (trim(mb_strtolower($v)) == 'now()')
+ $dates_values [$k] = 'NOW()';
+ else
+ $params[$k] = (trim(mb_strtolower($v)) == 'null' ? null : $v);
+ }
+
+ $separator = ((count($params) > 0 && count($dates_values) > 0) ? ', ' : '');
+
+ $defaults_stmt[] = array(
+ 'sql' =>
+ 'INSERT INTO `' . $table['name'] . '` (' . implode(', ', array_keys($params))
+ . $separator . implode(', ', array_keys($dates_values)) . ')
VALUES (:' . implode(', :', array_keys($params))
- . $separator . implode(', ', array_values($dates_values)) . ') '
- , 'params' => $params
- );
- }
- }
-
- $engine = mb_strtolower(trim($table->engine));
- $engine = in_array($engine, array('innodb', 'myisam')) ? $engine : 'innodb';
-
- $create_stmt .= implode(',', $field_stmt);
- $create_stmt .= ") ENGINE=" . $engine . " CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
-
- $stmt = $this->get_connection()->prepare($create_stmt);
- $stmt->execute();
- $stmt->closeCursor();
-
- foreach ($defaults_stmt as $def)
- {
- try
- {
- $stmt = $this->get_connection()->prepare($def['sql']);
- $stmt->execute($def['params']);
- $stmt->closeCursor();
- }
- catch (Exception $e)
- {
- $recommends[] = array(
- 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
- 'sql' => $def['sql']
- );
- }
- }
-
- return $this;
- }
-
- protected function upgradeTable(SimpleXMLElement $table)
- {
- $correct_table = array('fields' => array(), 'indexes' => array(), 'collation' => array());
- $alter = $alter_pre = $return = array();
-
- $registry = registry::get_instance();
-
- foreach ($table->fields->field as $field)
- {
- $expr = trim((string) $field->type);
-
- $_extra = trim((string) $field->extra);
- if ($_extra)
- $expr .= ' ' . $_extra;
-
- $collation = trim((string) $field->collation) != '' ? trim((string) $field->collation) : 'utf8_unicode_ci';
-
- if (in_array(strtolower((string) $field->type), array('text', 'longtext', 'mediumtext', 'tinytext'))
- || substr(strtolower((string) $field->type), 0, 7) == 'varchar'
- || in_array(substr(strtolower((string) $field->type), 0, 4), array('char', 'enum')))
- {
- $code = array_pop(array_reverse(explode('_', $collation)));
-
- $collation = ' CHARACTER SET ' . $code . ' COLLATE ' . $collation;
-
- $correct_table['collation'][trim((string) $field->name)] = $collation;
-
- $expr .= $collation;
- }
-
- $_null = mb_strtolower(trim((string) $field->null));
- if (!$_null || $_null == 'no')
- $expr .= ' NOT NULL';
-
- $_default = (string) $field->default;
- if ($_default && $_default != 'CURRENT_TIMESTAMP')
- $expr .= ' DEFAULT \'' . $_default . '\'';
- elseif ($_default == 'CURRENT_TIMESTAMP')
- $expr .= ' DEFAULT ' . $_default . '';
-
- $correct_table['fields'][trim((string) $field->name)] = $expr;
- }
- if ($table->indexes)
- {
- foreach ($table->indexes->index as $index)
- {
- $i_name = (string) $index->name;
- $expr = array();
- foreach ($index->fields->field as $field)
- $expr[] = '`' . trim((string) $field) . '`';
-
- $expr = implode(', ', $expr);
-
- switch ((string) $index->type)
- {
- case "PRIMARY":
- $correct_table['indexes']['PRIMARY'] = 'PRIMARY KEY (' . $expr . ')';
- break;
- case "UNIQUE":
- $correct_table['indexes'][$i_name] = 'UNIQUE KEY `' . $i_name . '` (' . $expr . ')';
- break;
- case "INDEX":
- $correct_table['indexes'][$i_name] = 'KEY `' . $i_name . '` (' . $expr . ')';
- break;
- }
- }
- }
-
-
- $sql = "SHOW FULL FIELDS FROM `" . $table['name'] . "`";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $rs2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs2 as $row2)
- {
- $f_name = $row2['Field'];
- $expr_found = trim($row2['Type']);
-
- $_extra = $row2['Extra'];
-
- if ($_extra)
- $expr_found .= ' ' . $_extra;
-
- $_collation = $row2['Collation'];
-
- $current_collation = '';
-
- if ($_collation)
- {
- $_collation = explode('_', $row2['Collation']);
-
- $expr_found .= $current_collation = ' CHARACTER SET ' . $_collation[0] . ' COLLATE ' . implode('_', $_collation);
- }
-
- $_null = mb_strtolower(trim($row2['Null']));
-
- if (!$_null || $_null == 'no')
- $expr_found .= ' NOT NULL';
-
- $_default = $row2['Default'];
-
- if ($_default)
- {
- if (trim($row2['Type']) == 'timestamp' && $_default == 'CURRENT_TIMESTAMP')
- $expr_found .= ' DEFAULT CURRENT_TIMESTAMP';
- else
- $expr_found .= ' DEFAULT \'' . $_default . '\'';
- }
-
-
- if (isset($correct_table['fields'][$f_name]))
- {
- if (isset($correct_table['collation'][$f_name]) && $correct_table['collation'][$f_name] != $current_collation)
- {
- $old_type = mb_strtolower(trim($row2['Type']));
- $new_type = false;
-
- switch ($old_type)
- {
- case 'text':
- $new_type = 'blob';
- break;
- case 'longtext':
- $new_type = 'longblob';
- break;
- case 'mediumtext':
- $new_type = 'mediumblob';
- break;
- case 'tinytext':
- $new_type = 'tinyblob';
- break;
- default:
- if (substr($old_type, 0, 4) == 'char')
- $new_type = 'varbinary(255)';
- if (substr($old_type, 0, 7) == 'varchar')
- $new_type = 'varbinary(767)';
- break;
- }
-
- if ($new_type)
- {
- $alter_pre[] = "ALTER TABLE `" . $table['name'] . "` CHANGE `$f_name` `$f_name` " . $new_type . "";
- }
+ . $separator . implode(', ', array_values($dates_values)) . ') '
+ , 'params' => $params
+ );
+ }
}
- if (strtolower($expr_found) !== strtolower($correct_table['fields'][$f_name]))
- {
- $alter[] = "ALTER TABLE `" . $table['name'] . "` CHANGE `$f_name` `$f_name` " . $correct_table['fields'][$f_name];
- }
- unset($correct_table['fields'][$f_name]);
- }
- else
- {
- $return[] = array(
- 'message' => 'Un champ pourrait etre supprime',
- 'sql' => "ALTER TABLE " . $this->dbname . ".`" . $table['name'] . "` DROP `$f_name`;"
- );
- }
- }
+ $engine = mb_strtolower(trim($table->engine));
+ $engine = in_array($engine, array('innodb', 'myisam')) ? $engine : 'innodb';
- foreach ($correct_table['fields'] as $f_name => $expr)
- {
- $alter[] = "ALTER TABLE `" . $table['name'] . "` ADD `$f_name` " . $correct_table['fields'][$f_name];
- }
+ $create_stmt .= implode(',', $field_stmt);
+ $create_stmt .= ") ENGINE=" . $engine . " CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
- $tIndex = array();
- $sql = "SHOW INDEXES FROM `" . $table['name'] . "`";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute();
- $rs2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs2 as $row2)
- {
- if (!isset($tIndex[$row2['Key_name']]))
- $tIndex[$row2['Key_name']] = array('unique' => ((int) ($row2['Non_unique']) == 0), 'columns' => array());
- $tIndex[$row2['Key_name']]['columns'][(int) ($row2['Seq_in_index'])] = $row2['Column_name'];
- }
-
- foreach ($tIndex as $kIndex => $vIndex)
- {
- $strColumns = array();
-
- foreach ($vIndex['columns'] as $column)
- $strColumns[] = '`' . $column . '`';
-
- $strColumns = '(' . implode(', ', $strColumns) . ')';
-
- if ($kIndex == 'PRIMARY')
- $expr_found = 'PRIMARY KEY ' . $strColumns;
- else
- {
- if ($vIndex['unique'])
- $expr_found = 'UNIQUE KEY `' . $kIndex . '` ' . $strColumns;
- else
- $expr_found = 'KEY `' . $kIndex . '` ' . $strColumns;
- }
-
- $full_name_index = ($kIndex == 'PRIMARY') ? 'PRIMARY KEY' : ('INDEX `' . $kIndex . '`');
-
- if (isset($correct_table['indexes'][$kIndex]))
- {
-
- if (mb_strtolower($expr_found) !== mb_strtolower($correct_table['indexes'][$kIndex]))
- {
- $alter[] = 'ALTER TABLE `' . $table['name'] . '` DROP ' . $full_name_index . ', ADD ' . $correct_table['indexes'][$kIndex];
- }
-
- unset($correct_table['indexes'][$kIndex]);
- }
- else
- {
- $return[] = array(
- 'message' => 'Un index pourrait etre supprime',
- 'sql' => 'ALTER TABLE ' . $this->dbname . '.`' . $table['name'] . '` DROP ' . $full_name_index . ';'
- );
- }
- }
-
- foreach ($correct_table['indexes'] as $kIndex => $expr)
- $alter[] = 'ALTER TABLE `' . $table['name'] . '` ADD ' . $expr;
-
- foreach ($alter_pre as $a)
- {
- try
- {
- $stmt = $this->get_connection()->prepare($a);
+ $stmt = $this->get_connection()->prepare($create_stmt);
$stmt->execute();
$stmt->closeCursor();
- }
- catch (Exception $e)
- {
- $return[] = array(
- 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
- 'sql' => $a
- );
- }
+
+ foreach ($defaults_stmt as $def) {
+ try {
+ $stmt = $this->get_connection()->prepare($def['sql']);
+ $stmt->execute($def['params']);
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+ $recommends[] = array(
+ 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
+ 'sql' => $def['sql']
+ );
+ }
+ }
+
+ return $this;
}
- foreach ($alter as $a)
+ protected function upgradeTable(SimpleXMLElement $table)
{
- try
- {
- $stmt = $this->get_connection()->prepare($a);
+ $correct_table = array('fields' => array(), 'indexes' => array(), 'collation' => array());
+ $alter = $alter_pre = $return = array();
+
+ $registry = registry::get_instance();
+
+ foreach ($table->fields->field as $field) {
+ $expr = trim((string) $field->type);
+
+ $_extra = trim((string) $field->extra);
+ if ($_extra)
+ $expr .= ' ' . $_extra;
+
+ $collation = trim((string) $field->collation) != '' ? trim((string) $field->collation) : 'utf8_unicode_ci';
+
+ if (in_array(strtolower((string) $field->type), array('text', 'longtext', 'mediumtext', 'tinytext'))
+ || substr(strtolower((string) $field->type), 0, 7) == 'varchar'
+ || in_array(substr(strtolower((string) $field->type), 0, 4), array('char', 'enum'))) {
+ $code = array_pop(array_reverse(explode('_', $collation)));
+
+ $collation = ' CHARACTER SET ' . $code . ' COLLATE ' . $collation;
+
+ $correct_table['collation'][trim((string) $field->name)] = $collation;
+
+ $expr .= $collation;
+ }
+
+ $_null = mb_strtolower(trim((string) $field->null));
+ if ( ! $_null || $_null == 'no')
+ $expr .= ' NOT NULL';
+
+ $_default = (string) $field->default;
+ if ($_default && $_default != 'CURRENT_TIMESTAMP')
+ $expr .= ' DEFAULT \'' . $_default . '\'';
+ elseif ($_default == 'CURRENT_TIMESTAMP')
+ $expr .= ' DEFAULT ' . $_default . '';
+
+ $correct_table['fields'][trim((string) $field->name)] = $expr;
+ }
+ if ($table->indexes) {
+ foreach ($table->indexes->index as $index) {
+ $i_name = (string) $index->name;
+ $expr = array();
+ foreach ($index->fields->field as $field)
+ $expr[] = '`' . trim((string) $field) . '`';
+
+ $expr = implode(', ', $expr);
+
+ switch ((string) $index->type) {
+ case "PRIMARY":
+ $correct_table['indexes']['PRIMARY'] = 'PRIMARY KEY (' . $expr . ')';
+ break;
+ case "UNIQUE":
+ $correct_table['indexes'][$i_name] = 'UNIQUE KEY `' . $i_name . '` (' . $expr . ')';
+ break;
+ case "INDEX":
+ $correct_table['indexes'][$i_name] = 'KEY `' . $i_name . '` (' . $expr . ')';
+ break;
+ }
+ }
+ }
+
+
+ $sql = "SHOW FULL FIELDS FROM `" . $table['name'] . "`";
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
+ $rs2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- }
- catch (Exception $e)
- {
- $return[] = array(
- 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
- 'sql' => $a
- );
- }
- }
- return $return;
- }
+ foreach ($rs2 as $row2) {
+ $f_name = $row2['Field'];
+ $expr_found = trim($row2['Type']);
- protected function apply_patches($from, $to, $post_process, Setup_Upgrade &$upgrader)
- {
- if (version_compare($from, $to, '='))
- {
- return true;
- }
+ $_extra = $row2['Extra'];
- $list_patches = array();
+ if ($_extra)
+ $expr_found .= ' ' . $_extra;
- $registry = registry::get_instance();
+ $_collation = $row2['Collation'];
- $upgrader->add_steps(1)->set_current_message(_('Looking for patches'));
+ $current_collation = '';
- $iterator = new DirectoryIterator($registry->get('GV_RootPath') . 'lib/classes/patch/');
+ if ($_collation) {
+ $_collation = explode('_', $row2['Collation']);
- foreach ($iterator as $fileinfo)
- {
- if (!$fileinfo->isDot())
- {
- if (substr($fileinfo->getFilename(), 0, 1) == '.')
- continue;
+ $expr_found .= $current_collation = ' CHARACTER SET ' . $_collation[0] . ' COLLATE ' . implode('_', $_collation);
+ }
- $classname = 'patch_' . array_pop(array_reverse(explode('.', $fileinfo->getFilename())));
+ $_null = mb_strtolower(trim($row2['Null']));
- $patch = new $classname();
+ if ( ! $_null || $_null == 'no')
+ $expr_found .= ' NOT NULL';
- if (!in_array($this->get_base_type(), $patch->concern()))
- continue;
+ $_default = $row2['Default'];
- if (!!$post_process !== !!$patch->require_all_upgrades())
- continue;
+ if ($_default) {
+ if (trim($row2['Type']) == 'timestamp' && $_default == 'CURRENT_TIMESTAMP')
+ $expr_found .= ' DEFAULT CURRENT_TIMESTAMP';
+ else
+ $expr_found .= ' DEFAULT \'' . $_default . '\'';
+ }
- if (!version_compare($patch->get_release(), $from, '>') || !version_compare($patch->get_release(), $to, '<='))
- {
- continue;
+
+ if (isset($correct_table['fields'][$f_name])) {
+ if (isset($correct_table['collation'][$f_name]) && $correct_table['collation'][$f_name] != $current_collation) {
+ $old_type = mb_strtolower(trim($row2['Type']));
+ $new_type = false;
+
+ switch ($old_type) {
+ case 'text':
+ $new_type = 'blob';
+ break;
+ case 'longtext':
+ $new_type = 'longblob';
+ break;
+ case 'mediumtext':
+ $new_type = 'mediumblob';
+ break;
+ case 'tinytext':
+ $new_type = 'tinyblob';
+ break;
+ default:
+ if (substr($old_type, 0, 4) == 'char')
+ $new_type = 'varbinary(255)';
+ if (substr($old_type, 0, 7) == 'varchar')
+ $new_type = 'varbinary(767)';
+ break;
+ }
+
+ if ($new_type) {
+ $alter_pre[] = "ALTER TABLE `" . $table['name'] . "` CHANGE `$f_name` `$f_name` " . $new_type . "";
+ }
+ }
+
+ if (strtolower($expr_found) !== strtolower($correct_table['fields'][$f_name])) {
+ $alter[] = "ALTER TABLE `" . $table['name'] . "` CHANGE `$f_name` `$f_name` " . $correct_table['fields'][$f_name];
+ }
+ unset($correct_table['fields'][$f_name]);
+ } else {
+ $return[] = array(
+ 'message' => 'Un champ pourrait etre supprime',
+ 'sql' => "ALTER TABLE " . $this->dbname . ".`" . $table['name'] . "` DROP `$f_name`;"
+ );
+ }
}
- $n = 0;
- do
- {
- $key = $patch->get_release() . '.' . $n;
- $n++;
+ foreach ($correct_table['fields'] as $f_name => $expr) {
+ $alter[] = "ALTER TABLE `" . $table['name'] . "` ADD `$f_name` " . $correct_table['fields'][$f_name];
}
- while (isset($list_patches[$key]));
- $list_patches[$key] = $patch;
- }
+ $tIndex = array();
+ $sql = "SHOW INDEXES FROM `" . $table['name'] . "`";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs2 as $row2) {
+ if ( ! isset($tIndex[$row2['Key_name']]))
+ $tIndex[$row2['Key_name']] = array('unique' => ((int) ($row2['Non_unique']) == 0), 'columns' => array());
+ $tIndex[$row2['Key_name']]['columns'][(int) ($row2['Seq_in_index'])] = $row2['Column_name'];
+ }
+
+ foreach ($tIndex as $kIndex => $vIndex) {
+ $strColumns = array();
+
+ foreach ($vIndex['columns'] as $column)
+ $strColumns[] = '`' . $column . '`';
+
+ $strColumns = '(' . implode(', ', $strColumns) . ')';
+
+ if ($kIndex == 'PRIMARY')
+ $expr_found = 'PRIMARY KEY ' . $strColumns;
+ else {
+ if ($vIndex['unique'])
+ $expr_found = 'UNIQUE KEY `' . $kIndex . '` ' . $strColumns;
+ else
+ $expr_found = 'KEY `' . $kIndex . '` ' . $strColumns;
+ }
+
+ $full_name_index = ($kIndex == 'PRIMARY') ? 'PRIMARY KEY' : ('INDEX `' . $kIndex . '`');
+
+ if (isset($correct_table['indexes'][$kIndex])) {
+
+ if (mb_strtolower($expr_found) !== mb_strtolower($correct_table['indexes'][$kIndex])) {
+ $alter[] = 'ALTER TABLE `' . $table['name'] . '` DROP ' . $full_name_index . ', ADD ' . $correct_table['indexes'][$kIndex];
+ }
+
+ unset($correct_table['indexes'][$kIndex]);
+ } else {
+ $return[] = array(
+ 'message' => 'Un index pourrait etre supprime',
+ 'sql' => 'ALTER TABLE ' . $this->dbname . '.`' . $table['name'] . '` DROP ' . $full_name_index . ';'
+ );
+ }
+ }
+
+ foreach ($correct_table['indexes'] as $kIndex => $expr)
+ $alter[] = 'ALTER TABLE `' . $table['name'] . '` ADD ' . $expr;
+
+ foreach ($alter_pre as $a) {
+ try {
+ $stmt = $this->get_connection()->prepare($a);
+ $stmt->execute();
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+ $return[] = array(
+ 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
+ 'sql' => $a
+ );
+ }
+ }
+
+ foreach ($alter as $a) {
+ try {
+ $stmt = $this->get_connection()->prepare($a);
+ $stmt->execute();
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+ $return[] = array(
+ 'message' => sprintf(_('Erreur lors de la tentative ; errreur : %s'), $e->getMessage()),
+ 'sql' => $a
+ );
+ }
+ }
+
+ return $return;
}
- $upgrader->add_steps_complete(1)
- ->add_steps(count($list_patches))
- ->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname()));
- ksort($list_patches);
-
- $success = true;
-
- foreach ($list_patches as $patch)
+ protected function apply_patches($from, $to, $post_process, Setup_Upgrade &$upgrader)
{
- if (!$patch->apply($this))
- $success = false;
- $upgrader->add_steps_complete(1);
+ if (version_compare($from, $to, '=')) {
+ return true;
+ }
+
+ $list_patches = array();
+
+ $registry = registry::get_instance();
+
+ $upgrader->add_steps(1)->set_current_message(_('Looking for patches'));
+
+ $iterator = new DirectoryIterator($registry->get('GV_RootPath') . 'lib/classes/patch/');
+
+ foreach ($iterator as $fileinfo) {
+ if ( ! $fileinfo->isDot()) {
+ if (substr($fileinfo->getFilename(), 0, 1) == '.')
+ continue;
+
+ $classname = 'patch_' . array_pop(array_reverse(explode('.', $fileinfo->getFilename())));
+
+ $patch = new $classname();
+
+ if ( ! in_array($this->get_base_type(), $patch->concern()))
+ continue;
+
+ if ( ! ! $post_process !== ! ! $patch->require_all_upgrades())
+ continue;
+
+ if ( ! version_compare($patch->get_release(), $from, '>') || ! version_compare($patch->get_release(), $to, '<=')) {
+ continue;
+ }
+
+ $n = 0;
+ do {
+ $key = $patch->get_release() . '.' . $n;
+ $n ++;
+ } while (isset($list_patches[$key]));
+
+ $list_patches[$key] = $patch;
+ }
+ }
+
+ $upgrader->add_steps_complete(1)
+ ->add_steps(count($list_patches))
+ ->set_current_message(sprintf(_('Applying patches on %s'), $this->get_dbname()));
+ ksort($list_patches);
+
+ $success = true;
+
+ foreach ($list_patches as $patch) {
+ if ( ! $patch->apply($this))
+ $success = false;
+ $upgrader->add_steps_complete(1);
+ }
+
+ return $success;
}
-
- return $success;
- }
-
}
diff --git a/lib/classes/bootstrap.class.php b/lib/classes/bootstrap.class.php
index 4885fa189c..81a635a0ef 100644
--- a/lib/classes/bootstrap.class.php
+++ b/lib/classes/bootstrap.class.php
@@ -20,54 +20,49 @@ use Alchemy\Phrasea\Core;
*/
class bootstrap
{
+ protected static $core;
- protected static $core;
-
- public static function set_php_configuration()
- {
- return Core::initPHPConf();
- }
-
- /**
- *
- * @param $env
- * @return Alchemy\Phrasea\Core
- */
- public static function execute($env = null)
- {
- if (static::$core)
+ public static function set_php_configuration()
{
- return static::$core;
+ return Core::initPHPConf();
}
- static::$core = new Core($env);
-
- if (static::$core->getConfiguration()->isInstalled())
+ /**
+ *
+ * @param $env
+ * @return Alchemy\Phrasea\Core
+ */
+ public static function execute($env = null)
{
- static::$core->enableEvents();
+ if (static::$core) {
+ return static::$core;
+ }
+
+ static::$core = new Core($env);
+
+ if (static::$core->getConfiguration()->isInstalled()) {
+ static::$core->enableEvents();
+ }
+
+ if (\setup::is_installed()) {
+ $gatekeeper = \gatekeeper::getInstance(static::$core);
+ $gatekeeper->check_directory();
+ }
+
+ return static::$core;
}
- if (\setup::is_installed())
+ /**
+ *
+ * @return Alchemy\Phrasea\Core
+ */
+ public static function getCore()
{
- $gatekeeper = \gatekeeper::getInstance(static::$core);
- $gatekeeper->check_directory();
+ return static::$core;
}
- return static::$core;
- }
-
- /**
- *
- * @return Alchemy\Phrasea\Core
- */
- public static function getCore()
- {
- return static::$core;
- }
-
- public static function register_autoloads()
- {
- return Core::initAutoloads();
- }
-
+ public static function register_autoloads()
+ {
+ return Core::initAutoloads();
+ }
}
diff --git a/lib/classes/cache/cacheableInterface.class.php b/lib/classes/cache/cacheableInterface.class.php
index 334abbb166..7e2b7d28a3 100644
--- a/lib/classes/cache/cacheableInterface.class.php
+++ b/lib/classes/cache/cacheableInterface.class.php
@@ -17,11 +17,12 @@
*/
interface cache_cacheableInterface
{
- public function get_cache_key($option = null);
- public function get_data_from_cache($option = null);
+ public function get_cache_key($option = null);
- public function set_data_to_cache($value, $option = null, $duration = 0);
+ public function get_data_from_cache($option = null);
- public function delete_data_from_cache($option = null);
+ public function set_data_to_cache($value, $option = null, $duration = 0);
+
+ public function delete_data_from_cache($option = null);
}
diff --git a/lib/classes/cache/databox.class.php b/lib/classes/cache/databox.class.php
index ec0f2b3dc3..e8c400ca70 100644
--- a/lib/classes/cache/databox.class.php
+++ b/lib/classes/cache/databox.class.php
@@ -17,200 +17,190 @@
*/
class cache_databox
{
- protected static $refreshing = false;
- /**
- *
- * @param int $sbas_id
- * @return cache_databox
- */
- public static function refresh($sbas_id)
- {
- if(self::$refreshing)
+ protected static $refreshing = false;
+
+ /**
+ *
+ * @param int $sbas_id
+ * @return cache_databox
+ */
+ public static function refresh($sbas_id)
{
- return;
- }
+ if (self::$refreshing) {
+ return;
+ }
- self::$refreshing = true;
+ self::$refreshing = true;
- $databox = \databox::get_instance((int) $sbas_id);
+ $databox = \databox::get_instance((int) $sbas_id);
- $date = new \DateTime('-3 seconds');
+ $date = new \DateTime('-3 seconds');
- $appbox = \appbox::get_instance(\bootstrap::getCore());
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
- $registry = \registry::get_instance();
+ $registry = \registry::get_instance();
- $last_update = null;
+ $last_update = null;
- try
- {
- $last_update = $appbox->get_data_from_cache('memcached_update_' . $sbas_id);
- }
- catch (\Exception $e)
- {
+ try {
+ $last_update = $appbox->get_data_from_cache('memcached_update_' . $sbas_id);
+ } catch (\Exception $e) {
- }
+ }
- if ($last_update)
- $last_update = new \DateTime($last_update);
- else
- $last_update = new \DateTime('-10 years');
+ if ($last_update)
+ $last_update = new \DateTime($last_update);
+ else
+ $last_update = new \DateTime('-10 years');
- if ($date <= $last_update)
- {
- self::$refreshing = false;
+ if ($date <= $last_update) {
+ self::$refreshing = false;
- return;
- }
+ return;
+ }
- $connsbas = \connection::getPDOConnection($sbas_id);
+ $connsbas = \connection::getPDOConnection($sbas_id);
- $sql = 'SELECT type, value FROM memcached WHERE site_id = :site_id';
- $stmt = $connsbas->prepare($sql);
- $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $sql = 'SELECT type, value FROM memcached WHERE site_id = :site_id';
+ $stmt = $connsbas->prepare($sql);
+ $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- switch ($row['type'])
- {
- case 'record':
- $key = 'record_' . $sbas_id . '_' . $row['value'];
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_SUBDEFS;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_GROUPING;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_MIME;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_ORIGINAL_NAME;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_SHA256;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_STATUS;
- $databox->delete_data_from_cache($key);
- $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_TECHNICAL_DATAS;
- $databox->delete_data_from_cache($key);
+ foreach ($rs as $row) {
+ switch ($row['type']) {
+ case 'record':
+ $key = 'record_' . $sbas_id . '_' . $row['value'];
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_SUBDEFS;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_GROUPING;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_MIME;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_ORIGINAL_NAME;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_SHA256;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_STATUS;
+ $databox->delete_data_from_cache($key);
+ $key = 'record_' . $sbas_id . '_' . $row['value'] . '_' . \record_adapter::CACHE_TECHNICAL_DATAS;
+ $databox->delete_data_from_cache($key);
- $sql = 'DELETE FROM memcached
+ $sql = 'DELETE FROM memcached
WHERE site_id = :site_id AND type="record" AND value = :value';
- $params = array(
- ':site_id' => $registry->get('GV_ServerName')
- , ':value' => $row['value']
- );
+ $params = array(
+ ':site_id' => $registry->get('GV_ServerName')
+ , ':value' => $row['value']
+ );
- $stmt = $connsbas->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $connsbas->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $record = new \record_adapter($sbas_id, $row['value']);
- $record->get_caption()->delete_data_from_cache();
+ $record = new \record_adapter($sbas_id, $row['value']);
+ $record->get_caption()->delete_data_from_cache();
- foreach($record->get_subdefs() as $subdef)
- {
- $subdef->delete_data_from_cache();
- }
+ foreach ($record->get_subdefs() as $subdef) {
+ $subdef->delete_data_from_cache();
+ }
- break;
- case 'structure':
- $appbox->delete_data_from_cache(\appbox::CACHE_LIST_BASES);
- $appbox->delete_data_from_cache(\appbox::CACHE_SBAS_IDS);
+ break;
+ case 'structure':
+ $appbox->delete_data_from_cache(\appbox::CACHE_LIST_BASES);
+ $appbox->delete_data_from_cache(\appbox::CACHE_SBAS_IDS);
- $sql = 'DELETE FROM memcached
+ $sql = 'DELETE FROM memcached
WHERE site_id = :site_id AND type="structure" AND value = :value';
- $params = array(
- ':site_id' => $registry->get('GV_ServerName')
- , ':value' => $row['value']
- );
+ $params = array(
+ ':site_id' => $registry->get('GV_ServerName')
+ , ':value' => $row['value']
+ );
- $stmt = $connsbas->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- break;
- }
+ $stmt = $connsbas->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ break;
+ }
+ }
+
+ $date = new \DateTime();
+ $now = $date->format(DATE_ISO8601);
+
+ $appbox->set_data_to_cache($now, 'memcached_update_' . $sbas_id);
+
+ $conn = \connection::getPDOConnection();
+
+ $sql = 'UPDATE sitepreff SET memcached_update = :date';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':date' => $now));
+ $stmt->closeCursor();
+
+ self::$refreshing = false;
+
+ return;
}
- $date = new \DateTime();
- $now = $date->format(DATE_ISO8601);
+ /**
+ *
+ * @param int $sbas_id
+ * @param string $type
+ * @param mixed content $value
+ * @return Void
+ */
+ public static function update($sbas_id, $type, $value = '')
+ {
- $appbox->set_data_to_cache($now, 'memcached_update_' . $sbas_id);
+ $connbas = \connection::getPDOConnection($sbas_id);
- $conn = \connection::getPDOConnection();
+ $registry = \registry::get_instance();
- $sql = 'UPDATE sitepreff SET memcached_update = :date';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':date' => $now));
- $stmt->closeCursor();
-
- self::$refreshing = false;
-
- return;
- }
-
- /**
- *
- * @param int $sbas_id
- * @param string $type
- * @param mixed content $value
- * @return Void
- */
- public static function update($sbas_id, $type, $value = '')
- {
-
- $connbas = \connection::getPDOConnection($sbas_id);
-
- $registry = \registry::get_instance();
-
- $sql = 'SELECT distinct site_id as site_id
+ $sql = 'SELECT distinct site_id as site_id
FROM clients
WHERE site_id != :site_id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
+ $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $sql = 'REPLACE INTO memcached (site_id, type, value)
+ $sql = 'REPLACE INTO memcached (site_id, type, value)
VALUES (:site_id, :type, :value)';
- $stmt = $connbas->prepare($sql);
+ $stmt = $connbas->prepare($sql);
- foreach ($rs as $row)
- {
- $stmt->execute(array(':site_id' => $row['site_id'], ':type' => $type, ':value' => $value));
+ foreach ($rs as $row) {
+ $stmt->execute(array(':site_id' => $row['site_id'], ':type' => $type, ':value' => $value));
+ }
+
+ $stmt->closeCursor();
+
+ return;
}
- $stmt->closeCursor();
-
- return;
- }
-
- public static function insertClient(\databox $databox)
- {
- $connbas = $databox->get_connection();
-
- $registry = \registry::get_instance();
-
- $sql = 'SELECT site_id FROM clients WHERE site_id = :site_id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
- $rowCount = $stmt->rowCount();
- $stmt->closeCursor();
-
- if ($rowCount > 0)
+ public static function insertClient(\databox $databox)
{
- return;
+ $connbas = $databox->get_connection();
+
+ $registry = \registry::get_instance();
+
+ $sql = 'SELECT site_id FROM clients WHERE site_id = :site_id';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
+ $rowCount = $stmt->rowCount();
+ $stmt->closeCursor();
+
+ if ($rowCount > 0) {
+ return;
+ }
+
+ $sql = 'INSERT INTO clients (site_id) VALUES (:site_id)';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
+ $stmt->closeCursor();
+
+ return;
}
-
- $sql = 'INSERT INTO clients (site_id) VALUES (:site_id)';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':site_id' => $registry->get('GV_ServerName')));
- $stmt->closeCursor();
-
- return;
- }
-
}
diff --git a/lib/classes/caption/Field/Value.class.php b/lib/classes/caption/Field/Value.class.php
index 67278db47e..7f1d54a9b8 100644
--- a/lib/classes/caption/Field/Value.class.php
+++ b/lib/classes/caption/Field/Value.class.php
@@ -19,529 +19,478 @@ use \Alchemy\Phrasea\Vocabulary;
*/
class caption_Field_Value
{
-
- /**
- *
- * @var int
- */
- protected $id;
-
- /**
- *
- * @var string
- */
- protected $value;
-
- /**
- *
- * @var type \Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface
- */
- protected $VocabularyType;
-
- /**
- *
- * @var int
- */
- protected $VocabularyId;
-
- /**
- *
- * @var databox_field
- */
- protected $databox_field;
-
- /**
- *
- * @var record_adapter
- */
- protected $record;
-
- /**
- *
- * @param databox_field $databox_field
- * @param record_adapter $record
- * @param type $id
- * @return \caption_Field_Value
- */
- public function __construct(databox_field $databox_field, record_adapter $record, $id)
- {
- $this->id = (int) $id;
- $this->databox_field = $databox_field;
- $this->record = $record;
-
- $connbas = $databox_field->get_databox()->get_connection();
-
- $sql = 'SELECT record_id, value, VocabularyType, VocabularyId
- FROM metadatas WHERE id = :id';
-
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':id' => $id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $this->value = $row ? $row['value'] : null;
-
- try
- {
- $this->VocabularyType = $row['VocabularyType'] ? Vocabulary\Controller::get($row['VocabularyType']) : null;
- $this->VocabularyId = $row['VocabularyId'];
- }
- catch (\Exception $e)
- {
-
- }
-
-
- if ($this->VocabularyType)
- {
- /**
- * Vocabulary Control has been deactivated
- */
- if ( ! $this->databox_field->getVocabularyControl())
- {
- $this->removeVocabulary();
- }
- /**
- * Vocabulary Control has changed
- */
- elseif ($this->databox_field->getVocabularyControl()->getType() !== $this->VocabularyType->getType())
- {
- $this->removeVocabulary();
- }
- /**
- * Current Id is not available anymore
- */
- elseif ( ! $this->VocabularyType->validate($this->VocabularyId))
- {
- $this->removeVocabulary();
- }
- /**
- * String equivalence has changed
- */
- elseif ($this->VocabularyType->getValue($this->VocabularyId) !== $this->value)
- {
- $this->set_value($this->VocabularyType->getValue($this->VocabularyId));
- }
- }
-
- return $this;
- }
-
- public function getVocabularyType()
- {
- return $this->VocabularyType;
- }
-
- public function getVocabularyId()
- {
- return $this->VocabularyId;
- }
-
- public function getId()
- {
- return $this->id;
- }
-
- public function getValue()
- {
- return $this->value;
- }
-
- public function getRessource()
- {
- return $this->VocabularyType ? $this->VocabularyType->getRessource($this->VocabularyId) : null;
- }
-
- public function getDatabox_field()
- {
- return $this->databox_field;
- }
-
- public function getRecord()
- {
- return $this->record;
- }
-
- public function delete()
- {
- $connbas = $this->databox_field->get_connection();
-
- $sql = 'DELETE FROM metadatas WHERE id = :id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':id' => $this->id));
- $stmt->closeCursor();
-
- $sbas_id = $this->record->get_sbas_id();
- $this->record->get_caption()->delete_data_from_cache();
-
- try
- {
- $registry = registry::get_instance();
- $sphinx_rt = sphinxrt::get_instance($registry);
-
- $sbas_params = phrasea::sbas_params();
-
- if (isset($sbas_params[$sbas_id]))
- {
- $params = $sbas_params[$sbas_id];
- $sbas_crc = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])));
- $sphinx_rt->delete(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_fr", "metadatas" . $sbas_crc . "_stemmed_en"), "metas_realtime" . $sbas_crc, $this->id);
- $sphinx_rt->delete(array("documents" . $sbas_crc, "documents" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc . "_stemmed_en"), "docs_realtime" . $sbas_crc, $this->record->get_record_id());
- }
- }
- catch (Exception $e)
- {
- unset($e);
- }
-
- return $this;
- }
-
- public function removeVocabulary()
- {
- $connbas = $this->databox_field->get_connection();
-
- $params = array(
- ':VocabType' => null
- , ':VocabularyId' => null
- , ':meta_id' => $this->getId()
- );
-
- $sql_up = 'UPDATE metadatas
- SET VocabularyType = :VocabType, VocabularyId = :VocabularyId
- WHERE id = :meta_id';
- $stmt_up = $connbas->prepare($sql_up);
- $stmt_up->execute($params);
- $stmt_up->closeCursor();
-
- $this->VocabularyId = $this->VocabularyType = null;
-
- return $this;
- }
-
- public function setVocab(Vocabulary\ControlProvider\ControlProviderInterface $vocabulary, $vocab_id)
- {
- $connbas = $this->databox_field->get_connection();
-
- $params = array(
- ':VocabType' => $vocabulary->getType()
- , ':VocabularyId' => $vocab_id
- , ':meta_id' => $this->getId()
- );
-
- $sql_up = 'UPDATE metadatas
- SET VocabularyType = :VocabType, VocabularyId = :VocabularyId
- WHERE id = :meta_id';
- $stmt_up = $connbas->prepare($sql_up);
- $stmt_up->execute($params);
- $stmt_up->closeCursor();
-
- $this->set_value($vocabulary->getValue($vocab_id));
-
- return $this;
- }
-
- public function set_value($value)
- {
- $this->value = $value;
-
- $sbas_id = $this->databox_field->get_databox()->get_sbas_id();
- $connbas = $this->databox_field->get_connection();
-
- $params = array(
- ':meta_id' => $this->id
- , ':value' => $value
- );
-
- $sql_up = 'UPDATE metadatas SET value = :value WHERE id = :meta_id';
- $stmt_up = $connbas->prepare($sql_up);
- $stmt_up->execute($params);
- $stmt_up->closeCursor();
-
- try
- {
- $registry = registry::get_instance();
- $sphinx_rt = sphinxrt::get_instance($registry);
-
- $sbas_params = phrasea::sbas_params();
-
- if (isset($sbas_params[$sbas_id]))
- {
- $params = $sbas_params[$sbas_id];
- $sbas_crc = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])));
- $sphinx_rt->delete(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_fr", "metadatas" . $sbas_crc . "_stemmed_en"), "", $this->id);
- $sphinx_rt->delete(array("documents" . $sbas_crc, "documents" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc . "_stemmed_en"), "", $this->record->get_record_id());
- }
- }
- catch (Exception $e)
- {
-
- }
-
- $this->update_cache_value($value);
-
- return $this;
- }
-
- /**
- *
- * @param array $value
- * @return caption_field
- */
- public function update_cache_value($value)
- {
- $this->record->get_caption()->delete_data_from_cache();
- $sbas_id = $this->databox_field->get_databox()->get_sbas_id();
- try
- {
- $registry = registry::get_instance();
-
- $sbas_params = phrasea::sbas_params();
-
- if (isset($sbas_params[$sbas_id]))
- {
- $params = $sbas_params[$sbas_id];
- $sbas_crc = crc32(
- str_replace(
- array('.', '%')
- , '_'
- , sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])
- )
- );
-
- $sphinx_rt = sphinxrt::get_instance($registry);
- $sphinx_rt->replace_in_metas(
- "metas_realtime" . $sbas_crc
- , $this->id
- , $this->databox_field->get_id()
- , $this->record->get_record_id()
- , $sbas_id
- , phrasea::collFromBas($this->record->get_base_id())
- , ($this->record->is_grouping() ? '1' : '0')
- , $this->record->get_type()
- , $value
- , ($this->databox_field->isBusiness() ? '1' : '0')
- , $this->record->get_creation_date()
- );
-
- $all_datas = array();
-
- foreach ($this->record->get_caption()->get_fields(null, true) as $field)
- {
- if ( ! $field->is_indexable())
- {
- continue;
- }
-
- $all_datas[] = $field->get_serialized_values();
- }
-
- $all_datas = implode(' ', $all_datas);
-
- $sphinx_rt->replace_in_documents(
- "docs_realtime" . $sbas_crc, //$this->id,
- $this->record->get_record_id(), $all_datas, $sbas_id, phrasea::collFromBas($this->record->get_base_id()), ($this->record->is_grouping() ? '1' : '0'), $this->record->get_type(), $this->record->get_creation_date()
- );
- }
- }
- catch (Exception $e)
- {
- unset($e);
- }
-
- return $this;
- }
-
- public static function create(databox_field &$databox_field, record_Interface $record, $value, Vocabulary\ControlProvider\ControlProviderInterface $vocabulary = null, $vocabularyId = null)
- {
- $connbas = $databox_field->get_connection();
+ /**
+ *
+ * @var int
+ */
+ protected $id;
/**
- * Check consistency
+ *
+ * @var string
*/
- if ( ! $databox_field->is_multi())
+ protected $value;
+
+ /**
+ *
+ * @var type \Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface
+ */
+ protected $VocabularyType;
+
+ /**
+ *
+ * @var int
+ */
+ protected $VocabularyId;
+
+ /**
+ *
+ * @var databox_field
+ */
+ protected $databox_field;
+
+ /**
+ *
+ * @var record_adapter
+ */
+ protected $record;
+
+ /**
+ *
+ * @param databox_field $databox_field
+ * @param record_adapter $record
+ * @param type $id
+ * @return \caption_Field_Value
+ */
+ public function __construct(databox_field $databox_field, record_adapter $record, $id)
{
- try
- {
- $field = $record->get_caption()->get_field($databox_field->get_name());
- $caption_field_value = array_pop($field->get_values());
- /* @var $value \caption_Field_Value */
- $caption_field_value->set_value($value);
+ $this->id = (int) $id;
+ $this->databox_field = $databox_field;
+ $this->record = $record;
+
+ $connbas = $databox_field->get_databox()->get_connection();
+
+ $sql = 'SELECT record_id, value, VocabularyType, VocabularyId
+ FROM metadatas WHERE id = :id';
+
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':id' => $id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $this->value = $row ? $row['value'] : null;
+
+ try {
+ $this->VocabularyType = $row['VocabularyType'] ? Vocabulary\Controller::get($row['VocabularyType']) : null;
+ $this->VocabularyId = $row['VocabularyId'];
+ } catch (\Exception $e) {
- if ( ! $vocabulary || ! $vocabularyId)
- {
- $caption_field_value->removeVocabulary();
- }
- else
- {
- $caption_field_value->setVocab($vocabulary, $vocabularyId);
}
- return $caption_field_value;
- }
- catch (\Exception $e)
- {
- }
+ if ($this->VocabularyType) {
+ /**
+ * Vocabulary Control has been deactivated
+ */
+ if ( ! $this->databox_field->getVocabularyControl()) {
+ $this->removeVocabulary();
+ }
+ /**
+ * Vocabulary Control has changed
+ */ elseif ($this->databox_field->getVocabularyControl()->getType() !== $this->VocabularyType->getType()) {
+ $this->removeVocabulary();
+ }
+ /**
+ * Current Id is not available anymore
+ */ elseif ( ! $this->VocabularyType->validate($this->VocabularyId)) {
+ $this->removeVocabulary();
+ }
+ /**
+ * String equivalence has changed
+ */ elseif ($this->VocabularyType->getValue($this->VocabularyId) !== $this->value) {
+ $this->set_value($this->VocabularyType->getValue($this->VocabularyId));
+ }
+ }
+
+ return $this;
}
- $sql_ins = 'INSERT INTO metadatas
+ public function getVocabularyType()
+ {
+ return $this->VocabularyType;
+ }
+
+ public function getVocabularyId()
+ {
+ return $this->VocabularyId;
+ }
+
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ public function getRessource()
+ {
+ return $this->VocabularyType ? $this->VocabularyType->getRessource($this->VocabularyId) : null;
+ }
+
+ public function getDatabox_field()
+ {
+ return $this->databox_field;
+ }
+
+ public function getRecord()
+ {
+ return $this->record;
+ }
+
+ public function delete()
+ {
+ $connbas = $this->databox_field->get_connection();
+
+ $sql = 'DELETE FROM metadatas WHERE id = :id';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':id' => $this->id));
+ $stmt->closeCursor();
+
+ $sbas_id = $this->record->get_sbas_id();
+ $this->record->get_caption()->delete_data_from_cache();
+
+ try {
+ $registry = registry::get_instance();
+ $sphinx_rt = sphinxrt::get_instance($registry);
+
+ $sbas_params = phrasea::sbas_params();
+
+ if (isset($sbas_params[$sbas_id])) {
+ $params = $sbas_params[$sbas_id];
+ $sbas_crc = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])));
+ $sphinx_rt->delete(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_fr", "metadatas" . $sbas_crc . "_stemmed_en"), "metas_realtime" . $sbas_crc, $this->id);
+ $sphinx_rt->delete(array("documents" . $sbas_crc, "documents" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc . "_stemmed_en"), "docs_realtime" . $sbas_crc, $this->record->get_record_id());
+ }
+ } catch (Exception $e) {
+ unset($e);
+ }
+
+ return $this;
+ }
+
+ public function removeVocabulary()
+ {
+ $connbas = $this->databox_field->get_connection();
+
+ $params = array(
+ ':VocabType' => null
+ , ':VocabularyId' => null
+ , ':meta_id' => $this->getId()
+ );
+
+ $sql_up = 'UPDATE metadatas
+ SET VocabularyType = :VocabType, VocabularyId = :VocabularyId
+ WHERE id = :meta_id';
+ $stmt_up = $connbas->prepare($sql_up);
+ $stmt_up->execute($params);
+ $stmt_up->closeCursor();
+
+ $this->VocabularyId = $this->VocabularyType = null;
+
+ return $this;
+ }
+
+ public function setVocab(Vocabulary\ControlProvider\ControlProviderInterface $vocabulary, $vocab_id)
+ {
+ $connbas = $this->databox_field->get_connection();
+
+ $params = array(
+ ':VocabType' => $vocabulary->getType()
+ , ':VocabularyId' => $vocab_id
+ , ':meta_id' => $this->getId()
+ );
+
+ $sql_up = 'UPDATE metadatas
+ SET VocabularyType = :VocabType, VocabularyId = :VocabularyId
+ WHERE id = :meta_id';
+ $stmt_up = $connbas->prepare($sql_up);
+ $stmt_up->execute($params);
+ $stmt_up->closeCursor();
+
+ $this->set_value($vocabulary->getValue($vocab_id));
+
+ return $this;
+ }
+
+ public function set_value($value)
+ {
+ $this->value = $value;
+
+ $sbas_id = $this->databox_field->get_databox()->get_sbas_id();
+ $connbas = $this->databox_field->get_connection();
+
+ $params = array(
+ ':meta_id' => $this->id
+ , ':value' => $value
+ );
+
+ $sql_up = 'UPDATE metadatas SET value = :value WHERE id = :meta_id';
+ $stmt_up = $connbas->prepare($sql_up);
+ $stmt_up->execute($params);
+ $stmt_up->closeCursor();
+
+ try {
+ $registry = registry::get_instance();
+ $sphinx_rt = sphinxrt::get_instance($registry);
+
+ $sbas_params = phrasea::sbas_params();
+
+ if (isset($sbas_params[$sbas_id])) {
+ $params = $sbas_params[$sbas_id];
+ $sbas_crc = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])));
+ $sphinx_rt->delete(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_fr", "metadatas" . $sbas_crc . "_stemmed_en"), "", $this->id);
+ $sphinx_rt->delete(array("documents" . $sbas_crc, "documents" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc . "_stemmed_en"), "", $this->record->get_record_id());
+ }
+ } catch (Exception $e) {
+
+ }
+
+ $this->update_cache_value($value);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param array $value
+ * @return caption_field
+ */
+ public function update_cache_value($value)
+ {
+ $this->record->get_caption()->delete_data_from_cache();
+ $sbas_id = $this->databox_field->get_databox()->get_sbas_id();
+ try {
+ $registry = registry::get_instance();
+
+ $sbas_params = phrasea::sbas_params();
+
+ if (isset($sbas_params[$sbas_id])) {
+ $params = $sbas_params[$sbas_id];
+ $sbas_crc = crc32(
+ str_replace(
+ array('.', '%')
+ , '_'
+ , sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])
+ )
+ );
+
+ $sphinx_rt = sphinxrt::get_instance($registry);
+ $sphinx_rt->replace_in_metas(
+ "metas_realtime" . $sbas_crc
+ , $this->id
+ , $this->databox_field->get_id()
+ , $this->record->get_record_id()
+ , $sbas_id
+ , phrasea::collFromBas($this->record->get_base_id())
+ , ($this->record->is_grouping() ? '1' : '0')
+ , $this->record->get_type()
+ , $value
+ , ($this->databox_field->isBusiness() ? '1' : '0')
+ , $this->record->get_creation_date()
+ );
+
+ $all_datas = array();
+
+ foreach ($this->record->get_caption()->get_fields(null, true) as $field) {
+ if ( ! $field->is_indexable()) {
+ continue;
+ }
+
+ $all_datas[] = $field->get_serialized_values();
+ }
+
+ $all_datas = implode(' ', $all_datas);
+
+ $sphinx_rt->replace_in_documents(
+ "docs_realtime" . $sbas_crc, //$this->id,
+ $this->record->get_record_id(), $all_datas, $sbas_id, phrasea::collFromBas($this->record->get_base_id()), ($this->record->is_grouping() ? '1' : '0'), $this->record->get_type(), $this->record->get_creation_date()
+ );
+ }
+ } catch (Exception $e) {
+ unset($e);
+ }
+
+ return $this;
+ }
+
+ public static function create(databox_field &$databox_field, record_Interface $record, $value, Vocabulary\ControlProvider\ControlProviderInterface $vocabulary = null, $vocabularyId = null)
+ {
+ $connbas = $databox_field->get_connection();
+
+ /**
+ * Check consistency
+ */
+ if ( ! $databox_field->is_multi()) {
+ try {
+ $field = $record->get_caption()->get_field($databox_field->get_name());
+ $caption_field_value = array_pop($field->get_values());
+ /* @var $value \caption_Field_Value */
+ $caption_field_value->set_value($value);
+
+ if ( ! $vocabulary || ! $vocabularyId) {
+ $caption_field_value->removeVocabulary();
+ } else {
+ $caption_field_value->setVocab($vocabulary, $vocabularyId);
+ }
+
+ return $caption_field_value;
+ } catch (\Exception $e) {
+
+ }
+ }
+
+ $sql_ins = 'INSERT INTO metadatas
(id, record_id, meta_struct_id, value, VocabularyType, VocabularyId)
VALUES
(null, :record_id, :field, :value, :VocabType, :VocabId)';
- $params = array(
- ':record_id' => $record->get_record_id(),
- ':field' => $databox_field->get_id(),
- ':value' => $value,
- ':VocabType' => $vocabulary ? $vocabulary->getType() : null,
- ':VocabId' => $vocabulary ? $vocabularyId : null,
- );
+ $params = array(
+ ':record_id' => $record->get_record_id(),
+ ':field' => $databox_field->get_id(),
+ ':value' => $value,
+ ':VocabType' => $vocabulary ? $vocabulary->getType() : null,
+ ':VocabId' => $vocabulary ? $vocabularyId : null,
+ );
- $stmt_ins = $connbas->prepare($sql_ins);
- $stmt_ins->execute($params);
+ $stmt_ins = $connbas->prepare($sql_ins);
+ $stmt_ins->execute($params);
- $stmt_ins->closeCursor();
- $meta_id = $connbas->lastInsertId();
+ $stmt_ins->closeCursor();
+ $meta_id = $connbas->lastInsertId();
- $caption_field_value = new self($databox_field, $record, $meta_id);
- $caption_field_value->update_cache_value($value);
+ $caption_field_value = new self($databox_field, $record, $meta_id);
+ $caption_field_value->update_cache_value($value);
- $record->get_caption()->delete_data_from_cache();
+ $record->get_caption()->delete_data_from_cache();
- return $caption_field_value;
- }
-
- /**
- *
- * @return string
- */
- public function highlight_thesaurus()
- {
- $value = $this->getValue();
-
- $databox = $this->databox_field->get_databox();
- $XPATH_thesaurus = $databox->get_xpath_thesaurus();
-
- $tbranch = $this->databox_field->get_tbranch();
-
- if ( ! $tbranch || ! $XPATH_thesaurus)
- {
- return $value;
+ return $caption_field_value;
}
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $unicode = new unicode();
-
- $DOM_branchs = $XPATH_thesaurus->query($tbranch);
-
- $fvalue = $value;
-
- $cleanvalue = str_replace(array("", " ", "'"), array("", "", "'"), $fvalue);
-
- list($term_noacc, $context_noacc) = $this->splitTermAndContext($cleanvalue);
- $term_noacc = $unicode->remove_indexer_chars($term_noacc);
- $context_noacc = $unicode->remove_indexer_chars($context_noacc);
- if ($context_noacc)
+ /**
+ *
+ * @return string
+ */
+ public function highlight_thesaurus()
{
- $q = "//sy[@w='" . $term_noacc . "' and @k='" . $context_noacc . "']";
- }
- else
- {
- $q = "//sy[@w='" . $term_noacc . "' and not(@k)]";
- }
- $qjs = $link = "";
- foreach ($DOM_branchs as $DOM_branch)
- {
- $nodes = $XPATH_thesaurus->cache_query($q, $DOM_branch);
- if ($nodes->length > 0)
- {
- $lngfound = false;
- foreach ($nodes as $node)
- {
- if ($node->getAttribute("lng") == $session->get_I18n())
- {
- // le terme est dans la bonne langue, on le rend cliquable
- list($term, $context) = $this->splitTermAndContext($fvalue);
- $term = str_replace(array("", " "), array("", ""), $term);
- $context = str_replace(array("", " "), array("", ""), $context);
- $qjs = $term;
- if ($context)
- {
- $qjs .= " [" . $context . "]";
- }
- $link = $fvalue;
+ $value = $this->getValue();
- $lngfound = true;
- break;
- }
+ $databox = $this->databox_field->get_databox();
+ $XPATH_thesaurus = $databox->get_xpath_thesaurus();
- $synonyms = $XPATH_thesaurus->query("sy[@lng='" . $session->usr_i18 . "']", $node->parentNode);
- foreach ($synonyms as $synonym)
- {
- $k = $synonym->getAttribute("k");
- if ($synonym->getAttribute("w") != $term_noacc || $k != $context_noacc)
- {
- $link = $qjs = $synonym->getAttribute("v");
- if ($k)
- {
- $link .= " (" . $k . ")";
- $qjs .= " [" . $k . "]";
- }
+ $tbranch = $this->databox_field->get_tbranch();
- $lngfound = true;
- break;
- }
- }
+ if ( ! $tbranch || ! $XPATH_thesaurus) {
+ return $value;
}
- if ( ! $lngfound)
- {
- list($term, $context) = $this->splitTermAndContext($fvalue);
- $term = str_replace(array("", " "), array("", ""), $term);
- $context = str_replace(array("", " "), array("", ""), $context);
- $qjs = $term;
- if ($context)
- {
- $qjs .= " [" . $context . "]";
- }
- $link = $fvalue;
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $unicode = new unicode();
+
+ $DOM_branchs = $XPATH_thesaurus->query($tbranch);
+
+ $fvalue = $value;
+
+ $cleanvalue = str_replace(array("", " ", "'"), array("", "", "'"), $fvalue);
+
+ list($term_noacc, $context_noacc) = $this->splitTermAndContext($cleanvalue);
+ $term_noacc = $unicode->remove_indexer_chars($term_noacc);
+ $context_noacc = $unicode->remove_indexer_chars($context_noacc);
+ if ($context_noacc) {
+ $q = "//sy[@w='" . $term_noacc . "' and @k='" . $context_noacc . "']";
+ } else {
+ $q = "//sy[@w='" . $term_noacc . "' and not(@k)]";
}
- }
+ $qjs = $link = "";
+ foreach ($DOM_branchs as $DOM_branch) {
+ $nodes = $XPATH_thesaurus->cache_query($q, $DOM_branch);
+ if ($nodes->length > 0) {
+ $lngfound = false;
+ foreach ($nodes as $node) {
+ if ($node->getAttribute("lng") == $session->get_I18n()) {
+ // le terme est dans la bonne langue, on le rend cliquable
+ list($term, $context) = $this->splitTermAndContext($fvalue);
+ $term = str_replace(array("", " "), array("", ""), $term);
+ $context = str_replace(array("", " "), array("", ""), $context);
+ $qjs = $term;
+ if ($context) {
+ $qjs .= " [" . $context . "]";
+ }
+ $link = $fvalue;
+
+ $lngfound = true;
+ break;
+ }
+
+ $synonyms = $XPATH_thesaurus->query("sy[@lng='" . $session->usr_i18 . "']", $node->parentNode);
+ foreach ($synonyms as $synonym) {
+ $k = $synonym->getAttribute("k");
+ if ($synonym->getAttribute("w") != $term_noacc || $k != $context_noacc) {
+ $link = $qjs = $synonym->getAttribute("v");
+ if ($k) {
+ $link .= " (" . $k . ")";
+ $qjs .= " [" . $k . "]";
+ }
+
+ $lngfound = true;
+ break;
+ }
+ }
+ }
+ if ( ! $lngfound) {
+ list($term, $context) = $this->splitTermAndContext($fvalue);
+ $term = str_replace(array("", " "), array("", ""), $term);
+ $context = str_replace(array("", " "), array("", ""), $context);
+ $qjs = $term;
+ if ($context) {
+ $qjs .= " [" . $context . "]";
+ }
+ $link = $fvalue;
+ }
+ }
+ }
+ if ($qjs) {
+ $value = "get_sbas_id() . "','"
+ . str_replace("'", "\'", $qjs)
+ . "', '"
+ . str_replace("'", "\'", $this->databox_field->get_name())
+ . "');return(false);\">"
+ . $link
+ . " ";
+ }
+
+ return $value;
}
- if ($qjs)
+
+ /**
+ *
+ * @param string $word
+ * @return array
+ */
+ protected function splitTermAndContext($word)
{
- $value = "get_sbas_id() . "','"
- . str_replace("'", "\'", $qjs)
- . "', '"
- . str_replace("'", "\'", $this->databox_field->get_name())
- . "');return(false);\">"
- . $link
- . " ";
+ $term = trim($word);
+ $context = "";
+ if (($po = strpos($term, "(")) !== false) {
+ if (($pc = strpos($term, ")", $po)) !== false) {
+ $context = trim(substr($term, $po + 1, $pc - $po - 1));
+ $term = trim(substr($term, 0, $po));
+ }
+ }
+
+ return array($term, $context);
}
-
- return $value;
- }
-
- /**
- *
- * @param string $word
- * @return array
- */
- protected function splitTermAndContext($word)
- {
- $term = trim($word);
- $context = "";
- if (($po = strpos($term, "(")) !== false)
- {
- if (($pc = strpos($term, ")", $po)) !== false)
- {
- $context = trim(substr($term, $po + 1, $pc - $po - 1));
- $term = trim(substr($term, 0, $po));
- }
- }
-
- return array($term, $context);
- }
-
}
diff --git a/lib/classes/caption/field.class.php b/lib/classes/caption/field.class.php
index 8cc754259e..6a10001ccb 100644
--- a/lib/classes/caption/field.class.php
+++ b/lib/classes/caption/field.class.php
@@ -17,455 +17,427 @@
*/
class caption_field
{
+ /**
+ *
+ * @var databox_field
+ */
+ protected $databox_field;
- /**
- *
- * @var databox_field
- */
- protected $databox_field;
+ /**
+ *
+ * @var string
+ */
+ protected $values;
- /**
- *
- * @var string
- */
- protected $values;
+ /**
+ *
+ * @var record
+ */
+ protected $record;
- /**
- *
- * @var record
- */
- protected $record;
+ /**
+ *
+ * @param databox_field $databox_field
+ * @param record_Interface $record
+ * @param int $id
+ * @return caption_field
+ */
+ public function __construct(databox_field &$databox_field, record_Interface $record)
+ {
+ $this->record = $record;
+ $this->databox_field = $databox_field;
+ $this->values = array();
- /**
- *
- * @param databox_field $databox_field
- * @param record_Interface $record
- * @param int $id
- * @return caption_field
- */
- public function __construct(databox_field &$databox_field, record_Interface $record)
- {
- $this->record = $record;
- $this->databox_field = $databox_field;
- $this->values = array();
+ $connbas = $databox_field->get_connection();
- $connbas = $databox_field->get_connection();
-
- $sql = 'SELECT id FROM metadatas
+ $sql = 'SELECT id FROM metadatas
WHERE record_id = :record_id
AND meta_struct_id = :meta_struct_id';
- $params = array(
- ':record_id' => $record->get_record_id()
- , ':meta_struct_id' => $databox_field->get_id()
- );
+ $params = array(
+ ':record_id' => $record->get_record_id()
+ , ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $this->values[$row['id']] = new caption_Field_Value($databox_field, $record, $row['id']);
+ foreach ($rs as $row) {
+ $this->values[$row['id']] = new caption_Field_Value($databox_field, $record, $row['id']);
- /**
- * Inconsistent, should not happen
- */
- if(!$databox_field->is_multi())
- {
- break;
- }
+ /**
+ * Inconsistent, should not happen
+ */
+ if ( ! $databox_field->is_multi()) {
+ break;
+ }
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @return record_adapter
- */
- public function get_record()
- {
- return $this->record;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_required()
- {
- return $this->databox_field->is_required();
- }
-
- /**
- *
- * @return boolean
- */
- public function is_multi()
- {
- return $this->databox_field->is_multi();
- }
-
- /**
- *
- * @return boolean
- */
- public function is_readonly()
- {
- return $this->databox_field->is_readonly();
- }
-
- /**
- *
- * @return caption_field
- */
- public function delete()
- {
-
- foreach ($this->get_values() as $value)
+ /**
+ *
+ * @return record_adapter
+ */
+ public function get_record()
{
- $value->delete();
+ return $this->record;
}
- return $this;
- }
-
- /**
- *
- * @param array $values
- * @param string $separator
- * @return string
- */
- protected static function serialize_value(Array $values, $separator, $highlight = false)
- {
- if (strlen($separator) > 1)
- $separator = $separator[0];
-
- if (trim($separator) === '')
- $separator = ' ';
- else
- $separator = ' ' . $separator . ' ';
-
- $array_values = array();
-
- foreach ($values as $value)
+ /**
+ *
+ * @return boolean
+ */
+ public function is_required()
{
- if ($highlight)
- $array_values[] = $value->highlight_thesaurus();
- else
- $array_values[] = $value->getValue();
+ return $this->databox_field->is_required();
}
- return implode($separator, $array_values);
- }
-
- /**
- *
- * @return array
- */
- public function get_values()
- {
- return $this->values;
- }
-
- /**
- *
- * @param int $meta_id
- * @return array
- */
- public function get_value($meta_id)
- {
- return $this->values[$meta_id];
- }
-
- /**
- *
- * @param string $custom_separator
- * @return mixed
- */
- public function get_serialized_values($custom_separator = false, $highlightTheso = false)
- {
- if ($this->databox_field->is_multi() === true)
+ /**
+ *
+ * @return boolean
+ */
+ public function is_multi()
{
- if ($custom_separator !== false)
- $separator = $custom_separator;
- else
- $separator = $this->databox_field->get_separator();
-
- return self::serialize_value($this->values, $separator, $highlightTheso);
- }
- else
- {
- foreach ($this->values as $value)
- {
- /* @var $value Caption_Field_Value */
-
- return $value->highlight_thesaurus();
- }
+ return $this->databox_field->is_multi();
}
- return null;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->databox_field->get_name();
- }
-
- /**
- *
- * @return int
- */
- public function get_meta_struct_id()
- {
- return $this->databox_field->get_id();
- }
-
- /**
- *
- * @return boolean
- */
- public function is_indexable()
- {
- return $this->databox_field->is_indexable();
- }
-
- /**
- *
- * @return databox_field
- */
- public function get_databox_field()
- {
- return $this->databox_field;
- }
-
- /**
- *
- * @return string
- */
- public function highlight_thesaurus()
- {
- $value = $this->get_serialized_values(false, true);
-
- return $value;
- }
-
- /**
- *
- * @param string $serialized_value
- * @param string $separator
- * @return array
- */
- public static function get_multi_values($serialized_value, $separator)
- {
- $values = array();
- if (strlen($separator) == 1)
+ /**
+ *
+ * @return boolean
+ */
+ public function is_readonly()
{
- $values = explode($separator, $serialized_value);
- }
- else
- {
- // s'il y'a plusieurs delimiters, on transforme
- // en regexp pour utiliser split
- $separator = preg_split('//', $separator, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
- $separator = '/\\' . implode('|\\', $separator) . '/';
- $values = preg_split($separator, $serialized_value);
+ return $this->databox_field->is_readonly();
}
- foreach ($values as $key => $value)
+ /**
+ *
+ * @return caption_field
+ */
+ public function delete()
{
- $values[$key] = trim($value);
+
+ foreach ($this->get_values() as $value) {
+ $value->delete();
+ }
+
+ return $this;
}
- return $values;
- }
+ /**
+ *
+ * @param array $values
+ * @param string $separator
+ * @return string
+ */
+ protected static function serialize_value(Array $values, $separator, $highlight = false)
+ {
+ if (strlen($separator) > 1)
+ $separator = $separator[0];
- public static function rename_all_metadatas(databox_field $databox_field)
- {
- $sql = 'SELECT count(id) as count_id FROM metadatas
+ if (trim($separator) === '')
+ $separator = ' ';
+ else
+ $separator = ' ' . $separator . ' ';
+
+ $array_values = array();
+
+ foreach ($values as $value) {
+ if ($highlight)
+ $array_values[] = $value->highlight_thesaurus();
+ else
+ $array_values[] = $value->getValue();
+ }
+
+ return implode($separator, $array_values);
+ }
+
+ /**
+ *
+ * @return array
+ */
+ public function get_values()
+ {
+ return $this->values;
+ }
+
+ /**
+ *
+ * @param int $meta_id
+ * @return array
+ */
+ public function get_value($meta_id)
+ {
+ return $this->values[$meta_id];
+ }
+
+ /**
+ *
+ * @param string $custom_separator
+ * @return mixed
+ */
+ public function get_serialized_values($custom_separator = false, $highlightTheso = false)
+ {
+ if ($this->databox_field->is_multi() === true) {
+ if ($custom_separator !== false)
+ $separator = $custom_separator;
+ else
+ $separator = $this->databox_field->get_separator();
+
+ return self::serialize_value($this->values, $separator, $highlightTheso);
+ }
+ else {
+ foreach ($this->values as $value) {
+ /* @var $value Caption_Field_Value */
+
+ return $value->highlight_thesaurus();
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->databox_field->get_name();
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_meta_struct_id()
+ {
+ return $this->databox_field->get_id();
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_indexable()
+ {
+ return $this->databox_field->is_indexable();
+ }
+
+ /**
+ *
+ * @return databox_field
+ */
+ public function get_databox_field()
+ {
+ return $this->databox_field;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function highlight_thesaurus()
+ {
+ $value = $this->get_serialized_values(false, true);
+
+ return $value;
+ }
+
+ /**
+ *
+ * @param string $serialized_value
+ * @param string $separator
+ * @return array
+ */
+ public static function get_multi_values($serialized_value, $separator)
+ {
+ $values = array();
+ if (strlen($separator) == 1) {
+ $values = explode($separator, $serialized_value);
+ } else {
+ // s'il y'a plusieurs delimiters, on transforme
+ // en regexp pour utiliser split
+ $separator = preg_split('//', $separator, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
+ $separator = '/\\' . implode('|\\', $separator) . '/';
+ $values = preg_split($separator, $serialized_value);
+ }
+
+ foreach ($values as $key => $value) {
+ $values[$key] = trim($value);
+ }
+
+ return $values;
+ }
+
+ public static function rename_all_metadatas(databox_field $databox_field)
+ {
+ $sql = 'SELECT count(id) as count_id FROM metadatas
WHERE meta_struct_id = :meta_struct_id';
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $params = array(
- ':meta_struct_id' => $databox_field->get_id()
- );
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt->execute($params);
- $rowcount = $stmt->rowCount();
- $stmt->closeCursor();
+ $stmt->execute($params);
+ $rowcount = $stmt->rowCount();
+ $stmt->closeCursor();
- $n = 0;
- $increment = 500;
+ $n = 0;
+ $increment = 500;
- while ($n < $rowcount)
- {
- $sql = 'SELECT record_id, id FROM metadatas
+ while ($n < $rowcount) {
+ $sql = 'SELECT record_id, id FROM metadatas
WHERE meta_struct_id = :meta_struct_id LIMIT ' . $n . ', ' . $increment;
- $params = array(
- ':meta_struct_id' => $databox_field->get_id()
- );
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $stmt->execute($params);
- $rowcount = $stmt->rowCount();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $rowcount = $stmt->rowCount();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
- foreach ($rs as $row)
- {
- try
- {
- $record = $databox_field->get_databox()->get_record($row['record_id']);
- $record->set_metadatas(array());
- unset($record);
+ foreach ($rs as $row) {
+ try {
+ $record = $databox_field->get_databox()->get_record($row['record_id']);
+ $record->set_metadatas(array());
+ unset($record);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ $n += $increment;
}
- catch (Exception $e)
- {
- }
- }
-
- $n += $increment;
+ return;
}
- return;
- }
-
- protected static function merge_metadatas(databox_field $databox_field, record_adapter $record)
- {
- $sql = 'SELECT record_id, id, value FROM metadatas
+ protected static function merge_metadatas(databox_field $databox_field, record_adapter $record)
+ {
+ $sql = 'SELECT record_id, id, value FROM metadatas
WHERE meta_struct_id = :meta_struct_id
AND record_id = :record_id';
- $params = array(
- ':meta_struct_id' => $databox_field->get_id(),
- ':record_id' => $record->get_record_id()
- );
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id(),
+ ':record_id' => $record->get_record_id()
+ );
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
- $values = $current_metadatas = array();
+ $values = $current_metadatas = array();
- foreach ($rs as $row)
- {
- $current_metadatas[] = array(
- 'meta_id' => $row['id']
- , 'meta_struct_id' => $databox_field->get_id()
- , 'value' => ''
- );
+ foreach ($rs as $row) {
+ $current_metadatas[] = array(
+ 'meta_id' => $row['id']
+ , 'meta_struct_id' => $databox_field->get_id()
+ , 'value' => ''
+ );
- $values[] = $row['value'];
+ $values[] = $row['value'];
+ }
+
+ try {
+ $record = $databox_field->get_databox()->get_record($record->get_record_id());
+ $record->set_metadatas($current_metadatas);
+ $record->set_metadatas(array(array(
+ 'meta_id' => null
+ , 'meta_struct_id' => $databox_field->get_id()
+ , 'value' => implode(' ; ', $values)
+ )));
+
+ unset($record);
+ } catch (Exception $e) {
+
+ }
+
+ return;
}
- try
+ public static function merge_all_metadatas(databox_field $databox_field)
{
- $record = $databox_field->get_databox()->get_record($record->get_record_id());
- $record->set_metadatas($current_metadatas);
- $record->set_metadatas(array(array(
- 'meta_id' => null
- , 'meta_struct_id' => $databox_field->get_id()
- , 'value' => implode(' ; ', $values)
- )));
-
- unset($record);
- }
- catch (Exception $e)
- {
-
- }
-
- return;
- }
-
- public static function merge_all_metadatas(databox_field $databox_field)
- {
- $sql = 'SELECT distinct record_id FROM metadatas
+ $sql = 'SELECT distinct record_id FROM metadatas
WHERE meta_struct_id = :meta_struct_id ';
- $params = array(
- ':meta_struct_id' => $databox_field->get_id()
- );
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
- foreach ($rs as $row)
- {
- self::merge_metadatas($databox_field, $databox_field->get_databox()->get_record($row['record_id']));
+ foreach ($rs as $row) {
+ self::merge_metadatas($databox_field, $databox_field->get_databox()->get_record($row['record_id']));
+ }
+
+ return;
}
- return;
- }
-
- public static function delete_all_metadatas(databox_field $databox_field)
- {
- $sql = 'SELECT count(id) as count_id FROM metadatas
+ public static function delete_all_metadatas(databox_field $databox_field)
+ {
+ $sql = 'SELECT count(id) as count_id FROM metadatas
WHERE meta_struct_id = :meta_struct_id';
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $params = array(
- ':meta_struct_id' => $databox_field->get_id()
- );
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt->execute($params);
- $rowcount = $stmt->rowCount();
- $stmt->closeCursor();
+ $stmt->execute($params);
+ $rowcount = $stmt->rowCount();
+ $stmt->closeCursor();
- $n = 0;
- $increment = 500;
+ $n = 0;
+ $increment = 500;
- while ($n < $rowcount)
- {
- $sql = 'SELECT record_id, id FROM metadatas
+ while ($n < $rowcount) {
+ $sql = 'SELECT record_id, id FROM metadatas
WHERE meta_struct_id = :meta_struct_id
LIMIT ' . $n . ', ' . $increment;
- $params = array(
- ':meta_struct_id' => $databox_field->get_id()
- );
+ $params = array(
+ ':meta_struct_id' => $databox_field->get_id()
+ );
- $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
- $stmt->execute($params);
- $rowcount = $stmt->rowCount();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $databox_field->get_databox()->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $rowcount = $stmt->rowCount();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ unset($stmt);
- foreach ($rs as $row)
- {
- try
- {
- $record = $databox_field->get_databox()->get_record($row['record_id']);
- $caption_field = new caption_field($databox_field, $record);
- $caption_field->delete();
- $record->set_metadatas(array());
- unset($caption_field);
- unset($record);
+ foreach ($rs as $row) {
+ try {
+ $record = $databox_field->get_databox()->get_record($row['record_id']);
+ $caption_field = new caption_field($databox_field, $record);
+ $caption_field->delete();
+ $record->set_metadatas(array());
+ unset($caption_field);
+ unset($record);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ $n += $increment;
}
- catch (Exception $e)
- {
- }
- }
-
- $n += $increment;
+ return;
}
-
- return;
- }
-
}
diff --git a/lib/classes/caption/interface.class.php b/lib/classes/caption/interface.class.php
index ff4e4e18c2..23187203b1 100644
--- a/lib/classes/caption/interface.class.php
+++ b/lib/classes/caption/interface.class.php
@@ -17,7 +17,8 @@
*/
interface caption_interface
{
- public function __construct(record_Interface &$record, databox &$databox);
- public function get_highlight_fields($highlight='', Array $grep_fields = null, searchEngine_adapter $searchEngine = null);
+ public function __construct(record_Interface &$record, databox &$databox);
+
+ public function get_highlight_fields($highlight = '', Array $grep_fields = null, searchEngine_adapter $searchEngine = null);
}
diff --git a/lib/classes/caption/record.class.php b/lib/classes/caption/record.class.php
index bb07aa402e..87fadf7bce 100644
--- a/lib/classes/caption/record.class.php
+++ b/lib/classes/caption/record.class.php
@@ -17,351 +17,324 @@
*/
class caption_record implements caption_interface, cache_cacheableInterface
{
+ /**
+ *
+ * @var array
+ */
+ protected $fields;
- /**
- *
- * @var array
- */
- protected $fields;
+ /**
+ *
+ * @var int
+ */
+ protected $sbas_id;
- /**
- *
- * @var int
- */
- protected $sbas_id;
+ /**
+ *
+ * @var record
+ */
+ protected $record;
+ protected $dces_elements = array();
+ protected $databox;
- /**
- *
- * @var record
- */
- protected $record;
- protected $dces_elements = array();
- protected $databox;
+ const SERIALIZE_XML = 'xml';
+ const SERIALIZE_YAML = 'yaml';
- const SERIALIZE_XML = 'xml';
- const SERIALIZE_YAML = 'yaml';
-
- /**
- *
- * @param record_Interface $record
- * @param databox $databox
- * @return caption_record
- */
- public function __construct(record_Interface &$record, databox &$databox)
- {
- $this->sbas_id = $record->get_sbas_id();
- $this->record = $record;
- $this->databox = $databox;
-
- return $this;
- }
-
- public function serialize($format, $includeBusinessFields = false)
- {
- switch ($format)
+ /**
+ *
+ * @param record_Interface $record
+ * @param databox $databox
+ * @return caption_record
+ */
+ public function __construct(record_Interface &$record, databox &$databox)
{
- case self::SERIALIZE_XML:
- return $this->serializeXML(!!$includeBusinessFields);
- break;
- case self::SERIALIZE_YAML:
- return $this->serializeYAML(!!$includeBusinessFields);
- break;
- default:
- throw new \Exception(sprintf('Unknown format %s', $format));
- break;
+ $this->sbas_id = $record->get_sbas_id();
+ $this->record = $record;
+ $this->databox = $databox;
+
+ return $this;
}
- }
- protected function serializeYAML($includeBusinessFields)
- {
- $buffer = array();
-
- foreach ($this->get_fields(array(), $includeBusinessFields) as $field)
+ public function serialize($format, $includeBusinessFields = false)
{
- $vi = $field->get_values();
-
- if ($field->is_multi())
- {
- $buffer[$field->get_name()] = array();
- foreach ($vi as $value)
- {
- $val = $value->getValue();
- $buffer[$field->get_name()][] = ctype_digit($val) ? (int) $val : $val;
+ switch ($format) {
+ case self::SERIALIZE_XML:
+ return $this->serializeXML( ! ! $includeBusinessFields);
+ break;
+ case self::SERIALIZE_YAML:
+ return $this->serializeYAML( ! ! $includeBusinessFields);
+ break;
+ default:
+ throw new \Exception(sprintf('Unknown format %s', $format));
+ break;
}
- }
- else
- {
- $value = array_pop($vi);
- $val = $value->getValue();
- $buffer[$field->get_name()] = ctype_digit($val) ? (int) $val : $val;
- }
}
- $buffer = array('record' => array('description' => $buffer));
-
- $dumper = new Symfony\Component\Yaml\Dumper();
-
- return $dumper->dump($buffer, 3);
- }
-
- protected function serializeXML($includeBusinessFields)
- {
- $dom_doc = new DOMDocument('1.0', 'UTF-8');
- $dom_doc->formatOutput = true;
- $dom_doc->standalone = true;
-
- $record = $dom_doc->createElement('record');
- $record->setAttribute('record_id', $this->record->get_record_id());
- $dom_doc->appendChild($record);
- $description = $dom_doc->createElement('description');
- $record->appendChild($description);
-
- foreach ($this->get_fields(array(), $includeBusinessFields) as $field)
+ protected function serializeYAML($includeBusinessFields)
{
- $values = $field->get_values();
+ $buffer = array();
- foreach ($values as $value)
- {
- $elem = $dom_doc->createElement($field->get_name());
- $elem->appendChild($dom_doc->createTextNode($value->getValue()));
- $elem->setAttribute('meta_id', $value->getId());
- $elem->setAttribute('meta_struct_id', $field->get_meta_struct_id());
- $description->appendChild($elem);
- }
+ foreach ($this->get_fields(array(), $includeBusinessFields) as $field) {
+ $vi = $field->get_values();
+
+ if ($field->is_multi()) {
+ $buffer[$field->get_name()] = array();
+ foreach ($vi as $value) {
+ $val = $value->getValue();
+ $buffer[$field->get_name()][] = ctype_digit($val) ? (int) $val : $val;
+ }
+ } else {
+ $value = array_pop($vi);
+ $val = $value->getValue();
+ $buffer[$field->get_name()] = ctype_digit($val) ? (int) $val : $val;
+ }
+ }
+
+ $buffer = array('record' => array('description' => $buffer));
+
+ $dumper = new Symfony\Component\Yaml\Dumper();
+
+ return $dumper->dump($buffer, 3);
}
- $doc = $dom_doc->createElement('doc');
-
- $tc_datas = $this->record->get_technical_infos();
-
- foreach ($tc_datas as $key => $data)
+ protected function serializeXML($includeBusinessFields)
{
- $doc->setAttribute($key, $data);
+ $dom_doc = new DOMDocument('1.0', 'UTF-8');
+ $dom_doc->formatOutput = true;
+ $dom_doc->standalone = true;
+
+ $record = $dom_doc->createElement('record');
+ $record->setAttribute('record_id', $this->record->get_record_id());
+ $dom_doc->appendChild($record);
+ $description = $dom_doc->createElement('description');
+ $record->appendChild($description);
+
+ foreach ($this->get_fields(array(), $includeBusinessFields) as $field) {
+ $values = $field->get_values();
+
+ foreach ($values as $value) {
+ $elem = $dom_doc->createElement($field->get_name());
+ $elem->appendChild($dom_doc->createTextNode($value->getValue()));
+ $elem->setAttribute('meta_id', $value->getId());
+ $elem->setAttribute('meta_struct_id', $field->get_meta_struct_id());
+ $description->appendChild($elem);
+ }
+ }
+
+ $doc = $dom_doc->createElement('doc');
+
+ $tc_datas = $this->record->get_technical_infos();
+
+ foreach ($tc_datas as $key => $data) {
+ $doc->setAttribute($key, $data);
+ }
+
+ $record->appendChild($doc);
+
+ return $dom_doc->saveXML();
}
- $record->appendChild($doc);
-
- return $dom_doc->saveXML();
- }
-
- protected function retrieve_fields()
- {
- if (is_array($this->fields))
+ protected function retrieve_fields()
{
- return $this->fields;
- }
+ if (is_array($this->fields)) {
+ return $this->fields;
+ }
- $fields = array();
- try
- {
- $fields = $this->get_data_from_cache();
- }
- catch (Exception $e)
- {
- $sql = "SELECT m.id as meta_id, s.id as structure_id
+ $fields = array();
+ try {
+ $fields = $this->get_data_from_cache();
+ } catch (Exception $e) {
+ $sql = "SELECT m.id as meta_id, s.id as structure_id
FROM metadatas m, metadatas_structure s
WHERE m.record_id = :record_id AND s.id = m.meta_struct_id";
- $stmt = $this->databox->get_connection()->prepare($sql);
- $stmt->execute(array(':record_id' => $this->record->get_record_id()));
- $fields = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- $this->set_data_to_cache($fields);
- }
-
- $rec_fields = array();
- foreach ($fields as $row)
- {
- $databox_meta_struct = databox_field::get_instance($this->databox, $row['structure_id']);
- $metadata = new caption_field($databox_meta_struct, $this->record);
-
- $rec_fields[$databox_meta_struct->get_id()] = $metadata;
- $dces_element = $metadata->get_databox_field()->get_dces_element();
- if ($dces_element instanceof databox_Field_DCESAbstract)
- {
- $this->dces_elements[$dces_element->get_label()] = $databox_meta_struct->get_id();
- }
- }
- $this->fields = $rec_fields;
-
- return $this->fields;
- }
-
- /**
- *
- * @param array $grep_fields
- * @return array
- */
- public function get_fields(Array $grep_fields = null, $IncludeBusiness = false)
- {
- $fields = array();
-
- foreach ($this->retrieve_fields() as $meta_struct_id => $field)
- {
- if ($grep_fields && !in_array($field->get_name(), $grep_fields))
- {
- continue;
- }
-
- if($field->get_databox_field()->isBusiness() === true && !$IncludeBusiness)
- {
- continue;
- }
-
- $fields[] = $field;
- }
-
- return $fields;
- }
-
- /**
- *
- * @param type $fieldname
- * @return \caption_field
- * @throws \Exception
- */
- public function get_field($fieldname)
- {
- foreach ($this->get_fields() as $meta_struct_id => $field)
- {
- if ($field->get_name() == $fieldname)
-
- return $field;
- }
-
- throw new \Exception('Field not found');
- }
-
- /**
- *
- * @param type $label
- * @return caption_field
- */
- public function get_dc_field($label)
- {
- $fields = $this->get_fields();
- if (isset($this->dces_elements[$label]))
- {
- return $fields[$this->dces_elements[$label]];
- }
-
- return null;
- }
-
- /**
- *
- * @param string $highlight
- * @param array $grep_fields
- * @param searchEngine_adapter $searchEngine
- * @return array
- */
- public function get_highlight_fields($highlight = '', Array $grep_fields = null, searchEngine_adapter $searchEngine = null, $includeBusiness = false)
- {
- return $this->highlight_fields($highlight, $grep_fields, $searchEngine, $includeBusiness);
- }
-
- /**
- * @todo move this fun in caption_field object
- * @param string $highlight
- * @param array $grep_fields
- * @param searchEngine_adapter $searchEngine
- * @return array
- */
- protected function highlight_fields($highlight, Array $grep_fields = null, searchEngine_adapter $searchEngine = null, $includeBusiness = false)
- {
- $fields = array();
-
- foreach ($this->get_fields(array(), $includeBusiness) as $meta_struct_id => $field)
- {
- if (is_array($grep_fields) && !in_array($field->get_name(), $grep_fields))
- continue;
-
- $value = preg_replace(
- "(([^']{1})((https?|file):((/{2,4})|(\\{2,4}))[\w:#%/;$()~_?/\-=\\\.&]*)([^']{1}))"
- , '$1 $2 $7'
- , $field->highlight_thesaurus()
- );
-
- $fields[$field->get_name()] = array(
- 'value' => $value
- , 'separator' => $field->get_databox_field()->get_separator()
- );
- }
-
- if ($searchEngine instanceof searchEngine_adapter)
- {
- $ret = $searchEngine->build_excerpt($highlight, $fields, $this->record);
-
- if ($ret)
- {
- $n = 0;
-
- foreach ($fields as $key => $value)
- {
- if (!isset($fields[$key]))
- continue;
-
- //if(strpos($fields[$key]['value'], 'databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':record_id' => $this->record->get_record_id()));
+ $fields = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ $this->set_data_to_cache($fields);
}
- }
+
+ $rec_fields = array();
+ foreach ($fields as $row) {
+ $databox_meta_struct = databox_field::get_instance($this->databox, $row['structure_id']);
+ $metadata = new caption_field($databox_meta_struct, $this->record);
+
+ $rec_fields[$databox_meta_struct->get_id()] = $metadata;
+ $dces_element = $metadata->get_databox_field()->get_dces_element();
+ if ($dces_element instanceof databox_Field_DCESAbstract) {
+ $this->dces_elements[$dces_element->get_label()] = $databox_meta_struct->get_id();
+ }
+ }
+ $this->fields = $rec_fields;
+
+ return $this->fields;
}
- return $fields;
- }
+ /**
+ *
+ * @param array $grep_fields
+ * @return array
+ */
+ public function get_fields(Array $grep_fields = null, $IncludeBusiness = false)
+ {
+ $fields = array();
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return string
- */
- public function get_cache_key($option = null)
- {
- return 'caption_' . $this->record->get_serialize_key() . ($option ? '_' . $option : '');
- }
+ foreach ($this->retrieve_fields() as $meta_struct_id => $field) {
+ if ($grep_fields && ! in_array($field->get_name(), $grep_fields)) {
+ continue;
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return mixed
- */
- public function get_data_from_cache($option = null)
- {
- $databox = databox::get_instance($this->record->get_sbas_id());
+ if ($field->get_databox_field()->isBusiness() === true && ! $IncludeBusiness) {
+ continue;
+ }
- return $databox->get_data_from_cache($this->get_cache_key($option));
- }
+ $fields[] = $field;
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param mixed $value
- * @param string $option
- * @param int $duration
- * @return caption_field
- */
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- $databox = databox::get_instance($this->record->get_sbas_id());
+ return $fields;
+ }
- return $databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ /**
+ *
+ * @param type $fieldname
+ * @return \caption_field
+ * @throws \Exception
+ */
+ public function get_field($fieldname)
+ {
+ foreach ($this->get_fields() as $meta_struct_id => $field) {
+ if ($field->get_name() == $fieldname)
+ return $field;
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return caption_field
- */
- public function delete_data_from_cache($option = null)
- {
- $databox = databox::get_instance($this->record->get_sbas_id());
- $this->fields = null;
+ throw new \Exception('Field not found');
+ }
- return $databox->delete_data_from_cache($this->get_cache_key($option));
- }
+ /**
+ *
+ * @param type $label
+ * @return caption_field
+ */
+ public function get_dc_field($label)
+ {
+ $fields = $this->get_fields();
+ if (isset($this->dces_elements[$label])) {
+ return $fields[$this->dces_elements[$label]];
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @param string $highlight
+ * @param array $grep_fields
+ * @param searchEngine_adapter $searchEngine
+ * @return array
+ */
+ public function get_highlight_fields($highlight = '', Array $grep_fields = null, searchEngine_adapter $searchEngine = null, $includeBusiness = false)
+ {
+ return $this->highlight_fields($highlight, $grep_fields, $searchEngine, $includeBusiness);
+ }
+
+ /**
+ * @todo move this fun in caption_field object
+ * @param string $highlight
+ * @param array $grep_fields
+ * @param searchEngine_adapter $searchEngine
+ * @return array
+ */
+ protected function highlight_fields($highlight, Array $grep_fields = null, searchEngine_adapter $searchEngine = null, $includeBusiness = false)
+ {
+ $fields = array();
+
+ foreach ($this->get_fields(array(), $includeBusiness) as $meta_struct_id => $field) {
+ if (is_array($grep_fields) && ! in_array($field->get_name(), $grep_fields))
+ continue;
+
+ $value = preg_replace(
+ "(([^']{1})((https?|file):((/{2,4})|(\\{2,4}))[\w:#%/;$()~_?/\-=\\\.&]*)([^']{1}))"
+ , '$1 $2 $7'
+ , $field->highlight_thesaurus()
+ );
+
+ $fields[$field->get_name()] = array(
+ 'value' => $value
+ , 'separator' => $field->get_databox_field()->get_separator()
+ );
+ }
+
+ if ($searchEngine instanceof searchEngine_adapter) {
+ $ret = $searchEngine->build_excerpt($highlight, $fields, $this->record);
+
+ if ($ret) {
+ $n = 0;
+
+ foreach ($fields as $key => $value) {
+ if ( ! isset($fields[$key]))
+ continue;
+
+ //if(strpos($fields[$key]['value'], 'record->get_serialize_key() . ($option ? '_' . $option : '');
+ }
+
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param string $option
+ * @return mixed
+ */
+ public function get_data_from_cache($option = null)
+ {
+ $databox = databox::get_instance($this->record->get_sbas_id());
+
+ return $databox->get_data_from_cache($this->get_cache_key($option));
+ }
+
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param mixed $value
+ * @param string $option
+ * @param int $duration
+ * @return caption_field
+ */
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ $databox = databox::get_instance($this->record->get_sbas_id());
+
+ return $databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param string $option
+ * @return caption_field
+ */
+ public function delete_data_from_cache($option = null)
+ {
+ $databox = databox::get_instance($this->record->get_sbas_id());
+ $this->fields = null;
+
+ return $databox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/collection.class.php b/lib/classes/collection.class.php
index 2de3adb689..3e8db55cb1 100644
--- a/lib/classes/collection.class.php
+++ b/lib/classes/collection.class.php
@@ -17,681 +17,657 @@
*/
class collection implements cache_cacheableInterface
{
+ protected $base_id;
+ protected $sbas_id;
+ protected $coll_id;
+ protected $available = false;
+ protected $name;
+ protected $prefs;
+ protected $pub_wm;
+ private static $_logos = array();
+ private static $_stamps = array();
+ private static $_watermarks = array();
+ private static $_presentations = array();
+ private static $_collections = array();
+ protected $databox;
+ protected $is_active;
+ protected $binary_logo;
- protected $base_id;
- protected $sbas_id;
- protected $coll_id;
- protected $available = false;
- protected $name;
- protected $prefs;
- protected $pub_wm;
- private static $_logos = array();
- private static $_stamps = array();
- private static $_watermarks = array();
- private static $_presentations = array();
- private static $_collections = array();
- protected $databox;
- protected $is_active;
- protected $binary_logo;
+ const PIC_LOGO = 'minilogos';
+ const PIC_WM = 'wm';
+ const PIC_STAMP = 'stamp';
+ const PIC_PRESENTATION = 'presentation';
- const PIC_LOGO = 'minilogos';
- const PIC_WM = 'wm';
- const PIC_STAMP = 'stamp';
- const PIC_PRESENTATION = 'presentation';
-
- protected function __construct($coll_id, databox &$databox)
- {
- $this->databox = $databox;
- $this->sbas_id = (int) $databox->get_sbas_id();
- $this->coll_id = (int) $coll_id;
- $this->load();
-
- return $this;
- }
-
- protected function load()
- {
- try
- {
- $datas = $this->get_data_from_cache();
- $this->is_active = $datas['is_active'];
- $this->base_id = $datas['base_id'];
- $this->available = $datas['available'];
- $this->pub_wm = $datas['pub_wm'];
- $this->name = $datas['name'];
- $this->prefs = $datas['prefs'];
-
- return $this;
- }
- catch (Exception $e)
+ protected function __construct($coll_id, databox &$databox)
{
+ $this->databox = $databox;
+ $this->sbas_id = (int) $databox->get_sbas_id();
+ $this->coll_id = (int) $coll_id;
+ $this->load();
+ return $this;
}
- $connbas = $this->databox->get_connection();
- $sql = 'SELECT asciiname, prefs, pub_wm, coll_id
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+ $this->is_active = $datas['is_active'];
+ $this->base_id = $datas['base_id'];
+ $this->available = $datas['available'];
+ $this->pub_wm = $datas['pub_wm'];
+ $this->name = $datas['name'];
+ $this->prefs = $datas['prefs'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $connbas = $this->databox->get_connection();
+ $sql = 'SELECT asciiname, prefs, pub_wm, coll_id
FROM coll WHERE coll_id = :coll_id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->coll_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->coll_id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
- if (!$row)
- throw new Exception('Unknown collection ' . $this->coll_id . ' on ' . $this->databox->get_dbname());
+ if ( ! $row)
+ throw new Exception('Unknown collection ' . $this->coll_id . ' on ' . $this->databox->get_dbname());
- $this->available = true;
- $this->pub_wm = $row['pub_wm'];
- $this->name = $row['asciiname'];
- $this->prefs = $row['prefs'];
+ $this->available = true;
+ $this->pub_wm = $row['pub_wm'];
+ $this->name = $row['asciiname'];
+ $this->prefs = $row['prefs'];
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
- $sql = 'SELECT server_coll_id, sbas_id, base_id, active FROM bas
+ $sql = 'SELECT server_coll_id, sbas_id, base_id, active FROM bas
WHERE server_coll_id = :coll_id AND sbas_id = :sbas_id';
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->coll_id, ':sbas_id' => $this->databox->get_sbas_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->coll_id, ':sbas_id' => $this->databox->get_sbas_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->is_active = false;
+ $this->is_active = false;
- if ($row)
- {
- $this->is_active = !!$row['active'];
- $this->base_id = (int) $row['base_id'];
+ if ($row) {
+ $this->is_active = ! ! $row['active'];
+ $this->base_id = (int) $row['base_id'];
+ }
+
+ $stmt->closeCursor();
+
+ $datas = array(
+ 'is_active' => $this->is_active
+ , 'base_id' => $this->base_id
+ , 'available' => $this->available
+ , 'pub_wm' => $this->pub_wm
+ , 'name' => $this->name
+ , 'prefs' => $this->prefs
+ );
+
+ $this->set_data_to_cache($datas);
+
+ return $this;
}
- $stmt->closeCursor();
+ public function enable(appbox &$appbox)
+ {
+ $sql = 'UPDATE bas SET active = "1" WHERE base_id = :base_id';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->get_base_id()));
+ $stmt->closeCursor();
- $datas = array(
- 'is_active' => $this->is_active
- , 'base_id' => $this->base_id
- , 'available' => $this->available
- , 'pub_wm' => $this->pub_wm
- , 'name' => $this->name
- , 'prefs' => $this->prefs
- );
+ $this->is_active = true;
+ $this->delete_data_from_cache();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
+ $this->databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
+ cache_databox::update($this->databox->get_sbas_id(), 'structure');
- $this->set_data_to_cache($datas);
+ return $this;
+ }
- return $this;
- }
+ public function disable(appbox &$appbox)
+ {
+ $sql = 'UPDATE bas SET active=0 WHERE base_id = :base_id';
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->get_base_id()));
+ $stmt->closeCursor();
+ $this->is_active = false;
+ $this->delete_data_from_cache();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
+ $this->databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
+ cache_databox::update($this->databox->get_sbas_id(), 'structure');
- public function enable(appbox &$appbox)
- {
- $sql = 'UPDATE bas SET active = "1" WHERE base_id = :base_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $this->get_base_id()));
- $stmt->closeCursor();
+ return $this;
+ }
- $this->is_active = true;
- $this->delete_data_from_cache();
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
- $this->databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
- cache_databox::update($this->databox->get_sbas_id(), 'structure');
+ public function empty_collection($pass_quantity = 100)
+ {
+ $pass_quantity = (int) $pass_quantity > 200 ? 200 : (int) $pass_quantity;
+ $pass_quantity = (int) $pass_quantity < 10 ? 10 : (int) $pass_quantity;
- return $this;
- }
-
- public function disable(appbox &$appbox)
- {
- $sql = 'UPDATE bas SET active=0 WHERE base_id = :base_id';
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $this->get_base_id()));
- $stmt->closeCursor();
- $this->is_active = false;
- $this->delete_data_from_cache();
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
- $this->databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
- cache_databox::update($this->databox->get_sbas_id(), 'structure');
-
- return $this;
- }
-
- public function empty_collection($pass_quantity = 100)
- {
- $pass_quantity = (int) $pass_quantity > 200 ? 200 : (int) $pass_quantity;
- $pass_quantity = (int) $pass_quantity < 10 ? 10 : (int) $pass_quantity;
-
- $sql = "SELECT record_id FROM record WHERE coll_id = :coll_id
+ $sql = "SELECT record_id FROM record WHERE coll_id = :coll_id
ORDER BY record_id DESC LIMIT 0, " . $pass_quantity;
- $stmt = $this->databox->get_connection()->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->get_coll_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->get_coll_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $record = new record_adapter($this->databox->get_sbas_id(), $row['record_id']);
- $record->delete();
- unset($record);
+ foreach ($rs as $row) {
+ $record = new record_adapter($this->databox->get_sbas_id(), $row['record_id']);
+ $record->delete();
+ unset($record);
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function is_active()
- {
- return $this->is_active;
- }
-
- /**
- *
- * @return databox
- */
- public function get_databox()
- {
- return $this->databox;
- }
-
- public function get_connection()
- {
- return $this->databox->get_connection();
- }
-
- public function set_public_presentation($publi)
- {
- if (in_array($publi, array('none', 'wm', 'stamp')))
+ public function is_active()
{
- $sql = 'UPDATE coll SET pub_wm = :pub_wm WHERE coll_id = :coll_id';
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':pub_wm' => $publi, ':coll_id' => $this->get_coll_id()));
- $stmt->closeCursor();
-
- $this->pub_wm = $publi;
-
- $this->delete_data_from_cache();
+ return $this->is_active;
}
- return $this;
- }
+ /**
+ *
+ * @return databox
+ */
+ public function get_databox()
+ {
+ return $this->databox;
+ }
- public function set_name($name)
- {
- $name = trim(strip_tags($name));
+ public function get_connection()
+ {
+ return $this->databox->get_connection();
+ }
- if ($name === '')
- throw new Exception_InvalidArgument ();
+ public function set_public_presentation($publi)
+ {
+ if (in_array($publi, array('none', 'wm', 'stamp'))) {
+ $sql = 'UPDATE coll SET pub_wm = :pub_wm WHERE coll_id = :coll_id';
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':pub_wm' => $publi, ':coll_id' => $this->get_coll_id()));
+ $stmt->closeCursor();
- $sql = "UPDATE coll SET htmlname = :htmlname, asciiname = :asciiname
+ $this->pub_wm = $publi;
+
+ $this->delete_data_from_cache();
+ }
+
+ return $this;
+ }
+
+ public function set_name($name)
+ {
+ $name = trim(strip_tags($name));
+
+ if ($name === '')
+ throw new Exception_InvalidArgument ();
+
+ $sql = "UPDATE coll SET htmlname = :htmlname, asciiname = :asciiname
WHERE coll_id = :coll_id";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':asciiname' => $name, ':htmlname' => $name, ':coll_id' => $this->get_coll_id()));
- $stmt->closeCursor();
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':asciiname' => $name, ':htmlname' => $name, ':coll_id' => $this->get_coll_id()));
+ $stmt->closeCursor();
- $this->name = $name;
+ $this->name = $name;
- $this->delete_data_from_cache();
+ $this->delete_data_from_cache();
- phrasea::reset_baseDatas();
+ phrasea::reset_baseDatas();
- return $this;
- }
+ return $this;
+ }
- public function get_record_amount()
- {
- $sql = "SELECT COUNT(record_id) AS n FROM record WHERE coll_id = :coll_id";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->get_coll_id()));
- $rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ public function get_record_amount()
+ {
+ $sql = "SELECT COUNT(record_id) AS n FROM record WHERE coll_id = :coll_id";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->get_coll_id()));
+ $rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $amount = $rowbas ? (int) $rowbas["n"] : null;
+ $amount = $rowbas ? (int) $rowbas["n"] : null;
- return $amount;
- }
+ return $amount;
+ }
- public function get_record_details()
- {
+ public function get_record_details()
+ {
- $sql = "SELECT record.coll_id,name,COALESCE(asciiname, CONCAT('_',record.coll_id)) AS asciiname,
+ $sql = "SELECT record.coll_id,name,COALESCE(asciiname, CONCAT('_',record.coll_id)) AS asciiname,
SUM(1) AS n, SUM(size) AS size
FROM record NATURAL JOIN subdef
INNER JOIN coll ON record.coll_id=coll.coll_id AND coll.coll_id = :coll_id
GROUP BY record.coll_id, subdef.name";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->get_coll_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->get_coll_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $ret = array();
- foreach ($rs as $row)
- {
- $ret[] = array(
- "coll_id" => (int) $row["coll_id"],
- "name" => $row["name"],
- "amount" => (int) $row["n"],
- "size" => (int) $row["size"]);
+ $ret = array();
+ foreach ($rs as $row) {
+ $ret[] = array(
+ "coll_id" => (int) $row["coll_id"],
+ "name" => $row["name"],
+ "amount" => (int) $row["n"],
+ "size" => (int) $row["size"]);
+ }
+
+ return $ret;
}
- return $ret;
- }
+ public function update_logo(system_file $pathfile = null)
+ {
+ if (is_null($pathfile))
+ $this->binary_logo = null;
+ else
+ $this->binary_logo = file_get_contents($pathfile->getPathname());
+ $sql = "UPDATE coll SET logo = :logo, majLogo=NOW() WHERE coll_id = :coll_id";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':logo' => $this->binary_logo, ':coll_id' => $this->get_coll_id()));
+ $stmt->closeCursor();
- public function update_logo(system_file $pathfile = null)
- {
- if (is_null($pathfile))
- $this->binary_logo = null;
- else
- $this->binary_logo = file_get_contents($pathfile->getPathname());
- $sql = "UPDATE coll SET logo = :logo, majLogo=NOW() WHERE coll_id = :coll_id";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':logo' => $this->binary_logo, ':coll_id' => $this->get_coll_id()));
- $stmt->closeCursor();
+ return $this;
+ }
- return $this;
- }
+ public function reset_watermark()
+ {
- public function reset_watermark()
- {
-
- $sql = 'SELECT path, file FROM record r INNER JOIN subdef s USING(record_id)
+ $sql = 'SELECT path, file FROM record r INNER JOIN subdef s USING(record_id)
WHERE r.coll_id = :coll_id AND r.type="image" AND s.name="preview"';
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->get_coll_id()));
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->get_coll_id()));
- while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC))
- {
- @unlink(p4string::addEndSlash($row2['path']) . 'watermark_' . $row2['file']);
+ while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ @unlink(p4string::addEndSlash($row2['path']) . 'watermark_' . $row2['file']);
+ }
+ $stmt->closeCursor();
+
+ return $this;
}
- $stmt->closeCursor();
- return $this;
- }
+ public function reset_stamp($record_id = null)
+ {
- public function reset_stamp($record_id = null)
- {
-
- $sql = 'SELECT path, file FROM record r INNER JOIN subdef s USING(record_id)
+ $sql = 'SELECT path, file FROM record r INNER JOIN subdef s USING(record_id)
WHERE r.coll_id = :coll_id
AND r.type="image" AND s.name IN ("preview", "document")';
- $params = array(':coll_id' => $this->get_coll_id());
+ $params = array(':coll_id' => $this->get_coll_id());
- if($record_id)
- {
- $sql .= ' AND record_id = :record_id';
- $params[':record_id'] = $record_id;
+ if ($record_id) {
+ $sql .= ' AND record_id = :record_id';
+ $params[':record_id'] = $record_id;
+ }
+
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute($params);
+
+ while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
+ @unlink(p4string::addEndSlash($row2['path']) . 'stamp_' . $row2['file']);
+ }
+ $stmt->closeCursor();
+
+ return $this;
}
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute($params);
-
- while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC))
+ public function delete()
{
- @unlink(p4string::addEndSlash($row2['path']) . 'stamp_' . $row2['file']);
- }
- $stmt->closeCursor();
+ while ($this->get_record_amount() > 0) {
+ $this->empty_collection();
+ }
- return $this;
- }
+ $sql = "DELETE FROM coll WHERE coll_id = :coll_id";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':coll_id' => $this->get_coll_id()));
+ $stmt->closeCursor();
- public function delete()
- {
- while ($this->get_record_amount() > 0)
- {
- $this->empty_collection();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+
+ $sql = "DELETE FROM bas WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->get_base_id()));
+ $stmt->closeCursor();
+
+ $sql = "DELETE FROM basusr WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->get_base_id()));
+ $stmt->closeCursor();
+
+ $sql = "DELETE FROM demand WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':base_id' => $this->get_base_id()));
+ $stmt->closeCursor();
+
+ $this->get_databox()->delete_data_from_cache(databox::CACHE_COLLECTIONS);
+
+ return;
}
- $sql = "DELETE FROM coll WHERE coll_id = :coll_id";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':coll_id' => $this->get_coll_id()));
- $stmt->closeCursor();
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
-
- $sql = "DELETE FROM bas WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $this->get_base_id()));
- $stmt->closeCursor();
-
- $sql = "DELETE FROM basusr WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $this->get_base_id()));
- $stmt->closeCursor();
-
- $sql = "DELETE FROM demand WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':base_id' => $this->get_base_id()));
- $stmt->closeCursor();
-
- $this->get_databox()->delete_data_from_cache(databox::CACHE_COLLECTIONS);
-
- return;
- }
-
- public function get_binary_minilogos()
- {
- return $this->binary_logo;
- }
-
- /**
- *
- * @param int $base_id
- * @return collection
- */
- public static function get_from_base_id($base_id)
- {
- $coll_id = phrasea::collFromBas($base_id);
- $sbas_id = phrasea::sbasFromBas($base_id);
- if (!$sbas_id || !$coll_id)
+ public function get_binary_minilogos()
{
- throw new Exception_Databox_CollectionNotFound(sprintf("Collection could not be found"));
- }
- $databox = databox::get_instance($sbas_id);
-
- return self::get_from_coll_id($databox, $coll_id);
- }
-
- /**
- *
- * @param int $sbas_id
- * @param int $coll_id
- * @return collection
- */
- public static function get_from_coll_id(databox $databox, $coll_id)
- {
- assert(is_int($coll_id));
-
- $key = sprintf('%d_%d', $databox->get_sbas_id(), $coll_id);
- if (!isset(self::$_collections[$key]))
- {
- self::$_collections[$key] = new self($coll_id, $databox);
+ return $this->binary_logo;
}
- return self::$_collections[$key];
- }
-
- public function get_base_id()
- {
- return $this->base_id;
- }
-
- public function get_sbas_id()
- {
- return $this->sbas_id;
- }
-
- public function get_coll_id()
- {
- return $this->coll_id;
- }
-
- public function get_prefs()
- {
- return $this->prefs;
- }
-
- public function set_prefs(DOMDocument $dom)
- {
- $this->prefs = $dom->saveXML();
-
- $sql = "UPDATE coll SET prefs = :prefs WHERE coll_id = :coll_id";
- $stmt = $this->get_connection()->prepare($sql);
- $stmt->execute(array(':prefs' => $this->prefs, ':coll_id' => $this->get_coll_id()));
- $stmt->closeCursor();
-
- $this->delete_data_from_cache();
-
- return $this->prefs;
- }
-
- public function get_name()
- {
- return $this->name;
- }
-
- public function get_pub_wm()
- {
- return $this->pub_wm;
- }
-
- public function is_available()
- {
- return $this->available;
- }
-
- public function unmount_collection(appbox &$appbox)
- {
- $params = array(':base_id' => $this->get_base_id());
-
- $query = new User_Query($appbox);
- $total = $query->on_base_ids(array($this->get_base_id()))
- ->include_phantoms(false)
- ->include_special_users(true)
- ->include_invite(true)
- ->include_templates(true)->get_total();
- $n = 0;
- while ($n < $total)
+ /**
+ *
+ * @param int $base_id
+ * @return collection
+ */
+ public static function get_from_base_id($base_id)
{
- $results = $query->limit($n, 50)->execute()->get_results();
- foreach ($results as $user)
- {
- $user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_SBAS);
- $user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_BAS);
- }
- $n+=50;
+ $coll_id = phrasea::collFromBas($base_id);
+ $sbas_id = phrasea::sbasFromBas($base_id);
+ if ( ! $sbas_id || ! $coll_id) {
+ throw new Exception_Databox_CollectionNotFound(sprintf("Collection could not be found"));
+ }
+ $databox = databox::get_instance($sbas_id);
+
+ return self::get_from_coll_id($databox, $coll_id);
}
- $sql = "DELETE FROM basusr WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ /**
+ *
+ * @param int $sbas_id
+ * @param int $coll_id
+ * @return collection
+ */
+ public static function get_from_coll_id(databox $databox, $coll_id)
+ {
+ assert(is_int($coll_id));
- $sql = "DELETE FROM sselcont WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $key = sprintf('%d_%d', $databox->get_sbas_id(), $coll_id);
+ if ( ! isset(self::$_collections[$key])) {
+ self::$_collections[$key] = new self($coll_id, $databox);
+ }
- $sql = "DELETE FROM bas WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ return self::$_collections[$key];
+ }
- $sql = "DELETE FROM demand WHERE base_id = :base_id";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ public function get_base_id()
+ {
+ return $this->base_id;
+ }
- phrasea::reset_baseDatas();
+ public function get_sbas_id()
+ {
+ return $this->sbas_id;
+ }
- return $this;
- }
+ public function get_coll_id()
+ {
+ return $this->coll_id;
+ }
- public static function create(databox $databox, appbox $appbox, $name, user_adapter $user)
- {
- $sbas_id = $databox->get_sbas_id();
- $connbas = $databox->get_connection();
- $conn = $appbox->get_connection();
- $new_bas = false;
+ public function get_prefs()
+ {
+ return $this->prefs;
+ }
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
+ public function set_prefs(DOMDocument $dom)
+ {
+ $this->prefs = $dom->saveXML();
- $prefs = '
+ $sql = "UPDATE coll SET prefs = :prefs WHERE coll_id = :coll_id";
+ $stmt = $this->get_connection()->prepare($sql);
+ $stmt->execute(array(':prefs' => $this->prefs, ':coll_id' => $this->get_coll_id()));
+ $stmt->closeCursor();
+
+ $this->delete_data_from_cache();
+
+ return $this->prefs;
+ }
+
+ public function get_name()
+ {
+ return $this->name;
+ }
+
+ public function get_pub_wm()
+ {
+ return $this->pub_wm;
+ }
+
+ public function is_available()
+ {
+ return $this->available;
+ }
+
+ public function unmount_collection(appbox &$appbox)
+ {
+ $params = array(':base_id' => $this->get_base_id());
+
+ $query = new User_Query($appbox);
+ $total = $query->on_base_ids(array($this->get_base_id()))
+ ->include_phantoms(false)
+ ->include_special_users(true)
+ ->include_invite(true)
+ ->include_templates(true)->get_total();
+ $n = 0;
+ while ($n < $total) {
+ $results = $query->limit($n, 50)->execute()->get_results();
+ foreach ($results as $user) {
+ $user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_SBAS);
+ $user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_BAS);
+ }
+ $n+=50;
+ }
+
+ $sql = "DELETE FROM basusr WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $sql = "DELETE FROM sselcont WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $sql = "DELETE FROM bas WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $sql = "DELETE FROM demand WHERE base_id = :base_id";
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ phrasea::reset_baseDatas();
+
+ return $this;
+ }
+
+ public static function create(databox $databox, appbox $appbox, $name, user_adapter $user)
+ {
+ $sbas_id = $databox->get_sbas_id();
+ $connbas = $databox->get_connection();
+ $conn = $appbox->get_connection();
+ $new_bas = false;
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+
+ $prefs = '
0
';
- $sql = "INSERT INTO coll (coll_id, htmlname, asciiname, prefs, logo)
+ $sql = "INSERT INTO coll (coll_id, htmlname, asciiname, prefs, logo)
VALUES (null, :name1, :name2, :prefs, '')";
- $params = array(
- ':name1' => $name
- , ':name2' => $name
- , 'prefs' => $prefs
- );
+ $params = array(
+ ':name1' => $name
+ , ':name2' => $name
+ , 'prefs' => $prefs
+ );
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
- $new_id = (int) $connbas->lastInsertId();
+ $new_id = (int) $connbas->lastInsertId();
- $sql = "INSERT INTO bas (base_id, active, server_coll_id, sbas_id, aliases)
+ $sql = "INSERT INTO bas (base_id, active, server_coll_id, sbas_id, aliases)
VALUES
(null, 1, :server_coll_id, :sbas_id, '')";
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':server_coll_id' => $new_id, ':sbas_id' => $sbas_id));
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':server_coll_id' => $new_id, ':sbas_id' => $sbas_id));
+ $stmt->closeCursor();
- $new_bas = $conn->lastInsertId();
- $databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
+ $new_bas = $conn->lastInsertId();
+ $databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
- $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
- cache_databox::update($sbas_id, 'structure');
+ $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
+ cache_databox::update($sbas_id, 'structure');
- phrasea::reset_baseDatas();
- self::set_admin($new_bas, $user);
+ phrasea::reset_baseDatas();
+ self::set_admin($new_bas, $user);
- $appbox->get_session()->renew_phrasea_session();
+ $appbox->get_session()->renew_phrasea_session();
- return self::get_from_coll_id($databox, $new_id);
- }
+ return self::get_from_coll_id($databox, $new_id);
+ }
- public function set_admin($base_id, user_adapter $user)
- {
+ public function set_admin($base_id, user_adapter $user)
+ {
- $rights = array(
- "canputinalbum" => "1",
- "candwnldhd" => "1",
- "nowatermark" => "1",
- "candwnldpreview" => "1",
- "cancmd" => "1",
- "canadmin" => "1",
- "actif" => "1",
- "canreport" => "1",
- "canpush" => "1",
- "basusr_infousr" => "",
- "canaddrecord" => "1",
- "canmodifrecord" => "1",
- "candeleterecord" => "1",
- "chgstatus" => "1",
- "imgtools" => "1",
- "manage" => "1",
- "modify_struct" => "1"
- );
+ $rights = array(
+ "canputinalbum" => "1",
+ "candwnldhd" => "1",
+ "nowatermark" => "1",
+ "candwnldpreview" => "1",
+ "cancmd" => "1",
+ "canadmin" => "1",
+ "actif" => "1",
+ "canreport" => "1",
+ "canpush" => "1",
+ "basusr_infousr" => "",
+ "canaddrecord" => "1",
+ "canmodifrecord" => "1",
+ "candeleterecord" => "1",
+ "chgstatus" => "1",
+ "imgtools" => "1",
+ "manage" => "1",
+ "modify_struct" => "1"
+ );
- $user->ACL()->update_rights_to_base($base_id, $rights);
+ $user->ACL()->update_rights_to_base($base_id, $rights);
- return true;
- }
+ return true;
+ }
- public static function mount_collection($sbas_id, $coll_id, User_Adapter $user)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
+ public static function mount_collection($sbas_id, $coll_id, User_Adapter $user)
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- $sql = "INSERT INTO bas (base_id, active, server_coll_id, sbas_id, aliases)
+ $sql = "INSERT INTO bas (base_id, active, server_coll_id, sbas_id, aliases)
VALUES
(null, 1, :server_coll_id, :sbas_id, '')";
- $stmt = $appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':server_coll_id' => $coll_id, ':sbas_id' => $sbas_id));
- $stmt->closeCursor();
+ $stmt = $appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':server_coll_id' => $coll_id, ':sbas_id' => $sbas_id));
+ $stmt->closeCursor();
- $new_bas = $appbox->get_connection()->lastInsertId();
- $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
+ $new_bas = $appbox->get_connection()->lastInsertId();
+ $appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
- $databox = databox::get_instance((int) $sbas_id);
- $databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
+ $databox = databox::get_instance((int) $sbas_id);
+ $databox->delete_data_from_cache(databox::CACHE_COLLECTIONS);
- cache_databox::update($sbas_id, 'structure');
+ cache_databox::update($sbas_id, 'structure');
- phrasea::reset_baseDatas();
+ phrasea::reset_baseDatas();
- self::set_admin($new_bas, $user);
+ self::set_admin($new_bas, $user);
- return $new_bas;
- }
-
- public static function getLogo($base_id, $printname = false)
- {
- $base_id_key = $base_id . '_' . ($printname ? '1' : '0');
-
- if (!isset(self::$_logos[$base_id_key]))
- {
-
- $registry = registry::get_instance();
- if (is_file($registry->get('GV_RootPath') . 'config/minilogos/' . $base_id))
- {
- $name = phrasea::bas_names($base_id);
- self::$_logos[$base_id_key] = ' ';
- }
- elseif ($printname)
- {
- self::$_logos[$base_id_key] = phrasea::bas_names($base_id);
- }
+ return $new_bas;
}
- return isset(self::$_logos[$base_id_key]) ? self::$_logos[$base_id_key] : '';
- }
-
- public static function getWatermark($base_id)
- {
- if (!isset(self::$_watermarks['base_id']))
+ public static function getLogo($base_id, $printname = false)
{
+ $base_id_key = $base_id . '_' . ($printname ? '1' : '0');
- $registry = registry::get_instance();
- if (is_file($registry->get('GV_RootPath') . 'config/wm/' . $base_id))
- self::$_watermarks['base_id'] = ' ';
+ if ( ! isset(self::$_logos[$base_id_key])) {
+
+ $registry = registry::get_instance();
+ if (is_file($registry->get('GV_RootPath') . 'config/minilogos/' . $base_id)) {
+ $name = phrasea::bas_names($base_id);
+ self::$_logos[$base_id_key] = ' ';
+ } elseif ($printname) {
+ self::$_logos[$base_id_key] = phrasea::bas_names($base_id);
+ }
+ }
+
+ return isset(self::$_logos[$base_id_key]) ? self::$_logos[$base_id_key] : '';
}
- return isset(self::$_watermarks['base_id']) ? self::$_watermarks['base_id'] : '';
- }
-
- public static function getPresentation($base_id)
- {
- if (!isset(self::$_presentations['base_id']))
+ public static function getWatermark($base_id)
{
+ if ( ! isset(self::$_watermarks['base_id'])) {
- $registry = registry::get_instance();
- if (is_file($registry->get('GV_RootPath') . 'config/presentation/' . $base_id))
- self::$_presentations['base_id'] = ' ';
+ $registry = registry::get_instance();
+ if (is_file($registry->get('GV_RootPath') . 'config/wm/' . $base_id))
+ self::$_watermarks['base_id'] = ' ';
+ }
+
+ return isset(self::$_watermarks['base_id']) ? self::$_watermarks['base_id'] : '';
}
- return isset(self::$_presentations['base_id']) ? self::$_presentations['base_id'] : '';
- }
-
- public static function getStamp($base_id)
- {
- if (!isset(self::$_stamps['base_id']))
+ public static function getPresentation($base_id)
{
+ if ( ! isset(self::$_presentations['base_id'])) {
- $registry = registry::get_instance();
- if (is_file($registry->get('GV_RootPath') . 'config/stamp/' . $base_id))
- self::$_stamps['base_id'] = ' ';
+ $registry = registry::get_instance();
+ if (is_file($registry->get('GV_RootPath') . 'config/presentation/' . $base_id))
+ self::$_presentations['base_id'] = ' ';
+ }
+
+ return isset(self::$_presentations['base_id']) ? self::$_presentations['base_id'] : '';
}
- return isset(self::$_stamps['base_id']) ? self::$_stamps['base_id'] : '';
- }
+ public static function getStamp($base_id)
+ {
+ if ( ! isset(self::$_stamps['base_id'])) {
- public function get_cache_key($option = null)
- {
- return 'collection_' . $this->coll_id . ($option ? '_' . $option : '');
- }
+ $registry = registry::get_instance();
+ if (is_file($registry->get('GV_RootPath') . 'config/stamp/' . $base_id))
+ self::$_stamps['base_id'] = ' ';
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->databox->get_data_from_cache($this->get_cache_key($option));
- }
+ return isset(self::$_stamps['base_id']) ? self::$_stamps['base_id'] : '';
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ public function get_cache_key($option = null)
+ {
+ return 'collection_' . $this->coll_id . ($option ? '_' . $option : '');
+ }
- public function delete_data_from_cache($option = null)
- {
- return $this->databox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function get_data_from_cache($option = null)
+ {
+ return $this->databox->get_data_from_cache($this->get_cache_key($option));
+ }
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->databox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/connection.class.php b/lib/classes/connection.class.php
index df7ce474b3..9f2ba604dd 100755
--- a/lib/classes/connection.class.php
+++ b/lib/classes/connection.class.php
@@ -17,177 +17,155 @@
*/
class connection
{
+ /**
+ *
+ * @var Array
+ */
+ private static $_PDO_instance = array();
- /**
- *
- * @var Array
- */
- private static $_PDO_instance = array();
+ /**
+ *
+ * @var boolean
+ */
+ private static $_selfinstance;
- /**
- *
- * @var boolean
- */
- private static $_selfinstance;
+ /**
+ *
+ * @var Array
+ */
+ public static $log = array();
- /**
- *
- * @var Array
- */
- public static $log = array();
-
- /**
- *
- */
- public function __destruct()
- {
- self::printLog();
-
- return;
- }
-
- /**
- *
- * @return Void
- */
- public static function printLog()
- {
- $registry = registry::get_instance();
- if (!$registry->get('GV_debug'))
-
- return;
- $totalTime = 0;
-
- foreach (self::$log as $entry)
+ /**
+ *
+ */
+ public function __destruct()
{
- $query = $entry['query'];
- do
- {
- $query = str_replace(array("\n", " "), " ", $query);
- }
- while ($query != str_replace(array("\n", " "), " ", $query));
+ self::printLog();
- $totalTime += $entry['time'];
- $string = $entry['time'] . "\t" . ' - ' . $query . ' - ' . "\n";
- file_put_contents($registry->get('GV_RootPath') . 'logs/mysql_log.log', $string, FILE_APPEND);
+ return;
}
- $string = count(self::$log) . ' queries - ' . $totalTime
+
+ /**
+ *
+ * @return Void
+ */
+ public static function printLog()
+ {
+ $registry = registry::get_instance();
+ if ( ! $registry->get('GV_debug'))
+ return;
+ $totalTime = 0;
+
+ foreach (self::$log as $entry) {
+ $query = $entry['query'];
+ do {
+ $query = str_replace(array("\n", " "), " ", $query);
+ } while ($query != str_replace(array("\n", " "), " ", $query));
+
+ $totalTime += $entry['time'];
+ $string = $entry['time'] . "\t" . ' - ' . $query . ' - ' . "\n";
+ file_put_contents($registry->get('GV_RootPath') . 'logs/mysql_log.log', $string, FILE_APPEND);
+ }
+ $string = count(self::$log) . ' queries - ' . $totalTime
. "\nEND OF QUERY " . $_SERVER['PHP_SELF']
. "?";
- foreach ($_GET as $key => $value)
- {
- $string .= $key . ' = ' . $value . ' & ';
+ foreach ($_GET as $key => $value) {
+ $string .= $key . ' = ' . $value . ' & ';
+ }
+ $string .= "\nPOST datas :\n ";
+ foreach ($_POST as $key => $value) {
+ $string .= "\t\t" . $key . ' = ' . $value . "\n";
+ }
+ $string .= "\n\n\n\n";
+
+ file_put_contents($registry->get('GV_RootPath') . 'logs/mysql_log.log', $string, FILE_APPEND);
+
+
+
+ return;
}
- $string .= "\nPOST datas :\n ";
- foreach ($_POST as $key => $value)
+
+ /**
+ *
+ * @return type
+ */
+ protected static function instantiate()
{
- $string .= "\t\t" . $key . ' = ' . $value . "\n";
+ if ( ! self::$_selfinstance)
+ self::$_selfinstance = new self();
+
+ return;
}
- $string .= "\n\n\n\n";
- file_put_contents($registry->get('GV_RootPath') . 'logs/mysql_log.log', $string, FILE_APPEND);
-
-
-
- return;
- }
-
- /**
- *
- * @return type
- */
- protected static function instantiate()
- {
- if (!self::$_selfinstance)
- self::$_selfinstance = new self();
-
- return;
- }
-
- /**
- *
- * @param string $name
- * @return connection_pdo
- */
- public static function getPDOConnection($name = null, registryInterface $registry = null)
- {
- self::instantiate();
- if (trim($name) == '')
+ /**
+ *
+ * @param string $name
+ * @return connection_pdo
+ */
+ public static function getPDOConnection($name = null, registryInterface $registry = null)
{
- $name = 'appbox';
- }
- elseif (is_int((int) $name))
- {
- $name = (int) $name;
- }
- else
+ self::instantiate();
+ if (trim($name) == '') {
+ $name = 'appbox';
+ } elseif (is_int((int) $name)) {
+ $name = (int) $name;
+ }
+ else
+ return false;
- return false;
+ if ( ! isset(self::$_PDO_instance[$name])) {
+ $hostname = $port = $user = $password = $dbname = false;
- if (!isset(self::$_PDO_instance[$name]))
- {
- $hostname = $port = $user = $password = $dbname = false;
+ $connection_params = array();
- $connection_params = array();
+ if (trim($name) !== 'appbox') {
+ $connection_params = phrasea::sbas_params();
+ } else {
+ $configuration = \Alchemy\Phrasea\Core\Configuration::build();
- if (trim($name) !== 'appbox')
- {
- $connection_params = phrasea::sbas_params();
- }
- else
- {
- $configuration = \Alchemy\Phrasea\Core\Configuration::build();
+ $choosenConnexion = $configuration->getPhraseanet()->get('database');
- $choosenConnexion = $configuration->getPhraseanet()->get('database');
+ $connexion = $configuration->getConnexion($choosenConnexion);
- $connexion = $configuration->getConnexion($choosenConnexion);
+ $hostname = $connexion->get('host');
+ $port = $connexion->get('port');
+ $user = $connexion->get('user');
+ $password = $connexion->get('password');
+ $dbname = $connexion->get('dbname');
+ }
- $hostname = $connexion->get('host');
- $port = $connexion->get('port');
- $user = $connexion->get('user');
- $password = $connexion->get('password');
- $dbname = $connexion->get('dbname');
- }
+ if (isset($connection_params[$name])) {
+ $hostname = $connection_params[$name]['host'];
+ $port = $connection_params[$name]['port'];
+ $user = $connection_params[$name]['user'];
+ $password = $connection_params[$name]['pwd'];
+ $dbname = $connection_params[$name]['dbname'];
+ }
- if (isset($connection_params[$name]))
- {
- $hostname = $connection_params[$name]['host'];
- $port = $connection_params[$name]['port'];
- $user = $connection_params[$name]['user'];
- $password = $connection_params[$name]['pwd'];
- $dbname = $connection_params[$name]['dbname'];
- }
-
- try
- {
- self::$_PDO_instance[$name] = new connection_pdo($name, $hostname, $port, $user, $password, $dbname, array(), $registry);
- self::$_PDO_instance[$name]->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
- }
- catch (Exception $e)
- {
+ try {
+ self::$_PDO_instance[$name] = new connection_pdo($name, $hostname, $port, $user, $password, $dbname, array(), $registry);
+ self::$_PDO_instance[$name]->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
+ } catch (Exception $e) {
+ throw new Exception('Connection not available');
+ }
+ }
+ if (array_key_exists($name, self::$_PDO_instance))
+ return self::$_PDO_instance[$name];
throw new Exception('Connection not available');
- }
}
- if (array_key_exists($name, self::$_PDO_instance))
- return self::$_PDO_instance[$name];
- throw new Exception('Connection not available');
- }
-
- /**
- *
- * @param type $name
- * @return type
- */
- public static function close_PDO_connection($name)
- {
- if (isset(self::$_PDO_instance[$name]))
+ /**
+ *
+ * @param type $name
+ * @return type
+ */
+ public static function close_PDO_connection($name)
{
- self::$_PDO_instance[$name] = null;
- unset(self::$_PDO_instance[$name]);
+ if (isset(self::$_PDO_instance[$name])) {
+ self::$_PDO_instance[$name] = null;
+ unset(self::$_PDO_instance[$name]);
+ }
+
+ return;
}
-
- return;
- }
-
}
diff --git a/lib/classes/connection/abstract.class.php b/lib/classes/connection/abstract.class.php
index 66c2a8ff64..e4922e1ff8 100644
--- a/lib/classes/connection/abstract.class.php
+++ b/lib/classes/connection/abstract.class.php
@@ -17,95 +17,89 @@
*/
abstract class connection_abstract extends PDO
{
+ protected $name;
+ protected $credentials = array();
+ protected $multi_db = true;
- protected $name;
- protected $credentials = array();
- protected $multi_db = true;
-
-
- public function get_credentials()
- {
- return $this->credentials;
- }
-
- public function is_multi_db()
- {
- return $this->multi_db;
- }
-
- /**
- * html debug message from PDOException object
- * @param PDOException $e
- */
- public static function html_pdo_exception(PDOException $e)
- {
- $p = array('e' => $e);
-
- $core = \bootstrap::getCore();
- $twig = $core->getTwig();
-
- return $twig->render('common/pdo_exception.html', $p);
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
-
- public function ping()
- {
- try
+ public function get_credentials()
{
- $this->query('SELECT 1');
- }
- catch (PDOException $e)
- {
- return false;
+ return $this->credentials;
}
- return true;
- }
+ public function is_multi_db()
+ {
+ return $this->multi_db;
+ }
- /**
- *
- * @param string $statement
- * @param array $driver_options
- * @return PDOStatement
- */
- public function prepare($statement, $driver_options = array())
- {
- return parent::prepare($statement, $driver_options);
- }
+ /**
+ * html debug message from PDOException object
+ * @param PDOException $e
+ */
+ public static function html_pdo_exception(PDOException $e)
+ {
+ $p = array('e' => $e);
- /**
- *
- * @return boolean
- */
- public function beginTransaction()
- {
- return parent::beginTransaction();
- }
+ $core = \bootstrap::getCore();
+ $twig = $core->getTwig();
- /**
- *
- * @return boolean
- */
- public function commit()
- {
- return parent::commit();
- }
+ return $twig->render('common/pdo_exception.html', $p);
+ }
- /**
- *
- * @return string
- */
- public function server_info()
- {
- return parent::getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
+ public function ping()
+ {
+ try {
+ $this->query('SELECT 1');
+ } catch (PDOException $e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ * @param string $statement
+ * @param array $driver_options
+ * @return PDOStatement
+ */
+ public function prepare($statement, $driver_options = array())
+ {
+ return parent::prepare($statement, $driver_options);
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function beginTransaction()
+ {
+ return parent::beginTransaction();
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function commit()
+ {
+ return parent::commit();
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function server_info()
+ {
+ return parent::getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
+ }
}
diff --git a/lib/classes/connection/interface.class.php b/lib/classes/connection/interface.class.php
index 3a09a67f8d..4dd3f130e7 100644
--- a/lib/classes/connection/interface.class.php
+++ b/lib/classes/connection/interface.class.php
@@ -17,21 +17,22 @@
*/
interface connection_interface
{
- public function ping();
- public function get_name();
+ public function ping();
- public function is_multi_db();
+ public function get_name();
- public function get_credentials();
+ public function is_multi_db();
- public function close();
+ public function get_credentials();
- public function prepare($statement, $driver_options = array());
+ public function close();
- public function beginTransaction();
+ public function prepare($statement, $driver_options = array());
- public function commit();
+ public function beginTransaction();
- public function server_info();
+ public function commit();
+
+ public function server_info();
}
diff --git a/lib/classes/connection/pdo.class.php b/lib/classes/connection/pdo.class.php
index 310848391a..15cc7ae698 100644
--- a/lib/classes/connection/pdo.class.php
+++ b/lib/classes/connection/pdo.class.php
@@ -17,81 +17,78 @@
*/
class connection_pdo extends connection_abstract implements connection_interface
{
+ protected $registry;
- protected $registry;
- /**
- *
- * @param string $name
- * @param string $hostname
- * @param int $port
- * @param string $user
- * @param string $passwd
- * @param string $dbname
- * @param array $options
- * @return connection_pdo
- */
- public function __construct($name, $hostname, $port, $user, $passwd, $dbname=false, $options=array(), registryInterface $registry = null)
- {
- $this->registry = $registry ? $registry : registry::get_instance();
- $this->name = $name;
- if ($dbname)
- $dsn = 'mysql:dbname=' . $dbname . ';host=' . $hostname . ';port=' . $port . ';';
- else
- $dsn = 'mysql:host=' . $hostname . ';port=' . $port . ';';
+ /**
+ *
+ * @param string $name
+ * @param string $hostname
+ * @param int $port
+ * @param string $user
+ * @param string $passwd
+ * @param string $dbname
+ * @param array $options
+ * @return connection_pdo
+ */
+ public function __construct($name, $hostname, $port, $user, $passwd, $dbname = false, $options = array(), registryInterface $registry = null)
+ {
+ $this->registry = $registry ? $registry : registry::get_instance();
+ $this->name = $name;
+ if ($dbname)
+ $dsn = 'mysql:dbname=' . $dbname . ';host=' . $hostname . ';port=' . $port . ';';
+ else
+ $dsn = 'mysql:host=' . $hostname . ';port=' . $port . ';';
- $this->credentials['hostname'] = $hostname;
- $this->credentials['port'] = $port;
- $this->credentials['user'] = $user;
- $this->credentials['password'] = $passwd;
- if ($dbname)
- $this->credentials['dbname'] = $dbname;
+ $this->credentials['hostname'] = $hostname;
+ $this->credentials['port'] = $port;
+ $this->credentials['user'] = $user;
+ $this->credentials['password'] = $passwd;
+ if ($dbname)
+ $this->credentials['dbname'] = $dbname;
- parent::__construct($dsn, $user, $passwd, $options);
+ parent::__construct($dsn, $user, $passwd, $options);
- $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $this->query("
+ $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ $this->query("
SET character_set_results = 'utf8', character_set_client = 'utf8',
character_set_connection = 'utf8', character_set_database = 'utf8',
character_set_server = 'utf8'");
- return $this;
- }
+ return $this;
+ }
- /**
- *
- * @param type $statement
- * @param type $driver_options
- * @return PDOStatement
- */
- public function prepare($statement, $driver_options = array())
- {
- if ($this->registry->get('GV_debug'))
+ /**
+ *
+ * @param type $statement
+ * @param type $driver_options
+ * @return PDOStatement
+ */
+ public function prepare($statement, $driver_options = array())
+ {
+ if ($this->registry->get('GV_debug'))
+ return new connection_pdoStatementDebugger(parent::prepare($statement, $driver_options));
+ else
+ return parent::prepare($statement, $driver_options);
+ }
- return new connection_pdoStatementDebugger(parent::prepare($statement, $driver_options));
- else
+ /**
+ *
+ * @return void
+ */
+ public function close()
+ {
+ connection::close_PDO_connection($this->name);
+ }
- return parent::prepare($statement, $driver_options);
- }
-
- /**
- *
- * @return void
- */
- public function close()
- {
- connection::close_PDO_connection($this->name);
- }
-
- /**
- *
- * @param string $message
- * @return connection_pdo
- */
- protected function log($message)
- {
- file_put_contents(__DIR__ . '/../../../logs/sql_log.log', $message . "\n", FILE_APPEND);
-
- return $this;
- }
+ /**
+ *
+ * @param string $message
+ * @return connection_pdo
+ */
+ protected function log($message)
+ {
+ file_put_contents(__DIR__ . '/../../../logs/sql_log.log', $message . "\n", FILE_APPEND);
+ return $this;
+ }
}
diff --git a/lib/classes/connection/pdoStatementDebugger.class.php b/lib/classes/connection/pdoStatementDebugger.class.php
index 3087213a9c..a32850e6b8 100644
--- a/lib/classes/connection/pdoStatementDebugger.class.php
+++ b/lib/classes/connection/pdoStatementDebugger.class.php
@@ -17,46 +17,41 @@
*/
class connection_pdoStatementDebugger
{
+ /**
+ *
+ * @var PDOStatement
+ */
+ protected $statement;
- /**
- *
- * @var PDOStatement
- */
- protected $statement;
-
- public function __construct(PDOStatement $statement)
- {
- $this->statement = $statement;
-
- return $this;
- }
-
- public function execute($params = array())
- {
- $start = microtime(true);
- $exception = null;
- try
+ public function __construct(PDOStatement $statement)
{
- $result = $this->statement->execute($params);
+ $this->statement = $statement;
+
+ return $this;
}
- catch(Exception $e)
+
+ public function execute($params = array())
{
- $exception = $e;
- }
- $time = microtime(true) - $start;
- connection::$log[] = array(
- 'query' => '' . str_replace(array_keys($params), array_values($params), $this->statement->queryString),
- 'time' => $time
+ $start = microtime(true);
+ $exception = null;
+ try {
+ $result = $this->statement->execute($params);
+ } catch (Exception $e) {
+ $exception = $e;
+ }
+ $time = microtime(true) - $start;
+ connection::$log[] = array(
+ 'query' => '' . str_replace(array_keys($params), array_values($params), $this->statement->queryString),
+ 'time' => $time
);
- if($exception instanceof Exception)
- throw $exception;
+ if ($exception instanceof Exception)
+ throw $exception;
- return $result;
- }
-
- public function __call($function_name, $parameters)
- {
- return call_user_func_array(array($this->statement, $function_name), $parameters);
- }
+ return $result;
+ }
+ public function __call($function_name, $parameters)
+ {
+ return call_user_func_array(array($this->statement, $function_name), $parameters);
+ }
}
diff --git a/lib/classes/databox.class.php b/lib/classes/databox.class.php
index b4706bb161..b1b312dfc8 100644
--- a/lib/classes/databox.class.php
+++ b/lib/classes/databox.class.php
@@ -11,7 +11,6 @@
class databox extends base
{
-
/**
*
* @var int
@@ -92,9 +91,9 @@ class databox extends base
const BASE_TYPE = self::DATA_BOX;
const CACHE_META_STRUCT = 'meta_struct';
- const CACHE_THESAURUS = 'thesaurus';
+ const CACHE_THESAURUS = 'thesaurus';
const CACHE_COLLECTIONS = 'collections';
- const CACHE_STRUCTURE = 'structure';
+ const CACHE_STRUCTURE = 'structure';
const PIC_PDF = 'logopdf';
protected $cache;
@@ -131,14 +130,10 @@ class databox extends base
{
$ret = array();
- foreach ($this->get_available_collections() as $coll_id)
- {
- try
- {
+ foreach ($this->get_available_collections() as $coll_id) {
+ try {
$ret[] = collection::get_from_coll_id($this, $coll_id);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
}
@@ -148,30 +143,26 @@ class databox extends base
protected function get_available_collections()
{
- try
- {
+ try {
return $this->get_data_from_cache(self::CACHE_COLLECTIONS);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
$conn = connection::getPDOConnection();
- $sql = "SELECT b.server_coll_id FROM sbas s, bas b
+ $sql = "SELECT b.server_coll_id FROM sbas s, bas b
WHERE s.sbas_id = b.sbas_id AND b.sbas_id = :sbas_id
AND b.active = '1'
ORDER BY s.ord ASC, b.ord,b.base_id ASC";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':sbas_id' => $this->get_sbas_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$ret = array();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$ret[] = (int) $row['server_coll_id'];
}
$this->set_data_to_cache($ret, self::CACHE_COLLECTIONS);
@@ -204,8 +195,7 @@ class databox extends base
{
assert(is_int($sbas_id));
assert($sbas_id > 0);
- if ( ! array_key_exists($sbas_id, self::$_instances))
- {
+ if ( ! array_key_exists($sbas_id, self::$_instances)) {
self::$_instances[$sbas_id] = new self($sbas_id);
}
@@ -235,7 +225,7 @@ class databox extends base
{
$sql = "SELECT COUNT(kword_id) AS n FROM kword";
- $stmt = $this->get_connection()->prepare($sql);
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
@@ -247,7 +237,7 @@ class databox extends base
{
$sql = "SELECT COUNT(idx_id) AS n FROM idx";
- $stmt = $this->get_connection()->prepare($sql);
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
@@ -259,7 +249,7 @@ class databox extends base
{
$sql = "SELECT COUNT(thit_id) AS n FROM thit";
- $stmt = $this->get_connection()->prepare($sql);
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
@@ -281,33 +271,29 @@ class databox extends base
WHERE ISNULL(record.coll_id)
GROUP BY record.coll_id, name";
- if ($sort == "obj")
- {
+ if ($sort == "obj") {
$sortk1 = "name";
$sortk2 = "asciiname";
- }
- else
- {
+ } else {
$sortk1 = "asciiname";
$sortk2 = "name";
}
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $rowbas)
- {
+ foreach ($rs as $rowbas) {
if ( ! isset($trows[$rowbas[$sortk1]]))
$trows[$rowbas[$sortk1]] = array();
$trows[$rowbas[$sortk1]][$rowbas[$sortk2]] = array(
- "coll_id" => $rowbas["coll_id"],
- "asciiname" => $rowbas["asciiname"],
- "lostcoll" => $rowbas["lostcoll"],
- "name" => $rowbas["name"],
- "n" => $rowbas["n"],
- "siz" => $rowbas["siz"]
+ "coll_id" => $rowbas["coll_id"],
+ "asciiname" => $rowbas["asciiname"],
+ "lostcoll" => $rowbas["lostcoll"],
+ "name" => $rowbas["name"],
+ "n" => $rowbas["n"],
+ "siz" => $rowbas["siz"]
);
}
@@ -321,8 +307,8 @@ class databox extends base
public function get_record_amount()
{
- $sql = "SELECT COUNT(record_id) AS n FROM record";
- $stmt = $this->get_connection()->prepare($sql);
+ $sql = "SELECT COUNT(record_id) AS n FROM record";
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$rowbas = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
@@ -335,15 +321,14 @@ class databox extends base
public function get_indexed_record_amount()
{
- $sql = "SELECT status & 3 AS status, SUM(1) AS n FROM record GROUP BY(status & 3)";
+ $sql = "SELECT status & 3 AS status, SUM(1) AS n FROM record GROUP BY(status & 3)";
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$ret = array('xml_indexed' => 0, 'thesaurus_indexed' => 0);
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$status = $row['status'];
if ($status & 1)
$ret['xml_indexed'] += $row['n'];
@@ -356,24 +341,21 @@ class databox extends base
public function unmount_databox(appbox $appbox)
{
- foreach ($this->get_collections() as $collection)
- {
+ foreach ($this->get_collections() as $collection) {
$collection->unmount_collection($appbox);
}
$query = new User_Query($appbox);
$total = $query->on_sbas_ids(array($this->get_sbas_id()))
- ->include_phantoms(false)
- ->include_special_users(true)
- ->include_invite(true)
- ->include_templates(true)
- ->get_total();
+ ->include_phantoms(false)
+ ->include_special_users(true)
+ ->include_invite(true)
+ ->include_templates(true)
+ ->get_total();
$n = 0;
- while ($n < $total)
- {
+ while ($n < $total) {
$results = $query->limit($n, 50)->execute()->get_results();
- foreach ($results as $user)
- {
+ foreach ($results as $user) {
$user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_SBAS);
$user->ACL()->delete_data_from_cache(ACL::CACHE_RIGHTS_BAS);
$user->ACL()->delete_injected_rights_sbas($this);
@@ -383,22 +365,22 @@ class databox extends base
$params = array(':site_id' => $this->get_registry()->get('GV_sit'));
- $sql = 'DELETE FROM clients WHERE site_id = :site_id';
+ $sql = 'DELETE FROM clients WHERE site_id = :site_id';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute($params);
$stmt->closeCursor();
- $sql = 'DELETE FROM memcached WHERE site_id = :site_id';
+ $sql = 'DELETE FROM memcached WHERE site_id = :site_id';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute($params);
$stmt->closeCursor();
- $sql = "DELETE FROM sbas WHERE sbas_id = :sbas_id";
+ $sql = "DELETE FROM sbas WHERE sbas_id = :sbas_id";
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':sbas_id' => $this->get_sbas_id()));
$stmt->closeCursor();
- $sql = "DELETE FROM sbasusr WHERE sbas_id = :sbas_id";
+ $sql = "DELETE FROM sbasusr WHERE sbas_id = :sbas_id";
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(':sbas_id' => $this->get_sbas_id()));
$stmt->closeCursor();
@@ -428,75 +410,71 @@ class databox extends base
WHERE host = :host AND port = :port AND dbname = :dbname
AND user = :user AND pwd = :password';
- $host = $credentials['hostname'];
- $port = $credentials['port'];
- $dbname = $credentials['dbname'];
- $user = $credentials['user'];
+ $host = $credentials['hostname'];
+ $port = $credentials['port'];
+ $dbname = $credentials['dbname'];
+ $user = $credentials['user'];
$password = $credentials['password'];
$params = array(
- ':host' => $host
- , ':port' => $port
- , ':dbname' => $dbname
- , ':user' => $user
- , ':password' => $password
+ ':host' => $host
+ , ':port' => $port
+ , ':dbname' => $dbname
+ , ':user' => $user
+ , ':password' => $password
);
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
-
return self::get_instance((int) $row['sbas_id']);
- try
- {
- $sql = 'CREATE DATABASE `' . $dbname . '`
+ try {
+ $sql = 'CREATE DATABASE `' . $dbname . '`
CHARACTER SET utf8 COLLATE utf8_unicode_ci';
$stmt = $connection->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
- $sql = 'USE `' . $dbname . '`';
+ $sql = 'USE `' . $dbname . '`';
$stmt = $connection->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
- $sql = 'SELECT MAX(ord) as ord FROM sbas';
+ $sql = 'SELECT MAX(ord) as ord FROM sbas';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
- $ord = $row['ord'] + 1;
+ $ord = $row['ord'] + 1;
- $sql = 'INSERT INTO sbas (sbas_id, ord, host, port, dbname, sqlengine, user, pwd)
+ $sql = 'INSERT INTO sbas (sbas_id, ord, host, port, dbname, sqlengine, user, pwd)
VALUES (null, :ord, :host, :port, :dbname, "MYSQL", :user, :password)';
$stmt = $appbox->get_connection()->prepare($sql);
$stmt->execute(array(
- ':ord' => $ord
- , ':host' => $host
- , ':port' => $port
- , ':dbname' => $dbname
- , ':user' => $user
- , ':password' => $password
+ ':ord' => $ord
+ , ':host' => $host
+ , ':port' => $port
+ , ':dbname' => $dbname
+ , ':user' => $user
+ , ':password' => $password
));
$stmt->closeCursor();
- $sbas_id = (int) $appbox->get_connection()->lastInsertId();
+ $sbas_id = (int) $appbox->get_connection()->lastInsertId();
$appbox->delete_data_from_cache(appbox::CACHE_LIST_BASES);
$databox = self::get_instance($sbas_id);
$databox->insert_datas();
$databox->setNewStructure(
- $data_template, $registry->get('GV_base_datapath_web'), $registry->get('GV_base_datapath_noweb'), $registry->get('GV_base_dataurl')
+ $data_template, $registry->get('GV_base_datapath_web'), $registry->get('GV_base_datapath_noweb'), $registry->get('GV_base_dataurl')
);
return $databox;
@@ -514,31 +492,31 @@ class databox extends base
*/
public static function mount(appbox $appbox, $host, $port, $user, $password, $dbname, registry $registry)
{
- $name = 'test';
+ $name = 'test';
$connection = new connection_pdo($name, $host, $port, $user, $password, $dbname, array(), $registry);
$conn = $appbox->get_connection();
- $sql = 'SELECT MAX(ord) as ord FROM sbas';
+ $sql = 'SELECT MAX(ord) as ord FROM sbas';
$stmt = $conn->prepare($sql);
$stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
- $ord = $row['ord'] + 1;
+ $ord = $row['ord'] + 1;
- $sql = 'INSERT INTO sbas (sbas_id, ord, host, port, dbname, sqlengine, user, pwd)
+ $sql = 'INSERT INTO sbas (sbas_id, ord, host, port, dbname, sqlengine, user, pwd)
VALUES (null, :ord, :host, :port, :dbname, "MYSQL", :user, :password)';
$stmt = $conn->prepare($sql);
$stmt->execute(array(
- ':ord' => $ord
- , ':host' => $host
- , ':port' => $port
- , ':dbname' => $dbname
- , ':user' => $user
- , ':password' => $password
+ ':ord' => $ord
+ , ':host' => $host
+ , ':port' => $port
+ , ':dbname' => $dbname
+ , ':user' => $user
+ , ':password' => $password
));
$stmt->closeCursor();
- $sbas_id = (int) $conn->lastInsertId();
+ $sbas_id = (int) $conn->lastInsertId();
phrasea::clear_sbas_params();
phrasea::reset_baseDatas();
phrasea::reset_sbasDatas();
@@ -572,39 +550,31 @@ class databox extends base
*/
public function get_meta_structure()
{
- if ($this->meta_struct)
- {
+ if ($this->meta_struct) {
return $this->meta_struct;
}
- try
- {
+ try {
$this->meta_struct = $this->get_data_from_cache(self::CACHE_META_STRUCT);
return $this->meta_struct;
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
unset($e);
}
$meta_struct = new databox_descriptionStructure();
- $sql = 'SELECT id, name FROM metadatas_structure ORDER BY sorter ASC';
+ $sql = 'SELECT id, name FROM metadatas_structure ORDER BY sorter ASC';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
- try
- {
+ try {
$meta = databox_field::get_instance($this, $row['id']);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$meta = databox_fieldUnknown::get_instance($this, $row['id']);
$meta->set_name($row['name']);
unset($e);
@@ -623,8 +593,7 @@ class databox extends base
*/
public function get_subdef_structure()
{
- if ( ! $this->subdef_struct)
- {
+ if ( ! $this->subdef_struct) {
$this->subdef_struct = new databox_subdefsStructure($this);
}
@@ -644,24 +613,22 @@ class databox extends base
$repository_path = p4string::addEndSlash($repository_path);
- $year = date('Y', strtotime($date));
+ $year = date('Y', strtotime($date));
$month = date('m', strtotime($date));
- $day = date('d', strtotime($date));
+ $day = date('d', strtotime($date));
- $n = 0;
+ $n = 0;
$comp = $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $day . DIRECTORY_SEPARATOR;
$condition = true;
$pathout = $repository_path . $comp;
- while (($pathout = $repository_path . $comp . self::addZeros($n)) && is_dir($pathout) && self::more_than_limit_in_dir($pathout))
- {
+ while (($pathout = $repository_path . $comp . self::addZeros($n)) && is_dir($pathout) && self::more_than_limit_in_dir($pathout)) {
$n ++;
}
- if ( ! is_dir($pathout))
- {
+ if ( ! is_dir($pathout)) {
system_file::mkdir($pathout);
}
@@ -673,7 +640,7 @@ class databox extends base
{
$appbox = appbox::get_instance(\bootstrap::getCore());
- $sql = 'DROP DATABASE `' . $this->get_dbname() . '`';
+ $sql = 'DROP DATABASE `' . $this->get_dbname() . '`';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
@@ -686,23 +653,18 @@ class databox extends base
private function more_than_limit_in_dir($path)
{
$limit = 100;
- $n = 0;
- if (is_dir($path))
- {
+ $n = 0;
+ if (is_dir($path)) {
$hdir = opendir($path);
- if ($hdir)
- {
- while ($file = readdir($hdir))
- {
- if ($file != '.' && $file != '..')
- {
+ if ($hdir) {
+ while ($file = readdir($hdir)) {
+ if ($file != '.' && $file != '..') {
$n ++;
}
}
}
}
if ($n > $limit)
-
return true;
return false;
@@ -729,16 +691,13 @@ class databox extends base
public static function get_available_metadatas()
{
$available_fields = array();
- $dir = __DIR__ . '/metadata/description/';
+ $dir = __DIR__ . '/metadata/description/';
$registry = registry::get_instance();
- foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file)
- {
- if ($file->isDir() || strpos($file->getPathname(), '/.svn/') !== false)
- {
+ foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
+ if ($file->isDir() || strpos($file->getPathname(), '/.svn/') !== false) {
continue;
}
- if ($file->isFile())
- {
+ if ($file->isFile()) {
$classname = str_replace(array($registry->get('GV_RootPath') . 'lib/classes/', '.class.php', '/'), array('', '', '_'), $file->getPathname());
$available_fields[$classname] = new $classname;
}
@@ -751,21 +710,21 @@ class databox extends base
public function get_available_dcfields()
{
return array(
- databox_Field_DCESAbstract::Contributor => new databox_Field_DCES_Contributor()
- , databox_Field_DCESAbstract::Coverage => new databox_Field_DCES_Coverage()
- , databox_Field_DCESAbstract::Creator => new databox_Field_DCES_Creator()
- , databox_Field_DCESAbstract::Date => new databox_Field_DCES_Date()
- , databox_Field_DCESAbstract::Description => new databox_Field_DCES_Description()
- , databox_Field_DCESAbstract::Format => new databox_Field_DCES_Format()
- , databox_Field_DCESAbstract::Identifier => new databox_Field_DCES_Identifier()
- , databox_Field_DCESAbstract::Language => new databox_Field_DCES_Language()
- , databox_Field_DCESAbstract::Publisher => new databox_Field_DCES_Publisher()
- , databox_Field_DCESAbstract::Relation => new databox_Field_DCES_Relation
- , databox_Field_DCESAbstract::Rights => new databox_Field_DCES_Rights
- , databox_Field_DCESAbstract::Source => new databox_Field_DCES_Source
- , databox_Field_DCESAbstract::Subject => new databox_Field_DCES_Subject()
- , databox_Field_DCESAbstract::Title => new databox_Field_DCES_Title()
- , databox_Field_DCESAbstract::Type => new databox_Field_DCES_Type()
+ databox_Field_DCESAbstract::Contributor => new databox_Field_DCES_Contributor()
+ , databox_Field_DCESAbstract::Coverage => new databox_Field_DCES_Coverage()
+ , databox_Field_DCESAbstract::Creator => new databox_Field_DCES_Creator()
+ , databox_Field_DCESAbstract::Date => new databox_Field_DCES_Date()
+ , databox_Field_DCESAbstract::Description => new databox_Field_DCES_Description()
+ , databox_Field_DCESAbstract::Format => new databox_Field_DCES_Format()
+ , databox_Field_DCESAbstract::Identifier => new databox_Field_DCES_Identifier()
+ , databox_Field_DCESAbstract::Language => new databox_Field_DCES_Language()
+ , databox_Field_DCESAbstract::Publisher => new databox_Field_DCES_Publisher()
+ , databox_Field_DCESAbstract::Relation => new databox_Field_DCES_Relation
+ , databox_Field_DCESAbstract::Rights => new databox_Field_DCES_Rights
+ , databox_Field_DCESAbstract::Source => new databox_Field_DCES_Source
+ , databox_Field_DCESAbstract::Subject => new databox_Field_DCES_Subject()
+ , databox_Field_DCESAbstract::Title => new databox_Field_DCES_Title()
+ , databox_Field_DCESAbstract::Type => new databox_Field_DCES_Type()
);
}
@@ -775,17 +734,16 @@ class databox extends base
*/
public function get_mountable_colls()
{
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
$colls = array();
- $sql = 'SELECT server_coll_id FROM bas WHERE sbas_id = :sbas_id';
+ $sql = 'SELECT server_coll_id FROM bas WHERE sbas_id = :sbas_id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':sbas_id' => $this->get_sbas_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$colls[] = (int) $row['server_coll_id'];
}
@@ -793,18 +751,16 @@ class databox extends base
$sql = 'SELECT coll_id, asciiname FROM coll';
- if (count($colls) > 0)
- {
+ if (count($colls) > 0) {
$sql .= ' WHERE coll_id NOT IN (' . implode(',', $colls) . ')';
}
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$mountable_colls[$row['coll_id']] = $row['asciiname'];
}
@@ -813,17 +769,16 @@ class databox extends base
public function get_activable_colls()
{
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
$base_ids = array();
- $sql = 'SELECT base_id FROM bas WHERE sbas_id = :sbas_id AND active = "0"';
+ $sql = 'SELECT base_id FROM bas WHERE sbas_id = :sbas_id AND active = "0"';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':sbas_id' => $this->get_sbas_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$base_ids[] = (int) $row['base_id'];
}
@@ -839,7 +794,7 @@ class databox extends base
{
$dom_struct->documentElement
- ->setAttribute("modification_date", $now = date("YmdHis"));
+ ->setAttribute("modification_date", $now = date("YmdHis"));
$sql = "UPDATE pref SET value= :structure, updated_on= :now
WHERE prop='structure'";
@@ -848,17 +803,17 @@ class databox extends base
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute(
- array(
- ':structure' => $this->structure,
- ':now' => $now
- )
+ array(
+ ':structure' => $this->structure,
+ ':now' => $now
+ )
);
$stmt->closeCursor();
$this->_sxml_structure = $this->_dom_structure = $this->_xpath_structure = null;
$com_struct = $this->get_dom_structure();
- $xp_struct = $this->get_xpath_structure();
+ $xp_struct = $this->get_xpath_structure();
$this->meta_struct = null;
@@ -882,8 +837,8 @@ class databox extends base
$this->cterms = $dom_cterms->saveXML();
$params = array(
- ':xml' => $this->cterms
- , ':date' => $now
+ ':xml' => $this->cterms
+ , ':date' => $now
);
$stmt = $this->get_connection()->prepare($sql);
@@ -893,7 +848,6 @@ class databox extends base
return $this;
}
-
protected $thesaurus;
public function saveThesaurus(DOMDocument $dom_thesaurus)
@@ -902,7 +856,7 @@ class databox extends base
$dom_thesaurus->documentElement->setAttribute("modification_date", $now = date("YmdHis"));
$this->thesaurus = $dom_thesaurus->saveXML();
- $sql = "UPDATE pref SET value = :xml, updated_on = :date WHERE prop='thesaurus'";
+ $sql = "UPDATE pref SET value = :xml, updated_on = :date WHERE prop='thesaurus'";
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute(array(':xml' => $this->thesaurus, ':date' => $now));
$stmt->closeCursor();
@@ -926,9 +880,9 @@ class databox extends base
$baseurl = $baseurl ? p4string::addEndSlash($baseurl) : '';
$contents = str_replace(
- array("{{dataurl}}", "{{basename}}", "{{datapathweb}}", "{{datapathnoweb}}")
- , array($baseurl, $this->dbname, $path_web, $path_doc)
- , $contents
+ array("{{dataurl}}", "{{basename}}", "{{datapathweb}}", "{{datapathnoweb}}")
+ , array($baseurl, $this->dbname, $path_web, $path_doc)
+ , $contents
);
$dom_doc = new DOMDocument();
@@ -944,12 +898,11 @@ class databox extends base
{
$sxe = $this->get_sxml_structure();
- foreach ($sxe->description->children() as $fname => $field)
- {
+ foreach ($sxe->description->children() as $fname => $field) {
$dom_struct = $this->get_dom_structure();
- $xp_struct = $this->get_xpath_structure();
- $fname = (string) $fname;
- $src = trim(isset($field['src']) ? $field['src'] : '');
+ $xp_struct = $this->get_xpath_structure();
+ $fname = (string) $fname;
+ $src = trim(isset($field['src']) ? $field['src'] : '');
$meta_id = isset($field['meta_id']) ? $field['meta_id'] : null;
if ( ! is_null($meta_id))
@@ -957,41 +910,37 @@ class databox extends base
$nodes = $xp_struct->query('/record/description/' . $fname);
- if ($nodes->length > 0)
- {
+ if ($nodes->length > 0) {
$nodes->item(0)->parentNode->removeChild($nodes->item(0));
}
$this->saveStructure($dom_struct);
$type = isset($field['type']) ? $field['type'] : 'string';
$type = in_array($type
- , array(
- databox_field::TYPE_DATE
- , databox_field::TYPE_NUMBER
- , databox_field::TYPE_STRING
- , databox_field::TYPE_TEXT
- )
- ) ? $type : databox_field::TYPE_STRING;
+ , array(
+ databox_field::TYPE_DATE
+ , databox_field::TYPE_NUMBER
+ , databox_field::TYPE_STRING
+ , databox_field::TYPE_TEXT
+ )
+ ) ? $type : databox_field::TYPE_STRING;
$meta_struct_field = databox_field::create($this, $fname);
$meta_struct_field
- ->set_readonly(isset($field['readonly']) ? $field['readonly'] : 0)
- ->set_indexable(isset($field['index']) ? $field['index'] : '1')
- ->set_separator(isset($field['separator']) ? $field['separator'] : '')
- ->set_required((isset($field['required']) && $field['required'] == 1))
- ->set_type($type)
- ->set_tbranch(isset($field['tbranch']) ? $field['tbranch'] : '')
- ->set_thumbtitle(isset($field['thumbtitle']) ? $field['thumbtitle'] : (isset($field['thumbTitle']) ? $field['thumbTitle'] : '0'))
- ->set_multi(isset($field['multi']) ? $field['multi'] : 0)
- ->set_report(isset($field['report']) ? $field['report'] : '1')
- ->save();
+ ->set_readonly(isset($field['readonly']) ? $field['readonly'] : 0)
+ ->set_indexable(isset($field['index']) ? $field['index'] : '1')
+ ->set_separator(isset($field['separator']) ? $field['separator'] : '')
+ ->set_required((isset($field['required']) && $field['required'] == 1))
+ ->set_type($type)
+ ->set_tbranch(isset($field['tbranch']) ? $field['tbranch'] : '')
+ ->set_thumbtitle(isset($field['thumbtitle']) ? $field['thumbtitle'] : (isset($field['thumbTitle']) ? $field['thumbTitle'] : '0'))
+ ->set_multi(isset($field['multi']) ? $field['multi'] : 0)
+ ->set_report(isset($field['report']) ? $field['report'] : '1')
+ ->save();
- try
- {
+ try {
$meta_struct_field->set_source($src)->save();
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
}
@@ -1006,59 +955,53 @@ class databox extends base
*/
public function registerAdmin(User_Interface $user)
{
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
$registry = registry::get_instance();
$user->ACL()
- ->give_access_to_sbas(array($this->get_sbas_id()))
- ->update_rights_to_sbas(
- $this->get_sbas_id(), array(
- 'bas_manage' => 1, 'bas_modify_struct' => 1,
- 'bas_modif_th' => 1, 'bas_chupub' => 1
- )
+ ->give_access_to_sbas(array($this->get_sbas_id()))
+ ->update_rights_to_sbas(
+ $this->get_sbas_id(), array(
+ 'bas_manage' => 1, 'bas_modify_struct' => 1,
+ 'bas_modif_th' => 1, 'bas_chupub' => 1
+ )
);
- $sql = "SELECT * FROM coll";
+ $sql = "SELECT * FROM coll";
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- $sql = "INSERT INTO bas
+ $sql = "INSERT INTO bas
(base_id, active, server_coll_id, sbas_id) VALUES
(null,'1', :coll_id, :sbas_id)";
$stmt = $conn->prepare($sql);
$base_ids = array();
- foreach ($rs as $row)
- {
- try
- {
+ foreach ($rs as $row) {
+ try {
$stmt->execute(array(':coll_id' => $row['coll_id'], ':sbas_id' => $this->get_sbas_id()));
- $base_ids[] = $base_id = $conn->lastInsertId();
+ $base_ids[] = $base_id = $conn->lastInsertId();
- if ( ! empty($row['logo']))
- {
+ if ( ! empty($row['logo'])) {
file_put_contents($registry->get('GV_RootPath') . 'config/minilogos/' . $base_id, $row['logo']);
}
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
unset($e);
}
}
$user->ACL()->give_access_to_base($base_ids);
- foreach ($base_ids as $base_id)
- {
+ foreach ($base_ids as $base_id) {
$user->ACL()->update_rights_to_base($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
- )
+ '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
+ )
);
}
@@ -1076,18 +1019,17 @@ class databox extends base
{
$registry = registry::get_instance();
- $out = '';
+ $out = '';
if (is_file(($filename = $registry->get('GV_RootPath') . 'config/minilogos/logopdf_' . $sbas_id . '.jpg')))
- $out = file_get_contents($filename);
+ $out = file_get_contents($filename);
return $out;
}
public function clear_logs()
{
- foreach (array('log', 'exports', 'quest') as $table)
- {
- $sql = 'TRUNCATE ' . $table;
+ foreach (array('log', 'exports', 'quest') as $table) {
+ $sql = 'TRUNCATE ' . $table;
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
@@ -1098,7 +1040,7 @@ class databox extends base
public function reindex()
{
- $sql = 'UPDATE pref SET updated_on="0000-00-00 00:00:00" WHERE prop="indexes"';
+ $sql = 'UPDATE pref SET updated_on="0000-00-00 00:00:00" WHERE prop="indexes"';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
$stmt->closeCursor();
@@ -1114,8 +1056,7 @@ class databox extends base
public function get_dom_thesaurus()
{
$sbas_id = $this->get_sbas_id();
- if (isset(self::$_dom_thesaurus[$sbas_id]))
- {
+ if (isset(self::$_dom_thesaurus[$sbas_id])) {
return self::$_dom_thesaurus[$sbas_id];
}
@@ -1137,8 +1078,7 @@ class databox extends base
public function get_xpath_thesaurus()
{
$sbas_id = $this->get_sbas_id();
- if (isset(self::$_xpath_thesaurus[$sbas_id]))
- {
+ if (isset(self::$_xpath_thesaurus[$sbas_id])) {
return self::$_xpath_thesaurus[$sbas_id];
}
@@ -1160,8 +1100,7 @@ class databox extends base
public function get_sxml_thesaurus()
{
$sbas_id = $this->get_sbas_id();
- if (isset(self::$_sxml_thesaurus[$sbas_id]))
- {
+ if (isset(self::$_sxml_thesaurus[$sbas_id])) {
return self::$_sxml_thesaurus[$sbas_id];
}
@@ -1182,30 +1121,24 @@ class databox extends base
*/
public function get_thesaurus()
{
- try
- {
+ try {
$this->thesaurus = $this->get_data_from_cache(self::CACHE_THESAURUS);
return $this->thesaurus;
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
unset($e);
}
$thesaurus = false;
- try
- {
- $sql = 'SELECT value AS thesaurus FROM pref WHERE prop="thesaurus" LIMIT 1;';
+ try {
+ $sql = 'SELECT value AS thesaurus FROM pref WHERE prop="thesaurus" LIMIT 1;';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$this->thesaurus = $row['thesaurus'];
$this->set_data_to_cache($this->thesaurus, self::CACHE_THESAURUS);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
unset($e);
}
@@ -1219,7 +1152,6 @@ class databox extends base
public function get_structure()
{
if ($this->structure)
-
return $this->structure;
$this->structure = $this->retrieve_structure();
@@ -1228,20 +1160,17 @@ class databox extends base
protected function retrieve_structure()
{
- try
- {
+ try {
return $this->get_data_from_cache(self::CACHE_STRUCTURE);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
$structure = null;
- $sql = "SELECT value FROM pref WHERE prop='structure'";
- $stmt = $this->get_connection()->prepare($sql);
+ $sql = "SELECT value FROM pref WHERE prop='structure'";
+ $stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
@@ -1250,7 +1179,6 @@ class databox extends base
return $structure;
}
-
protected $cterms;
/**
@@ -1260,13 +1188,12 @@ class databox extends base
public function get_cterms()
{
if ($this->cterms)
-
return $this->cterms;
- $sql = "SELECT value FROM pref WHERE prop='cterms'";
+ $sql = "SELECT value FROM pref WHERE prop='cterms'";
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row)
@@ -1282,8 +1209,7 @@ class databox extends base
*/
public function get_dom_structure()
{
- if ($this->_dom_structure)
- {
+ if ($this->_dom_structure) {
return $this->_dom_structure;
}
@@ -1310,8 +1236,7 @@ class databox extends base
*/
public function get_dom_cterms()
{
- if ($this->_dom_cterms)
- {
+ if ($this->_dom_cterms) {
return $this->_dom_cterms;
}
@@ -1337,8 +1262,7 @@ class databox extends base
*/
public function get_sxml_structure()
{
- if ($this->_sxml_structure)
- {
+ if ($this->_sxml_structure) {
return $this->_sxml_structure;
}
@@ -1359,8 +1283,7 @@ class databox extends base
*/
public function get_xpath_structure()
{
- if ($this->_xpath_structure)
- {
+ if ($this->_xpath_structure) {
return $this->_xpath_structure;
}
@@ -1384,16 +1307,14 @@ class databox extends base
$sx_structure = simplexml_load_string($structure);
$subdefgroup = $sx_structure->subdefs[0];
- $AvSubdefs = array();
+ $AvSubdefs = array();
$errors = array();
- foreach ($subdefgroup as $k => $subdefs)
- {
+ foreach ($subdefgroup as $k => $subdefs) {
$subdefgroup_name = trim((string) $subdefs->attributes()->name);
- if ($subdefgroup_name == '')
- {
+ if ($subdefgroup_name == '') {
$errors[] = _('ERREUR : TOUTES LES BALISES subdefgroup necessitent un attribut name');
continue;
}
@@ -1401,18 +1322,15 @@ class databox extends base
if ( ! isset($AvSubdefs[$subdefgroup_name]))
$AvSubdefs[$subdefgroup_name] = array();
- foreach ($subdefs as $sd)
- {
- $sd_name = trim(mb_strtolower((string) $sd->attributes()->name));
+ foreach ($subdefs as $sd) {
+ $sd_name = trim(mb_strtolower((string) $sd->attributes()->name));
$sd_class = trim(mb_strtolower((string) $sd->attributes()->class));
- if ($sd_name == '' || isset($AvSubdefs[$subdefgroup_name][$sd_name]))
- {
+ if ($sd_name == '' || isset($AvSubdefs[$subdefgroup_name][$sd_name])) {
$errors[] = _('ERREUR : Les name de subdef sont uniques par groupe de subdefs et necessaire');
continue;
}
- if ( ! in_array($sd_class, array('thumbnail', 'preview', 'document')))
- {
- $errors[] = _('ERREUR : La classe de subdef est necessaire et egal a "thumbnail","preview" ou "document"');
+ if ( ! in_array($sd_class, array('thumbnail', 'preview', 'document'))) {
+ $errors[] = _('ERREUR : La classe de subdef est necessaire et egal a "thumbnail","preview" ou "document"');
continue;
}
$AvSubdefs[$subdefgroup_name][$sd_name] = $sd;
@@ -1421,13 +1339,11 @@ class databox extends base
return $errors;
}
-
protected $cgus;
public function get_cgus()
{
if ($this->cgus)
-
return $this->cgus;
$this->load_cgus();
@@ -1437,45 +1353,40 @@ class databox extends base
protected function load_cgus()
{
- try
- {
+ try {
$this->cgus = $this->get_data_from_cache(self::CACHE_CGUS);
return $this;
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
- $sql = 'SELECT value, locale, updated_on FROM pref WHERE prop ="ToU"';
+ $sql = 'SELECT value, locale, updated_on FROM pref WHERE prop ="ToU"';
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
+ foreach ($rs as $row) {
$TOU[$row['locale']] = array('updated_on' => $row['updated_on'], 'value' => $row['value']);
}
$missing_locale = array();
- $avLanguages = User_Adapter::avLanguages();
+ $avLanguages = User_Adapter::avLanguages();
foreach ($avLanguages as $lang)
foreach ($lang as $k => $v)
if ( ! isset($TOU[$k]))
$missing_locale[] = $k;
$date_obj = new DateTime();
- $date = phraseadate::format_mysql($date_obj);
- $sql = "INSERT INTO pref (id, prop, value, locale, updated_on, created_on)
+ $date = phraseadate::format_mysql($date_obj);
+ $sql = "INSERT INTO pref (id, prop, value, locale, updated_on, created_on)
VALUES (null, 'ToU', '', :locale, :date, NOW())";
- $stmt = $this->get_connection()->prepare($sql);
- foreach ($missing_locale as $v)
- {
+ $stmt = $this->get_connection()->prepare($sql);
+ foreach ($missing_locale as $v) {
$stmt->execute(array(':locale' => $v, ':date' => $date));
- $TOU[$v] = array('updated_on' => $date, 'value' => '');
+ $TOU[$v] = array('updated_on' => $date, 'value' => '');
}
$stmt->closeCursor();
$this->cgus = $TOU;
@@ -1484,7 +1395,6 @@ class databox extends base
return $this;
}
-
const CACHE_CGUS = 'cgus';
public function update_cgus($locale, $terms, $reset_date)
@@ -1500,7 +1410,7 @@ class databox extends base
$stmt = $this->get_connection()->prepare($sql);
$stmt->execute(array(':terms' => $terms, ':locale' => $locale));
$stmt->closeCursor();
- $update = true;
+ $update = true;
$this->cgus = null;
$this->delete_data_from_cache(self::CACHE_CGUS);
@@ -1509,8 +1419,7 @@ class databox extends base
public function delete_data_from_cache($option = null)
{
- switch ($option)
- {
+ switch ($option) {
case self::CACHE_CGUS:
$this->cgus = null;
break;
@@ -1528,5 +1437,4 @@ class databox extends base
}
parent::delete_data_from_cache($option);
}
-
}
diff --git a/lib/classes/databox/Field/DCES/Contributor.class.php b/lib/classes/databox/Field/DCES/Contributor.class.php
index b06176ca1a..44361a4ca6 100644
--- a/lib/classes/databox/Field/DCES/Contributor.class.php
+++ b/lib/classes/databox/Field/DCES/Contributor.class.php
@@ -17,22 +17,23 @@
*/
class databox_Field_DCES_Contributor extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Contributor';
- /**
- *
- * @var string
- */
- protected $label = 'Contributor';
- /**
- *
- * @var string
- */
- protected $definition = 'An entity responsible for making contributions
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'An entity responsible for making contributions
to the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#contributor';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#contributor';
}
diff --git a/lib/classes/databox/Field/DCES/Coverage.class.php b/lib/classes/databox/Field/DCES/Coverage.class.php
index 652a3f60aa..e791bf535c 100644
--- a/lib/classes/databox/Field/DCES/Coverage.class.php
+++ b/lib/classes/databox/Field/DCES/Coverage.class.php
@@ -17,23 +17,25 @@
*/
class databox_Field_DCES_Coverage extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Coverage';
- /**
- *
- * @var string
- */
- protected $label = 'Coverage';
- /**
- *
- * @var string
- */
- protected $definition = 'The spatial or temporal topic of the resource,
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'The spatial or temporal topic of the resource,
the spatial applicability of the resource,
or the jurisdiction under which the resource
is relevant.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#coverage';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#coverage';
+
}
diff --git a/lib/classes/databox/Field/DCES/Creator.class.php b/lib/classes/databox/Field/DCES/Creator.class.php
index 2d2110b17d..77e8fca505 100644
--- a/lib/classes/databox/Field/DCES/Creator.class.php
+++ b/lib/classes/databox/Field/DCES/Creator.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Creator extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Creator';
- /**
- *
- * @var string
- */
- protected $label = 'Creator';
- /**
- *
- * @var string
- */
- protected $definition = 'An entity primarily responsible
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'An entity primarily responsible
for making the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#creator';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#creator';
+
}
diff --git a/lib/classes/databox/Field/DCES/Date.class.php b/lib/classes/databox/Field/DCES/Date.class.php
index 5e76bb46c1..7bb93ba304 100644
--- a/lib/classes/databox/Field/DCES/Date.class.php
+++ b/lib/classes/databox/Field/DCES/Date.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Date extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Date';
- /**
- *
- * @var string
- */
- protected $label = 'Date';
- /**
- *
- * @var string
- */
- protected $definition = 'A point or period of time associated with an event
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'A point or period of time associated with an event
in the lifecycle of the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#date';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#date';
+
}
diff --git a/lib/classes/databox/Field/DCES/Description.class.php b/lib/classes/databox/Field/DCES/Description.class.php
index 48dc53ed1b..687a4ec23f 100644
--- a/lib/classes/databox/Field/DCES/Description.class.php
+++ b/lib/classes/databox/Field/DCES/Description.class.php
@@ -17,20 +17,22 @@
*/
class databox_Field_DCES_Description extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Description';
+
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'An account of the resource.';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#description';
- /**
- *
- * @var string
- */
- protected $label = 'Description';
- /**
- *
- * @var string
- */
- protected $definition = 'An account of the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#description';
}
diff --git a/lib/classes/databox/Field/DCES/Format.class.php b/lib/classes/databox/Field/DCES/Format.class.php
index 1a1957244e..7871313fa6 100644
--- a/lib/classes/databox/Field/DCES/Format.class.php
+++ b/lib/classes/databox/Field/DCES/Format.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Format extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Format';
- /**
- *
- * @var string
- */
- protected $label = 'Format';
- /**
- *
- * @var string
- */
- protected $definition = 'The file format, physical medium,
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'The file format, physical medium,
or dimensions of the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#format';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#format';
+
}
diff --git a/lib/classes/databox/Field/DCES/Identifier.class.php b/lib/classes/databox/Field/DCES/Identifier.class.php
index d9a92fd3ce..f14ba714f3 100644
--- a/lib/classes/databox/Field/DCES/Identifier.class.php
+++ b/lib/classes/databox/Field/DCES/Identifier.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Identifier extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Identifier';
- /**
- *
- * @var string
- */
- protected $label = 'Identifier';
- /**
- *
- * @var string
- */
- protected $definition = 'An unambiguous reference to the resource
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'An unambiguous reference to the resource
within a given context.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#identifier';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#identifier';
+
}
diff --git a/lib/classes/databox/Field/DCES/Language.class.php b/lib/classes/databox/Field/DCES/Language.class.php
index 676c07efa7..4b70c2a182 100644
--- a/lib/classes/databox/Field/DCES/Language.class.php
+++ b/lib/classes/databox/Field/DCES/Language.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Language extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Language';
- /**
- *
- * @var string
- */
- protected $label = 'Language';
- /**
- *
- * @var string
- */
- protected $definition = 'A language of the resource.
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'A language of the resource.
(see [RFC4646] http://www.ietf.org/rfc/rfc4646.txt)';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#language';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#language';
+
}
diff --git a/lib/classes/databox/Field/DCES/Publisher.class.php b/lib/classes/databox/Field/DCES/Publisher.class.php
index ebd94e4acb..213c3bee47 100644
--- a/lib/classes/databox/Field/DCES/Publisher.class.php
+++ b/lib/classes/databox/Field/DCES/Publisher.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Publisher extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Publisher';
- /**
- *
- * @var string
- */
- protected $label = 'Publisher';
- /**
- *
- * @var string
- */
- protected $definition = 'An entity responsible for making the resource
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'An entity responsible for making the resource
available.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#publisher';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#publisher';
+
}
diff --git a/lib/classes/databox/Field/DCES/Relation.class.php b/lib/classes/databox/Field/DCES/Relation.class.php
index 335a066b37..1b846962d5 100644
--- a/lib/classes/databox/Field/DCES/Relation.class.php
+++ b/lib/classes/databox/Field/DCES/Relation.class.php
@@ -17,20 +17,22 @@
*/
class databox_Field_DCES_Relation extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Relation';
+
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'A related resource.';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#relation';
- /**
- *
- * @var string
- */
- protected $label = 'Relation';
- /**
- *
- * @var string
- */
- protected $definition = 'A related resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#relation';
}
diff --git a/lib/classes/databox/Field/DCES/Rights.class.php b/lib/classes/databox/Field/DCES/Rights.class.php
index 866ad4f475..b63569e639 100644
--- a/lib/classes/databox/Field/DCES/Rights.class.php
+++ b/lib/classes/databox/Field/DCES/Rights.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Rights extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Rights';
- /**
- *
- * @var string
- */
- protected $label = 'Rights';
- /**
- *
- * @var string
- */
- protected $definition = 'Information about rights held
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'Information about rights held
in and over the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#rights';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#rights';
+
}
diff --git a/lib/classes/databox/Field/DCES/Source.class.php b/lib/classes/databox/Field/DCES/Source.class.php
index 8ffe6d34ea..a1a4f3af21 100644
--- a/lib/classes/databox/Field/DCES/Source.class.php
+++ b/lib/classes/databox/Field/DCES/Source.class.php
@@ -17,21 +17,23 @@
*/
class databox_Field_DCES_Source extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Source';
- /**
- *
- * @var string
- */
- protected $label = 'Source';
- /**
- *
- * @var string
- */
- protected $definition = 'A related resource from which
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'A related resource from which
the described resource is derived.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#source';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#source';
+
}
diff --git a/lib/classes/databox/Field/DCES/Subject.class.php b/lib/classes/databox/Field/DCES/Subject.class.php
index 169f788fe3..0b6e4496d7 100644
--- a/lib/classes/databox/Field/DCES/Subject.class.php
+++ b/lib/classes/databox/Field/DCES/Subject.class.php
@@ -17,20 +17,22 @@
*/
class databox_Field_DCES_Subject extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Subject';
+
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'The topic of the resource.';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#subject';
- /**
- *
- * @var string
- */
- protected $label = 'Subject';
- /**
- *
- * @var string
- */
- protected $definition = 'The topic of the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#subject';
}
diff --git a/lib/classes/databox/Field/DCES/Title.class.php b/lib/classes/databox/Field/DCES/Title.class.php
index a9c3037230..8260b4d9a8 100644
--- a/lib/classes/databox/Field/DCES/Title.class.php
+++ b/lib/classes/databox/Field/DCES/Title.class.php
@@ -17,20 +17,22 @@
*/
class databox_Field_DCES_Title extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Title';
+
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'A name given to the resource.';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#title';
- /**
- *
- * @var string
- */
- protected $label = 'Title';
- /**
- *
- * @var string
- */
- protected $definition = 'A name given to the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#title';
}
diff --git a/lib/classes/databox/Field/DCES/Type.class.php b/lib/classes/databox/Field/DCES/Type.class.php
index c4b7ea92e8..6a9c1ad9fb 100644
--- a/lib/classes/databox/Field/DCES/Type.class.php
+++ b/lib/classes/databox/Field/DCES/Type.class.php
@@ -17,20 +17,22 @@
*/
class databox_Field_DCES_Type extends databox_Field_DCESAbstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $label = 'Type';
+
+ /**
+ *
+ * @var string
+ */
+ protected $definition = 'The nature or genre of the resource.';
+
+ /**
+ *
+ * @var string
+ */
+ protected $URI = 'http://dublincore.org/documents/dces/#type';
- /**
- *
- * @var string
- */
- protected $label = 'Type';
- /**
- *
- * @var string
- */
- protected $definition = 'The nature or genre of the resource.';
- /**
- *
- * @var string
- */
- protected $URI = 'http://dublincore.org/documents/dces/#type';
}
diff --git a/lib/classes/databox/cgu.class.php b/lib/classes/databox/cgu.class.php
index 2306d9d13c..e0edcc6e6b 100644
--- a/lib/classes/databox/cgu.class.php
+++ b/lib/classes/databox/cgu.class.php
@@ -17,104 +17,94 @@
*/
class databox_cgu
{
- public function __construct(databox $databox, $locale)
- {
- return $this;
- }
- public static function askAgreement()
- {
- $terms = self::getUnvalidated();
-
- $out = '';
-
- foreach ($terms as $name => $term)
+ public function __construct(databox $databox, $locale)
{
- if (trim($term['terms']) == '')
- {
- continue;
- }
- $out .= '';
+ return $this;
+ }
- $out .= '
' . $term['terms'] . ' ';
- $out .= '
' . _('cgus:: Pour continuer a utiliser lapplication, vous devez accepter les conditions precedentes') . '
+ public static function askAgreement()
+ {
+ $terms = self::getUnvalidated();
+
+ $out = '';
+
+ foreach ($terms as $name => $term) {
+ if (trim($term['terms']) == '') {
+ continue;
+ }
+ $out .= '
';
- }
-
- return $out;
- }
-
- private static function getUnvalidated($home=false)
- {
- $terms = array();
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- if(!$home)
- {
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
- }
-
- foreach ($appbox->get_databoxes() as $databox)
- {
- try
- {
- $cgus = $databox->get_cgus();
-
- if (!isset($cgus[Session_Handler::get_locale()]))
- throw new Exception('No CGus for this locale');
- $name = $databox->get_viewname();
-
- $update = $cgus[Session_Handler::get_locale()]['updated_on'];
- $value = $cgus[Session_Handler::get_locale()]['value'];
- $userValidation = true;
-
- if (!$home)
- {
- if(!$user->ACL()->has_access_to_sbas($databox->get_sbas_id()))
- {
- continue;
- }
- $userValidation = ($user->getPrefs('terms_of_use_' . $databox->get_sbas_id()) !== $update && trim($value) !== '');
+ $out .= '
';
}
- if ($userValidation)
- $terms[$name] = array('sbas_id' => $databox->get_sbas_id(), 'terms' => $value, 'date' => $update);
- }
- catch (Exception $e)
- {
-
- }
+ return $out;
}
- return $terms;
- }
-
- public static function getHome()
- {
- $terms = self::getUnvalidated(true);
-
- $out = '';
-
- foreach ($terms as $name => $term)
+ private static function getUnvalidated($home = false)
{
- if (trim($term['terms']) == '')
- continue;
+ $terms = array();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- if ($out != '')
- $out .= '
';
+ if ( ! $home) {
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+ }
- $out .= '
' . str_replace('"', '"', sprintf(_('cgus:: CGUs de la base %s'), $name)) . ' ';
+ foreach ($appbox->get_databoxes() as $databox) {
+ try {
+ $cgus = $databox->get_cgus();
- $out .= '
' . $term['terms'] . ' ';
+ if ( ! isset($cgus[Session_Handler::get_locale()]))
+ throw new Exception('No CGus for this locale');
+ $name = $databox->get_viewname();
- $out .= '
';
+ $update = $cgus[Session_Handler::get_locale()]['updated_on'];
+ $value = $cgus[Session_Handler::get_locale()]['value'];
+ $userValidation = true;
+
+ if ( ! $home) {
+ if ( ! $user->ACL()->has_access_to_sbas($databox->get_sbas_id())) {
+ continue;
+ }
+ $userValidation = ($user->getPrefs('terms_of_use_' . $databox->get_sbas_id()) !== $update && trim($value) !== '');
+ }
+
+ if ($userValidation)
+ $terms[$name] = array('sbas_id' => $databox->get_sbas_id(), 'terms' => $value, 'date' => $update);
+ } catch (Exception $e) {
+
+ }
+ }
+
+ return $terms;
}
- return $out;
- }
+ public static function getHome()
+ {
+ $terms = self::getUnvalidated(true);
+ $out = '';
+
+ foreach ($terms as $name => $term) {
+ if (trim($term['terms']) == '')
+ continue;
+
+ if ($out != '')
+ $out .= '
';
+
+ $out .= '
' . str_replace('"', '"', sprintf(_('cgus:: CGUs de la base %s'), $name)) . ' ';
+
+ $out .= '
' . $term['terms'] . ' ';
+
+ $out .= '
';
+ }
+
+ return $out;
+ }
}
diff --git a/lib/classes/databox/descriptionStructure.class.php b/lib/classes/databox/descriptionStructure.class.php
index 83faa90e2c..f2e2e42e2a 100644
--- a/lib/classes/databox/descriptionStructure.class.php
+++ b/lib/classes/databox/descriptionStructure.class.php
@@ -17,109 +17,105 @@
*/
class databox_descriptionStructure implements IteratorAggregate
{
+ /**
+ *
+ * @var Array
+ */
+ protected $elements = array();
- /**
- *
- * @var Array
- */
- protected $elements = array();
- /**
- * Cache array for the get element by name function
- *
- * @var Array
- */
- protected $cache_name_id = array();
+ /**
+ * Cache array for the get element by name function
+ *
+ * @var Array
+ */
+ protected $cache_name_id = array();
- /**
- *
- * @return databox_field
- */
- public function getIterator()
- {
- return new ArrayIterator($this->elements);
- }
-
- /**
- *
- * @param databox_field $field
- * @return databox_descriptionStructure
- */
- public function add_element(databox_field $field)
- {
- $this->elements[$field->get_id()] = $field;
-
- return $this;
- }
-
- /**
- *
- * @param databox_field $field
- * @return databox_descriptionStructure
- */
- public function remove_element(databox_field $field)
- {
- if (isset($this->elements[$field->get_id()]))
- unset($this->elements[$field->get_id()]);
-
- return $this;
- }
-
- /**
- *
- * @return array
- */
- public function get_elements()
- {
- return $this->elements;
- }
-
- /**
- *
- * @param int $id
- * @return databox_field
- */
- public function get_element($id)
- {
- if (!isset($this->elements[$id]))
- throw new Exception_Databox_FieldNotFound ();
-
- return $this->elements[$id];
- }
-
- /**
- *
- * @param string $name
- * @return databox_field
- */
- public function get_element_by_name($name)
- {
- $name = databox_field::generateName($name);
-
- if (isset($this->cache_name_id[$name]))
-
- return $this->elements[$this->cache_name_id[$name]];
-
- foreach ($this->elements as $id => $meta)
+ /**
+ *
+ * @return databox_field
+ */
+ public function getIterator()
{
- if ($meta->get_name() === $name)
- {
- $this->cache_name_id[$name] = $id;
-
- return $meta;
- }
+ return new ArrayIterator($this->elements);
}
- return null;
- }
+ /**
+ *
+ * @param databox_field $field
+ * @return databox_descriptionStructure
+ */
+ public function add_element(databox_field $field)
+ {
+ $this->elements[$field->get_id()] = $field;
- /**
- *
- * @param string $id
- * @return boolean
- */
- public function isset_element($id)
- {
- return isset($this->elements[$id]);
- }
+ return $this;
+ }
+ /**
+ *
+ * @param databox_field $field
+ * @return databox_descriptionStructure
+ */
+ public function remove_element(databox_field $field)
+ {
+ if (isset($this->elements[$field->get_id()]))
+ unset($this->elements[$field->get_id()]);
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return array
+ */
+ public function get_elements()
+ {
+ return $this->elements;
+ }
+
+ /**
+ *
+ * @param int $id
+ * @return databox_field
+ */
+ public function get_element($id)
+ {
+ if ( ! isset($this->elements[$id]))
+ throw new Exception_Databox_FieldNotFound ();
+
+ return $this->elements[$id];
+ }
+
+ /**
+ *
+ * @param string $name
+ * @return databox_field
+ */
+ public function get_element_by_name($name)
+ {
+ $name = databox_field::generateName($name);
+
+ if (isset($this->cache_name_id[$name]))
+ return $this->elements[$this->cache_name_id[$name]];
+
+ foreach ($this->elements as $id => $meta) {
+ if ($meta->get_name() === $name) {
+ $this->cache_name_id[$name] = $id;
+
+ return $meta;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ *
+ * @param string $id
+ * @return boolean
+ */
+ public function isset_element($id)
+ {
+ return isset($this->elements[$id]);
+ }
}
diff --git a/lib/classes/databox/field.class.php b/lib/classes/databox/field.class.php
index d0fc336589..e7e3b721c6 100644
--- a/lib/classes/databox/field.class.php
+++ b/lib/classes/databox/field.class.php
@@ -19,312 +19,302 @@ use \Alchemy\Phrasea\Vocabulary;
*/
class databox_field implements cache_cacheableInterface
{
+ /**
+ *
+ * @var
+ */
+ protected $id;
- /**
- *
- * @var
- */
- protected $id;
+ /**
+ *
+ * @var databox
+ */
+ protected $databox;
- /**
- *
- * @var databox
- */
- protected $databox;
+ /**
+ *
+ * @var
+ */
+ protected $source;
- /**
- *
- * @var
- */
- protected $source;
+ /**
+ *
+ * @var
+ */
+ protected $name;
- /**
- *
- * @var
- */
- protected $name;
+ /**
+ *
+ * @var
+ */
+ protected $indexable;
- /**
- *
- * @var
- */
- protected $indexable;
+ /**
+ *
+ * @var
+ */
+ protected $readonly;
- /**
- *
- * @var
- */
- protected $readonly;
+ /**
+ *
+ * @var
+ */
+ protected $required;
- /**
- *
- * @var
- */
- protected $required;
+ /**
+ *
+ * @var
+ */
+ protected $multi;
- /**
- *
- * @var
- */
- protected $multi;
+ /**
+ *
+ * @var
+ */
+ protected $report;
- /**
- *
- * @var
- */
- protected $report;
+ /**
+ *
+ * @var
+ */
+ protected $type;
- /**
- *
- * @var
- */
- protected $type;
+ /**
+ *
+ * @var
+ */
+ protected $tbranch;
- /**
- *
- * @var
- */
- protected $tbranch;
+ /**
+ *
+ * @var
+ */
+ protected $separator;
- /**
- *
- * @var
- */
- protected $separator;
+ /**
+ *
+ * @var
+ */
+ protected $thumbtitle;
- /**
- *
- * @var
- */
- protected $thumbtitle;
+ /**
+ *
+ * @var boolean
+ */
+ protected $Business;
+ protected $renamed = false;
+ protected $metaToMerge = false;
- /**
- *
- * @var boolean
- */
- protected $Business;
- protected $renamed = false;
- protected $metaToMerge = false;
+ /**
+ *
+ *
+ * To implement : change multi
+ * Change vocab Id
+ *
+ */
- /**
- *
- *
- * To implement : change multi
- * Change vocab Id
- *
- */
+ /**
+ *
+ * @var int
+ */
+ protected $sbas_id;
+ protected static $_instance = array();
+ protected $dces_element;
+ protected $Vocabulary;
+ protected $VocabularyRestriction = false;
- /**
- *
- * @var int
- */
- protected $sbas_id;
- protected static $_instance = array();
- protected $dces_element;
- protected $Vocabulary;
- protected $VocabularyRestriction = false;
+ const TYPE_TEXT = "text";
+ const TYPE_DATE = "date";
+ const TYPE_STRING = "string";
+ const TYPE_NUMBER = "number";
- const TYPE_TEXT = "text";
- const TYPE_DATE = "date";
- const TYPE_STRING = "string";
- const TYPE_NUMBER = "number";
+ /**
+ * http://dublincore.org/documents/dces/
+ */
+ const DCES_TITLE = 'Title';
+ const DCES_CREATOR = 'Creator';
+ const DCES_SUBJECT = 'Subject';
+ const DCES_DESCRIPTION = 'Description';
+ const DCES_PUBLISHER = 'Publisher';
+ const DCES_CONTRIBUTOR = 'Contributor';
+ const DCES_DATE = 'Date';
+ const DCES_TYPE = 'Type';
+ const DCES_FORMAT = 'Format';
+ const DCES_IDENTIFIER = 'Identifier';
+ const DCES_SOURCE = 'Source';
+ const DCES_LANGUAGE = 'Language';
+ const DCES_RELATION = 'Relation';
+ const DCES_COVERAGE = 'Coverage';
+ const DCES_RIGHTS = 'Rights';
- /**
- * http://dublincore.org/documents/dces/
- */
- const DCES_TITLE = 'Title';
- const DCES_CREATOR = 'Creator';
- const DCES_SUBJECT = 'Subject';
- const DCES_DESCRIPTION = 'Description';
- const DCES_PUBLISHER = 'Publisher';
- const DCES_CONTRIBUTOR = 'Contributor';
- const DCES_DATE = 'Date';
- const DCES_TYPE = 'Type';
- const DCES_FORMAT = 'Format';
- const DCES_IDENTIFIER = 'Identifier';
- const DCES_SOURCE = 'Source';
- const DCES_LANGUAGE = 'Language';
- const DCES_RELATION = 'Relation';
- const DCES_COVERAGE = 'Coverage';
- const DCES_RIGHTS = 'Rights';
+ /**
+ *
+ * @param databox $databox
+ * @param $id
+ * @return databox_field
+ */
+ protected function __construct(databox &$databox, $id)
+ {
+ $this->set_databox($databox);
+ $this->sbas_id = $databox->get_sbas_id();
- /**
- *
- * @param databox $databox
- * @param $id
- * @return databox_field
- */
- protected function __construct(databox &$databox, $id)
- {
- $this->set_databox($databox);
- $this->sbas_id = $databox->get_sbas_id();
+ $connbas = $this->get_connection();
- $connbas = $this->get_connection();
-
- $sql = "SELECT `thumbtitle`, `separator`
+ $sql = "SELECT `thumbtitle`, `separator`
, `dces_element`, `tbranch`, `type`, `report`, `multi`, `required`
, `readonly`, `indexable`, `name`, `src`, `business`
, `VocabularyControlType`, `RestrictToVocabularyControl`
FROM metadatas_structure WHERE id=:id";
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':id' => $id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':id' => $id));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->id = (int) $id;
- $this->source = self::load_class_from_xpath($row['src']);
- $this->name = $row['name'];
- $this->indexable = !!$row['indexable'];
- $this->readonly = !!$row['readonly'];
- $this->required = !!$row['required'];
- $this->multi = !!$row['multi'];
- $this->Business = !!$row['business'];
- $this->report = !!$row['report'];
- $this->type = $row['type'] ? : self::TYPE_STRING;
- $this->tbranch = $row['tbranch'];
+ $this->id = (int) $id;
+ $this->source = self::load_class_from_xpath($row['src']);
+ $this->name = $row['name'];
+ $this->indexable = ! ! $row['indexable'];
+ $this->readonly = ! ! $row['readonly'];
+ $this->required = ! ! $row['required'];
+ $this->multi = ! ! $row['multi'];
+ $this->Business = ! ! $row['business'];
+ $this->report = ! ! $row['report'];
+ $this->type = $row['type'] ? : self::TYPE_STRING;
+ $this->tbranch = $row['tbranch'];
- try
- {
- $this->Vocabulary = Vocabulary\Controller::get($row['VocabularyControlType']);
- $this->VocabularyRestriction = !!$row['RestrictToVocabularyControl'];
- }
- catch (Exception $e)
- {
+ try {
+ $this->Vocabulary = Vocabulary\Controller::get($row['VocabularyControlType']);
+ $this->VocabularyRestriction = ! ! $row['RestrictToVocabularyControl'];
+ } catch (Exception $e) {
+ }
+
+ if ($row['dces_element']) {
+ $dc_class = 'databox_Field_DCES_' . $row['dces_element'];
+ $this->dces_element = new $dc_class();
+ }
+
+ $this->separator = self::checkMultiSeparator($row['separator'], $this->multi);
+
+ $this->thumbtitle = $row['thumbtitle'];
+
+ return $this;
}
- if ($row['dces_element'])
+ /**
+ *
+ * @return type \Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface
+ */
+ public function getVocabularyControl()
{
- $dc_class = 'databox_Field_DCES_' . $row['dces_element'];
- $this->dces_element = new $dc_class();
+ return $this->Vocabulary;
}
- $this->separator = self::checkMultiSeparator($row['separator'], $this->multi);
-
- $this->thumbtitle = $row['thumbtitle'];
-
- return $this;
- }
-
- /**
- *
- * @return type \Alchemy\Phrasea\Vocabulary\ControlProvider\ControlProviderInterface
- */
- public function getVocabularyControl()
- {
- return $this->Vocabulary;
- }
-
- /**
- *
- * @return boolean
- */
- public function isVocabularyRestricted()
- {
- return $this->VocabularyRestriction;
- }
-
- /**
- *
- * @return boolean
- */
- public function isBusiness()
- {
- return $this->Business;
- }
-
- /**
- *
- * @param \databox $databox
- * @param int $id
- * @return \databox_field
- */
- public static function get_instance(databox &$databox, $id)
- {
- $cache_key = 'field_' . $id;
- $instance_id = $databox->get_sbas_id() . '_' . $id;
- if (!isset(self::$_instance[$instance_id]) || (self::$_instance[$instance_id] instanceof self) === false)
+ /**
+ *
+ * @return boolean
+ */
+ public function isVocabularyRestricted()
{
- try
- {
- self::$_instance[$instance_id] = $databox->get_data_from_cache($cache_key);
- }
- catch (Exception $e)
- {
- self::$_instance[$instance_id] = new self($databox, $id);
- $databox->set_data_to_cache(self::$_instance[$instance_id], $cache_key);
- }
+ return $this->VocabularyRestriction;
}
- return self::$_instance[$instance_id];
- }
-
- /**
- *
- * @param databox $databox
- */
- public function set_databox(databox &$databox)
- {
- $this->databox = $databox;
- }
-
- /**
- *
- * @return connection_pdo
- */
- public function get_connection()
- {
- return $this->databox->get_connection();
- }
-
- /**
- *
- * @return databox
- */
- public function get_databox()
- {
- return $this->databox;
- }
-
- public function delete()
- {
- caption_field::delete_all_metadatas($this);
-
- $connbas = $this->get_connection();
- $sql = 'DELETE FROM metadatas_structure WHERE id = :id';
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':id' => $this->get_id()));
- $stmt->closeCursor();
-
- $dom_struct = $this->databox->get_dom_structure();
- $xp_struct = $this->databox->get_xpath_structure();
-
- $nodes = $xp_struct->query(
- '/record/description/*[@meta_id=' . $this->id . ']'
- );
-
- foreach ($nodes as $node)
+ /**
+ *
+ * @return boolean
+ */
+ public function isBusiness()
{
- /* @var $node DOMNode */
- $node->parentNode->removeChild($node);
+ return $this->Business;
}
- $this->delete_data_from_cache();
- $this->databox->saveStructure($dom_struct);
+ /**
+ *
+ * @param \databox $databox
+ * @param int $id
+ * @return \databox_field
+ */
+ public static function get_instance(databox &$databox, $id)
+ {
+ $cache_key = 'field_' . $id;
+ $instance_id = $databox->get_sbas_id() . '_' . $id;
+ if ( ! isset(self::$_instance[$instance_id]) || (self::$_instance[$instance_id] instanceof self) === false) {
+ try {
+ self::$_instance[$instance_id] = $databox->get_data_from_cache($cache_key);
+ } catch (Exception $e) {
+ self::$_instance[$instance_id] = new self($databox, $id);
+ $databox->set_data_to_cache(self::$_instance[$instance_id], $cache_key);
+ }
+ }
- return;
- }
+ return self::$_instance[$instance_id];
+ }
- /**
- *
- * @return databox_field
- */
- public function save()
- {
- $connbas = $this->get_connection();
+ /**
+ *
+ * @param databox $databox
+ */
+ public function set_databox(databox &$databox)
+ {
+ $this->databox = $databox;
+ }
- $sql = 'UPDATE metadatas_structure SET
+ /**
+ *
+ * @return connection_pdo
+ */
+ public function get_connection()
+ {
+ return $this->databox->get_connection();
+ }
+
+ /**
+ *
+ * @return databox
+ */
+ public function get_databox()
+ {
+ return $this->databox;
+ }
+
+ public function delete()
+ {
+ caption_field::delete_all_metadatas($this);
+
+ $connbas = $this->get_connection();
+ $sql = 'DELETE FROM metadatas_structure WHERE id = :id';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ $dom_struct = $this->databox->get_dom_structure();
+ $xp_struct = $this->databox->get_xpath_structure();
+
+ $nodes = $xp_struct->query(
+ '/record/description/*[@meta_id=' . $this->id . ']'
+ );
+
+ foreach ($nodes as $node) {
+ /* @var $node DOMNode */
+ $node->parentNode->removeChild($node);
+ }
+
+ $this->delete_data_from_cache();
+ $this->databox->saveStructure($dom_struct);
+
+ return;
+ }
+
+ /**
+ *
+ * @return databox_field
+ */
+ public function save()
+ {
+ $connbas = $this->get_connection();
+
+ $sql = 'UPDATE metadatas_structure SET
`name` = :name,
`src` = :source,
`indexable` = :indexable,
@@ -341,490 +331,478 @@ class databox_field implements cache_cacheableInterface
`RestrictToVocabularyControl` = :RestrictVocab
WHERE id = :id';
- $params = array(
- ':name' => $this->name,
- ':source' => $this->source->get_source(),
- ':indexable' => $this->indexable ? '1' : '0',
- ':readonly' => $this->readonly ? '1' : '0',
- ':required' => $this->required ? '1' : '0',
- ':separator' => $this->separator,
- ':multi' => $this->multi ? '1' : '0',
- ':business' => $this->Business ? '1' : '0',
- ':report' => $this->report ? '1' : '0',
- ':type' => $this->type,
- ':tbranch' => $this->tbranch,
- ':thumbtitle' => $this->thumbtitle,
- ':VocabularyControlType' => $this->Vocabulary ? $this->Vocabulary->getType() : null,
- ':RestrictVocab' => $this->Vocabulary ? ($this->VocabularyRestriction ? '1' : '0') : '0',
- ':id' => $this->id
- );
+ $params = array(
+ ':name' => $this->name,
+ ':source' => $this->source->get_source(),
+ ':indexable' => $this->indexable ? '1' : '0',
+ ':readonly' => $this->readonly ? '1' : '0',
+ ':required' => $this->required ? '1' : '0',
+ ':separator' => $this->separator,
+ ':multi' => $this->multi ? '1' : '0',
+ ':business' => $this->Business ? '1' : '0',
+ ':report' => $this->report ? '1' : '0',
+ ':type' => $this->type,
+ ':tbranch' => $this->tbranch,
+ ':thumbtitle' => $this->thumbtitle,
+ ':VocabularyControlType' => $this->Vocabulary ? $this->Vocabulary->getType() : null,
+ ':RestrictVocab' => $this->Vocabulary ? ($this->VocabularyRestriction ? '1' : '0') : '0',
+ ':id' => $this->id
+ );
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
- if ($this->renamed)
- {
- caption_field::rename_all_metadatas($this);
- $this->renamed = false;
+ if ($this->renamed) {
+ caption_field::rename_all_metadatas($this);
+ $this->renamed = false;
+ }
+
+ if ($this->metaToMerge) {
+ caption_field::merge_all_metadatas($this);
+ $this->metaToMerge = false;
+ }
+
+ $dom_struct = $this->databox->get_dom_structure();
+ $xp_struct = $this->databox->get_xpath_structure();
+
+ $nodes = $xp_struct->query(
+ '/record/description/*[@meta_id=' . $this->id . ']'
+ );
+
+ if ($nodes->length == 0) {
+ $meta = $dom_struct->createElement($this->name);
+ $nodes_parent = $xp_struct->query('/record/description');
+ $nodes_parent->item(0)->appendChild($meta);
+ } else {
+ $meta = $nodes->item(0);
+
+ $current_name = $meta->nodeName;
+ if ($this->name != $meta->nodeName) {
+ $old_meta = $meta;
+ $meta = $dom_struct->createElement($this->name);
+ $nodes_parent = $xp_struct->query('/record/description');
+ $nodes_parent->item(0)->replaceChild($meta, $old_meta);
+ }
+ }
+ $meta->setAttribute('src', $this->source->get_source());
+ $meta->setAttribute('index', $this->indexable ? '1' : '0');
+ $meta->setAttribute('readonly', $this->readonly ? '1' : '0');
+ $meta->setAttribute('required', $this->required ? '1' : '0');
+ $meta->setAttribute('multi', $this->multi ? '1' : '0');
+ $meta->setAttribute('report', $this->report ? '1' : '0');
+ $meta->setAttribute('type', $this->type);
+ $meta->setAttribute('tbranch', $this->tbranch);
+ if ($this->multi) {
+ $meta->setAttribute('separator', $this->separator);
+ }
+ $meta->setAttribute('thumbtitle', $this->thumbtitle);
+ $meta->setAttribute('meta_id', $this->id);
+
+ $this->delete_data_from_cache();
+ $this->databox->saveStructure($dom_struct);
+
+ return $this;
}
- if ($this->metaToMerge)
+ /**
+ *
+ * @param string $name
+ * @return databox_field
+ */
+ public function set_name($name)
{
- caption_field::merge_all_metadatas($this);
- $this->metaToMerge = false;
+ $previous_name = $this->name;
+
+ $name = self::generateName($name);
+
+ if ($name === '') {
+ throw new \Exception_InvalidArgument();
+ }
+
+ $this->name = $name;
+
+ if ($this->name !== $previous_name) {
+ $this->renamed = true;
+ }
+
+ return $this;
}
- $dom_struct = $this->databox->get_dom_structure();
- $xp_struct = $this->databox->get_xpath_structure();
-
- $nodes = $xp_struct->query(
- '/record/description/*[@meta_id=' . $this->id . ']'
- );
-
- if ($nodes->length == 0)
+ /**
+ *
+ * @param string $xpath
+ * @return metadata_Abstract
+ */
+ public static function load_class_from_xpath($xpath)
{
- $meta = $dom_struct->createElement($this->name);
- $nodes_parent = $xp_struct->query('/record/description');
- $nodes_parent->item(0)->appendChild($meta);
- }
- else
- {
- $meta = $nodes->item(0);
+ if (trim($xpath) === '')
+ $classname = 'metadata_description_nosource';
+ else
+ $classname = 'metadata_description_' . str_replace(
+ array('/rdf:RDF/rdf:Description/', ':', '-'), array('', '_', ''), $xpath
+ );
- $current_name = $meta->nodeName;
- if ($this->name != $meta->nodeName)
- {
- $old_meta = $meta;
- $meta = $dom_struct->createElement($this->name);
- $nodes_parent = $xp_struct->query('/record/description');
- $nodes_parent->item(0)->replaceChild($meta, $old_meta);
- }
- }
- $meta->setAttribute('src', $this->source->get_source());
- $meta->setAttribute('index', $this->indexable ? '1' : '0');
- $meta->setAttribute('readonly', $this->readonly ? '1' : '0');
- $meta->setAttribute('required', $this->required ? '1' : '0');
- $meta->setAttribute('multi', $this->multi ? '1' : '0');
- $meta->setAttribute('report', $this->report ? '1' : '0');
- $meta->setAttribute('type', $this->type);
- $meta->setAttribute('tbranch', $this->tbranch);
- if ($this->multi)
- {
- $meta->setAttribute('separator', $this->separator);
- }
- $meta->setAttribute('thumbtitle', $this->thumbtitle);
- $meta->setAttribute('meta_id', $this->id);
+ if ( ! class_exists($classname))
+ throw new Exception_Databox_metadataDescriptionNotFound();
- $this->delete_data_from_cache();
- $this->databox->saveStructure($dom_struct);
-
- return $this;
- }
-
- /**
- *
- * @param string $name
- * @return databox_field
- */
- public function set_name($name)
- {
- $previous_name = $this->name;
-
- $name = self::generateName($name);
-
- if($name === '')
- {
- throw new \Exception_InvalidArgument();
+ return new $classname();
}
- $this->name = $name;
-
- if ($this->name !== $previous_name)
+ /**
+ *
+ * @param string $source
+ * @return databox_field
+ */
+ public function set_source($source)
{
- $this->renamed = true;
+ $this->source = self::load_class_from_xpath($source);
+
+ return $this;
}
- return $this;
- }
+ /**
+ *
+ * @return metadata_Abstract
+ */
+ public function get_source()
+ {
+ return $this->source;
+ }
- /**
- *
- * @param string $xpath
- * @return metadata_Abstract
- */
- public static function load_class_from_xpath($xpath)
- {
- if (trim($xpath) === '')
- $classname = 'metadata_description_nosource';
- else
- $classname = 'metadata_description_' . str_replace(
- array('/rdf:RDF/rdf:Description/', ':', '-'), array('', '_', ''), $xpath
- );
+ /**
+ *
+ * @return databox_Field_DCESAbstract
+ */
+ public function get_dces_element()
+ {
+ return $this->dces_element;
+ }
- if (!class_exists($classname))
- throw new Exception_Databox_metadataDescriptionNotFound();
-
- return new $classname();
- }
-
- /**
- *
- * @param string $source
- * @return databox_field
- */
- public function set_source($source)
- {
- $this->source = self::load_class_from_xpath($source);
-
- return $this;
- }
-
- /**
- *
- * @return metadata_Abstract
- */
- public function get_source()
- {
- return $this->source;
- }
-
- /**
- *
- * @return databox_Field_DCESAbstract
- */
- public function get_dces_element()
- {
- return $this->dces_element;
- }
-
- public function set_dces_element(databox_Field_DCESAbstract $DCES_element = null)
- {
- $sql = 'UPDATE metadatas_structure
+ public function set_dces_element(databox_Field_DCESAbstract $DCES_element = null)
+ {
+ $sql = 'UPDATE metadatas_structure
SET dces_element = :dces_element WHERE id = :id';
- $connbas = $this->get_connection();
+ $connbas = $this->get_connection();
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(
- ':dces_element' => $DCES_element ? $DCES_element->get_label() : null
- , ':id' => $this->id
- ));
- $stmt->closeCursor();
- $this->dces_element = $DCES_element;
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(
+ ':dces_element' => $DCES_element ? $DCES_element->get_label() : null
+ , ':id' => $this->id
+ ));
+ $stmt->closeCursor();
+ $this->dces_element = $DCES_element;
- $this->delete_data_from_cache();
+ $this->delete_data_from_cache();
- return $this;
- }
-
- /**
- *
- * @param boolean $bool
- * @return databox_field
- */
- public function set_indexable($bool)
- {
- $this->indexable = !!$bool;
-
- return $this;
- }
-
- public function setVocabularyControl(Vocabulary\ControlProvider\ControlProviderInterface $vocabulary = null)
- {
- $this->Vocabulary = $vocabulary;
-
- return $this;
- }
-
- public function setVocabularyRestricted($boolean)
- {
- $this->VocabularyRestriction = !!$boolean;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $bool
- * @return databox_field
- */
- public function set_readonly($readonly)
- {
- $this->readonly = !!$readonly;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $boolean
- * @return databox_field
- */
- public function set_business($boolean)
- {
- $this->Business = !!$boolean;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $bool
- * @return databox_field
- */
- public function set_required($required)
- {
- $this->required = !!$required;
-
- return $this;
- }
-
- /**
- *
- * @param boolean $bool
- * @return databox_field
- */
- public function set_multi($multi)
- {
- $multi = !!$multi;
-
- if ($this->multi !== $multi && !$multi)
- {
- $this->metaToMerge = true;
+ return $this;
}
- $this->multi = $multi;
-
- $this->set_separator(';');
-
- return $this;
- }
-
- /**
- *
- * @param boolean $bool
- * @return databox_field
- */
- public function set_report($report)
- {
- $this->report = !!$report;
-
- return $this;
- }
-
- /**
- *
- * @param string $type
- * @return databox_field
- */
- public function set_type($type)
- {
- $this->type = $type;
-
- return $this;
- }
-
- /**
- *
- * @param string $type
- * @return databox_field
- */
- public function set_tbranch($branch)
- {
- $this->tbranch = $branch;
-
- return $this;
- }
-
- /**
- *
- * @param string $type
- * @return databox_field
- */
- public function set_separator($separator)
- {
- $this->separator = self::checkMultiSeparator($separator, $this->multi);
-
- return $this;
- }
-
- protected static function checkMultiSeparator($separator, $multi)
- {
- if (!$multi)
+ /**
+ *
+ * @param boolean $bool
+ * @return databox_field
+ */
+ public function set_indexable($bool)
{
- return '';
+ $this->indexable = ! ! $bool;
+
+ return $this;
}
- if (strpos($separator, ';') === false)
+ public function setVocabularyControl(Vocabulary\ControlProvider\ControlProviderInterface $vocabulary = null)
{
- $separator .= ';';
+ $this->Vocabulary = $vocabulary;
+
+ return $this;
}
- return $separator;
- }
+ public function setVocabularyRestricted($boolean)
+ {
+ $this->VocabularyRestriction = ! ! $boolean;
- /**
- *
- * @param string $type
- * @return databox_field
- */
- public function set_thumbtitle($value)
- {
- $this->thumbtitle = $value;
+ return $this;
+ }
- return $this;
- }
+ /**
+ *
+ * @param boolean $bool
+ * @return databox_field
+ */
+ public function set_readonly($readonly)
+ {
+ $this->readonly = ! ! $readonly;
- /**
- *
- * @return string
- */
- public function get_thumbtitle()
- {
- return $this->thumbtitle;
- }
+ return $this;
+ }
- /**
- *
- * @return integer
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @param boolean $boolean
+ * @return databox_field
+ */
+ public function set_business($boolean)
+ {
+ $this->Business = ! ! $boolean;
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return $this->type;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_tbranch()
- {
- return $this->tbranch;
- }
+ /**
+ *
+ * @param boolean $bool
+ * @return databox_field
+ */
+ public function set_required($required)
+ {
+ $this->required = ! ! $required;
- /**
- *
- * @return string
- */
- public function get_separator()
- {
- return $this->separator;
- }
+ return $this;
+ }
- /**
- *
- * @return boolean
- */
- public function is_indexable()
- {
- return $this->indexable;
- }
+ /**
+ *
+ * @param boolean $bool
+ * @return databox_field
+ */
+ public function set_multi($multi)
+ {
+ $multi = ! ! $multi;
- /**
- *
- * @return boolean
- */
- public function is_readonly()
- {
- return $this->readonly;
- }
+ if ($this->multi !== $multi && ! $multi) {
+ $this->metaToMerge = true;
+ }
- /**
- *
- * @return boolean
- */
- public function is_required()
- {
- return $this->required;
- }
+ $this->multi = $multi;
- /**
- *
- * @return boolean
- */
- public function is_multi()
- {
- return $this->multi;
- }
+ $this->set_separator(';');
- /**
- *
- * @return boolean
- */
- public function is_report()
- {
- return $this->report;
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
+ /**
+ *
+ * @param boolean $bool
+ * @return databox_field
+ */
+ public function set_report($report)
+ {
+ $this->report = ! ! $report;
- /**
- *
- * @return string
- */
- public function get_metadata_source()
- {
- return $this->source->get_source();
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_metadata_namespace()
- {
- return $this->source->get_namespace();
- }
+ /**
+ *
+ * @param string $type
+ * @return databox_field
+ */
+ public function set_type($type)
+ {
+ $this->type = $type;
- /**
- *
- * @return string
- */
- public function get_metadata_tagname()
- {
- return $this->source->get_tagname();
- }
+ return $this;
+ }
- /**
- * Return true is the field is unknown
- *
- * @return boolean
- */
- public function is_on_error()
- {
- return false;
- }
+ /**
+ *
+ * @param string $type
+ * @return databox_field
+ */
+ public function set_tbranch($branch)
+ {
+ $this->tbranch = $branch;
- public static function create(databox $databox, $name)
- {
- $sorter = 0;
+ return $this;
+ }
- $sql = 'SELECT (MAX(sorter) + 1) as sorter FROM metadatas_structure';
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ /**
+ *
+ * @param string $type
+ * @return databox_field
+ */
+ public function set_separator($separator)
+ {
+ $this->separator = self::checkMultiSeparator($separator, $this->multi);
- if ($row)
- $sorter = (int) $row['sorter'];
+ return $this;
+ }
- $sql = "INSERT INTO metadatas_structure
+ protected static function checkMultiSeparator($separator, $multi)
+ {
+ if ( ! $multi) {
+ return '';
+ }
+
+ if (strpos($separator, ';') === false) {
+ $separator .= ';';
+ }
+
+ return $separator;
+ }
+
+ /**
+ *
+ * @param string $type
+ * @return databox_field
+ */
+ public function set_thumbtitle($value)
+ {
+ $this->thumbtitle = $value;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_thumbtitle()
+ {
+ return $this->thumbtitle;
+ }
+
+ /**
+ *
+ * @return integer
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return $this->type;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_tbranch()
+ {
+ return $this->tbranch;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_separator()
+ {
+ return $this->separator;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_indexable()
+ {
+ return $this->indexable;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_readonly()
+ {
+ return $this->readonly;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_required()
+ {
+ return $this->required;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_multi()
+ {
+ return $this->multi;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_report()
+ {
+ return $this->report;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_metadata_source()
+ {
+ return $this->source->get_source();
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_metadata_namespace()
+ {
+ return $this->source->get_namespace();
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_metadata_tagname()
+ {
+ return $this->source->get_tagname();
+ }
+
+ /**
+ * Return true is the field is unknown
+ *
+ * @return boolean
+ */
+ public function is_on_error()
+ {
+ return false;
+ }
+
+ public static function create(databox $databox, $name)
+ {
+ $sorter = 0;
+
+ $sql = 'SELECT (MAX(sorter) + 1) as sorter FROM metadatas_structure';
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ($row)
+ $sorter = (int) $row['sorter'];
+
+ $sql = "INSERT INTO metadatas_structure
(`id`, `name`, `src`, `readonly`, `indexable`, `type`, `tbranch`,
`thumbtitle`, `multi`, `business`,
`report`, `sorter`)
@@ -832,105 +810,102 @@ class databox_field implements cache_cacheableInterface
null, 0,
0, 1, :sorter)";
- $name = self::generateName($name);
+ $name = self::generateName($name);
- if($name === '')
- {
- throw new \Exception_InvalidArgument();
+ if ($name === '') {
+ throw new \Exception_InvalidArgument();
+ }
+
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':name' => $name, ':sorter' => $sorter));
+ $id = $databox->get_connection()->lastInsertId();
+ $stmt->closeCursor();
+
+ $databox->delete_data_from_cache(databox::CACHE_META_STRUCT);
+
+ return self::get_instance($databox, $id);
}
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute(array(':name' => $name, ':sorter' => $sorter));
- $id = $databox->get_connection()->lastInsertId();
- $stmt->closeCursor();
-
- $databox->delete_data_from_cache(databox::CACHE_META_STRUCT);
-
- return self::get_instance($databox, $id);
- }
-
- public static function generateName($name)
- {
- $unicode_processor = new unicode();
-
- $name = $unicode_processor->remove_nonazAZ09($name, false, false);
-
- return $unicode_processor->remove_first_digits($name);
- }
-
- /**
- *
- * @return array
- */
- public function __sleep()
- {
- $vars = array();
- foreach ($this as $key => $value)
+ public static function generateName($name)
{
- if (in_array($key, array('databox')))
- continue;
- $vars[] = $key;
+ $unicode_processor = new unicode();
+
+ $name = $unicode_processor->remove_nonazAZ09($name, false, false);
+
+ return $unicode_processor->remove_first_digits($name);
}
- return $vars;
- }
+ /**
+ *
+ * @return array
+ */
+ public function __sleep()
+ {
+ $vars = array();
+ foreach ($this as $key => $value) {
+ if (in_array($key, array('databox')))
+ continue;
+ $vars[] = $key;
+ }
- /**
- *
- * @return void
- */
- public function __wakeup()
- {
- $databox = databox::get_instance($this->sbas_id);
- $this->set_databox($databox);
+ return $vars;
+ }
- return;
- }
+ /**
+ *
+ * @return void
+ */
+ public function __wakeup()
+ {
+ $databox = databox::get_instance($this->sbas_id);
+ $this->set_databox($databox);
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return string
- */
- public function get_cache_key($option = null)
- {
- return 'field_' . $this->get_id() . ($option ? $option . '_' : '');
- }
+ return;
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return mixed
- */
- public function get_data_from_cache($option = null)
- {
- return $this->databox->get_data_from_cache($this->get_cache_key($option));
- }
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param string $option
+ * @return string
+ */
+ public function get_cache_key($option = null)
+ {
+ return 'field_' . $this->get_id() . ($option ? $option . '_' : '');
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param mixed $value
- * @param string $option
- * @param int $duration
- * @return caption_field
- */
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param string $option
+ * @return mixed
+ */
+ public function get_data_from_cache($option = null)
+ {
+ return $this->databox->get_data_from_cache($this->get_cache_key($option));
+ }
- /**
- * Part of the cache_cacheableInterface
- *
- * @param string $option
- * @return caption_field
- */
- public function delete_data_from_cache($option = null)
- {
- return $this->databox->delete_data_from_cache($this->get_cache_key($option));
- }
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param mixed $value
+ * @param string $option
+ * @param int $duration
+ * @return caption_field
+ */
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+ /**
+ * Part of the cache_cacheableInterface
+ *
+ * @param string $option
+ * @return caption_field
+ */
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->databox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/databox/fieldUnknown.class.php b/lib/classes/databox/fieldUnknown.class.php
index b410c9b7d9..df74b914ce 100644
--- a/lib/classes/databox/fieldUnknown.class.php
+++ b/lib/classes/databox/fieldUnknown.class.php
@@ -18,78 +18,73 @@
class databox_fieldUnknown extends databox_field
{
- /**
- *
- * @param databox $databox
- * @param int $id
- * @return databox_fieldUnknown
- */
- public function __construct(databox $databox, $id)
- {
- $this->set_databox($databox);
- $this->sbas_id = $databox->get_sbas_id();
- $this->id = $id;
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @param int $id
- * @return databox_fieldUnknown
- */
- public static function get_instance(databox &$databox, $id)
- {
- $cache_key = 'field_' . $id;
- $instance_id = $databox->get_sbas_id() . '_' . $id;
- if (!isset(self::$_instance[$instance_id]) || (self::$_instance[$instance_id] instanceof self) === false)
+ /**
+ *
+ * @param databox $databox
+ * @param int $id
+ * @return databox_fieldUnknown
+ */
+ public function __construct(databox $databox, $id)
{
- try
- {
- self::$_instance[$instance_id] = $databox->get_data_from_cache($cache_key);
- }
- catch (Exception $e)
- {
- self::$_instance[$instance_id] = new self($databox, $id);
- $databox->set_data_to_cache(self::$_instance[$instance_id], $cache_key);
- }
+ $this->set_databox($databox);
+ $this->sbas_id = $databox->get_sbas_id();
+ $this->id = $id;
+
+ return $this;
}
- return self::$_instance[$instance_id];
- }
+ /**
+ *
+ * @param databox $databox
+ * @param int $id
+ * @return databox_fieldUnknown
+ */
+ public static function get_instance(databox &$databox, $id)
+ {
+ $cache_key = 'field_' . $id;
+ $instance_id = $databox->get_sbas_id() . '_' . $id;
+ if ( ! isset(self::$_instance[$instance_id]) || (self::$_instance[$instance_id] instanceof self) === false) {
+ try {
+ self::$_instance[$instance_id] = $databox->get_data_from_cache($cache_key);
+ } catch (Exception $e) {
+ self::$_instance[$instance_id] = new self($databox, $id);
+ $databox->set_data_to_cache(self::$_instance[$instance_id], $cache_key);
+ }
+ }
- /**
- *
- * @return string
- */
- public function get_metadata_source()
- {
- return '';
- }
+ return self::$_instance[$instance_id];
+ }
- public function get_metadata_namespace()
- {
- return '';
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_metadata_source()
+ {
+ return '';
+ }
- /**
- *
- * @return string
- */
- public function get_metadata_tagname()
- {
- return '';
- }
+ public function get_metadata_namespace()
+ {
+ return '';
+ }
- /**
- * Return true because the field is unknown
- *
- * @return boolean
- */
- public function is_on_error()
- {
- return true;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_metadata_tagname()
+ {
+ return '';
+ }
+ /**
+ * Return true because the field is unknown
+ *
+ * @return boolean
+ */
+ public function is_on_error()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/databox/status.class.php b/lib/classes/databox/status.class.php
index c78dd9df2b..3dcfb72f43 100644
--- a/lib/classes/databox/status.class.php
+++ b/lib/classes/databox/status.class.php
@@ -17,623 +17,559 @@
*/
class databox_status
{
+ /**
+ *
+ * @var Array
+ */
+ private static $_status = array();
- /**
- *
- * @var Array
- */
- private static $_status = array();
+ /**
+ *
+ * @var Array
+ */
+ protected static $_statuses;
- /**
- *
- * @var Array
- */
- protected static $_statuses;
+ /**
+ *
+ * @var Array
+ */
+ private $status = array();
- /**
- *
- * @var Array
- */
- private $status = array();
+ /**
+ *
+ * @var string
+ */
+ private $path = '';
- /**
- *
- * @var string
- */
- private $path = '';
+ /**
+ *
+ * @var string
+ */
+ private $url = '';
- /**
- *
- * @var string
- */
- private $url = '';
-
- /**
- *
- * @param int $sbas_id
- * @return status
- */
- private function __construct($sbas_id)
- {
-
- $this->status = array();
-
- $path = $url = false;
-
- $sbas_params = phrasea::sbas_params();
- $registry = registry::get_instance();
-
- if (!isset($sbas_params[$sbas_id]))
-
- return;
-
- $path = $this->path = $registry->get('GV_RootPath') . "config/status/" . urlencode($sbas_params[$sbas_id]["host"]) . "-" . urlencode($sbas_params[$sbas_id]["port"]) . "-" . urlencode($sbas_params[$sbas_id]["dbname"]);
- $url = $this->url = "/custom/status/" . urlencode($sbas_params[$sbas_id]["host"]) . "-" . urlencode($sbas_params[$sbas_id]["port"]) . "-" . urlencode($sbas_params[$sbas_id]["dbname"]);
-
- $databox = databox::get_instance((int) $sbas_id);
- $xmlpref = $databox->get_structure();
- $sxe = simplexml_load_string($xmlpref);
-
- if ($sxe)
+ /**
+ *
+ * @param int $sbas_id
+ * @return status
+ */
+ private function __construct($sbas_id)
{
- foreach ($sxe->statbits->bit as $sb)
- {
- $bit = (int) ($sb["n"]);
- if ($bit < 4 && $bit > 63)
- continue;
+ $this->status = array();
- $this->status[$bit]["name"] = (string) ($sb);
- $this->status[$bit]["labeloff"] = (string) $sb['labelOff'];
- $this->status[$bit]["labelon"] = (string) $sb['labelOn'];
+ $path = $url = false;
- $this->status[$bit]["img_off"] = false;
- $this->status[$bit]["img_on"] = false;
+ $sbas_params = phrasea::sbas_params();
+ $registry = registry::get_instance();
- if (is_file($path . "-stat_" . $bit . "_0.gif"))
- {
- $this->status[$bit]["img_off"] = $url . "-stat_" . $bit . "_0.gif";
- $this->status[$bit]["path_off"] = $path . "-stat_" . $bit . "_0.gif";
- }
- if (is_file($path . "-stat_" . $bit . "_1.gif"))
- {
- $this->status[$bit]["img_on"] = $url . "-stat_" . $bit . "_1.gif";
- $this->status[$bit]["path_on"] = $path . "-stat_" . $bit . "_1.gif";
- }
+ if ( ! isset($sbas_params[$sbas_id]))
+ return;
- $this->status[$bit]["searchable"] = isset($sb['searchable']) ? (int) $sb['searchable'] : 0;
- $this->status[$bit]["printable"] = isset($sb['printable']) ? (int) $sb['printable'] : 0;
- }
- }
- ksort($this->status);
+ $path = $this->path = $registry->get('GV_RootPath') . "config/status/" . urlencode($sbas_params[$sbas_id]["host"]) . "-" . urlencode($sbas_params[$sbas_id]["port"]) . "-" . urlencode($sbas_params[$sbas_id]["dbname"]);
+ $url = $this->url = "/custom/status/" . urlencode($sbas_params[$sbas_id]["host"]) . "-" . urlencode($sbas_params[$sbas_id]["port"]) . "-" . urlencode($sbas_params[$sbas_id]["dbname"]);
- return $this;
- }
+ $databox = databox::get_instance((int) $sbas_id);
+ $xmlpref = $databox->get_structure();
+ $sxe = simplexml_load_string($xmlpref);
- public static function getStatus($sbas_id)
- {
+ if ($sxe) {
- if (!isset(self::$_status[$sbas_id]))
- self::$_status[$sbas_id] = new databox_status($sbas_id);
+ foreach ($sxe->statbits->bit as $sb) {
+ $bit = (int) ($sb["n"]);
+ if ($bit < 4 && $bit > 63)
+ continue;
- return self::$_status[$sbas_id]->status;
- }
+ $this->status[$bit]["name"] = (string) ($sb);
+ $this->status[$bit]["labeloff"] = (string) $sb['labelOff'];
+ $this->status[$bit]["labelon"] = (string) $sb['labelOn'];
- public static function getDisplayStatus()
- {
- if (self::$_statuses)
+ $this->status[$bit]["img_off"] = false;
+ $this->status[$bit]["img_on"] = false;
- return self::$_statuses;
+ if (is_file($path . "-stat_" . $bit . "_0.gif")) {
+ $this->status[$bit]["img_off"] = $url . "-stat_" . $bit . "_0.gif";
+ $this->status[$bit]["path_off"] = $path . "-stat_" . $bit . "_0.gif";
+ }
+ if (is_file($path . "-stat_" . $bit . "_1.gif")) {
+ $this->status[$bit]["img_on"] = $url . "-stat_" . $bit . "_1.gif";
+ $this->status[$bit]["path_on"] = $path . "-stat_" . $bit . "_1.gif";
+ }
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- $sbas_ids = $user->ACL()->get_granted_sbas();
-
- $statuses = array();
-
- foreach ($sbas_ids as $databox)
- {
- try
- {
- $statuses[$databox->get_sbas_id()] = $databox->get_statusbits();
- }
- catch (Exception $e)
- {
-
- }
- }
-
- self::$_statuses = $statuses;
-
- return self::$_statuses;
- }
-
- public static function getSearchStatus()
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- $statuses = array();
-
- $sbas_ids = $user->ACL()->get_granted_sbas();
-
- $see_all = array();
-
- foreach ($sbas_ids as $databox)
- {
- $see_all[$databox->get_sbas_id()] = false;
-
- foreach($databox->get_collections() as $collection)
- {
- if($user->ACL()->has_right_on_base($collection->get_base_id(), 'chgstatus'))
- {
- $see_all[$databox->get_sbas_id()] = true;
- break;
- }
- }
- try
- {
- $statuses[$databox->get_sbas_id()] = $databox->get_statusbits();
- }
- catch (Exception $e)
- {
-
- }
- }
-
- $stats = array();
-
- foreach ($statuses as $sbas_id => $status)
- {
-
- $see_this = isset($see_all[$sbas_id]) ? $see_all[$sbas_id] : false;
-
- if ($user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
- $see_this = true;
-
- foreach ($status as $bit => $props)
- {
-
- if ($props['searchable'] == 0 && !$see_this)
- continue;
-
- $set = false;
- if (isset($stats[$bit]))
- {
- foreach ($stats[$bit] as $k => $s_desc)
- {
- if (mb_strtolower($s_desc['labelon']) == mb_strtolower($props['labelon'])
- && mb_strtolower($s_desc['labeloff']) == mb_strtolower($props['labeloff']))
- {
- $stats[$bit][$k]['sbas'][] = $sbas_id;
- $set = true;
+ $this->status[$bit]["searchable"] = isset($sb['searchable']) ? (int) $sb['searchable'] : 0;
+ $this->status[$bit]["printable"] = isset($sb['printable']) ? (int) $sb['printable'] : 0;
}
- }
- if (!$set)
- {
- $stats[$bit][] = array(
- 'sbas' => array($sbas_id),
- 'labeloff' => $props['labeloff'],
- 'labelon' => $props['labelon'],
- 'imgoff' => $props['img_off'],
- 'imgon' => $props['img_on']
- );
- $set = true;
- }
}
+ ksort($this->status);
- if (!$set)
- {
- $stats[$bit] = array(
- array(
- 'sbas' => array($sbas_id),
- 'labeloff' => $props['labeloff'],
- 'labelon' => $props['labelon'],
- 'imgoff' => $props['img_off'],
- 'imgon' => $props['img_on']
- )
- );
- }
- }
+ return $this;
}
- return $stats;
- }
-
- public static function getPath($sbas_id)
- {
-
- if (!isset(self::$_status[$sbas_id]))
- self::$_status[$sbas_id] = new databox_status($sbas_id);
-
- return self::$_status[$sbas_id]->path;
- }
-
- public static function getUrl($sbas_id)
- {
-
- if (!isset(self::$_status[$sbas_id]))
- self::$_status[$sbas_id] = new databox_status($sbas_id);
-
- return self::$_status[$sbas_id]->url;
- }
-
- public static function deleteStatus($sbas_id, $bit)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
-
- return false;
-
- $status = self::getStatus($sbas_id);
-
- if (isset($status[$bit]))
+ public static function getStatus($sbas_id)
{
- $connbas = connection::getPDOConnection($sbas_id);
- $databox = databox::get_instance((int) $sbas_id);
+ if ( ! isset(self::$_status[$sbas_id]))
+ self::$_status[$sbas_id] = new databox_status($sbas_id);
- $doc = $databox->get_dom_structure();
- if ($doc)
- {
- $xpath = $databox->get_xpath_structure();
- $entries = $xpath->query($q = "/record/statbits/bit[@n=" . $bit . "]");
+ return self::$_status[$sbas_id]->status;
+ }
- foreach ($entries as $sbit)
- {
- if ($p = $sbit->previousSibling)
- {
- if ($p->nodeType == XML_TEXT_NODE && $p->nodeValue == "\n\t\t")
- $p->parentNode->removeChild($p);
- }
- if ($sbit->parentNode->removeChild($sbit))
- {
- $sql = 'UPDATE record SET status = status&(~(1<<' . $bit . '))';
- $stmt = $connbas->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
- }
+ public static function getDisplayStatus()
+ {
+ if (self::$_statuses)
+ return self::$_statuses;
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ $sbas_ids = $user->ACL()->get_granted_sbas();
+
+ $statuses = array();
+
+ foreach ($sbas_ids as $databox) {
+ try {
+ $statuses[$databox->get_sbas_id()] = $databox->get_statusbits();
+ } catch (Exception $e) {
+
+ }
}
- $databox->saveStructure($doc);
+ self::$_statuses = $statuses;
- if (self::$_status[$sbas_id]->status[$bit]['img_off'])
- {
- unlink(self::$_status[$sbas_id]->status[$bit]['path_off']);
- }
- if (self::$_status[$sbas_id]->status[$bit]['img_on'])
- {
- unlink(self::$_status[$sbas_id]->status[$bit]['path_on']);
+ return self::$_statuses;
+ }
+
+ public static function getSearchStatus()
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ $statuses = array();
+
+ $sbas_ids = $user->ACL()->get_granted_sbas();
+
+ $see_all = array();
+
+ foreach ($sbas_ids as $databox) {
+ $see_all[$databox->get_sbas_id()] = false;
+
+ foreach ($databox->get_collections() as $collection) {
+ if ($user->ACL()->has_right_on_base($collection->get_base_id(), 'chgstatus')) {
+ $see_all[$databox->get_sbas_id()] = true;
+ break;
+ }
+ }
+ try {
+ $statuses[$databox->get_sbas_id()] = $databox->get_statusbits();
+ } catch (Exception $e) {
+
+ }
}
- unset(self::$_status[$sbas_id]->status[$bit]);
+ $stats = array();
+
+ foreach ($statuses as $sbas_id => $status) {
+
+ $see_this = isset($see_all[$sbas_id]) ? $see_all[$sbas_id] : false;
+
+ if ($user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
+ $see_this = true;
+
+ foreach ($status as $bit => $props) {
+
+ if ($props['searchable'] == 0 && ! $see_this)
+ continue;
+
+ $set = false;
+ if (isset($stats[$bit])) {
+ foreach ($stats[$bit] as $k => $s_desc) {
+ if (mb_strtolower($s_desc['labelon']) == mb_strtolower($props['labelon'])
+ && mb_strtolower($s_desc['labeloff']) == mb_strtolower($props['labeloff'])) {
+ $stats[$bit][$k]['sbas'][] = $sbas_id;
+ $set = true;
+ }
+ }
+ if ( ! $set) {
+ $stats[$bit][] = array(
+ 'sbas' => array($sbas_id),
+ 'labeloff' => $props['labeloff'],
+ 'labelon' => $props['labelon'],
+ 'imgoff' => $props['img_off'],
+ 'imgon' => $props['img_on']
+ );
+ $set = true;
+ }
+ }
+
+ if ( ! $set) {
+ $stats[$bit] = array(
+ array(
+ 'sbas' => array($sbas_id),
+ 'labeloff' => $props['labeloff'],
+ 'labelon' => $props['labelon'],
+ 'imgoff' => $props['img_off'],
+ 'imgon' => $props['img_on']
+ )
+ );
+ }
+ }
+ }
+
+ return $stats;
+ }
+
+ public static function getPath($sbas_id)
+ {
+
+ if ( ! isset(self::$_status[$sbas_id]))
+ self::$_status[$sbas_id] = new databox_status($sbas_id);
+
+ return self::$_status[$sbas_id]->path;
+ }
+
+ public static function getUrl($sbas_id)
+ {
+
+ if ( ! isset(self::$_status[$sbas_id]))
+ self::$_status[$sbas_id] = new databox_status($sbas_id);
+
+ return self::$_status[$sbas_id]->url;
+ }
+
+ public static function deleteStatus($sbas_id, $bit)
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
+ return false;
+
+ $status = self::getStatus($sbas_id);
+
+ if (isset($status[$bit])) {
+ $connbas = connection::getPDOConnection($sbas_id);
+
+ $databox = databox::get_instance((int) $sbas_id);
+
+ $doc = $databox->get_dom_structure();
+ if ($doc) {
+ $xpath = $databox->get_xpath_structure();
+ $entries = $xpath->query($q = "/record/statbits/bit[@n=" . $bit . "]");
+
+ foreach ($entries as $sbit) {
+ if ($p = $sbit->previousSibling) {
+ if ($p->nodeType == XML_TEXT_NODE && $p->nodeValue == "\n\t\t")
+ $p->parentNode->removeChild($p);
+ }
+ if ($sbit->parentNode->removeChild($sbit)) {
+ $sql = 'UPDATE record SET status = status&(~(1<<' . $bit . '))';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+ }
+ }
+
+ $databox->saveStructure($doc);
+
+ if (self::$_status[$sbas_id]->status[$bit]['img_off']) {
+ unlink(self::$_status[$sbas_id]->status[$bit]['path_off']);
+ }
+ if (self::$_status[$sbas_id]->status[$bit]['img_on']) {
+ unlink(self::$_status[$sbas_id]->status[$bit]['path_on']);
+ }
+
+ unset(self::$_status[$sbas_id]->status[$bit]);
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public static function updateStatus($sbas_id, $bit, $properties)
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
+ return false;
+
+ $status = self::getStatus($sbas_id);
+
+ $databox = $appbox->get_databox((int) $sbas_id);
+
+ $doc = $databox->get_dom_structure($sbas_id);
+ if ($doc) {
+ $xpath = $databox->get_xpath_structure($sbas_id);
+ $entries = $xpath->query("/record/statbits");
+ if ($entries->length == 0) {
+ $statbits = $doc->documentElement->appendChild($doc->createElement("statbits"));
+ } else {
+ $statbits = $entries->item(0);
+ }
+
+ if ($statbits) {
+ $entries = $xpath->query("/record/statbits/bit[@n=" . $bit . "]");
+
+ if ($entries->length >= 1) {
+ foreach ($entries as $k => $sbit) {
+ if ($p = $sbit->previousSibling) {
+ if ($p->nodeType == XML_TEXT_NODE && $p->nodeValue == "\n\t\t")
+ $p->parentNode->removeChild($p);
+ }
+ $sbit->parentNode->removeChild($sbit);
+ }
+ }
+
+ $sbit = $statbits->appendChild($doc->createElement("bit"));
+
+ if ($n = $sbit->appendChild($doc->createAttribute("n"))) {
+ $n->value = $bit;
+ $sbit->appendChild($doc->createTextNode($properties['name']));
+ }
+
+ if ($labOn = $sbit->appendChild($doc->createAttribute("labelOn"))) {
+ $labOn->value = $properties['labelon'];
+ }
+
+ if ($searchable = $sbit->appendChild($doc->createAttribute("searchable"))) {
+ $searchable->value = $properties['searchable'];
+ }
+
+ if ($printable = $sbit->appendChild($doc->createAttribute("printable"))) {
+ $printable->value = $properties['printable'];
+ }
+
+ if ($labOff = $sbit->appendChild($doc->createAttribute("labelOff"))) {
+ $labOff->value = $properties['labeloff'];
+ }
+ }
+
+ $databox->saveStructure($doc);
+
+ self::$_status[$sbas_id]->status[$bit]["name"] = $properties['name'];
+ self::$_status[$sbas_id]->status[$bit]["labelon"] = $properties['labelon'];
+ self::$_status[$sbas_id]->status[$bit]["labeloff"] = $properties['labeloff'];
+ self::$_status[$sbas_id]->status[$bit]["searchable"] = (int) $properties['searchable'];
+ self::$_status[$sbas_id]->status[$bit]["printable"] = (int) $properties['printable'];
+
+ if ( ! isset(self::$_status[$sbas_id]->status[$bit]['img_on']))
+ self::$_status[$sbas_id]->status[$bit]['img_on'] = false;
+ if ( ! isset(self::$_status[$sbas_id]->status[$bit]['img_off']))
+ self::$_status[$sbas_id]->status[$bit]['img_off'] = false;
+ }
+
+ return false;
+ }
+
+ public static function deleteIcon($sbas_id, $bit, $switch)
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
+ return false;
+
+ $status = self::getStatus($sbas_id);
+
+ $switch = in_array($switch, array('on', 'off')) ? $switch : false;
+
+ if ( ! $switch)
+ return false;
+
+ if ($status[$bit]['img_' . $switch]) {
+ if (isset($status[$bit]['path_' . $switch]))
+ unlink($status[$bit]['path_' . $switch]);
+
+ $status[$bit]['img_' . $switch] = false;
+ unset($status[$bit]['path_' . $switch]);
+ }
return true;
- }
}
- return false;
- }
-
- public static function updateStatus($sbas_id, $bit, $properties)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
-
- return false;
-
- $status = self::getStatus($sbas_id);
-
- $databox = $appbox->get_databox((int) $sbas_id);
-
- $doc = $databox->get_dom_structure($sbas_id);
- if ($doc)
+ public static function updateIcon($sbas_id, $bit, $switch, $file)
{
- $xpath = $databox->get_xpath_structure($sbas_id);
- $entries = $xpath->query("/record/statbits");
- if ($entries->length == 0)
- {
- $statbits = $doc->documentElement->appendChild($doc->createElement("statbits"));
- }
- else
- {
- $statbits = $entries->item(0);
- }
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- if ($statbits)
- {
- $entries = $xpath->query("/record/statbits/bit[@n=" . $bit . "]");
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
- if ($entries->length >= 1)
- {
- foreach ($entries as $k => $sbit)
- {
- if ($p = $sbit->previousSibling)
- {
- if ($p->nodeType == XML_TEXT_NODE && $p->nodeValue == "\n\t\t")
- $p->parentNode->removeChild($p);
- }
- $sbit->parentNode->removeChild($sbit);
- }
+ $registry = registry::get_instance();
+
+ if ( ! $user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
+ throw new Exception_Forbidden();
+
+ $switch = in_array($switch, array('on', 'off')) ? $switch : false;
+
+ if ( ! $switch)
+ throw new Exception_InvalidArgument();
+
+ $status = self::getStatus($sbas_id);
+ $url = self::getUrl($sbas_id);
+ $path = self::getPath($sbas_id);
+ if ($file['size'] >= 65535)
+ throw new Exception_Upload_FileTooBig();
+
+ if ($file['error'] !== UPLOAD_ERR_OK)
+ throw new Exception_Upload_Error();
+
+ self::deleteIcon($sbas_id, $bit, $switch);
+ $name = "-stat_" . $bit . "_" . ($switch == 'on' ? '1' : '0') . ".gif";
+
+ if ( ! move_uploaded_file($file["tmp_name"], $path . $name))
+ throw new Exception_Upload_CannotWriteFile();
+
+ $custom_path = $registry->get('GV_RootPath') . 'www/custom/status/';
+
+ if ( ! is_dir($custom_path))
+ system_file::mkdir($custom_path);
+
+ copy($path . $name, $custom_path . basename($path . $name));
+ self::$_status[$sbas_id]->status[$bit]['img_' . $switch] = $url . $name;
+ self::$_status[$sbas_id]->status[$bit]['path_' . $switch] = $path . $name;
+
+ return true;
+ }
+
+ public static function operation_and($stat1, $stat2)
+ {
+ $conn = connection::getPDOConnection();
+
+ $status = '0';
+
+ if (substr($stat1, 0, 2) === '0x') {
+ $stat1 = self::hex2bin(substr($stat1, 2));
+ }
+ if (substr($stat2, 0, 2) === '0x') {
+ $stat2 = self::hex2bin(substr($stat2, 2));
}
- $sbit = $statbits->appendChild($doc->createElement("bit"));
+ $sql = 'select bin(0b' . trim($stat1) . ' & 0b' . trim($stat2) . ') as result';
- if ($n = $sbit->appendChild($doc->createAttribute("n")))
- {
- $n->value = $bit;
- $sbit->appendChild($doc->createTextNode($properties['name']));
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ($row) {
+ $status = $row['result'];
}
- if ($labOn = $sbit->appendChild($doc->createAttribute("labelOn")))
- {
- $labOn->value = $properties['labelon'];
+ return $status;
+ }
+
+ public static function operation_and_not($stat1, $stat2)
+ {
+ $conn = connection::getPDOConnection();
+
+ $status = '0';
+
+ if (substr($stat1, 0, 2) === '0x') {
+ $stat1 = self::hex2bin(substr($stat1, 2));
+ }
+ if (substr($stat2, 0, 2) === '0x') {
+ $stat2 = self::hex2bin(substr($stat2, 2));
}
- if ($searchable = $sbit->appendChild($doc->createAttribute("searchable")))
- {
- $searchable->value = $properties['searchable'];
+ $sql = 'select bin(0b' . trim($stat1) . ' & ~0b' . trim($stat2) . ') as result';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ($row) {
+ $status = $row['result'];
}
- if ($printable = $sbit->appendChild($doc->createAttribute("printable")))
- {
- $printable->value = $properties['printable'];
+ return $status;
+ }
+
+ public static function operation_or($stat1, $stat2)
+ {
+ $conn = connection::getPDOConnection();
+
+ $status = '0';
+
+ if (substr($stat1, 0, 2) === '0x') {
+ $stat1 = self::hex2bin(substr($stat1, 2));
+ }
+ if (substr($stat2, 0, 2) === '0x') {
+ $stat2 = self::hex2bin(substr($stat2, 2));
}
- if ($labOff = $sbit->appendChild($doc->createAttribute("labelOff")))
- {
- $labOff->value = $properties['labeloff'];
+ $sql = 'select bin(0b' . trim($stat1) . ' | 0b' . trim($stat2) . ') as result';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ if ($row) {
+ $status = $row['result'];
}
- }
- $databox->saveStructure($doc);
-
- self::$_status[$sbas_id]->status[$bit]["name"] = $properties['name'];
- self::$_status[$sbas_id]->status[$bit]["labelon"] = $properties['labelon'];
- self::$_status[$sbas_id]->status[$bit]["labeloff"] = $properties['labeloff'];
- self::$_status[$sbas_id]->status[$bit]["searchable"] = (int) $properties['searchable'];
- self::$_status[$sbas_id]->status[$bit]["printable"] = (int) $properties['printable'];
-
- if (!isset(self::$_status[$sbas_id]->status[$bit]['img_on']))
- self::$_status[$sbas_id]->status[$bit]['img_on'] = false;
- if (!isset(self::$_status[$sbas_id]->status[$bit]['img_off']))
- self::$_status[$sbas_id]->status[$bit]['img_off'] = false;
+ return $status;
}
- return false;
- }
-
- public static function deleteIcon($sbas_id, $bit, $switch)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
-
- return false;
-
- $status = self::getStatus($sbas_id);
-
- $switch = in_array($switch, array('on', 'off')) ? $switch : false;
-
- if (!$switch)
-
- return false;
-
- if ($status[$bit]['img_' . $switch])
+ public static function dec2bin($status)
{
- if (isset($status[$bit]['path_' . $switch]))
- unlink($status[$bit]['path_' . $switch]);
+ $status = (string) $status;
- $status[$bit]['img_' . $switch] = false;
- unset($status[$bit]['path_' . $switch]);
+ if ( ! ctype_digit($status)) {
+ throw new \Exception('Non-decimal value');
+ }
+
+ $conn = connection::getPDOConnection();
+
+ $sql = 'select bin(' . $status . ') as result';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $status = '0';
+
+ if ($row) {
+ $status = $row['result'];
+ }
+
+ return $status;
}
- return true;
- }
-
- public static function updateIcon($sbas_id, $bit, $switch, $file)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- $registry = registry::get_instance();
-
- if (!$user->ACL()->has_right_on_sbas($sbas_id, 'bas_modify_struct'))
- throw new Exception_Forbidden();
-
- $switch = in_array($switch, array('on', 'off')) ? $switch : false;
-
- if (!$switch)
- throw new Exception_InvalidArgument();
-
- $status = self::getStatus($sbas_id);
- $url = self::getUrl($sbas_id);
- $path = self::getPath($sbas_id);
- if ($file['size'] >= 65535)
- throw new Exception_Upload_FileTooBig();
-
- if ($file['error'] !== UPLOAD_ERR_OK)
- throw new Exception_Upload_Error();
-
- self::deleteIcon($sbas_id, $bit, $switch);
- $name = "-stat_" . $bit . "_" . ($switch == 'on' ? '1' : '0') . ".gif";
-
- if (!move_uploaded_file($file["tmp_name"], $path . $name))
- throw new Exception_Upload_CannotWriteFile();
-
- $custom_path = $registry->get('GV_RootPath') . 'www/custom/status/';
-
- if (!is_dir($custom_path))
- system_file::mkdir($custom_path);
-
- copy($path . $name, $custom_path . basename($path . $name));
- self::$_status[$sbas_id]->status[$bit]['img_' . $switch] = $url . $name;
- self::$_status[$sbas_id]->status[$bit]['path_' . $switch] = $path . $name;
-
- return true;
- }
-
- public static function operation_and($stat1, $stat2)
- {
- $conn = connection::getPDOConnection();
-
- $status = '0';
-
- if(substr($stat1, 0, 2) === '0x')
+ public static function hex2bin($status)
{
- $stat1 = self::hex2bin(substr($stat1, 2));
+ $status = (string) $status;
+ if (substr($status, 0, 2) === '0x') {
+ $status = substr($status, 2);
+ }
+
+ if ( ! ctype_xdigit($status)) {
+ throw new \Exception('Non-hexadecimal value');
+ }
+
+ $conn = connection::getPDOConnection();
+
+ $sql = 'select BIN( CAST( 0x' . trim($status) . ' AS UNSIGNED ) ) as result';
+
+ $stmt = $conn->prepare($sql);
+ $stmt->execute();
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $status = '0';
+
+ if ($row) {
+ $status = $row['result'];
+ }
+
+ return $status;
}
- if(substr($stat2, 0, 2) === '0x')
- {
- $stat2 = self::hex2bin(substr($stat2, 2));
- }
-
- $sql = 'select bin(0b' . trim($stat1) . ' & 0b' . trim($stat2) . ') as result';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if ($row)
- {
- $status = $row['result'];
- }
-
- return $status;
- }
-
- public static function operation_and_not($stat1, $stat2)
- {
- $conn = connection::getPDOConnection();
-
- $status = '0';
-
- if(substr($stat1, 0, 2) === '0x')
- {
- $stat1 = self::hex2bin(substr($stat1, 2));
- }
- if(substr($stat2, 0, 2) === '0x')
- {
- $stat2 = self::hex2bin(substr($stat2, 2));
- }
-
- $sql = 'select bin(0b' . trim($stat1) . ' & ~0b' . trim($stat2) . ') as result';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if ($row)
- {
- $status = $row['result'];
- }
-
- return $status;
- }
-
- public static function operation_or($stat1, $stat2)
- {
- $conn = connection::getPDOConnection();
-
- $status = '0';
-
- if(substr($stat1, 0, 2) === '0x')
- {
- $stat1 = self::hex2bin(substr($stat1, 2));
- }
- if(substr($stat2, 0, 2) === '0x')
- {
- $stat2 = self::hex2bin(substr($stat2, 2));
- }
-
- $sql = 'select bin(0b' . trim($stat1) . ' | 0b' . trim($stat2) . ') as result';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if ($row)
- {
- $status = $row['result'];
- }
-
- return $status;
- }
-
- public static function dec2bin($status)
- {
- $status = (string) $status;
-
- if(!ctype_digit($status))
- {
- throw new \Exception('Non-decimal value');
- }
-
- $conn = connection::getPDOConnection();
-
- $sql = 'select bin(' . $status . ') as result';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $status = '0';
-
- if ($row)
- {
- $status = $row['result'];
- }
-
- return $status;
- }
-
- public static function hex2bin($status)
- {
- $status = (string) $status;
- if(substr($status, 0, 2) === '0x')
- {
- $status = substr($status, 2);
- }
-
- if(!ctype_xdigit($status))
- {
- throw new \Exception('Non-hexadecimal value');
- }
-
- $conn = connection::getPDOConnection();
-
- $sql = 'select BIN( CAST( 0x'.trim($status).' AS UNSIGNED ) ) as result';
-
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $status = '0';
-
- if ($row)
- {
- $status = $row['result'];
- }
-
- return $status;
- }
-
}
diff --git a/lib/classes/databox/subdef.class.php b/lib/classes/databox/subdef.class.php
index adaafd3b72..daeef496e5 100644
--- a/lib/classes/databox/subdef.class.php
+++ b/lib/classes/databox/subdef.class.php
@@ -26,7 +26,6 @@ use Alchemy\Phrasea\Media\Type\Type as SubdefType;
*/
class databox_subdef
{
-
/**
* The class type of the subdef
* Is null or one of the CLASS_* constants
@@ -42,16 +41,16 @@ class databox_subdef
protected $write_meta;
protected $downloadable;
protected static $mediaTypeToSubdefTypes = array(
- SubdefType::TYPE_AUDIO => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_AUDIO),
- SubdefType::TYPE_DOCUMENT => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_FLEXPAPER),
- SubdefType::TYPE_FLASH => array(SubdefSpecs::TYPE_IMAGE),
- SubdefType::TYPE_IMAGE => array(SubdefSpecs::TYPE_IMAGE),
- SubdefType::TYPE_VIDEO => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_VIDEO, SubdefSpecs::TYPE_ANIMATION),
+ SubdefType::TYPE_AUDIO => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_AUDIO),
+ SubdefType::TYPE_DOCUMENT => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_FLEXPAPER),
+ SubdefType::TYPE_FLASH => array(SubdefSpecs::TYPE_IMAGE),
+ SubdefType::TYPE_IMAGE => array(SubdefSpecs::TYPE_IMAGE),
+ SubdefType::TYPE_VIDEO => array(SubdefSpecs::TYPE_IMAGE, SubdefSpecs::TYPE_VIDEO, SubdefSpecs::TYPE_ANIMATION),
);
const CLASS_THUMBNAIL = 'thumbnail';
- const CLASS_PREVIEW = 'preview';
- const CLASS_DOCUMENT = 'document';
+ const CLASS_PREVIEW = 'preview';
+ const CLASS_DOCUMENT = 'document';
/**
*
@@ -70,18 +69,15 @@ class databox_subdef
$this->write_meta = p4field::isyes((string) $sd->meta);
- foreach ($sd->label as $label)
- {
+ foreach ($sd->label as $label) {
$lang = trim((string) $label->attributes()->lang);
- if ($lang)
- {
+ if ($lang) {
$this->labels[$lang] = (string) $label;
}
}
- switch ((string) $sd->mediatype)
- {
+ switch ((string) $sd->mediatype) {
default:
case SubdefSpecs::TYPE_IMAGE:
$this->subdef_type = $this->buildImageSubdef($sd);
@@ -107,20 +103,16 @@ class databox_subdef
{
$image = new Image();
- if ($sd->size)
- {
+ if ($sd->size) {
$image->setOptionValue(Image::OPTION_SIZE, (int) $sd->size);
}
- if ($sd->quality)
- {
+ if ($sd->quality) {
$image->setOptionValue(Image::OPTION_QUALITY, (int) $sd->quality);
}
- if ($sd->strip)
- {
+ if ($sd->strip) {
$image->setOptionValue(Image::OPTION_STRIP, p4field::isyes($sd->strip));
}
- if ($sd->dpi)
- {
+ if ($sd->dpi) {
$image->setOptionValue(Image::OPTION_RESOLUTION, (int) $sd->dpi);
}
@@ -141,12 +133,10 @@ class databox_subdef
{
$gif = new Gif();
- if ($sd->size)
- {
+ if ($sd->size) {
$gif->setOptionValue(Gif::OPTION_SIZE, (int) $sd->size);
}
- if ($sd->delay)
- {
+ if ($sd->delay) {
$gif->setOptionValue(Gif::OPTION_DELAY, (int) $sd->delay);
}
@@ -157,24 +147,19 @@ class databox_subdef
{
$video = new Video();
- if ($sd->size)
- {
+ if ($sd->size) {
$video->setOptionValue(Video::OPTION_SIZE, (int) $sd->size);
}
- if ($sd->a_codec)
- {
+ if ($sd->a_codec) {
$video->setOptionValue(Video::OPTION_ACODEC, (string) $sd->acodec);
}
- if ($sd->v_codec)
- {
+ if ($sd->v_codec) {
$video->setOptionValue(Video::OPTION_VCODEC, (string) $sd->vcodec);
}
- if ($sd->fps)
- {
+ if ($sd->fps) {
$video->setOptionValue(Video::OPTION_FRAMERATE, (int) $sd->fps);
}
- if ($sd->bitrate)
- {
+ if ($sd->bitrate) {
$video->setOptionValue(Video::OPTION_BITRATE, (int) $sd->bitrate);
}
@@ -244,18 +229,12 @@ class databox_subdef
{
$subdefTypes = array();
- if (isset(self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()]))
- {
- foreach (self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()] as $subdefType)
- {
- if ($subdefType == $this->subdef_type->getType())
- {
+ if (isset(self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()])) {
+ foreach (self::$mediaTypeToSubdefTypes[$this->subdef_group->getType()] as $subdefType) {
+ if ($subdefType == $this->subdef_type->getType()) {
$mediatype_obj = $this->subdef_type;
- }
- else
- {
- switch ($subdefType)
- {
+ } else {
+ switch ($subdefType) {
case SubdefSpecs::TYPE_ANIMATION:
$mediatype_obj = new Gif();
break;
@@ -316,5 +295,4 @@ class databox_subdef
{
return $this->subdef_type->getOptions();
}
-
}
diff --git a/lib/classes/databox/subdefsStructure.class.php b/lib/classes/databox/subdefsStructure.class.php
index 9be5dc7af0..0bd410f976 100644
--- a/lib/classes/databox/subdefsStructure.class.php
+++ b/lib/classes/databox/subdefsStructure.class.php
@@ -17,7 +17,6 @@
*/
class databox_subdefsStructure implements IteratorAggregate
{
-
/**
*
* @var Array
@@ -51,10 +50,8 @@ class databox_subdefsStructure implements IteratorAggregate
{
$searchGroup = strtolower($searchGroup);
- foreach ($this->AvSubdefs as $groupname => $subdefgroup)
- {
- if ($searchGroup == $groupname)
- {
+ foreach ($this->AvSubdefs as $groupname => $subdefgroup) {
+ if ($searchGroup == $groupname) {
return $subdefgroup;
}
}
@@ -71,36 +68,31 @@ class databox_subdefsStructure implements IteratorAggregate
$sx_struct = $this->databox->get_sxml_structure();
$this->AvSubdefs = array(
- 'image' => array(),
- 'video' => array(),
- 'audio' => array(),
- 'document' => array(),
- 'flash' => array()
+ 'image' => array(),
+ 'video' => array(),
+ 'audio' => array(),
+ 'document' => array(),
+ 'flash' => array()
);
- if ( ! $sx_struct)
- {
+ if ( ! $sx_struct) {
return $this;
}
$subdefgroup = $sx_struct->subdefs[0];
- foreach ($subdefgroup as $k => $subdefs)
- {
+ foreach ($subdefgroup as $k => $subdefs) {
$subdefgroup_name = strtolower($subdefs->attributes()->name);
- if ( ! isset($AvSubdefs[$subdefgroup_name]))
- {
+ if ( ! isset($AvSubdefs[$subdefgroup_name])) {
$AvSubdefs[$subdefgroup_name] = array();
}
- foreach ($subdefs as $sd)
- {
+ foreach ($subdefs as $sd) {
$subdef_name = strtolower($sd->attributes()->name);
- switch ($subdefgroup_name)
- {
+ switch ($subdefgroup_name) {
case 'audio':
$type = new \Alchemy\Phrasea\Media\Type\Audio();
break;
@@ -137,8 +129,7 @@ class databox_subdefsStructure implements IteratorAggregate
*/
public function get_subdef($subdef_type, $subdef_name)
{
- if (isset($this->AvSubdefs[$subdef_type]) && isset($this->AvSubdefs[$subdef_type][$subdef_name]))
- {
+ if (isset($this->AvSubdefs[$subdef_type]) && isset($this->AvSubdefs[$subdef_type][$subdef_name])) {
return $this->AvSubdefs[$subdef_type][$subdef_name];
}
throw new Exception_Databox_SubdefNotFound();
@@ -154,16 +145,15 @@ class databox_subdefsStructure implements IteratorAggregate
{
$dom_struct = $this->databox->get_dom_structure();
- $dom_xp = $this->databox->get_xpath_structure();
- $nodes = $dom_xp->query(
- '//record/subdefs/'
- . 'subdefgroup[@name="' . $group . '"]/'
- . 'subdef[@name="' . $name . '"]'
+ $dom_xp = $this->databox->get_xpath_structure();
+ $nodes = $dom_xp->query(
+ '//record/subdefs/'
+ . 'subdefgroup[@name="' . $group . '"]/'
+ . 'subdef[@name="' . $name . '"]'
);
- if ($nodes->length > 0)
- {
- $node = $nodes->item(0);
+ if ($nodes->length > 0) {
+ $node = $nodes->item(0);
$parent = $node->parentNode;
$parent->removeChild($node);
}
@@ -192,17 +182,14 @@ class databox_subdefsStructure implements IteratorAggregate
$subdef->setAttribute('name', mb_strtolower($name));
$dom_xp = $this->databox->get_xpath_structure();
- $query = '//record/subdefs/subdefgroup[@name="' . $groupname . '"]';
+ $query = '//record/subdefs/subdefgroup[@name="' . $groupname . '"]';
$groups = $dom_xp->query($query);
- if ($groups->length == 0)
- {
+ if ($groups->length == 0) {
$group = $dom_struct->createElement('subdefgroup');
$group->setAttribute('name', $groupname);
$dom_xp->query('/record/subdefs')->item(0)->appendChild($group);
- }
- else
- {
+ } else {
$group = $groups->item(0);
}
@@ -233,8 +220,7 @@ class databox_subdefsStructure implements IteratorAggregate
$subdef->setAttribute('name', mb_strtolower($name));
$subdef->setAttribute('downloadable', ($downloadable ? 'true' : 'false'));
- foreach ($options as $option => $value)
- {
+ foreach ($options as $option => $value) {
$child = $dom_struct->createElement($option);
$child->appendChild($dom_struct->createTextNode($value));
$subdef->appendChild($child);
@@ -243,37 +229,29 @@ class databox_subdefsStructure implements IteratorAggregate
$dom_xp = $this->databox->get_xpath_structure();
$nodes = $dom_xp->query('//record/subdefs/'
- . 'subdefgroup[@name="' . $group . '"]');
- if ($nodes->length > 0)
- {
+ . 'subdefgroup[@name="' . $group . '"]');
+ if ($nodes->length > 0) {
$dom_group = $nodes->item(0);
- }
- else
- {
+ } else {
$dom_group = $dom_struct->createElement('subdefgroup');
$dom_group->setAttribute('name', $group);
$nodes = $dom_xp->query('//record/subdefs');
- if ($nodes->length > 0)
- {
+ if ($nodes->length > 0) {
$nodes->item(0)->appendChild($dom_group);
- }
- else
- {
+ } else {
throw new Exception('Unable to find /record/subdefs xquery');
}
}
$nodes = $dom_xp->query(
- '//record/subdefs/'
- . 'subdefgroup[@name="' . $group . '"]/'
- . 'subdef[@name="' . $name . '"]'
+ '//record/subdefs/'
+ . 'subdefgroup[@name="' . $group . '"]/'
+ . 'subdef[@name="' . $name . '"]'
);
- if ($nodes->length > 0)
- {
- for ($i = 0; $i < $nodes->length; $i ++ )
- {
+ if ($nodes->length > 0) {
+ for ($i = 0; $i < $nodes->length; $i ++ ) {
$dom_group->removeChild($nodes->item($i));
}
}
@@ -286,5 +264,4 @@ class databox_subdefsStructure implements IteratorAggregate
return $this;
}
-
}
diff --git a/lib/classes/deprecated/countries.php b/lib/classes/deprecated/countries.php
index 6bc8d6cd0d..ee911411a0 100644
--- a/lib/classes/deprecated/countries.php
+++ b/lib/classes/deprecated/countries.php
@@ -17,510 +17,509 @@
*/
function getCountries($lng = 'fr')
{
- $countries['en'] = array(
- 'AF' => 'AFGHANISTAN',
- 'AX' => 'ÅLAND ISLANDS',
- 'AL' => 'ALBANIA',
- 'DZ' => 'ALGERIA',
- 'AS' => 'AMERICAN SAMOA',
- 'AD' => 'ANDORRA',
- 'AO' => 'ANGOLA',
- 'AI' => 'ANGUILLA',
- 'AQ' => 'ANTARCTICA',
- 'AG' => 'ANTIGUA AND BARBUDA',
- 'AR' => 'ARGENTINA',
- 'AM' => 'ARMENIA',
- 'AW' => 'ARUBA',
- 'AU' => 'AUSTRALIA',
- 'AT' => 'AUSTRIA',
- 'AZ' => 'AZERBAIJAN',
- 'BS' => 'BAHAMAS',
- 'BH' => 'BAHRAIN',
- 'BD' => 'BANGLADESH',
- 'BB' => 'BARBADOS',
- 'BY' => 'BELARUS',
- 'BE' => 'BELGIUM',
- 'BZ' => 'BELIZE',
- 'BJ' => 'BENIN',
- 'BM' => 'BERMUDA',
- 'BT' => 'BHUTAN',
- 'BO' => 'BOLIVIA',
- 'BA' => 'BOSNIA AND HERZEGOVINA',
- 'BW' => 'BOTSWANA',
- 'BV' => 'BOUVET ISLAND',
- 'BR' => 'BRAZIL',
- 'IO' => 'BRITISH INDIAN OCEAN TERRITORY',
- 'BN' => 'BRUNEI DARUSSALAM',
- 'BG' => 'BULGARIA',
- 'BF' => 'BURKINA FASO',
- 'BI' => 'BURUNDI',
- 'KH' => 'CAMBODIA',
- 'CM' => 'CAMEROON',
- 'CA' => 'CANADA',
- 'CV' => 'CAPE VERDE',
- 'KY' => 'CAYMAN ISLANDS',
- 'CF' => 'CENTRAL AFRICAN REPUBLIC',
- 'TD' => 'CHAD',
- 'CL' => 'CHILE',
- 'CN' => 'CHINA',
- 'CX' => 'CHRISTMAS ISLAND',
- 'CC' => 'COCOS (KEELING) ISLANDS',
- 'CO' => 'COLOMBIA',
- 'KM' => 'COMOROS',
- 'CG' => 'CONGO',
- 'CD' => 'CONGO, THE DEMOCRATIC REPUBLIC OF THE',
- 'CK' => 'COOK ISLANDS',
- 'CR' => 'COSTA RICA',
- 'CI' => 'CÔTE D\'IVOIRE',
- 'HR' => 'CROATIA',
- 'CU' => 'CUBA',
- 'CY' => 'CYPRUS',
- 'CZ' => 'CZECH REPUBLIC',
- 'DK' => 'DENMARK',
- 'DJ' => 'DJIBOUTI',
- 'DM' => 'DOMINICA',
- 'DO' => 'DOMINICAN REPUBLIC',
- 'EC' => 'ECUADOR',
- 'EG' => 'EGYPT',
- 'SV' => 'EL SALVADOR',
- 'GQ' => 'EQUATORIAL GUINEA',
- 'ER' => 'ERITREA',
- 'EE' => 'ESTONIA',
- 'ET' => 'ETHIOPIA',
- 'FK' => 'FALKLAND ISLANDS (MALVINAS)',
- 'FO' => 'FAROE ISLANDS',
- 'FJ' => 'FIJI',
- 'FI' => 'FINLAND',
- 'FR' => 'FRANCE',
- 'GF' => 'FRENCH GUIANA',
- 'PF' => 'FRENCH POLYNESIA',
- 'TF' => 'FRENCH SOUTHERN TERRITORIES',
- 'GA' => 'GABON',
- 'GM' => 'GAMBIA',
- 'GE' => 'GEORGIA',
- 'DE' => 'GERMANY',
- 'GH' => 'GHANA',
- 'GI' => 'GIBRALTAR',
- 'GR' => 'GREECE',
- 'GL' => 'GREENLAND',
- 'GD' => 'GRENADA',
- 'GP' => 'GUADELOUPE',
- 'GU' => 'GUAM',
- 'GT' => 'GUATEMALA',
- 'GG' => 'GUERNSEY',
- 'GN' => 'GUINEA',
- 'GW' => 'GUINEA-BISSAU',
- 'GY' => 'GUYANA',
- 'HT' => 'HAITI',
- 'HM' => 'HEARD ISLAND AND MCDONALD ISLANDS',
- 'VA' => 'HOLY SEE (VATICAN CITY STATE)',
- 'HN' => 'HONDURAS',
- 'HK' => 'HONG KONG',
- 'HU' => 'HUNGARY',
- 'IS' => 'ICELAND',
- 'IN' => 'INDIA',
- 'ID' => 'INDONESIA',
- 'IR' => 'IRAN, ISLAMIC REPUBLIC OF',
- 'IQ' => 'IRAQ',
- 'IE' => 'IRELAND',
- 'IM' => 'ISLE OF MAN',
- 'IL' => 'ISRAEL',
- 'IT' => 'ITALY',
- 'JM' => 'JAMAICA',
- 'JP' => 'JAPAN',
- 'JE' => 'JERSEY',
- 'JO' => 'JORDAN',
- 'KZ' => 'KAZAKHSTAN',
- 'KE' => 'KENYA',
- 'KI' => 'KIRIBATI',
- 'KP' => 'KOREA, DEMOCRATIC PEOPLE\'S REPUBLIC OF',
- 'KR' => 'KOREA, REPUBLIC OF',
- 'KW' => 'KUWAIT',
- 'KG' => 'KYRGYZSTAN',
- 'LA' => 'LAO PEOPLE\'S DEMOCRATIC REPUBLIC',
- 'LV' => 'LATVIA',
- 'LB' => 'LEBANON',
- 'LS' => 'LESOTHO',
- 'LR' => 'LIBERIA',
- 'LY' => 'LIBYAN ARAB JAMAHIRIYA',
- 'LI' => 'LIECHTENSTEIN',
- 'LT' => 'LITHUANIA',
- 'LU' => 'LUXEMBOURG',
- 'MO' => 'MACAO',
- 'MK' => 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF',
- 'MG' => 'MADAGASCAR',
- 'MW' => 'MALAWI',
- 'MY' => 'MALAYSIA',
- 'MV' => 'MALDIVES',
- 'ML' => 'MALI',
- 'MT' => 'MALTA',
- 'MH' => 'MARSHALL ISLANDS',
- 'MQ' => 'MARTINIQUE',
- 'MR' => 'MAURITANIA',
- 'MU' => 'MAURITIUS',
- 'YT' => 'MAYOTTE',
- 'MX' => 'MEXICO',
- 'FM' => 'MICRONESIA, FEDERATED STATES OF',
- 'MD' => 'MOLDOVA, REPUBLIC OF',
- 'MC' => 'MONACO',
- 'MN' => 'MONGOLIA',
- 'ME' => 'MONTENEGRO',
- 'MS' => 'MONTSERRAT',
- 'MA' => 'MOROCCO',
- 'MZ' => 'MOZAMBIQUE',
- 'MM' => 'MYANMAR',
- 'NA' => 'NAMIBIA',
- 'NR' => 'NAURU',
- 'NP' => 'NEPAL',
- 'NL' => 'NETHERLANDS',
- 'AN' => 'NETHERLANDS ANTILLES',
- 'NC' => 'NEW CALEDONIA',
- 'NZ' => 'NEW ZEALAND',
- 'NI' => 'NICARAGUA',
- 'NE' => 'NIGER',
- 'NG' => 'NIGERIA',
- 'NU' => 'NIUE',
- 'NF' => 'NORFOLK ISLAND',
- 'MP' => 'NORTHERN MARIANA ISLANDS',
- 'NO' => 'NORWAY',
- 'OM' => 'OMAN',
- 'PK' => 'PAKISTAN',
- 'PW' => 'PALAU',
- 'PS' => 'PALESTINIAN TERRITORY, OCCUPIED',
- 'PA' => 'PANAMA',
- 'PG' => 'PAPUA NEW GUINEA',
- 'PY' => 'PARAGUAY',
- 'PE' => 'PERU',
- 'PH' => 'PHILIPPINES',
- 'PN' => 'PITCAIRN',
- 'PL' => 'POLAND',
- 'PT' => 'PORTUGAL',
- 'PR' => 'PUERTO RICO',
- 'QA' => 'QATAR',
- 'RE' => 'REUNION',
- 'RO' => 'ROMANIA',
- 'RU' => 'RUSSIAN FEDERATION',
- 'RW' => 'RWANDA',
- 'BL' => 'SAINT BARTHÉLEMY',
- 'SH' => 'SAINT HELENA',
- 'KN' => 'SAINT KITTS AND NEVIS',
- 'LC' => 'SAINT LUCIA',
- 'MF' => 'SAINT MARTIN',
- 'PM' => 'SAINT PIERRE AND MIQUELON',
- 'VC' => 'SAINT VINCENT AND THE GRENADINES',
- 'WS' => 'SAMOA',
- 'SM' => 'SAN MARINO',
- 'ST' => 'SAO TOME AND PRINCIPE',
- 'SA' => 'SAUDI ARABIA',
- 'SN' => 'SENEGAL',
- 'RS' => 'SERBIA',
- 'SC' => 'SEYCHELLES',
- 'SL' => 'SIERRA LEONE',
- 'SG' => 'SINGAPORE',
- 'SK' => 'SLOVAKIA',
- 'SI' => 'SLOVENIA',
- 'SB' => 'SOLOMON ISLANDS',
- 'SO' => 'SOMALIA',
- 'ZA' => 'SOUTH AFRICA',
- 'GS' => 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS',
- 'ES' => 'SPAIN',
- 'LK' => 'SRI LANKA',
- 'SD' => 'SUDAN',
- 'SR' => 'SURINAME',
- 'SJ' => 'SVALBARD AND JAN MAYEN',
- 'SZ' => 'SWAZILAND',
- 'SE' => 'SWEDEN',
- 'CH' => 'SWITZERLAND',
- 'SY' => 'SYRIAN ARAB REPUBLIC',
- 'TW' => 'TAIWAN, PROVINCE OF CHINA',
- 'TJ' => 'TAJIKISTAN',
- 'TZ' => 'TANZANIA, UNITED REPUBLIC OF',
- 'TH' => 'THAILAND',
- 'TL' => 'TIMOR-LESTE',
- 'TG' => 'TOGO',
- 'TK' => 'TOKELAU',
- 'TO' => 'TONGA',
- 'TT' => 'TRINIDAD AND TOBAGO',
- 'TN' => 'TUNISIA',
- 'TR' => 'TURKEY',
- 'TM' => 'TURKMENISTAN',
- 'TC' => 'TURKS AND CAICOS ISLANDS',
- 'TV' => 'TUVALU',
- 'UG' => 'UGANDA',
- 'UA' => 'UKRAINE',
- 'AE' => 'UNITED ARAB EMIRATES',
- 'GB' => 'UNITED KINGDOM',
- 'US' => 'UNITED STATES',
- 'UM' => 'UNITED STATES MINOR OUTLYING ISLANDS',
- 'UY' => 'URUGUAY',
- 'UZ' => 'UZBEKISTAN',
- 'VU' => 'VANUATU',
- 'VE' => 'VENEZUELA',
- 'VN' => 'VIET NAM',
- 'VG' => 'VIRGIN ISLANDS, BRITISH',
- 'VI' => 'VIRGIN ISLANDS, U.S.',
- 'WF' => 'WALLIS AND FUTUNA',
- 'EH' => 'WESTERN SAHARA',
- 'YE' => 'YEMEN',
- 'ZM' => 'ZAMBIA',
- 'ZW' => 'ZIMBABWE',
- );
+ $countries['en'] = array(
+ 'AF' => 'AFGHANISTAN',
+ 'AX' => 'ÅLAND ISLANDS',
+ 'AL' => 'ALBANIA',
+ 'DZ' => 'ALGERIA',
+ 'AS' => 'AMERICAN SAMOA',
+ 'AD' => 'ANDORRA',
+ 'AO' => 'ANGOLA',
+ 'AI' => 'ANGUILLA',
+ 'AQ' => 'ANTARCTICA',
+ 'AG' => 'ANTIGUA AND BARBUDA',
+ 'AR' => 'ARGENTINA',
+ 'AM' => 'ARMENIA',
+ 'AW' => 'ARUBA',
+ 'AU' => 'AUSTRALIA',
+ 'AT' => 'AUSTRIA',
+ 'AZ' => 'AZERBAIJAN',
+ 'BS' => 'BAHAMAS',
+ 'BH' => 'BAHRAIN',
+ 'BD' => 'BANGLADESH',
+ 'BB' => 'BARBADOS',
+ 'BY' => 'BELARUS',
+ 'BE' => 'BELGIUM',
+ 'BZ' => 'BELIZE',
+ 'BJ' => 'BENIN',
+ 'BM' => 'BERMUDA',
+ 'BT' => 'BHUTAN',
+ 'BO' => 'BOLIVIA',
+ 'BA' => 'BOSNIA AND HERZEGOVINA',
+ 'BW' => 'BOTSWANA',
+ 'BV' => 'BOUVET ISLAND',
+ 'BR' => 'BRAZIL',
+ 'IO' => 'BRITISH INDIAN OCEAN TERRITORY',
+ 'BN' => 'BRUNEI DARUSSALAM',
+ 'BG' => 'BULGARIA',
+ 'BF' => 'BURKINA FASO',
+ 'BI' => 'BURUNDI',
+ 'KH' => 'CAMBODIA',
+ 'CM' => 'CAMEROON',
+ 'CA' => 'CANADA',
+ 'CV' => 'CAPE VERDE',
+ 'KY' => 'CAYMAN ISLANDS',
+ 'CF' => 'CENTRAL AFRICAN REPUBLIC',
+ 'TD' => 'CHAD',
+ 'CL' => 'CHILE',
+ 'CN' => 'CHINA',
+ 'CX' => 'CHRISTMAS ISLAND',
+ 'CC' => 'COCOS (KEELING) ISLANDS',
+ 'CO' => 'COLOMBIA',
+ 'KM' => 'COMOROS',
+ 'CG' => 'CONGO',
+ 'CD' => 'CONGO, THE DEMOCRATIC REPUBLIC OF THE',
+ 'CK' => 'COOK ISLANDS',
+ 'CR' => 'COSTA RICA',
+ 'CI' => 'CÔTE D\'IVOIRE',
+ 'HR' => 'CROATIA',
+ 'CU' => 'CUBA',
+ 'CY' => 'CYPRUS',
+ 'CZ' => 'CZECH REPUBLIC',
+ 'DK' => 'DENMARK',
+ 'DJ' => 'DJIBOUTI',
+ 'DM' => 'DOMINICA',
+ 'DO' => 'DOMINICAN REPUBLIC',
+ 'EC' => 'ECUADOR',
+ 'EG' => 'EGYPT',
+ 'SV' => 'EL SALVADOR',
+ 'GQ' => 'EQUATORIAL GUINEA',
+ 'ER' => 'ERITREA',
+ 'EE' => 'ESTONIA',
+ 'ET' => 'ETHIOPIA',
+ 'FK' => 'FALKLAND ISLANDS (MALVINAS)',
+ 'FO' => 'FAROE ISLANDS',
+ 'FJ' => 'FIJI',
+ 'FI' => 'FINLAND',
+ 'FR' => 'FRANCE',
+ 'GF' => 'FRENCH GUIANA',
+ 'PF' => 'FRENCH POLYNESIA',
+ 'TF' => 'FRENCH SOUTHERN TERRITORIES',
+ 'GA' => 'GABON',
+ 'GM' => 'GAMBIA',
+ 'GE' => 'GEORGIA',
+ 'DE' => 'GERMANY',
+ 'GH' => 'GHANA',
+ 'GI' => 'GIBRALTAR',
+ 'GR' => 'GREECE',
+ 'GL' => 'GREENLAND',
+ 'GD' => 'GRENADA',
+ 'GP' => 'GUADELOUPE',
+ 'GU' => 'GUAM',
+ 'GT' => 'GUATEMALA',
+ 'GG' => 'GUERNSEY',
+ 'GN' => 'GUINEA',
+ 'GW' => 'GUINEA-BISSAU',
+ 'GY' => 'GUYANA',
+ 'HT' => 'HAITI',
+ 'HM' => 'HEARD ISLAND AND MCDONALD ISLANDS',
+ 'VA' => 'HOLY SEE (VATICAN CITY STATE)',
+ 'HN' => 'HONDURAS',
+ 'HK' => 'HONG KONG',
+ 'HU' => 'HUNGARY',
+ 'IS' => 'ICELAND',
+ 'IN' => 'INDIA',
+ 'ID' => 'INDONESIA',
+ 'IR' => 'IRAN, ISLAMIC REPUBLIC OF',
+ 'IQ' => 'IRAQ',
+ 'IE' => 'IRELAND',
+ 'IM' => 'ISLE OF MAN',
+ 'IL' => 'ISRAEL',
+ 'IT' => 'ITALY',
+ 'JM' => 'JAMAICA',
+ 'JP' => 'JAPAN',
+ 'JE' => 'JERSEY',
+ 'JO' => 'JORDAN',
+ 'KZ' => 'KAZAKHSTAN',
+ 'KE' => 'KENYA',
+ 'KI' => 'KIRIBATI',
+ 'KP' => 'KOREA, DEMOCRATIC PEOPLE\'S REPUBLIC OF',
+ 'KR' => 'KOREA, REPUBLIC OF',
+ 'KW' => 'KUWAIT',
+ 'KG' => 'KYRGYZSTAN',
+ 'LA' => 'LAO PEOPLE\'S DEMOCRATIC REPUBLIC',
+ 'LV' => 'LATVIA',
+ 'LB' => 'LEBANON',
+ 'LS' => 'LESOTHO',
+ 'LR' => 'LIBERIA',
+ 'LY' => 'LIBYAN ARAB JAMAHIRIYA',
+ 'LI' => 'LIECHTENSTEIN',
+ 'LT' => 'LITHUANIA',
+ 'LU' => 'LUXEMBOURG',
+ 'MO' => 'MACAO',
+ 'MK' => 'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF',
+ 'MG' => 'MADAGASCAR',
+ 'MW' => 'MALAWI',
+ 'MY' => 'MALAYSIA',
+ 'MV' => 'MALDIVES',
+ 'ML' => 'MALI',
+ 'MT' => 'MALTA',
+ 'MH' => 'MARSHALL ISLANDS',
+ 'MQ' => 'MARTINIQUE',
+ 'MR' => 'MAURITANIA',
+ 'MU' => 'MAURITIUS',
+ 'YT' => 'MAYOTTE',
+ 'MX' => 'MEXICO',
+ 'FM' => 'MICRONESIA, FEDERATED STATES OF',
+ 'MD' => 'MOLDOVA, REPUBLIC OF',
+ 'MC' => 'MONACO',
+ 'MN' => 'MONGOLIA',
+ 'ME' => 'MONTENEGRO',
+ 'MS' => 'MONTSERRAT',
+ 'MA' => 'MOROCCO',
+ 'MZ' => 'MOZAMBIQUE',
+ 'MM' => 'MYANMAR',
+ 'NA' => 'NAMIBIA',
+ 'NR' => 'NAURU',
+ 'NP' => 'NEPAL',
+ 'NL' => 'NETHERLANDS',
+ 'AN' => 'NETHERLANDS ANTILLES',
+ 'NC' => 'NEW CALEDONIA',
+ 'NZ' => 'NEW ZEALAND',
+ 'NI' => 'NICARAGUA',
+ 'NE' => 'NIGER',
+ 'NG' => 'NIGERIA',
+ 'NU' => 'NIUE',
+ 'NF' => 'NORFOLK ISLAND',
+ 'MP' => 'NORTHERN MARIANA ISLANDS',
+ 'NO' => 'NORWAY',
+ 'OM' => 'OMAN',
+ 'PK' => 'PAKISTAN',
+ 'PW' => 'PALAU',
+ 'PS' => 'PALESTINIAN TERRITORY, OCCUPIED',
+ 'PA' => 'PANAMA',
+ 'PG' => 'PAPUA NEW GUINEA',
+ 'PY' => 'PARAGUAY',
+ 'PE' => 'PERU',
+ 'PH' => 'PHILIPPINES',
+ 'PN' => 'PITCAIRN',
+ 'PL' => 'POLAND',
+ 'PT' => 'PORTUGAL',
+ 'PR' => 'PUERTO RICO',
+ 'QA' => 'QATAR',
+ 'RE' => 'REUNION',
+ 'RO' => 'ROMANIA',
+ 'RU' => 'RUSSIAN FEDERATION',
+ 'RW' => 'RWANDA',
+ 'BL' => 'SAINT BARTHÉLEMY',
+ 'SH' => 'SAINT HELENA',
+ 'KN' => 'SAINT KITTS AND NEVIS',
+ 'LC' => 'SAINT LUCIA',
+ 'MF' => 'SAINT MARTIN',
+ 'PM' => 'SAINT PIERRE AND MIQUELON',
+ 'VC' => 'SAINT VINCENT AND THE GRENADINES',
+ 'WS' => 'SAMOA',
+ 'SM' => 'SAN MARINO',
+ 'ST' => 'SAO TOME AND PRINCIPE',
+ 'SA' => 'SAUDI ARABIA',
+ 'SN' => 'SENEGAL',
+ 'RS' => 'SERBIA',
+ 'SC' => 'SEYCHELLES',
+ 'SL' => 'SIERRA LEONE',
+ 'SG' => 'SINGAPORE',
+ 'SK' => 'SLOVAKIA',
+ 'SI' => 'SLOVENIA',
+ 'SB' => 'SOLOMON ISLANDS',
+ 'SO' => 'SOMALIA',
+ 'ZA' => 'SOUTH AFRICA',
+ 'GS' => 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS',
+ 'ES' => 'SPAIN',
+ 'LK' => 'SRI LANKA',
+ 'SD' => 'SUDAN',
+ 'SR' => 'SURINAME',
+ 'SJ' => 'SVALBARD AND JAN MAYEN',
+ 'SZ' => 'SWAZILAND',
+ 'SE' => 'SWEDEN',
+ 'CH' => 'SWITZERLAND',
+ 'SY' => 'SYRIAN ARAB REPUBLIC',
+ 'TW' => 'TAIWAN, PROVINCE OF CHINA',
+ 'TJ' => 'TAJIKISTAN',
+ 'TZ' => 'TANZANIA, UNITED REPUBLIC OF',
+ 'TH' => 'THAILAND',
+ 'TL' => 'TIMOR-LESTE',
+ 'TG' => 'TOGO',
+ 'TK' => 'TOKELAU',
+ 'TO' => 'TONGA',
+ 'TT' => 'TRINIDAD AND TOBAGO',
+ 'TN' => 'TUNISIA',
+ 'TR' => 'TURKEY',
+ 'TM' => 'TURKMENISTAN',
+ 'TC' => 'TURKS AND CAICOS ISLANDS',
+ 'TV' => 'TUVALU',
+ 'UG' => 'UGANDA',
+ 'UA' => 'UKRAINE',
+ 'AE' => 'UNITED ARAB EMIRATES',
+ 'GB' => 'UNITED KINGDOM',
+ 'US' => 'UNITED STATES',
+ 'UM' => 'UNITED STATES MINOR OUTLYING ISLANDS',
+ 'UY' => 'URUGUAY',
+ 'UZ' => 'UZBEKISTAN',
+ 'VU' => 'VANUATU',
+ 'VE' => 'VENEZUELA',
+ 'VN' => 'VIET NAM',
+ 'VG' => 'VIRGIN ISLANDS, BRITISH',
+ 'VI' => 'VIRGIN ISLANDS, U.S.',
+ 'WF' => 'WALLIS AND FUTUNA',
+ 'EH' => 'WESTERN SAHARA',
+ 'YE' => 'YEMEN',
+ 'ZM' => 'ZAMBIA',
+ 'ZW' => 'ZIMBABWE',
+ );
- $countries['us'] = $countries['en'];
+ $countries['us'] = $countries['en'];
- $countries['fr'] = array(
- 'AF' => 'AFGHANISTAN',
- 'ZA' => 'AFRIQUE DU SUD',
- 'AX' => 'ÅLAND, ÎLES',
- 'AL' => 'ALBANIE',
- 'DZ' => 'ALGÉRIE',
- 'DE' => 'ALLEMAGNE',
- 'AD' => 'ANDORRE',
- 'AO' => 'ANGOLA',
- 'AI' => 'ANGUILLA',
- 'AQ' => 'ANTARCTIQUE',
- 'AG' => 'ANTIGUA-ET-BARBUDA',
- 'AN' => 'ANTILLES NÉERLANDAISES',
- 'SA' => 'ARABIE SAOUDITE',
- 'AR' => 'ARGENTINE',
- 'AM' => 'ARMÉNIE',
- 'AW' => 'ARUBA',
- 'AU' => 'AUSTRALIE',
- 'AT' => 'AUTRICHE',
- 'AZ' => 'AZERBAÏDJAN',
- 'BS' => 'BAHAMAS',
- 'BH' => 'BAHREÏN',
- 'BD' => 'BANGLADESH',
- 'BB' => 'BARBADE',
- 'BY' => 'BÉLARUS',
- 'BE' => 'BELGIQUE',
- 'BZ' => 'BELIZE',
- 'BJ' => 'BÉNIN',
- 'BM' => 'BERMUDES',
- 'BT' => 'BHOUTAN',
- 'BO' => 'BOLIVIE',
- 'BA' => 'BOSNIE-HERZÉGOVINE',
- 'BW' => 'BOTSWANA',
- 'BV' => 'BOUVET, ÎLE',
- 'BR' => 'BRÉSIL',
- 'BN' => 'BRUNÉI DARUSSALAM',
- 'BG' => 'BULGARIE',
- 'BF' => 'BURKINA FASO',
- 'BI' => 'BURUNDI',
- 'KY' => 'CAÏMANES, ÎLES',
- 'KH' => 'CAMBODGE',
- 'CM' => 'CAMEROUN',
- 'CA' => 'CANADA',
- 'CV' => 'CAP-VERT',
- 'CF' => 'CENTRAFRICAINE, RÉPUBLIQUE',
- 'CL' => 'CHILI',
- 'CN' => 'CHINE',
- 'CX' => 'CHRISTMAS, ÎLE',
- 'CY' => 'CHYPRE',
- 'CC' => 'COCOS (KEELING), ÎLES',
- 'CO' => 'COLOMBIE',
- 'KM' => 'COMORES',
- 'CG' => 'CONGO',
- 'CD' => 'CONGO, LA RÉPUBLIQUE DÉMOCRATIQUE DU',
- 'CK' => 'COOK, ÎLES',
- 'KR' => 'CORÉE, RÉPUBLIQUE DE',
- 'KP' => 'CORÉE, RÉPUBLIQUE POPULAIRE DÉMOCRATIQUE DE',
- 'CR' => 'COSTA RICA',
- 'CI' => 'CÔTE D\'IVOIRE',
- 'HR' => 'CROATIE',
- 'CU' => 'CUBA',
- 'DK' => 'DANEMARK',
- 'DJ' => 'DJIBOUTI',
- 'DO' => 'DOMINICAINE, RÉPUBLIQUE',
- 'DM' => 'DOMINIQUE',
- 'EG' => 'ÉGYPTE',
- 'SV' => 'EL SALVADOR',
- 'AE' => 'ÉMIRATS ARABES UNIS',
- 'EC' => 'ÉQUATEUR',
- 'ER' => 'ÉRYTHRÉE',
- 'ES' => 'ESPAGNE',
- 'EE' => 'ESTONIE',
- 'US' => 'ÉTATS-UNIS',
- 'ET' => 'ÉTHIOPIE',
- 'FK' => 'FALKLAND, ÎLES (MALVINAS)',
- 'FO' => 'FÉROÉ, ÎLES',
- 'FJ' => 'FIDJI',
- 'FI' => 'FINLANDE',
- 'FR' => 'FRANCE',
- 'GA' => 'GABON',
- 'GM' => 'GAMBIE',
- 'GE' => 'GÉORGIE',
- 'GS' => 'GÉORGIE DU SUD ET LES ÎLES SANDWICH DU SUD',
- 'GH' => 'GHANA',
- 'GI' => 'GIBRALTAR',
- 'GR' => 'GRÈCE',
- 'GD' => 'GRENADE',
- 'GL' => 'GROENLAND',
- 'GP' => 'GUADELOUPE',
- 'GU' => 'GUAM',
- 'GT' => 'GUATEMALA',
- 'GG' => 'GUERNESEY',
- 'GN' => 'GUINÉE',
- 'GW' => 'GUINÉE-BISSAU',
- 'GQ' => 'GUINÉE ÉQUATORIALE',
- 'GY' => 'GUYANA',
- 'GF' => 'GUYANE FRANÇAISE',
- 'HT' => 'HAÏTI',
- 'HM' => 'HEARD, ÎLE ET MCDONALD, ÎLES',
- 'HN' => 'HONDURAS',
- 'HK' => 'HONG-KONG',
- 'HU' => 'HONGRIE',
- 'IM' => 'ÎLE DE MAN',
- 'UM' => 'ÎLES MINEURES ÉLOIGNÉES DES ÉTATS-UNIS',
- 'VG' => 'ÎLES VIERGES BRITANNIQUES',
- 'VI' => 'ÎLES VIERGES DES ÉTATS-UNIS',
- 'IN' => 'INDE',
- 'ID' => 'INDONÉSIE',
- 'IR' => 'IRAN, RÉPUBLIQUE ISLAMIQUE D\'',
- 'IQ' => 'IRAQ',
- 'IE' => 'IRLANDE',
- 'IS' => 'ISLANDE',
- 'IL' => 'ISRAËL',
- 'IT' => 'ITALIE',
- 'JM' => 'JAMAÏQUE',
- 'JP' => 'JAPON',
- 'JE' => 'JERSEY',
- 'JO' => 'JORDANIE',
- 'KZ' => 'KAZAKHSTAN',
- 'KE' => 'KENYA',
- 'KG' => 'KIRGHIZISTAN',
- 'KI' => 'KIRIBATI',
- 'KW' => 'KOWEÏT',
- 'LA' => 'LAO, RÉPUBLIQUE DÉMOCRATIQUE POPULAIRE',
- 'LS' => 'LESOTHO',
- 'LV' => 'LETTONIE',
- 'LB' => 'LIBAN',
- 'LR' => 'LIBÉRIA',
- 'LY' => 'LIBYENNE, JAMAHIRIYA ARABE',
- 'LI' => 'LIECHTENSTEIN',
- 'LT' => 'LITUANIE',
- 'LU' => 'LUXEMBOURG',
- 'MO' => 'MACAO',
- 'MK' => 'MACÉDOINE, L\'EX-RÉPUBLIQUE YOUGOSLAVE DE',
- 'MG' => 'MADAGASCAR',
- 'MY' => 'MALAISIE',
- 'MW' => 'MALAWI',
- 'MV' => 'MALDIVES',
- 'ML' => 'MALI',
- 'MT' => 'MALTE',
- 'MP' => 'MARIANNES DU NORD, ÎLES',
- 'MA' => 'MAROC',
- 'MH' => 'MARSHALL, ÎLES',
- 'MQ' => 'MARTINIQUE',
- 'MU' => 'MAURICE',
- 'MR' => 'MAURITANIE',
- 'YT' => 'MAYOTTE',
- 'MX' => 'MEXIQUE',
- 'FM' => 'MICRONÉSIE, ÉTATS FÉDÉRÉS DE',
- 'MD' => 'MOLDOVA, RÉPUBLIQUE DE',
- 'MC' => 'MONACO',
- 'MN' => 'MONGOLIE',
- 'ME' => 'MONTÉNÉGRO',
- 'MS' => 'MONTSERRAT',
- 'MZ' => 'MOZAMBIQUE',
- 'MM' => 'MYANMAR',
- 'NA' => 'NAMIBIE',
- 'NR' => 'NAURU',
- 'NP' => 'NÉPAL',
- 'NI' => 'NICARAGUA',
- 'NE' => 'NIGER',
- 'NG' => 'NIGÉRIA',
- 'NU' => 'NIUÉ',
- 'NF' => 'NORFOLK, ÎLE',
- 'NO' => 'NORVÈGE',
- 'NC' => 'NOUVELLE-CALÉDONIE',
- 'NZ' => 'NOUVELLE-ZÉLANDE',
- 'IO' => 'OCÉAN INDIEN, TERRITOIRE BRITANNIQUE DE L\'',
- 'OM' => 'OMAN',
- 'UG' => 'OUGANDA',
- 'UZ' => 'OUZBÉKISTAN',
- 'PK' => 'PAKISTAN',
- 'PW' => 'PALAOS',
- 'PS' => 'PALESTINIEN OCCUPÉ, TERRITOIRE',
- 'PA' => 'PANAMA',
- 'PG' => 'PAPOUASIE-NOUVELLE-GUINÉE',
- 'PY' => 'PARAGUAY',
- 'NL' => 'PAYS-BAS',
- 'PE' => 'PÉROU',
- 'PH' => 'PHILIPPINES',
- 'PN' => 'PITCAIRN',
- 'PL' => 'POLOGNE',
- 'PF' => 'POLYNÉSIE FRANÇAISE',
- 'PR' => 'PORTO RICO',
- 'PT' => 'PORTUGAL',
- 'QA' => 'QATAR',
- 'RE' => 'RÉUNION',
- 'RO' => 'ROUMANIE',
- 'GB' => 'ROYAUME-UNI',
- 'RU' => 'RUSSIE, FÉDÉRATION DE',
- 'RW' => 'RWANDA',
- 'EH' => 'SAHARA OCCIDENTAL',
- 'BL' => 'SAINT-BARTHÉLEMY',
- 'SH' => 'SAINTE-HÉLÈNE',
- 'LC' => 'SAINTE-LUCIE',
- 'KN' => 'SAINT-KITTS-ET-NEVIS',
- 'SM' => 'SAINT-MARIN',
- 'MF' => 'SAINT-MARTIN',
- 'PM' => 'SAINT-PIERRE-ET-MIQUELON',
- 'VA' => 'SAINT-SIÈGE (ÉTAT DE LA CITÉ DU VATICAN)',
- 'VC' => 'SAINT-VINCENT-ET-LES GRENADINES',
- 'SB' => 'SALOMON, ÎLES',
- 'WS' => 'SAMOA',
- 'AS' => 'SAMOA AMÉRICAINES',
- 'ST' => 'SAO TOMÉ-ET-PRINCIPE',
- 'SN' => 'SÉNÉGAL',
- 'RS' => 'SERBIE',
- 'SC' => 'SEYCHELLES',
- 'SL' => 'SIERRA LEONE',
- 'SG' => 'SINGAPOUR',
- 'SK' => 'SLOVAQUIE',
- 'SI' => 'SLOVÉNIE',
- 'SO' => 'SOMALIE',
- 'SD' => 'SOUDAN',
- 'LK' => 'SRI LANKA',
- 'SE' => 'SUÈDE',
- 'CH' => 'SUISSE',
- 'SR' => 'SURINAME',
- 'SJ' => 'SVALBARD ET ÎLE JAN MAYEN',
- 'SZ' => 'SWAZILAND',
- 'SY' => 'SYRIENNE, RÉPUBLIQUE ARABE',
- 'TJ' => 'TADJIKISTAN',
- 'TW' => 'TAÏWAN, PROVINCE DE CHINE',
- 'TZ' => 'TANZANIE, RÉPUBLIQUE-UNIE DE',
- 'TD' => 'TCHAD',
- 'CZ' => 'TCHÈQUE, RÉPUBLIQUE',
- 'TF' => 'TERRES AUSTRALES FRANÇAISES',
- 'TH' => 'THAÏLANDE',
- 'TL' => 'TIMOR-LESTE',
- 'TG' => 'TOGO',
- 'TK' => 'TOKELAU',
- 'TO' => 'TONGA',
- 'TT' => 'TRINITÉ-ET-TOBAGO',
- 'TN' => 'TUNISIE',
- 'TM' => 'TURKMÉNISTAN',
- 'TC' => 'TURKS ET CAÏQUES, ÎLES',
- 'TR' => 'TURQUIE',
- 'TV' => 'TUVALU',
- 'UA' => 'UKRAINE',
- 'UY' => 'URUGUAY',
- 'VU' => 'VANUATU',
- 'VE' => 'VENEZUELA',
- 'VN' => 'VIET NAM',
- 'WF' => 'WALLIS ET FUTUNA',
- 'YE' => 'YÉMEN',
- 'ZM' => 'ZAMBIE',
- 'ZW' => 'ZIMBABWE'
- );
- if (!isset($countries[$lng]))
- $lng = 'us';
- foreach ($countries[$lng] as $k => $country)
- $countries[$lng][$k] = mb_strtolower($country);
+ $countries['fr'] = array(
+ 'AF' => 'AFGHANISTAN',
+ 'ZA' => 'AFRIQUE DU SUD',
+ 'AX' => 'ÅLAND, ÎLES',
+ 'AL' => 'ALBANIE',
+ 'DZ' => 'ALGÉRIE',
+ 'DE' => 'ALLEMAGNE',
+ 'AD' => 'ANDORRE',
+ 'AO' => 'ANGOLA',
+ 'AI' => 'ANGUILLA',
+ 'AQ' => 'ANTARCTIQUE',
+ 'AG' => 'ANTIGUA-ET-BARBUDA',
+ 'AN' => 'ANTILLES NÉERLANDAISES',
+ 'SA' => 'ARABIE SAOUDITE',
+ 'AR' => 'ARGENTINE',
+ 'AM' => 'ARMÉNIE',
+ 'AW' => 'ARUBA',
+ 'AU' => 'AUSTRALIE',
+ 'AT' => 'AUTRICHE',
+ 'AZ' => 'AZERBAÏDJAN',
+ 'BS' => 'BAHAMAS',
+ 'BH' => 'BAHREÏN',
+ 'BD' => 'BANGLADESH',
+ 'BB' => 'BARBADE',
+ 'BY' => 'BÉLARUS',
+ 'BE' => 'BELGIQUE',
+ 'BZ' => 'BELIZE',
+ 'BJ' => 'BÉNIN',
+ 'BM' => 'BERMUDES',
+ 'BT' => 'BHOUTAN',
+ 'BO' => 'BOLIVIE',
+ 'BA' => 'BOSNIE-HERZÉGOVINE',
+ 'BW' => 'BOTSWANA',
+ 'BV' => 'BOUVET, ÎLE',
+ 'BR' => 'BRÉSIL',
+ 'BN' => 'BRUNÉI DARUSSALAM',
+ 'BG' => 'BULGARIE',
+ 'BF' => 'BURKINA FASO',
+ 'BI' => 'BURUNDI',
+ 'KY' => 'CAÏMANES, ÎLES',
+ 'KH' => 'CAMBODGE',
+ 'CM' => 'CAMEROUN',
+ 'CA' => 'CANADA',
+ 'CV' => 'CAP-VERT',
+ 'CF' => 'CENTRAFRICAINE, RÉPUBLIQUE',
+ 'CL' => 'CHILI',
+ 'CN' => 'CHINE',
+ 'CX' => 'CHRISTMAS, ÎLE',
+ 'CY' => 'CHYPRE',
+ 'CC' => 'COCOS (KEELING), ÎLES',
+ 'CO' => 'COLOMBIE',
+ 'KM' => 'COMORES',
+ 'CG' => 'CONGO',
+ 'CD' => 'CONGO, LA RÉPUBLIQUE DÉMOCRATIQUE DU',
+ 'CK' => 'COOK, ÎLES',
+ 'KR' => 'CORÉE, RÉPUBLIQUE DE',
+ 'KP' => 'CORÉE, RÉPUBLIQUE POPULAIRE DÉMOCRATIQUE DE',
+ 'CR' => 'COSTA RICA',
+ 'CI' => 'CÔTE D\'IVOIRE',
+ 'HR' => 'CROATIE',
+ 'CU' => 'CUBA',
+ 'DK' => 'DANEMARK',
+ 'DJ' => 'DJIBOUTI',
+ 'DO' => 'DOMINICAINE, RÉPUBLIQUE',
+ 'DM' => 'DOMINIQUE',
+ 'EG' => 'ÉGYPTE',
+ 'SV' => 'EL SALVADOR',
+ 'AE' => 'ÉMIRATS ARABES UNIS',
+ 'EC' => 'ÉQUATEUR',
+ 'ER' => 'ÉRYTHRÉE',
+ 'ES' => 'ESPAGNE',
+ 'EE' => 'ESTONIE',
+ 'US' => 'ÉTATS-UNIS',
+ 'ET' => 'ÉTHIOPIE',
+ 'FK' => 'FALKLAND, ÎLES (MALVINAS)',
+ 'FO' => 'FÉROÉ, ÎLES',
+ 'FJ' => 'FIDJI',
+ 'FI' => 'FINLANDE',
+ 'FR' => 'FRANCE',
+ 'GA' => 'GABON',
+ 'GM' => 'GAMBIE',
+ 'GE' => 'GÉORGIE',
+ 'GS' => 'GÉORGIE DU SUD ET LES ÎLES SANDWICH DU SUD',
+ 'GH' => 'GHANA',
+ 'GI' => 'GIBRALTAR',
+ 'GR' => 'GRÈCE',
+ 'GD' => 'GRENADE',
+ 'GL' => 'GROENLAND',
+ 'GP' => 'GUADELOUPE',
+ 'GU' => 'GUAM',
+ 'GT' => 'GUATEMALA',
+ 'GG' => 'GUERNESEY',
+ 'GN' => 'GUINÉE',
+ 'GW' => 'GUINÉE-BISSAU',
+ 'GQ' => 'GUINÉE ÉQUATORIALE',
+ 'GY' => 'GUYANA',
+ 'GF' => 'GUYANE FRANÇAISE',
+ 'HT' => 'HAÏTI',
+ 'HM' => 'HEARD, ÎLE ET MCDONALD, ÎLES',
+ 'HN' => 'HONDURAS',
+ 'HK' => 'HONG-KONG',
+ 'HU' => 'HONGRIE',
+ 'IM' => 'ÎLE DE MAN',
+ 'UM' => 'ÎLES MINEURES ÉLOIGNÉES DES ÉTATS-UNIS',
+ 'VG' => 'ÎLES VIERGES BRITANNIQUES',
+ 'VI' => 'ÎLES VIERGES DES ÉTATS-UNIS',
+ 'IN' => 'INDE',
+ 'ID' => 'INDONÉSIE',
+ 'IR' => 'IRAN, RÉPUBLIQUE ISLAMIQUE D\'',
+ 'IQ' => 'IRAQ',
+ 'IE' => 'IRLANDE',
+ 'IS' => 'ISLANDE',
+ 'IL' => 'ISRAËL',
+ 'IT' => 'ITALIE',
+ 'JM' => 'JAMAÏQUE',
+ 'JP' => 'JAPON',
+ 'JE' => 'JERSEY',
+ 'JO' => 'JORDANIE',
+ 'KZ' => 'KAZAKHSTAN',
+ 'KE' => 'KENYA',
+ 'KG' => 'KIRGHIZISTAN',
+ 'KI' => 'KIRIBATI',
+ 'KW' => 'KOWEÏT',
+ 'LA' => 'LAO, RÉPUBLIQUE DÉMOCRATIQUE POPULAIRE',
+ 'LS' => 'LESOTHO',
+ 'LV' => 'LETTONIE',
+ 'LB' => 'LIBAN',
+ 'LR' => 'LIBÉRIA',
+ 'LY' => 'LIBYENNE, JAMAHIRIYA ARABE',
+ 'LI' => 'LIECHTENSTEIN',
+ 'LT' => 'LITUANIE',
+ 'LU' => 'LUXEMBOURG',
+ 'MO' => 'MACAO',
+ 'MK' => 'MACÉDOINE, L\'EX-RÉPUBLIQUE YOUGOSLAVE DE',
+ 'MG' => 'MADAGASCAR',
+ 'MY' => 'MALAISIE',
+ 'MW' => 'MALAWI',
+ 'MV' => 'MALDIVES',
+ 'ML' => 'MALI',
+ 'MT' => 'MALTE',
+ 'MP' => 'MARIANNES DU NORD, ÎLES',
+ 'MA' => 'MAROC',
+ 'MH' => 'MARSHALL, ÎLES',
+ 'MQ' => 'MARTINIQUE',
+ 'MU' => 'MAURICE',
+ 'MR' => 'MAURITANIE',
+ 'YT' => 'MAYOTTE',
+ 'MX' => 'MEXIQUE',
+ 'FM' => 'MICRONÉSIE, ÉTATS FÉDÉRÉS DE',
+ 'MD' => 'MOLDOVA, RÉPUBLIQUE DE',
+ 'MC' => 'MONACO',
+ 'MN' => 'MONGOLIE',
+ 'ME' => 'MONTÉNÉGRO',
+ 'MS' => 'MONTSERRAT',
+ 'MZ' => 'MOZAMBIQUE',
+ 'MM' => 'MYANMAR',
+ 'NA' => 'NAMIBIE',
+ 'NR' => 'NAURU',
+ 'NP' => 'NÉPAL',
+ 'NI' => 'NICARAGUA',
+ 'NE' => 'NIGER',
+ 'NG' => 'NIGÉRIA',
+ 'NU' => 'NIUÉ',
+ 'NF' => 'NORFOLK, ÎLE',
+ 'NO' => 'NORVÈGE',
+ 'NC' => 'NOUVELLE-CALÉDONIE',
+ 'NZ' => 'NOUVELLE-ZÉLANDE',
+ 'IO' => 'OCÉAN INDIEN, TERRITOIRE BRITANNIQUE DE L\'',
+ 'OM' => 'OMAN',
+ 'UG' => 'OUGANDA',
+ 'UZ' => 'OUZBÉKISTAN',
+ 'PK' => 'PAKISTAN',
+ 'PW' => 'PALAOS',
+ 'PS' => 'PALESTINIEN OCCUPÉ, TERRITOIRE',
+ 'PA' => 'PANAMA',
+ 'PG' => 'PAPOUASIE-NOUVELLE-GUINÉE',
+ 'PY' => 'PARAGUAY',
+ 'NL' => 'PAYS-BAS',
+ 'PE' => 'PÉROU',
+ 'PH' => 'PHILIPPINES',
+ 'PN' => 'PITCAIRN',
+ 'PL' => 'POLOGNE',
+ 'PF' => 'POLYNÉSIE FRANÇAISE',
+ 'PR' => 'PORTO RICO',
+ 'PT' => 'PORTUGAL',
+ 'QA' => 'QATAR',
+ 'RE' => 'RÉUNION',
+ 'RO' => 'ROUMANIE',
+ 'GB' => 'ROYAUME-UNI',
+ 'RU' => 'RUSSIE, FÉDÉRATION DE',
+ 'RW' => 'RWANDA',
+ 'EH' => 'SAHARA OCCIDENTAL',
+ 'BL' => 'SAINT-BARTHÉLEMY',
+ 'SH' => 'SAINTE-HÉLÈNE',
+ 'LC' => 'SAINTE-LUCIE',
+ 'KN' => 'SAINT-KITTS-ET-NEVIS',
+ 'SM' => 'SAINT-MARIN',
+ 'MF' => 'SAINT-MARTIN',
+ 'PM' => 'SAINT-PIERRE-ET-MIQUELON',
+ 'VA' => 'SAINT-SIÈGE (ÉTAT DE LA CITÉ DU VATICAN)',
+ 'VC' => 'SAINT-VINCENT-ET-LES GRENADINES',
+ 'SB' => 'SALOMON, ÎLES',
+ 'WS' => 'SAMOA',
+ 'AS' => 'SAMOA AMÉRICAINES',
+ 'ST' => 'SAO TOMÉ-ET-PRINCIPE',
+ 'SN' => 'SÉNÉGAL',
+ 'RS' => 'SERBIE',
+ 'SC' => 'SEYCHELLES',
+ 'SL' => 'SIERRA LEONE',
+ 'SG' => 'SINGAPOUR',
+ 'SK' => 'SLOVAQUIE',
+ 'SI' => 'SLOVÉNIE',
+ 'SO' => 'SOMALIE',
+ 'SD' => 'SOUDAN',
+ 'LK' => 'SRI LANKA',
+ 'SE' => 'SUÈDE',
+ 'CH' => 'SUISSE',
+ 'SR' => 'SURINAME',
+ 'SJ' => 'SVALBARD ET ÎLE JAN MAYEN',
+ 'SZ' => 'SWAZILAND',
+ 'SY' => 'SYRIENNE, RÉPUBLIQUE ARABE',
+ 'TJ' => 'TADJIKISTAN',
+ 'TW' => 'TAÏWAN, PROVINCE DE CHINE',
+ 'TZ' => 'TANZANIE, RÉPUBLIQUE-UNIE DE',
+ 'TD' => 'TCHAD',
+ 'CZ' => 'TCHÈQUE, RÉPUBLIQUE',
+ 'TF' => 'TERRES AUSTRALES FRANÇAISES',
+ 'TH' => 'THAÏLANDE',
+ 'TL' => 'TIMOR-LESTE',
+ 'TG' => 'TOGO',
+ 'TK' => 'TOKELAU',
+ 'TO' => 'TONGA',
+ 'TT' => 'TRINITÉ-ET-TOBAGO',
+ 'TN' => 'TUNISIE',
+ 'TM' => 'TURKMÉNISTAN',
+ 'TC' => 'TURKS ET CAÏQUES, ÎLES',
+ 'TR' => 'TURQUIE',
+ 'TV' => 'TUVALU',
+ 'UA' => 'UKRAINE',
+ 'UY' => 'URUGUAY',
+ 'VU' => 'VANUATU',
+ 'VE' => 'VENEZUELA',
+ 'VN' => 'VIET NAM',
+ 'WF' => 'WALLIS ET FUTUNA',
+ 'YE' => 'YÉMEN',
+ 'ZM' => 'ZAMBIE',
+ 'ZW' => 'ZIMBABWE'
+ );
+ if ( ! isset($countries[$lng]))
+ $lng = 'us';
+ foreach ($countries[$lng] as $k => $country)
+ $countries[$lng][$k] = mb_strtolower($country);
- return $countries[$lng];
+ return $countries[$lng];
}
-
diff --git a/lib/classes/deprecated/inscript.api.php b/lib/classes/deprecated/inscript.api.php
index 7b7879760d..5355724194 100644
--- a/lib/classes/deprecated/inscript.api.php
+++ b/lib/classes/deprecated/inscript.api.php
@@ -15,19 +15,18 @@
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link www.phraseanet.com
*/
-function giveMeBases($usr=null)
+function giveMeBases($usr = null)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $conn = $appbox->get_connection();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $conn = $appbox->get_connection();
- $inscriptions = null;
+ $inscriptions = null;
- $usrerRegis = null;
+ $usrerRegis = null;
- if ($usr != null)
- {
+ if ($usr != null) {
- $sqlU = 'SELECT sbas.dbname, time_limited, UNIX_TIMESTAMP( limited_from ) AS limited_from,
+ $sqlU = 'SELECT sbas.dbname, time_limited, UNIX_TIMESTAMP( limited_from ) AS limited_from,
UNIX_TIMESTAMP( limited_to ) AS limited_to, bas.server_coll_id,
usr.usr_id, basusr.actif, demand.en_cours, demand.refuser
FROM (usr, bas, sbas)
@@ -40,426 +39,374 @@ function giveMeBases($usr=null)
WHERE bas.active >0 AND bas.sbas_id = sbas.sbas_id
AND usr.usr_id = :usr_id AND model_of = 0';
- $stmt = $conn->prepare($sqlU);
- $stmt->execute(array(':usr_id' => $usr));
- $rsU = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sqlU);
+ $stmt->execute(array(':usr_id' => $usr));
+ $rsU = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (count($rsU) == 0)
+ if (count($rsU) == 0)
+ return null;
- return null;
+ foreach ($rsU as $rowU) {
+ if ( ! isset($usrerRegis[$rowU['dbname']]))
+ $usrerRegis[$rowU['dbname']] = null;
- foreach ($rsU as $rowU)
- {
- if (!isset($usrerRegis[$rowU['dbname']]))
- $usrerRegis[$rowU['dbname']] = null;
+ if ( ! is_null($rowU['actif']) || ! is_null($rowU['en_cours'])) {
- if (!is_null($rowU['actif']) || !is_null($rowU['en_cours']))
- {
-
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = true;
- if ($rowU['actif'] == '0')
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'NONACTIF';
- elseif ($rowU['time_limited'] == '1' && !($rowU['limited_from'] >= time() && $rowU['limited_to'] <= time()))
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'OUTTIME';
- elseif ($rowU['time_limited'] == '1' && ($rowU['limited_from'] > time() && $rowU['limited_to'] < time()))
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'INTIME';
- elseif ($rowU['en_cours'] == '1')
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'WAIT';
- elseif ($rowU['refuser'] == '1')
- $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'REFUSE';
- }
- }
- }
-
- foreach ($appbox->get_databoxes() as $databox)
- {
- $collname = $basname = null;
- $sbas_id = $databox->get_sbas_id();
- $inscriptions[$sbas_id] = array();
- $inscriptions[$sbas_id]['CGU'] = false;
- $inscriptions[$sbas_id]['CGUrelease'] = false;
- $inscriptions[$sbas_id]['inscript'] = false;
- $inscriptions[$sbas_id]['CollsCGU'] = null;
- $inscriptions[$sbas_id]['Colls'] = null;
- $inscriptions[$sbas_id]['CollsRegistered'] = null;
- $inscriptions[$sbas_id]['CollsWait'] = null;
- $inscriptions[$sbas_id]['CollsRefuse'] = null;
- $inscriptions[$sbas_id]['CollsIntime'] = null;
- $inscriptions[$sbas_id]['CollsOuttime'] = null;
- $inscriptions[$sbas_id]['CollsNonactif'] = null;
-
- foreach ($databox->get_collections() as $key => $coll)
- {
- $collname[$key] = $coll->get_name();
- $basname[$key] = $coll->get_coll_id();
- }
- $sbpcgu = '';
-
- $xml = $databox->get_sxml_structure();
- if ($xml)
- {
- foreach ($xml->xpath('/record/caninscript') as $caninscript)
- {
- if ($inscriptions[$sbas_id]['inscript'] === false)
- $inscriptions[$sbas_id]['inscript'] = ((string) $caninscript == "1");
- }
- foreach ($xml->xpath('/record/cgu') as $sbpcgu)
- {
- foreach ($sbpcgu->attributes() as $a => $b)
- {
- if ($a == "release")
- $inscriptions[$sbas_id]['CGUrelease'] = (string) $b;
- }
- $inscriptions[$sbas_id]['CGU'] = (string) $sbpcgu->saveXML();
- }
- }
- $baseInscript = $inscriptions[$sbas_id]['inscript'];
- foreach ($databox->get_collections() as $collection)
- {
- $cguColl = false;
-
- $collInscript = $baseInscript;
- $defined = false;
- $cguSpec = false;
- if ($xml = simplexml_load_string($collection->get_prefs()))
- {
- $defined = true;
- foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript)
- {
- $tmp = (string) $caninscript;
- if ($tmp === "1")
- $collInscript = true;
- elseif ($tmp === "0")
- $collInscript = false;
- }
- if ($collInscript)
- {
- $cguCollRelease = false;
-
- if ($inscriptions[$sbas_id]['inscript'] === false)
- $inscriptions[$sbas_id]['inscript'] = !!$collInscript;
-
- foreach ($xml->xpath('/baseprefs/cgu') as $bpcgu)
- {
- foreach ($bpcgu->attributes() as $a => $b)
- {
- if ($a == "release")
- $cguCollRelease = (string) $b;
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = true;
+ if ($rowU['actif'] == '0')
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'NONACTIF';
+ elseif ($rowU['time_limited'] == '1' && ! ($rowU['limited_from'] >= time() && $rowU['limited_to'] <= time()))
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'OUTTIME';
+ elseif ($rowU['time_limited'] == '1' && ($rowU['limited_from'] > time() && $rowU['limited_to'] < time()))
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'INTIME';
+ elseif ($rowU['en_cours'] == '1')
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'WAIT';
+ elseif ($rowU['refuser'] == '1')
+ $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'REFUSE';
}
- $cguColl = (string) $bpcgu->saveXML();
- }
- if ($cguColl)
- {
- $cguSpec = true;
- }
- else
- {
- if (!isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()]))
- $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_name();
- }
}
- }
- $lacgu = $cguColl ? $cguColl : (string) $sbpcgu;
-
- if (isset($usrerRegis[$databox->get_dbname()]) && isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()]))
- {
- if ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "WAIT")
- $inscriptions[$sbas_id]['CollsWait'][$collection->get_coll_id()] = $lacgu;
- elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "REFUSE")
- $inscriptions[$sbas_id]['CollsRefuse'][$collection->get_coll_id()] = $lacgu;
- elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "INTIME")
- $inscriptions[$sbas_id]['CollsIntime'][$collection->get_coll_id()] = $lacgu;
- elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "OUTTIME")
- $inscriptions[$sbas_id]['CollsOuttime'][$collection->get_coll_id()] = $lacgu;
- elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "NONACTIF")
- $inscriptions[$sbas_id]['CollsNonactif'][$collection->get_coll_id()] = $lacgu;
- elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === true)
- $inscriptions[$sbas_id]['CollsRegistered'][$collection->get_coll_id()] = $lacgu;
- }
- elseif (!$cguSpec && $collInscript)//ne va pas.. si l'inscriptio na la coll est explicitement non autorise, je refuse'
- {
- $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_name();
- }
- elseif ($cguSpec)
- {
- $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['name'] = $collection->get_name();
- $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGU'] = $cguColl;
- $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGUrelease'] = $cguCollRelease;
- }
}
- }
- return $inscriptions;
+ foreach ($appbox->get_databoxes() as $databox) {
+ $collname = $basname = null;
+ $sbas_id = $databox->get_sbas_id();
+ $inscriptions[$sbas_id] = array();
+ $inscriptions[$sbas_id]['CGU'] = false;
+ $inscriptions[$sbas_id]['CGUrelease'] = false;
+ $inscriptions[$sbas_id]['inscript'] = false;
+ $inscriptions[$sbas_id]['CollsCGU'] = null;
+ $inscriptions[$sbas_id]['Colls'] = null;
+ $inscriptions[$sbas_id]['CollsRegistered'] = null;
+ $inscriptions[$sbas_id]['CollsWait'] = null;
+ $inscriptions[$sbas_id]['CollsRefuse'] = null;
+ $inscriptions[$sbas_id]['CollsIntime'] = null;
+ $inscriptions[$sbas_id]['CollsOuttime'] = null;
+ $inscriptions[$sbas_id]['CollsNonactif'] = null;
+
+ foreach ($databox->get_collections() as $key => $coll) {
+ $collname[$key] = $coll->get_name();
+ $basname[$key] = $coll->get_coll_id();
+ }
+ $sbpcgu = '';
+
+ $xml = $databox->get_sxml_structure();
+ if ($xml) {
+ foreach ($xml->xpath('/record/caninscript') as $caninscript) {
+ if ($inscriptions[$sbas_id]['inscript'] === false)
+ $inscriptions[$sbas_id]['inscript'] = ((string) $caninscript == "1");
+ }
+ foreach ($xml->xpath('/record/cgu') as $sbpcgu) {
+ foreach ($sbpcgu->attributes() as $a => $b) {
+ if ($a == "release")
+ $inscriptions[$sbas_id]['CGUrelease'] = (string) $b;
+ }
+ $inscriptions[$sbas_id]['CGU'] = (string) $sbpcgu->saveXML();
+ }
+ }
+ $baseInscript = $inscriptions[$sbas_id]['inscript'];
+ foreach ($databox->get_collections() as $collection) {
+ $cguColl = false;
+
+ $collInscript = $baseInscript;
+ $defined = false;
+ $cguSpec = false;
+ if ($xml = simplexml_load_string($collection->get_prefs())) {
+ $defined = true;
+ foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript) {
+ $tmp = (string) $caninscript;
+ if ($tmp === "1")
+ $collInscript = true;
+ elseif ($tmp === "0")
+ $collInscript = false;
+ }
+ if ($collInscript) {
+ $cguCollRelease = false;
+
+ if ($inscriptions[$sbas_id]['inscript'] === false)
+ $inscriptions[$sbas_id]['inscript'] = ! ! $collInscript;
+
+ foreach ($xml->xpath('/baseprefs/cgu') as $bpcgu) {
+ foreach ($bpcgu->attributes() as $a => $b) {
+ if ($a == "release")
+ $cguCollRelease = (string) $b;
+ }
+ $cguColl = (string) $bpcgu->saveXML();
+ }
+ if ($cguColl) {
+ $cguSpec = true;
+ } else {
+ if ( ! isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()]))
+ $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_name();
+ }
+ }
+ }
+ $lacgu = $cguColl ? $cguColl : (string) $sbpcgu;
+
+ if (isset($usrerRegis[$databox->get_dbname()]) && isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()])) {
+ if ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "WAIT")
+ $inscriptions[$sbas_id]['CollsWait'][$collection->get_coll_id()] = $lacgu;
+ elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "REFUSE")
+ $inscriptions[$sbas_id]['CollsRefuse'][$collection->get_coll_id()] = $lacgu;
+ elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "INTIME")
+ $inscriptions[$sbas_id]['CollsIntime'][$collection->get_coll_id()] = $lacgu;
+ elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "OUTTIME")
+ $inscriptions[$sbas_id]['CollsOuttime'][$collection->get_coll_id()] = $lacgu;
+ elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "NONACTIF")
+ $inscriptions[$sbas_id]['CollsNonactif'][$collection->get_coll_id()] = $lacgu;
+ elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === true)
+ $inscriptions[$sbas_id]['CollsRegistered'][$collection->get_coll_id()] = $lacgu;
+ }
+ elseif ( ! $cguSpec && $collInscript) {//ne va pas.. si l'inscriptio na la coll est explicitement non autorise, je refuse'
+ $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_name();
+ } elseif ($cguSpec) {
+ $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['name'] = $collection->get_name();
+ $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGU'] = $cguColl;
+ $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGUrelease'] = $cguCollRelease;
+ }
+ }
+ }
+
+ return $inscriptions;
}
function giveMeBaseUsr($usr, $lng)
{
- $noDemand = true;
- $appbox = appbox::get_instance(\bootstrap::getCore());
+ $noDemand = true;
+ $appbox = appbox::get_instance(\bootstrap::getCore());
- $out = '' .
- '' .
- ' ' .
- ' ' .
- ' ' .
- ' ';
+ $out = '' .
+ '' .
+ ' ' .
+ ' ' .
+ ' ' .
+ ' ';
- $inscriptions = giveMeBases($usr);
- foreach ($inscriptions as $sbasId => $baseInsc)
- {
- //je presente la base
- if (($baseInsc['CollsRegistered'] || $baseInsc['CollsRefuse'] || $baseInsc['CollsWait'] || $baseInsc['CollsIntime'] || $baseInsc['CollsOuttime'] || $baseInsc['CollsNonactif'] || $baseInsc['CollsCGU'] || $baseInsc['Colls']))//&& $baseInsc['inscript'])
- $out .= '' . phrasea::sbas_names ($sbasId) . ' ';
+ $inscriptions = giveMeBases($usr);
+ foreach ($inscriptions as $sbasId => $baseInsc) {
+ //je presente la base
+ if (($baseInsc['CollsRegistered'] || $baseInsc['CollsRefuse'] || $baseInsc['CollsWait'] || $baseInsc['CollsIntime'] || $baseInsc['CollsOuttime'] || $baseInsc['CollsNonactif'] || $baseInsc['CollsCGU'] || $baseInsc['Colls']))//&& $baseInsc['inscript'])
+ $out .= '' . phrasea::sbas_names($sbasId) . ' ';
- if ($baseInsc['CollsRegistered'])
- {
- foreach ($baseInsc['CollsRegistered'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: acces authorise sur la collection ') . phrasea::bas_names($base_id);
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
- if ($baseInsc['CollsRefuse'])
- {
- foreach ($baseInsc['CollsRefuse'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: acces refuse sur la collection ') . phrasea::bas_names($base_id) . ' ';
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
- if ($baseInsc['CollsWait'])
- {
- foreach ($baseInsc['CollsWait'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: en attente d\'acces sur') .' '. phrasea::bas_names($base_id) . ' ';
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
- if ($baseInsc['CollsIntime'])
- {
- foreach ($baseInsc['CollsIntime'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: acces temporaire sur') . phrasea::bas_names($base_id) . '';
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
- if ($baseInsc['CollsOuttime'])
- {
- foreach ($baseInsc['CollsOuttime'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: acces temporaire termine sur ') . phrasea::bas_names($base_id) . ' ';
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
- if ($baseInsc['CollsNonactif'])
- {
- foreach ($baseInsc['CollsNonactif'] as $collId => $isTrue)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' . _('login::register: acces supendu sur') . phrasea::bas_names($base_id) . ' ';
- if (trim($isTrue) != '')
- $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
- $out .= ' ';
- }
- $out .= ' ';
- }
-
- $out .= ' ';
- if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript'])// il y a des coll ou s'inscrire !
- {
- $noDemand = false;
-
- if ($baseInsc['Colls'])//des coll ou on peut s'inscrire sans cgu specifiques
- {
- //je check si ya des cgu pour la base
- if ($baseInsc['CGU'])
- {
- $out .= '' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' ';
- $out .= '' . $baseInsc['CGU'] . '
';
+ if ($baseInsc['CollsRegistered']) {
+ foreach ($baseInsc['CollsRegistered'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: acces authorise sur la collection ') . phrasea::bas_names($base_id);
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
}
- foreach ($baseInsc['Colls'] as $collId => $collName)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= '' .
- '' . $collName . ' ' .
- ' ' .
- '' .
- ' ' .
- '' . _('login::register: Faire une demande d\'acces') . ' ' .
- ' ' .
- ' ';
+ if ($baseInsc['CollsRefuse']) {
+ foreach ($baseInsc['CollsRefuse'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: acces refuse sur la collection ') . phrasea::bas_names($base_id) . ' ';
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
}
- }
- if ($baseInsc['CollsCGU'])
- {
- foreach ($baseInsc['CollsCGU'] as $collId => $collDesc)
- {
- $base_id = phrasea::baseFromColl($sbasId, $collId);
- $out .= ' ' .
- '' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' ' .
- '' .
- '' .
- '' . $collDesc['CGU'] . '
' .
- ' ' .
- ' ' .
- '' .
- '' . $collDesc['name'] . ' ' .
- ' ' .
- '' .
- ' ' .
- '' . _('login::register: Faire une demande d\'acces') . ' ' .
- ' ' .
- ' ';
+ if ($baseInsc['CollsWait']) {
+ foreach ($baseInsc['CollsWait'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: en attente d\'acces sur') . ' ' . phrasea::bas_names($base_id) . ' ';
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
+ }
+ if ($baseInsc['CollsIntime']) {
+ foreach ($baseInsc['CollsIntime'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: acces temporaire sur') . phrasea::bas_names($base_id) . '';
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
+ }
+ if ($baseInsc['CollsOuttime']) {
+ foreach ($baseInsc['CollsOuttime'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: acces temporaire termine sur ') . phrasea::bas_names($base_id) . ' ';
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
+ }
+ if ($baseInsc['CollsNonactif']) {
+ foreach ($baseInsc['CollsNonactif'] as $collId => $isTrue) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' . _('login::register: acces supendu sur') . phrasea::bas_names($base_id) . ' ';
+ if (trim($isTrue) != '')
+ $out .= ' ' . _('login::register::CGU: lire les CGU') . ' ';
+ $out .= ' ';
+ }
+ $out .= ' ';
+ }
+
+ $out .= ' ';
+ if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript']) {// il y a des coll ou s'inscrire !
+ $noDemand = false;
+
+ if ($baseInsc['Colls']) {//des coll ou on peut s'inscrire sans cgu specifiques
+ //je check si ya des cgu pour la base
+ if ($baseInsc['CGU']) {
+ $out .= '' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' ';
+ $out .= '' . $baseInsc['CGU'] . '
';
+ }
+ foreach ($baseInsc['Colls'] as $collId => $collName) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= '' .
+ '' . $collName . ' ' .
+ ' ' .
+ '' .
+ ' ' .
+ '' . _('login::register: Faire une demande d\'acces') . ' ' .
+ ' ' .
+ ' ';
+ }
+ }
+ if ($baseInsc['CollsCGU']) {
+ foreach ($baseInsc['CollsCGU'] as $collId => $collDesc) {
+ $base_id = phrasea::baseFromColl($sbasId, $collId);
+ $out .= ' ' .
+ '' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' ' .
+ '' .
+ '' .
+ '' . $collDesc['CGU'] . '
' .
+ ' ' .
+ ' ' .
+ '' .
+ '' . $collDesc['name'] . ' ' .
+ ' ' .
+ '' .
+ ' ' .
+ '' . _('login::register: Faire une demande d\'acces') . ' ' .
+ ' ' .
+ ' ';
+ }
+ }
}
- }
}
- }
- $out .= '
';
+ $out .= '
';
- return array('tab' => $out, 'demandes' => $noDemand);
+ return array('tab' => $out, 'demandes' => $noDemand);
}
function giveModInscript($usr, $lng)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $out = '' .
- '' .
- '' .
- '' .
- '' . _('admin::compte-utilisateur actuellement, acces aux bases suivantes : ') . ' :
' .
- '';
- if ($noDemand)
- {
- $out .= '' . _('login::register: Vous avez acces a toutes les collections de toutes les bases') . '
';
- }
- else
- {
- $out .= '
';
- }
-
- $out .= ' ' .
- '' .
- '';
-
- return $out;
-}
-
-function giveInscript($lng, $demandes=null)
-{
- $appbox = appbox::get_instance(\bootstrap::getCore());
-
- $out = ' ';
- return $out;
+ $out .= '' .
+ '' .
+ '';
+
+ return $out;
}
+function giveInscript($lng, $demandes = null)
+{
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+
+ $out = '';
+
+ return $out;
+}
?>
diff --git a/lib/classes/deprecated/php_phrasea2.php b/lib/classes/deprecated/php_phrasea2.php
deleted file mode 100644
index 1f79bb4032..0000000000
--- a/lib/classes/deprecated/php_phrasea2.php
+++ /dev/null
@@ -1,173 +0,0 @@
-0
-// ORDER BY sbas.ord, sbas.sbas_id, bas.ord";
-// $stmt = $conn->prepare($sql);
-// $stmt->execute();
-// $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
-// $stmt->closeCursor();
-//
-// $last_sbas_id = false;
-//
-// $list = array('bases' => array());
-//
-// foreach ($rs as $row)
-// {
-// $basid = $row['base_id'];
-// $sbas_id = $row['sbas_id'];
-// $viewname = (trim($row['viewname']) !== '') ? $row['viewname'] : $row['dbname'];
-//
-// try
-// {
-// $connbas = connection::getPDOConnection($sbas_id);
-//
-//
-// $list['bases'][$sbas_id] = array(
-// 'sbas_id' => $sbas_id,
-// 'host' => $row['host'],
-// 'port' => $row['port'],
-// 'dbname' => $row['dbname'],
-// 'user' => $row['user'],
-// 'pwd' => $row['pwd'],
-// 'online' => false,
-// 'collections' => array(),
-// );
-//
-// $sql = "SELECT asciiname, prefs FROM coll WHERE coll_id = :coll_id";
-// $stmt = $connbas->prepare($sql);
-// $stmt->execute(array(':coll_id' => $row['coll_id']));
-// $row2 = $stmt->fetch(PDO::FETCH_ASSOC);
-//
-// $list['bases'][$sbas_id]['collections'][$row['coll_id']] =
-// array('asciiname' => $row2['asciiname'], 'prefs' => $row2['prefs']);
-//
-//
-// if ($last_sbas_id == $sbas_id)
-// continue;
-//
-// $list['bases'][$sbas_id]['online'] = true;
-// $last_sbas_id = $sbas_id;
-// }
-// catch (Exception $e)
-// {
-//
-// }
-// }
-// }
-//
-//}
-
-if (!function_exists('phrasea_open_session'))
-{
-
- function phrasea_open_session($ses_id, $usr_id)
- {
- $conn = connection::getPDOConnection();
- $sql = "UPDATE cache SET nact=nact+1, lastaccess=NOW()
- WHERE session_id = :session_id AND usr_id = :usr_id";
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':session_id' => $ses_id, ':usr_id' => $usr_id));
-
- return;
- }
-
-}
-
-
-
-if (!function_exists('phrasea_clear_cache'))
-{
-
- function phrasea_clear_cache()
- {
- $registry = registry::get_instance();
- $filename = $registry->get('GV_RootPath') . '_phrasea_' . $registry->get('GV_sit') . '.answers.' . $ses_id . '';
- unlink($filename);
- $filename = $registry->get('GV_RootPath') . '_phrasea_' . $registry->get('GV_sit') . '.spots.' . $ses_id . '';
- unlink($filename);
- }
-
-}
-
-
-
-if (!function_exists('phrasea_create_session'))
-{
-
- function phrasea_create_session($usr_id)
- {
- try
- {
- $conn = connection::getPDOConnection();
- $sql = "INSERT INTO cache (session_id, nact, lastaccess, answers, spots, session, usr_id)
- VALUES (null, 0, NOW(), '', '', '', :usr_id)";
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':usr_id', $usr_id));
- $ses_id = $conn->lastInsertId();
-
- return $ses_id;
- }
- catch (Exception $e)
- {
- return false;
- }
- }
-
-}
-
-
-if (!function_exists('phrasea_register_base'))
-{
-
- function phrasea_register_base($ses_id, $base_id)
- {
- $registered[$base_id] = true;
- }
-
-}
-
-if (!function_exists('phrasea_close_session'))
-{
-
- function phrasea_close_session($ses_id)
- {
- try
- {
- $conn = connection::getPDOConnection();
- $sql = "DELETE FROM cache WHERE session_id= :session_id";
- $stmt = $conn->prepare($sql);
- $stmt->execute(array(':session_id', $ses_id));
-
- return true;
- }
- catch (Exception $e)
- {
- return false;
- }
- }
-
-}
diff --git a/lib/classes/deprecated/prodUtils.php b/lib/classes/deprecated/prodUtils.php
index 274fba6cd6..f7f6867d99 100644
--- a/lib/classes/deprecated/prodUtils.php
+++ b/lib/classes/deprecated/prodUtils.php
@@ -17,136 +17,121 @@
*/
function deleteRecord($lst, $del_children)
{
- $Core = bootstrap::getCore();
- $em = $Core->getEntityManager();
- $BE_repository = $em->getRepository('\Entities\BasketElement');
+ $Core = bootstrap::getCore();
+ $em = $Core->getEntityManager();
+ $BE_repository = $em->getRepository('\Entities\BasketElement');
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $registry = $Core->getRegistry();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $registry = $Core->getRegistry();
- $user = $Core->getAuthenticatedUser();
- $ACL = $user->ACL();
+ $user = $Core->getAuthenticatedUser();
+ $ACL = $user->ACL();
- $lst = explode(";", $lst);
+ $lst = explode(";", $lst);
- $tcoll = array();
- $tbase = array();
+ $tcoll = array();
+ $tbase = array();
- $conn = $appbox->get_connection();
+ $conn = $appbox->get_connection();
- foreach ($lst as $basrec)
- {
- $basrec = explode("_", $basrec);
- if (!$basrec || count($basrec) !== 2)
- continue;
+ foreach ($lst as $basrec) {
+ $basrec = explode("_", $basrec);
+ if ( ! $basrec || count($basrec) !== 2)
+ continue;
- $record = new record_adapter($basrec[0], $basrec[1]);
- $base_id = $record->get_base_id();
- if (!isset($tcoll["c" . $base_id]))
- {
+ $record = new record_adapter($basrec[0], $basrec[1]);
+ $base_id = $record->get_base_id();
+ if ( ! isset($tcoll["c" . $base_id])) {
- $tcoll["c" . $base_id] = null;
+ $tcoll["c" . $base_id] = null;
- foreach ($appbox->get_databoxes() as $databox)
- {
- foreach ($databox->get_collections() as $collection)
- {
- if ($collection->get_base_id() == $base_id)
- {
- $tcoll["c" . $base_id] = array("base_id" => $databox->get_sbas_id(), "id" => $base_id);
- if (!isset($tbase["b" . $base_id]))
- {
- $x = $databox->get_structure();
- $tbase["b" . $collection->get_base_id()] = array("id" => $collection->get_base_id(), "rids" => array());
+ foreach ($appbox->get_databoxes() as $databox) {
+ foreach ($databox->get_collections() as $collection) {
+ if ($collection->get_base_id() == $base_id) {
+ $tcoll["c" . $base_id] = array("base_id" => $databox->get_sbas_id(), "id" => $base_id);
+ if ( ! isset($tbase["b" . $base_id])) {
+ $x = $databox->get_structure();
+ $tbase["b" . $collection->get_base_id()] = array("id" => $collection->get_base_id(), "rids" => array());
+ }
+ break;
+ }
+ }
}
- break;
- }
- }
- }
- }
-
- $temp = null;
- $temp[0] = $basrec[0];
- $temp[1] = $basrec[1];
-
- $tbase["b" . $tcoll["c" . $base_id]["base_id"]]["rids"][] = $temp;
- }
- $ret = array();
-
- foreach ($tbase as $base)
- {
- try
- {
- foreach ($base["rids"] as $rid)
- {
- $record = new record_adapter($rid[0], $rid[1]);
- if (!$ACL->has_right_on_base($record->get_base_id(), 'candeleterecord'))
- continue;
- if ($del_children == "1")
- {
- foreach ($record->get_children() as $oneson)
- {
- if (!$ACL->has_right_on_base($oneson->get_base_id(), 'candeleterecord'))
- continue;
-
- $oneson->delete();
- $ret[] = $oneson->get_serialize_key();
- }
- }
- $ret[] = $record->get_serialize_key();
-
- $basket_elements = $BE_repository->findElementsByRecord($record);
-
- foreach($basket_elements as $basket_element)
- {
- $em->remove($basket_element);
}
- $record->delete();
- unset($record);
- }
+ $temp = null;
+ $temp[0] = $basrec[0];
+ $temp[1] = $basrec[1];
+
+ $tbase["b" . $tcoll["c" . $base_id]["base_id"]]["rids"][] = $temp;
}
- catch (Exception $e)
- {
+ $ret = array();
+ foreach ($tbase as $base) {
+ try {
+ foreach ($base["rids"] as $rid) {
+ $record = new record_adapter($rid[0], $rid[1]);
+ if ( ! $ACL->has_right_on_base($record->get_base_id(), 'candeleterecord'))
+ continue;
+ if ($del_children == "1") {
+ foreach ($record->get_children() as $oneson) {
+ if ( ! $ACL->has_right_on_base($oneson->get_base_id(), 'candeleterecord'))
+ continue;
+
+ $oneson->delete();
+ $ret[] = $oneson->get_serialize_key();
+ }
+ }
+ $ret[] = $record->get_serialize_key();
+
+ $basket_elements = $BE_repository->findElementsByRecord($record);
+
+ foreach ($basket_elements as $basket_element) {
+ $em->remove($basket_element);
+ }
+
+ $record->delete();
+ unset($record);
+ }
+ } catch (Exception $e) {
+
+ }
}
- }
- $em->flush();
+ $em->flush();
- return p4string::jsonencode($ret);
+ return p4string::jsonencode($ret);
}
function whatCanIDelete($lst)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- $usr_id = $session->get_usr_id();
+ $usr_id = $session->get_usr_id();
- $conn = $appbox->get_connection();
+ $conn = $appbox->get_connection();
- $nbdocsel = 0;
- $nbgrp = 0;
- $oksel = array();
- $arrSel = explode(";", $lst);
+ $nbdocsel = 0;
+ $nbgrp = 0;
+ $oksel = array();
+ $arrSel = explode(";", $lst);
- if (!is_array($lst))
- $lst = explode(';', $lst);
+ if ( ! is_array($lst))
+ $lst = explode(';', $lst);
- foreach ($lst as $sel)
- {
- if ($sel == "")
- continue;
- $exp = explode("_", $sel);
+ foreach ($lst as $sel) {
+ if ($sel == "")
+ continue;
+ $exp = explode("_", $sel);
- if (count($exp) !== 2)
- continue;
+ if (count($exp) !== 2)
+ continue;
- $record = new record_adapter($exp[0], $exp[1]);
- $sqlV = 'SELECT mask_and, mask_xor, sb.*
+ $record = new record_adapter($exp[0], $exp[1]);
+ $sqlV = 'SELECT mask_and, mask_xor, sb.*
FROM (sbas sb, bas b, usr u)
LEFT JOIN basusr bu ON
(bu.base_id = b.base_id AND bu.candeleterecord = "1"
@@ -154,46 +139,41 @@ function whatCanIDelete($lst)
WHERE u.usr_id = :usr_id AND b.base_id = :base_id
AND b.sbas_id = sb.sbas_id';
- $params = array(
- ':base_id' => $record->get_base_id()
- , ':usr_id' => $usr_id
- );
+ $params = array(
+ ':base_id' => $record->get_base_id()
+ , ':usr_id' => $usr_id
+ );
- $stmt = $conn->prepare($sqlV);
- $stmt->execute($params);
- $rowV = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sqlV);
+ $stmt->execute($params);
+ $rowV = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($rowV && $rowV['mask_and'] != '' && $rowV['mask_xor'] != '')
- {
- try
- {
- $connbas = connection::getPDOConnection($rowV['sbas_id']);
- $sqlS2 = 'SELECT record_id FROM record
+ if ($rowV && $rowV['mask_and'] != '' && $rowV['mask_xor'] != '') {
+ try {
+ $connbas = connection::getPDOConnection($rowV['sbas_id']);
+ $sqlS2 = 'SELECT record_id FROM record
WHERE ((status ^ ' . $rowV['mask_xor'] . ') & ' . $rowV['mask_and'] . ')=0
AND record_id = :record_id';
- $stmt = $connbas->prepare($sqlS2);
- $stmt->execute(array(':record_id' => $exp[1]));
- $num_rows = $stmt->rowCount();
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sqlS2);
+ $stmt->execute(array(':record_id' => $exp[1]));
+ $num_rows = $stmt->rowCount();
+ $stmt->closeCursor();
- if ($num_rows > 0)
- {
- $oksel[] = implode('_', $exp);
- $nbdocsel++;
- if ($record->is_grouping())
- $nbgrp++;
+ if ($num_rows > 0) {
+ $oksel[] = implode('_', $exp);
+ $nbdocsel ++;
+ if ($record->is_grouping())
+ $nbgrp ++;
+ }
+ } catch (Exception $e) {
+
+ }
}
- }
- catch (Exception $e)
- {
-
- }
}
- }
- $ret = array('lst' => $oksel, 'groupings' => $nbgrp);
+ $ret = array('lst' => $oksel, 'groupings' => $nbgrp);
- return p4string::jsonencode($ret);
+ return p4string::jsonencode($ret);
}
diff --git a/lib/classes/eventsmanager/broker.class.php b/lib/classes/eventsmanager/broker.class.php
index d4b6048266..e422f56307 100644
--- a/lib/classes/eventsmanager/broker.class.php
+++ b/lib/classes/eventsmanager/broker.class.php
@@ -2,394 +2,363 @@
class eventsmanager_broker
{
+ private static $_instance = false;
+ protected $events = array();
+ protected $notifications = array();
+ protected $pool_classes = array();
- private static $_instance = false;
- protected $events = array();
- protected $notifications = array();
- protected $pool_classes = array();
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var \Alchemy\Phrasea\Core
- */
- protected $core;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
- private function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core)
- {
- $this->appbox = $appbox;
- $this->core = $core;
+ /**
+ *
+ * @var \Alchemy\Phrasea\Core
+ */
+ protected $core;
- return $this;
- }
-
- /**
- * @return \eventsmanager_broker
- */
- public static function getInstance(appbox &$appbox, \Alchemy\Phrasea\Core $core)
- {
- if (!self::$_instance)
+ private function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core)
{
- self::$_instance = new self($appbox, $core);
+ $this->appbox = $appbox;
+ $this->core = $core;
+
+ return $this;
}
- return self::$_instance;
- }
-
- function start()
- {
- $iterators_pool = array(
- 'event' => (is_array($this->appbox->get_registry()->get('GV_events')) ? $this->appbox->get_registry()->get('GV_events') : array()),
- 'notify' => (is_array($this->appbox->get_registry()->get('GV_notifications')) ? $this->appbox->get_registry()->get('GV_notifications') : array())
- );
-
- foreach ($iterators_pool as $type => $iterators)
+ /**
+ * @return \eventsmanager_broker
+ */
+ public static function getInstance(appbox &$appbox, \Alchemy\Phrasea\Core $core)
{
- foreach ($iterators as $fileinfo)
- {
- $classname = $fileinfo;
-
- if (!class_exists($classname, true))
- {
- continue;
+ if ( ! self::$_instance) {
+ self::$_instance = new self($appbox, $core);
}
- $this->pool_classes[$classname] = new $classname($this->appbox, $this->core, $this);
- foreach ($this->pool_classes[$classname]->get_events() as $event)
- $this->bind($event, $classname);
-
- if ($type === 'notify' && $this->pool_classes[$classname]->is_available())
- $this->notifications[] = $classname;
- }
+ return self::$_instance;
}
- return;
- }
-
- public function list_all($type)
- {
- $iterators_pool = array();
-
- $root = __DIR__ . '/../../';
-
- if ($type == 'event')
+ function start()
{
- $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
- if (file_exists(__DIR__ . '/event/'))
- $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
- }
- if ($type == 'notify')
- {
- $iterators_pool['notify'][] = new DirectoryIterator(__DIR__ . '/notify/');
- }
+ $iterators_pool = array(
+ 'event' => (is_array($this->appbox->get_registry()->get('GV_events')) ? $this->appbox->get_registry()->get('GV_events') : array()),
+ 'notify' => (is_array($this->appbox->get_registry()->get('GV_notifications')) ? $this->appbox->get_registry()->get('GV_notifications') : array())
+ );
- $ret = array();
+ foreach ($iterators_pool as $type => $iterators) {
+ foreach ($iterators as $fileinfo) {
+ $classname = $fileinfo;
- foreach ($iterators_pool as $type => $iterators)
- {
- foreach ($iterators as $iterator)
- {
- foreach ($iterator as $fileinfo)
- {
- if (!$fileinfo->isDot())
- {
- if (substr($fileinfo->getFilename(), 0, 1) == '.')
- continue;
+ if ( ! class_exists($classname, true)) {
+ continue;
+ }
+ $this->pool_classes[$classname] = new $classname($this->appbox, $this->core, $this);
- $filename = explode('.', $fileinfo->getFilename());
- $classname = 'eventsmanager_' . $type . '_' . $filename[0];
+ foreach ($this->pool_classes[$classname]->get_events() as $event)
+ $this->bind($event, $classname);
- if (!class_exists($classname))
- {
- continue;
+ if ($type === 'notify' && $this->pool_classes[$classname]->is_available())
+ $this->notifications[] = $classname;
}
- $obj = new $classname($this->appbox, $this->core, $this);
-
- $ret[$classname] = $obj->get_name();
- }
}
- }
+
+ return;
}
- return $ret;
- }
-
- function trigger($event, $array_params=array(), &$object = false)
- {
- if (array_key_exists($event, $this->events))
+ public function list_all($type)
{
- foreach ($this->events[$event] as $classname)
- {
- $this->pool_classes[$classname]->fire($event, $array_params, $object);
- }
+ $iterators_pool = array();
+
+ $root = __DIR__ . '/../../';
+
+ if ($type == 'event') {
+ $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
+ if (file_exists(__DIR__ . '/event/'))
+ $iterators_pool['event'][] = new DirectoryIterator(__DIR__ . '/event/');
+ }
+ if ($type == 'notify') {
+ $iterators_pool['notify'][] = new DirectoryIterator(__DIR__ . '/notify/');
+ }
+
+ $ret = array();
+
+ foreach ($iterators_pool as $type => $iterators) {
+ foreach ($iterators as $iterator) {
+ foreach ($iterator as $fileinfo) {
+ if ( ! $fileinfo->isDot()) {
+ if (substr($fileinfo->getFilename(), 0, 1) == '.')
+ continue;
+
+ $filename = explode('.', $fileinfo->getFilename());
+ $classname = 'eventsmanager_' . $type . '_' . $filename[0];
+
+ if ( ! class_exists($classname)) {
+ continue;
+ }
+ $obj = new $classname($this->appbox, $this->core, $this);
+
+ $ret[$classname] = $obj->get_name();
+ }
+ }
+ }
+ }
+
+ return $ret;
}
- return;
- }
-
- function bind($event, $object_name)
- {
-
- if (!array_key_exists($event, $this->events))
- $this->events[$event] = array();
-
- $this->events[$event][] = $object_name;
- }
-
- function notify($usr_id, $event_type, $datas, $mailed=false)
- {
- try
+ function trigger($event, $array_params = array(), &$object = false)
{
- $event_type = str_replace('eventsmanager_', '', $event_type);
+ if (array_key_exists($event, $this->events)) {
+ foreach ($this->events[$event] as $classname) {
+ $this->pool_classes[$classname]->fire($event, $array_params, $object);
+ }
+ }
- $sql = 'INSERT INTO notifications (id, usr_id, type, unread, mailed, datas, created_on)
+ return;
+ }
+
+ function bind($event, $object_name)
+ {
+
+ if ( ! array_key_exists($event, $this->events))
+ $this->events[$event] = array();
+
+ $this->events[$event][] = $object_name;
+ }
+
+ function notify($usr_id, $event_type, $datas, $mailed = false)
+ {
+ try {
+ $event_type = str_replace('eventsmanager_', '', $event_type);
+
+ $sql = 'INSERT INTO notifications (id, usr_id, type, unread, mailed, datas, created_on)
VALUES
(null, :usr_id, :event_type, 1, :mailed, :datas, NOW())';
- $params = array(
- ':usr_id' => $usr_id
- , ':event_type' => $event_type
- , ':mailed' => ($mailed ? 1 : 0)
- , ':datas' => $datas
- );
+ $params = array(
+ ':usr_id' => $usr_id
+ , ':event_type' => $event_type
+ , ':mailed' => ($mailed ? 1 : 0)
+ , ':datas' => $datas
+ );
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+ return false;
+ }
+
+ return true;
}
- catch (Exception $e)
+
+ function get_json_notifications($page = 0)
{
- return false;
- }
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- return true;
- }
+ $unread = 0;
+ $total = 0;
- function get_json_notifications($page=0)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $unread = 0;
- $total = 0;
-
- $sql = 'SELECT count(id) as total, sum(unread) as unread
+ $sql = 'SELECT count(id) as total, sum(unread) as unread
FROM notifications WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($row)
- {
- $unread = $row['unread'];
- $total = $row['total'];
- }
+ if ($row) {
+ $unread = $row['unread'];
+ $total = $row['total'];
+ }
- $n = 10;
+ $n = 10;
- $sql = 'SELECT * FROM notifications
+ $sql = 'SELECT * FROM notifications
WHERE usr_id = :usr_id
ORDER BY created_on DESC
LIMIT ' . ((int) $page * $n) . ', ' . $n;
- $datas = array('notifications' => array(), 'next' => '');
+ $datas = array('notifications' => array(), 'next' => '');
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs as $row)
- {
- $type = 'eventsmanager_' . $row['type'];
- $data = $this->pool_classes[$type]->datas($row['datas'], $row['unread']);
-
- if (!isset($this->pool_classes[$type]) || count($datas) === 0)
- {
- $sql = 'DELETE FROM notifications WHERE id = :id';
$stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $row['id']));
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- continue;
- }
- $date_key = str_replace('-', '_', substr($row['created_on'], 0, 10));
- $display_date = phraseadate::getDate(new DateTime($row['created_on']));
+ foreach ($rs as $row) {
+ $type = 'eventsmanager_' . $row['type'];
+ $data = $this->pool_classes[$type]->datas($row['datas'], $row['unread']);
- if (!isset($datas['notifications'][$date_key]))
- {
- $datas['notifications'][$date_key] = array(
- 'display' => $display_date
- , 'notifications' => array()
- );
- }
+ if ( ! isset($this->pool_classes[$type]) || count($datas) === 0) {
+ $sql = 'DELETE FROM notifications WHERE id = :id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $row['id']));
+ $stmt->closeCursor();
+ continue;
+ }
- $datas['notifications'][$date_key]['notifications'][$row['id']] = array(
- 'classname' => $data['class']
- , 'time' => phraseadate::getTime(new DateTime($row['created_on']))
- , 'icon' => ' '
- , 'id' => $row['id']
- , 'text' => $data['text']
- );
+ $date_key = str_replace('-', '_', substr($row['created_on'], 0, 10));
+ $display_date = phraseadate::getDate(new DateTime($row['created_on']));
+
+ if ( ! isset($datas['notifications'][$date_key])) {
+ $datas['notifications'][$date_key] = array(
+ 'display' => $display_date
+ , 'notifications' => array()
+ );
+ }
+
+ $datas['notifications'][$date_key]['notifications'][$row['id']] = array(
+ 'classname' => $data['class']
+ , 'time' => phraseadate::getTime(new DateTime($row['created_on']))
+ , 'icon' => ' '
+ , 'id' => $row['id']
+ , 'text' => $data['text']
+ );
+ }
+
+ if (((int) $page + 1) * $n < $total) {
+ $datas['next'] = '' . _('charger d\'avantages de notifications') . ' ';
+ }
+
+ return p4string::jsonencode($datas);
}
- if (((int) $page + 1) * $n < $total)
+ function get_unread_notifications_number()
{
- $datas['next'] = '' . _('charger d\'avantages de notifications') . ' ';
- }
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- return p4string::jsonencode($datas);
- }
+ $total = 0;
- function get_unread_notifications_number()
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $total = 0;
-
- $sql = 'SELECT count(id) as total
+ $sql = 'SELECT count(id) as total
FROM notifications
WHERE usr_id = :usr_id AND unread="1"';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if ($row)
- {
- $total = $row['total'];
+ if ($row) {
+ $total = $row['total'];
+ }
+
+ return $total;
}
- return $total;
- }
+ function get_notifications()
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- function get_notifications()
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
+ $unread = 0;
+ $total = 0;
- $unread = 0;
- $total = 0;
-
- $sql = 'SELECT count(id) as total, sum(unread) as unread
+ $sql = 'SELECT count(id) as total, sum(unread) as unread
FROM notifications WHERE usr_id = :usr_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- if ($row)
- {
- $unread = $row['unread'];
- $total = $row['total'];
- }
-
- if ($unread < 3)
- {
- $sql = 'SELECT * FROM notifications
- WHERE usr_id = :usr_id ORDER BY created_on DESC LIMIT 0,4';
- }
- else
- {
- $sql = 'SELECT * FROM notifications
- WHERE usr_id = :usr_id AND unread="1" ORDER BY created_on DESC';
- }
-
- $ret = $bloc = array();
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $session->get_usr_id()));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs as $row)
- {
- $type = 'eventsmanager_' . $row['type'];
- if (!isset($this->pool_classes[$type]))
- {
- continue;
- }
- $datas = $this->pool_classes[$type]->datas($row['datas'], $row['unread']);
-
- if (!isset($this->pool_classes[$type]) || count($datas) === 0)
- {
- $sql = 'DELETE FROM notifications WHERE id = :id';
$stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':id' => $row['id']));
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- continue;
- }
- $ret[] = array_merge(
- $datas
- , array(
- 'created_on' => phraseadate::getPrettyString(new DateTime($row['created_on']))
- , 'icon' => $this->pool_classes[$type]->icon_url()
- , 'id' => $row['id']
- , 'unread' => $row['unread']
- )
- );
+ if ($row) {
+ $unread = $row['unread'];
+ $total = $row['total'];
+ }
+
+ if ($unread < 3) {
+ $sql = 'SELECT * FROM notifications
+ WHERE usr_id = :usr_id ORDER BY created_on DESC LIMIT 0,4';
+ } else {
+ $sql = 'SELECT * FROM notifications
+ WHERE usr_id = :usr_id AND unread="1" ORDER BY created_on DESC';
+ }
+
+ $ret = $bloc = array();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $session->get_usr_id()));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs as $row) {
+ $type = 'eventsmanager_' . $row['type'];
+ if ( ! isset($this->pool_classes[$type])) {
+ continue;
+ }
+ $datas = $this->pool_classes[$type]->datas($row['datas'], $row['unread']);
+
+ if ( ! isset($this->pool_classes[$type]) || count($datas) === 0) {
+ $sql = 'DELETE FROM notifications WHERE id = :id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':id' => $row['id']));
+ $stmt->closeCursor();
+ continue;
+ }
+
+ $ret[] = array_merge(
+ $datas
+ , array(
+ 'created_on' => phraseadate::getPrettyString(new DateTime($row['created_on']))
+ , 'icon' => $this->pool_classes[$type]->icon_url()
+ , 'id' => $row['id']
+ , 'unread' => $row['unread']
+ )
+ );
+ }
+
+ $html = '';
+
+ return $ret;
}
- $html = '';
+ function read(Array $notifications, $usr_id)
+ {
+ if (count($notifications) == 0)
+ return false;
- return $ret;
- }
-
- function read(Array $notifications, $usr_id)
- {
- if (count($notifications) == 0)
-
- return false;
-
- $sql = 'UPDATE notifications SET unread="0"
+ $sql = 'UPDATE notifications SET unread="0"
WHERE usr_id = :usr_id
AND (id="' . implode('" OR id="', $notifications) . '")';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $usr_id));
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $usr_id));
+ $stmt->closeCursor();
- return $this;
- }
-
- function mailed($notification, $usr_id)
- {
- $sql = 'UPDATE notifications SET mailed="0"
- WHERE usr_id = :usr_id AND id = :notif_id';
-
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':usr_id' => $usr_id, ':notif_id' => $notifications));
- $stmt->closeCursor();
-
- return;
- }
-
- function list_notifications_available($usr_id)
- {
-
- $personnal_notifications = array();
-
- foreach ($this->notifications as $notification)
- {
- $group = $this->pool_classes[$notification]->get_group();
- $group = $group === null ? _('Notifications globales') : $group;
-
- $personnal_notifications[$group][] = array(
- 'name' => $this->pool_classes[$notification]->get_name()
- , 'id' => $notification
- , 'description' => $this->pool_classes[$notification]->get_description()
- , 'subscribe_emails' => true
- );
+ return $this;
}
- return $personnal_notifications;
- }
+ function mailed($notification, $usr_id)
+ {
+ $sql = 'UPDATE notifications SET mailed="0"
+ WHERE usr_id = :usr_id AND id = :notif_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':usr_id' => $usr_id, ':notif_id' => $notifications));
+ $stmt->closeCursor();
+
+ return;
+ }
+
+ function list_notifications_available($usr_id)
+ {
+
+ $personnal_notifications = array();
+
+ foreach ($this->notifications as $notification) {
+ $group = $this->pool_classes[$notification]->get_group();
+ $group = $group === null ? _('Notifications globales') : $group;
+
+ $personnal_notifications[$group][] = array(
+ 'name' => $this->pool_classes[$notification]->get_name()
+ , 'id' => $notification
+ , 'description' => $this->pool_classes[$notification]->get_description()
+ , 'subscribe_emails' => true
+ );
+ }
+
+ return $personnal_notifications;
+ }
}
diff --git a/lib/classes/eventsmanager/event/test.class.php b/lib/classes/eventsmanager/event/test.class.php
index f5eecc56e3..ae77ed077d 100644
--- a/lib/classes/eventsmanager/event/test.class.php
+++ b/lib/classes/eventsmanager/event/test.class.php
@@ -17,28 +17,26 @@
*/
class eventsmanager_event_test extends eventsmanager_eventAbstract
{
+ /**
+ *
+ * @var Array
+ */
+ protected $events = array('__EVENT__');
- /**
- *
- * @var Array
- */
- protected $events = array('__EVENT__');
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return event_test
- */
- public function fire($event, $params, &$object)
- {
- return $this;
- }
-
- public function get_name()
- {
- return 'Test event';
- }
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return event_test
+ */
+ public function fire($event, $params, &$object)
+ {
+ return $this;
+ }
+ public function get_name()
+ {
+ return 'Test event';
+ }
}
diff --git a/lib/classes/eventsmanager/eventAbstract.class.php b/lib/classes/eventsmanager/eventAbstract.class.php
index 343567774a..1b6b771634 100644
--- a/lib/classes/eventsmanager/eventAbstract.class.php
+++ b/lib/classes/eventsmanager/eventAbstract.class.php
@@ -2,52 +2,54 @@
abstract class eventsmanager_eventAbstract
{
+ protected $events = array();
+ protected $group = null;
- protected $events = array();
- protected $group = null;
- /**
- *
- * @var appbox
- */
- protected $appbox;
- /**
- *
- * @var registryInterface
- */
- protected $registry;
- /**
- *
- * @var \Alchemy\Phrasea\Core
- */
- protected $core;
- /**
- *
- * @var eventsmanager
- */
- protected $broker;
+ /**
+ *
+ * @var appbox
+ */
+ protected $appbox;
+ /**
+ *
+ * @var registryInterface
+ */
+ protected $registry;
- public function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->appbox = $appbox;
- $this->registry = $core->getRegistry();
- $this->core = $core;
- $this->broker = $broker;
+ /**
+ *
+ * @var \Alchemy\Phrasea\Core
+ */
+ protected $core;
- return $this;
- }
+ /**
+ *
+ * @var eventsmanager
+ */
+ protected $broker;
- public function get_group()
- {
- return $this->group;
- }
+ public function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
+ {
+ $this->appbox = $appbox;
+ $this->registry = $core->getRegistry();
+ $this->core = $core;
+ $this->broker = $broker;
- public function get_events()
- {
- return $this->events;
- }
+ return $this;
+ }
- abstract public function get_name();
+ public function get_group()
+ {
+ return $this->group;
+ }
- abstract public function fire($event, $params, &$object);
+ public function get_events()
+ {
+ return $this->events;
+ }
+
+ abstract public function get_name();
+
+ abstract public function fire($event, $params, &$object);
}
diff --git a/lib/classes/eventsmanager/notify/autoregister.class.php b/lib/classes/eventsmanager/notify/autoregister.class.php
index fb42f178b4..d6414b4d0f 100644
--- a/lib/classes/eventsmanager/notify/autoregister.class.php
+++ b/lib/classes/eventsmanager/notify/autoregister.class.php
@@ -17,46 +17,44 @@
*/
class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__REGISTER_AUTOREGISTER__');
- /**
- *
- * @var string
- */
- public $events = array('__REGISTER_AUTOREGISTER__');
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
+ {
+ return '/skins/icons/user.png';
+ }
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/user.png';
- }
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return Void
+ */
+ public function fire($event, $params, &$object)
+ {
+ $default = array(
+ 'usr_id' => ''
+ , 'autoregister' => array()
+ );
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return Void
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'usr_id' => ''
- , 'autoregister' => array()
- );
+ $params = array_merge($default, $params);
+ $base_ids = array_keys($params['autoregister']);
- $params = array_merge($default, $params);
- $base_ids = array_keys($params['autoregister']);
+ if (count($base_ids) == 0)
+ return;
- if (count($base_ids) == 0)
+ $mailColl = array();
- return;
-
- $mailColl = array();
-
- $sql = 'SELECT u.usr_id, b.base_id FROM usr u, basusr b
+ $sql = 'SELECT u.usr_id, b.base_id FROM usr u, basusr b
WHERE u.usr_id = b.usr_id
AND b.base_id
IN (' . implode(', ', array_keys($base_ids)) . ')
@@ -65,242 +63,217 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract
AND b.canadmin="1"
AND u.usr_login NOT LIKE "(#deleted%"';
- try
- {
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ try {
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- if (!isset($mailColl[$row['usr_id']]))
- $mailColl[$row['usr_id']] = array();
+ foreach ($rs as $row) {
+ if ( ! isset($mailColl[$row['usr_id']]))
+ $mailColl[$row['usr_id']] = array();
- $mailColl[$row['usr_id']][] = $row['base_id'];
- }
- }
- catch (Exception $e)
- {
+ $mailColl[$row['usr_id']][] = $row['base_id'];
+ }
+ } catch (Exception $e) {
- }
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $usr_id = $dom_xml->createElement('usr_id');
- $base_ids = $dom_xml->createElement('base_ids');
-
- $usr_id->appendChild($dom_xml->createTextNode($params['usr_id']));
-
- foreach ($params['autoregister'] as $base_id => $collection)
- {
- $base_id_node = $dom_xml->createElement('base_id');
- $base_id_node->appendChild($dom_xml->createTextNode($base_id));
- $base_ids->appendChild($base_id_node);
- }
-
- $root->appendChild($usr_id);
- $root->appendChild($base_ids);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- foreach ($mailColl as $usr_id => $base_ids)
- {
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
-
- if ($send_notif)
- {
- try
- {
- $admin_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- continue;
}
- $dest = $admin_user->get_email();
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
- if (trim($admin_user->get_firstname() . ' ' . $admin_user->get_lastname()) != '')
- $dest = $admin_user->get_firstname() . ' ' . $admin_user->get_lastname();
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
- $to = array('email' => $admin_user->get_email(), 'name' => $dest);
- $from = array(
- 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
- 'name' => $this->registry->get('GV_homeTitle')
+ $root = $dom_xml->createElement('datas');
+
+ $usr_id = $dom_xml->createElement('usr_id');
+ $base_ids = $dom_xml->createElement('base_ids');
+
+ $usr_id->appendChild($dom_xml->createTextNode($params['usr_id']));
+
+ foreach ($params['autoregister'] as $base_id => $collection) {
+ $base_id_node = $dom_xml->createElement('base_id');
+ $base_id_node->appendChild($dom_xml->createTextNode($base_id));
+ $base_ids->appendChild($base_id_node);
+ }
+
+ $root->appendChild($usr_id);
+ $root->appendChild($base_ids);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ foreach ($mailColl as $usr_id => $base_ids) {
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
+
+ if ($send_notif) {
+ try {
+ $admin_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ continue;
+ }
+
+ $dest = $admin_user->get_email();
+
+ if (trim($admin_user->get_firstname() . ' ' . $admin_user->get_lastname()) != '')
+ $dest = $admin_user->get_firstname() . ' ' . $admin_user->get_lastname();
+
+ $to = array('email' => $admin_user->get_email(), 'name' => $dest);
+ $from = array(
+ 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
+ 'name' => $this->registry->get('GV_homeTitle')
+ );
+
+ if (self::mail($to, $from, $datas))
+ $mailed = true;
+ }
+
+
+ $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
+
+ $usr_id = (string) $sx->usr_id;
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return array();
+ }
+
+ $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+
+ $ret = array(
+ 'text' => sprintf(
+ _('%1$s s\'est enregistre sur une ou plusieurs %2$scollections%3$s'), $sender, '', ' ')
+ , 'class' => ''
);
- if (self::mail($to, $from, $datas))
- $mailed = true;
- }
-
-
- $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ return $ret;
}
- return;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $usr_id = (string) $sx->usr_id;
- try
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
{
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ return _('AutoRegister information');
}
- catch (Exception $e)
+
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
{
- return array();
+ return _('Recevoir des notifications lorsqu\'un'
+ . ' utilisateur s\'inscrit sur une collection');
}
- $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param Array $datas
+ * @return boolean
+ */
+ function mail($to, $from, $datas)
+ {
+ $subject = sprintf(_('admin::register: Inscription automatique sur %s')
+ , $this->registry->get('GV_homeTitle'));
- $ret = array(
- 'text' => sprintf(
- _('%1$s s\'est enregistre sur une ou plusieurs %2$scollections%3$s'),
- $sender,
- '', ' ')
- , 'class' => ''
- );
-
- return $ret;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('AutoRegister information');
- }
-
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'un'
- . ' utilisateur s\'inscrit sur une collection');
- }
-
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param Array $datas
- * @return boolean
- */
- function mail($to, $from, $datas)
- {
- $subject = sprintf(_('admin::register: Inscription automatique sur %s')
- , $this->registry->get('GV_homeTitle'));
-
- $body = "" . _('admin::register: un utilisateur s\'est inscrit')
+ $body = "
" . _('admin::register: un utilisateur s\'est inscrit')
. "
\n";
- $sx = simplexml_load_string($datas);
+ $sx = simplexml_load_string($datas);
- $usr_id = (string) $sx->usr_id;
+ $usr_id = (string) $sx->usr_id;
- try
- {
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
- $body .= "
\n
Login : " . $registered_user->get_login() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur nom')
+ $body .= "
\n
Login : " . $registered_user->get_login() . "
\n";
+ $body .= "
" . _('admin::compte-utilisateur nom')
. " : " . $registered_user->get_firstname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur prenom')
+ $body .= "
" . _('admin::compte-utilisateur prenom')
. " : " . $registered_user->get_lastname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur email')
+ $body .= "
" . _('admin::compte-utilisateur email')
. " : " . $registered_user->get_email() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur adresse')
+ $body .= "
" . _('admin::compte-utilisateur adresse')
. " : " . $registered_user->get_address() . "
\n";
- $body .= "
" . $registered_user->get_city() . " "
+ $body .= "
" . $registered_user->get_city() . " "
. $registered_user->get_zipcode() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur telephone')
+ $body .= "
" . _('admin::compte-utilisateur telephone')
. " : " . $registered_user->get_tel() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur fax')
+ $body .= "
" . _('admin::compte-utilisateur fax')
. " : " . $registered_user->get_fax() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur poste')
+ $body .= "
" . _('admin::compte-utilisateur poste')
. "/" . _('admin::compte-utilisateur societe') . " "
. $registered_user->get_job() . " " . $registered_user->get_company()
. "
\n";
- $base_ids = $sx->base_ids;
+ $base_ids = $sx->base_ids;
- $body .= "
\n
"
+ $body .= "
\n
"
. _('admin::register: l\'utilisateur s\'est inscrit sur les bases suivantes')
. "
\n";
- $body .= "
\n";
+ $body .= "\n";
- foreach ($base_ids->base_id as $base_id)
- {
- $body .= ""
- . phrasea::sbas_names(phrasea::sbasFromBas((string) $base_id))
- . ' - ' . phrasea::bas_names((string) $base_id) . " \n";
- }
+ foreach ($base_ids->base_id as $base_id) {
+ $body .= ""
+ . phrasea::sbas_names(phrasea::sbasFromBas((string) $base_id))
+ . ' - ' . phrasea::bas_names((string) $base_id) . " \n";
+ }
- $body .= " \n";
+ $body .= " \n";
- $body .= "
\n
"
+ $body .= " \n\n";
- return mail::send_mail($subject, $body, $to, $from);
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- $bool = false;
- $session = $this->appbox->get_session();
- if (!$session->is_authenticated() || !login::register_enabled())
-
- return false;
-
- try
- {
- $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
+ return mail::send_mail($subject, $body, $to, $from);
}
- if ($user->ACL()->has_right('manageusers') === true)
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
{
- $bool = true;
+ $bool = false;
+ $session = $this->appbox->get_session();
+ if ( ! $session->is_authenticated() || ! login::register_enabled())
+ return false;
+
+ try {
+ $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ if ($user->ACL()->has_right('manageusers') === true) {
+ $bool = true;
+ }
+
+ return $bool;
}
-
- return $bool;
- }
-
}
diff --git a/lib/classes/eventsmanager/notify/bridgeuploadfail.class.php b/lib/classes/eventsmanager/notify/bridgeuploadfail.class.php
index d25ac34480..aaece491c0 100644
--- a/lib/classes/eventsmanager/notify/bridgeuploadfail.class.php
+++ b/lib/classes/eventsmanager/notify/bridgeuploadfail.class.php
@@ -17,172 +17,166 @@
*/
class eventsmanager_notify_bridgeuploadfail extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__BRIDGE_UPLOAD_FAIL__');
- /**
- *
- * @var string
- */
- public $events = array('__BRIDGE_UPLOAD_FAIL__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/user.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return Void
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'usr_id' => null
- , 'reason' => ''
- , 'account_id' => null
- , 'base_id' => null
- , 'record_id' => null
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $reason = $dom_xml->createElement('reason');
- $account_id = $dom_xml->createElement('account_id');
- $sbas_id = $dom_xml->createElement('sbas_id');
- $record_id = $dom_xml->createElement('record_id');
-
- $reason->appendChild($dom_xml->createTextNode($params['reason']));
- $account_id->appendChild($dom_xml->createTextNode($params['account_id']));
- $sbas_id->appendChild($dom_xml->createTextNode($params['sbas_id']));
- $record_id->appendChild($dom_xml->createTextNode($params['record_id']));
-
- $root->appendChild($reason);
- $root->appendChild($account_id);
- $root->appendChild($sbas_id);
- $root->appendChild($record_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['usr_id']) != '0');
-
- if ($send_notif)
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $user = User_Adapter::getInstance($params['usr_id'], $this->appbox);
- $name = $user->get_display_name();
-
- $to = array('email' => $user->get_email(), 'name' => $name);
-
- $from = array(
- 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
- 'name' => $this->registry->get('GV_homeTitle')
- );
-
- if (self::mail($to, $from, $datas))
- $mailed = true;
+ return '/skins/icons/user.png';
}
- $this->broker->notify($params['usr_id'], __CLASS__, $datas, $mailed);
-
- return;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $reason = (string) $sx->reason;
- $account_id = (int) $sx->account_id;
- $sbas_id = (int) $sx->sbas_id;
- $rid = (int) $sx->record_id;
-
- try
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return Void
+ */
+ public function fire($event, $params, &$object)
{
- $account = Bridge_Account::load_account($this->appbox, $account_id);
- $record = new record_adapter($sbas_id, $rid);
- }
- catch (Exception $e)
- {
- return array();
+ $default = array(
+ 'usr_id' => null
+ , 'reason' => ''
+ , 'account_id' => null
+ , 'base_id' => null
+ , 'record_id' => null
+ );
+
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $reason = $dom_xml->createElement('reason');
+ $account_id = $dom_xml->createElement('account_id');
+ $sbas_id = $dom_xml->createElement('sbas_id');
+ $record_id = $dom_xml->createElement('record_id');
+
+ $reason->appendChild($dom_xml->createTextNode($params['reason']));
+ $account_id->appendChild($dom_xml->createTextNode($params['account_id']));
+ $sbas_id->appendChild($dom_xml->createTextNode($params['sbas_id']));
+ $record_id->appendChild($dom_xml->createTextNode($params['record_id']));
+
+ $root->appendChild($reason);
+ $root->appendChild($account_id);
+ $root->appendChild($sbas_id);
+ $root->appendChild($record_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['usr_id']) != '0');
+
+ if ($send_notif) {
+ $user = User_Adapter::getInstance($params['usr_id'], $this->appbox);
+ $name = $user->get_display_name();
+
+ $to = array('email' => $user->get_email(), 'name' => $name);
+
+ $from = array(
+ 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
+ 'name' => $this->registry->get('GV_homeTitle')
+ );
+
+ if (self::mail($to, $from, $datas))
+ $mailed = true;
+ }
+
+ $this->broker->notify($params['usr_id'], __CLASS__, $datas, $mailed);
+
+ return;
}
- $ret = array(
- 'text' => sprintf("L'upload concernant le record %s sur le comptre %s a echoue pour les raisons suivantes : %s"
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
+
+ $reason = (string) $sx->reason;
+ $account_id = (int) $sx->account_id;
+ $sbas_id = (int) $sx->sbas_id;
+ $rid = (int) $sx->record_id;
+
+ try {
+ $account = Bridge_Account::load_account($this->appbox, $account_id);
+ $record = new record_adapter($sbas_id, $rid);
+ } catch (Exception $e) {
+ return array();
+ }
+
+ $ret = array(
+ 'text' => sprintf("L'upload concernant le record %s sur le comptre %s a echoue pour les raisons suivantes : %s"
, $record->get_title(), $account->get_api()->get_connector()->get_name(), $reason)
- , 'class' => ''
- );
+ , 'class' => ''
+ );
- return $ret;
- }
+ return $ret;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Bridge upload fail');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Bridge upload fail');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'un'
- . ' upload echoue sur un bridge');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Recevoir des notifications lorsqu\'un'
+ . ' upload echoue sur un bridge');
+ }
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param Array $datas
- * @return boolean
- */
- function mail($to, $from, $datas)
- {
- $subject = sprintf('Echec upload sur %s'
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param Array $datas
+ * @return boolean
+ */
+ function mail($to, $from, $datas)
+ {
+ $subject = sprintf('Echec upload sur %s'
, $this->registry->get('GV_homeTitle'));
- $sx = simplexml_load_string($datas);
+ $sx = simplexml_load_string($datas);
- $reason = (string) $sx->reason;
- $body = "reason : " . $reason;
+ $reason = (string) $sx->reason;
+ $body = "reason : " . $reason;
- return mail::send_mail($subject, $body, $to, $from);
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ return mail::send_mail($subject, $body, $to, $from);
+ }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notify/downloadmailfail.class.php b/lib/classes/eventsmanager/notify/downloadmailfail.class.php
index 4ca0204621..e11de9034c 100644
--- a/lib/classes/eventsmanager/notify/downloadmailfail.class.php
+++ b/lib/classes/eventsmanager/notify/downloadmailfail.class.php
@@ -17,161 +17,153 @@
*/
class eventsmanager_notify_downloadmailfail extends eventsmanager_notifyAbstract
{
+ const MAIL_NO_VALID = 1;
+ const MAIL_FAIL = 2;
- const MAIL_NO_VALID = 1;
- const MAIL_FAIL = 2;
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__EXPORT_MAIL_FAIL__');
- /**
- *
- * @var string
- */
- public $events = array('__EXPORT_MAIL_FAIL__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/user.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return Void
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'usr_id' => null
- , 'lst' => ''
- , 'ssttid' => ''
- , 'dest' => ''
- , 'reason' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $lst = $dom_xml->createElement('lst');
- $ssttid = $dom_xml->createElement('ssttid');
- $dest = $dom_xml->createElement('dest');
- $reason = $dom_xml->createElement('reason');
-
- $lst->appendChild($dom_xml->createTextNode($params['lst']));
- $ssttid->appendChild($dom_xml->createTextNode($params['ssttid']));
- $dest->appendChild($dom_xml->createTextNode($params['dest']));
- $reason->appendChild($dom_xml->createTextNode($params['reason']));
-
- $root->appendChild($lst);
- $root->appendChild($ssttid);
- $root->appendChild($dest);
- $root->appendChild($reason);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['usr_id']) != '0');
-
- if ($send_notif)
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $user = User_Adapter::getInstance($params['usr_id'], $this->appbox);
- $name = $user->get_display_name();
-
- $to = array('email' => $user->get_email(), 'name' => $name);
-
- $from = array(
- 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
- 'name' => $this->registry->get('GV_homeTitle')
- );
-
- if (parent::email())
- $mailed = true;
+ return '/skins/icons/user.png';
}
- $this->broker->notify($params['usr_id'], __CLASS__, $datas, $mailed);
-
- return;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
- $usr_id = (int) $sx->usr_id;
- $reason = (int) $sx->reason;
- $lst = (string) $sx->lst;
- $ssttid = (int) $sx->ssttid;
- $dest = (string) $sx->dest;
-
- if ($reason == self::MAIL_NO_VALID)
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return Void
+ */
+ public function fire($event, $params, &$object)
{
- $reason = _('email is not valid');
- }
- elseif ($reason == self::MAIL_FAIL)
- {
- $reason = _('failed to send mail');
- }
- else
- {
- $reason = _('an error occured while exporting records');
+ $default = array(
+ 'usr_id' => null
+ , 'lst' => ''
+ , 'ssttid' => ''
+ , 'dest' => ''
+ , 'reason' => ''
+ );
+
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $lst = $dom_xml->createElement('lst');
+ $ssttid = $dom_xml->createElement('ssttid');
+ $dest = $dom_xml->createElement('dest');
+ $reason = $dom_xml->createElement('reason');
+
+ $lst->appendChild($dom_xml->createTextNode($params['lst']));
+ $ssttid->appendChild($dom_xml->createTextNode($params['ssttid']));
+ $dest->appendChild($dom_xml->createTextNode($params['dest']));
+ $reason->appendChild($dom_xml->createTextNode($params['reason']));
+
+ $root->appendChild($lst);
+ $root->appendChild($ssttid);
+ $root->appendChild($dest);
+ $root->appendChild($reason);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['usr_id']) != '0');
+
+ if ($send_notif) {
+ $user = User_Adapter::getInstance($params['usr_id'], $this->appbox);
+ $name = $user->get_display_name();
+
+ $to = array('email' => $user->get_email(), 'name' => $name);
+
+ $from = array(
+ 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
+ 'name' => $this->registry->get('GV_homeTitle')
+ );
+
+ if (parent::email())
+ $mailed = true;
+ }
+
+ $this->broker->notify($params['usr_id'], __CLASS__, $datas, $mailed);
+
+ return;
}
- $text = sprintf(
- _("The delivery to %s failed for the following reason : %s")
- , $dest
- , $reason
- );
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
+ $usr_id = (int) $sx->usr_id;
+ $reason = (int) $sx->reason;
+ $lst = (string) $sx->lst;
+ $ssttid = (int) $sx->ssttid;
+ $dest = (string) $sx->dest;
- $ret = array(
- 'text' => $text
- , 'class' => ''
- );
+ if ($reason == self::MAIL_NO_VALID) {
+ $reason = _('email is not valid');
+ } elseif ($reason == self::MAIL_FAIL) {
+ $reason = _('failed to send mail');
+ } else {
+ $reason = _('an error occured while exporting records');
+ }
- return $ret;
- }
+ $text = sprintf(
+ _("The delivery to %s failed for the following reason : %s")
+ , $dest
+ , $reason
+ );
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Email export fails');
- }
+ $ret = array(
+ 'text' => $text
+ , 'class' => ''
+ );
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Get a notification when a mail export fails');
- }
+ return $ret;
+ }
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Email export fails');
+ }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Get a notification when a mail export fails');
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notify/feed.class.php b/lib/classes/eventsmanager/notify/feed.class.php
index 6cb94c51e7..9251fa14a4 100644
--- a/lib/classes/eventsmanager/notify/feed.class.php
+++ b/lib/classes/eventsmanager/notify/feed.class.php
@@ -17,192 +17,183 @@
*/
class eventsmanager_notify_feed extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__FEED_ENTRY_CREATE__');
- /**
- *
- * @var string
- */
- public $events = array('__FEED_ENTRY_CREATE__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/rss16.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return boolean
- */
- public function fire($event, $params, &$entry)
- {
- $params = array(
- 'entry_id' => $entry->get_id()
- );
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $entry_id = $dom_xml->createElement('entry_id');
-
- $entry_id->appendChild($dom_xml->createTextNode($params['entry_id']));
-
- $root->appendChild($entry_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $Query = new \User_Query($this->appbox);
-
- $Query->include_phantoms(true)->include_invite(false)->include_templates(false);
-
- if ($entry->get_feed()->get_collection())
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $Query->on_base_ids(array($entry->get_feed()->get_collection()->get_base_id()));
+ return '/skins/icons/rss16.png';
}
- $start = 0;
- $perLoop = 100;
-
- $from = array(
- 'email' => $entry->get_author_email(),
- 'name' => $entry->get_author_name()
- );
-
- do
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$entry)
{
- $results = $Query->limit($start, $perLoop)->execute()->get_results();
+ $params = array(
+ 'entry_id' => $entry->get_id()
+ );
- foreach ($results as $user_to_notif)
- {
- /* @var $user_to_notif \User_Adapter */
- $mailed = false;
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
- $send_notif = ($this->get_prefs(__CLASS__, $user_to_notif->get_id()) != '0');
- if ($send_notif)
- {
- $email = array(
- 'email' => $user_to_notif->get_email(),
- 'name' => $user_to_notif->get_display_name()
- );
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
- $token = \random::getUrlToken(
- \random::TYPE_FEED_ENTRY
- , $user_to_notif->get_id()
- , null
- , $entry->get_id()
- );
+ $root = $dom_xml->createElement('datas');
- $url = $this->appbox->get_registry()->get('GV_ServerName') . 'lightbox/index.php?LOG=' . $token;
+ $entry_id = $dom_xml->createElement('entry_id');
- if (self::mail($email, $from, $url, $entry))
- $mailed = true;
+ $entry_id->appendChild($dom_xml->createTextNode($params['entry_id']));
+
+ $root->appendChild($entry_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $Query = new \User_Query($this->appbox);
+
+ $Query->include_phantoms(true)->include_invite(false)->include_templates(false);
+
+ if ($entry->get_feed()->get_collection()) {
+ $Query->on_base_ids(array($entry->get_feed()->get_collection()->get_base_id()));
}
- $this->broker->notify($user_to_notif->get_id(), __CLASS__, $datas, $mailed);
- }
- $start += $perLoop;
+ $start = 0;
+ $perLoop = 100;
+
+ $from = array(
+ 'email' => $entry->get_author_email(),
+ 'name' => $entry->get_author_name()
+ );
+
+ do {
+ $results = $Query->limit($start, $perLoop)->execute()->get_results();
+
+ foreach ($results as $user_to_notif) {
+ /* @var $user_to_notif \User_Adapter */
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $user_to_notif->get_id()) != '0');
+ if ($send_notif) {
+ $email = array(
+ 'email' => $user_to_notif->get_email(),
+ 'name' => $user_to_notif->get_display_name()
+ );
+
+ $token = \random::getUrlToken(
+ \random::TYPE_FEED_ENTRY
+ , $user_to_notif->get_id()
+ , null
+ , $entry->get_id()
+ );
+
+ $url = $this->appbox->get_registry()->get('GV_ServerName') . 'lightbox/index.php?LOG=' . $token;
+
+ if (self::mail($email, $from, $url, $entry))
+ $mailed = true;
+ }
+
+ $this->broker->notify($user_to_notif->get_id(), __CLASS__, $datas, $mailed);
+ }
+ $start += $perLoop;
+ }
+ while (count($results) > 0);
+
+ return true;
}
- while (count($results) > 0);
- return true;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- try
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
{
- $entry = \Feed_Entry_Adapter::load_from_id($this->appbox, (int) $sx->entry_id);
+ $sx = simplexml_load_string($datas);
+
+ try {
+ $entry = \Feed_Entry_Adapter::load_from_id($this->appbox, (int) $sx->entry_id);
+ } catch (\Exception $e) {
+ return array();
+ }
+
+ $ret = array(
+ 'text' => sprintf(
+ _('%1$s has published %2$s')
+ , $entry->get_author_name()
+ , ' ' . $entry->get_title() . ' '
+ )
+ , 'class' => ($unread == 1 ? 'reload_baskets' : '')
+ );
+
+ return $ret;
}
- catch (\Exception $e)
+
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
{
- return array();
+ return _('Feeds');
}
- $ret = array(
- 'text' => sprintf(
- _('%1$s has published %2$s')
- , $entry->get_author_name()
- , '
' . $entry->get_title() . ' '
- )
- , 'class' => ($unread == 1 ? 'reload_baskets' : '')
- );
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Recevoir des notifications lorsqu\'on me push quelque chose');
+ }
- return $ret;
- }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Feeds');
- }
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param string $message
+ * @param string $url
+ * @param boolean $accuse
+ * @return boolean
+ */
+ function mail($to, $from, $url, \Feed_Entry_Adapter $entry)
+ {
+ $subject = sprintf(_('Nouvelle publication : %s'), $entry->get_title());
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'on me push quelque chose');
- }
+ $body = "
"
+ . sprintf('%s vient de publier %s', $entry->get_author_name(), $entry->get_title())
+ . _('Connectez vous a l\'adresse suivante pour la consulter')
+ . "
\n";
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ $body .= '
\n";
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param string $message
- * @param string $url
- * @param boolean $accuse
- * @return boolean
- */
- function mail($to, $from, $url, \Feed_Entry_Adapter $entry)
- {
- $subject = sprintf(_('Nouvelle publication : %s'), $entry->get_title());
+ $body .= "
";
- $body = "
"
- . sprintf('%s vient de publier %s', $entry->get_author_name(), $entry->get_title())
- . _('Connectez vous a l\'adresse suivante pour la consulter')
- . "
\n";
-
- $body .= '
\n";
-
- $body .= "
";
-
- $body .= "
\n
\n
\n"
- . _('push::atention: ce lien est unique et son contenu confidentiel, ne divulguez pas');
-
- return mail::send_mail($subject, $body, $to, $from, array());
- }
+ $body .= "
\n
\n
\n"
+ . _('push::atention: ce lien est unique et son contenu confidentiel, ne divulguez pas');
+ return mail::send_mail($subject, $body, $to, $from, array());
+ }
}
diff --git a/lib/classes/eventsmanager/notify/order.class.php b/lib/classes/eventsmanager/notify/order.class.php
index 4e5253b288..c080c6ebd1 100644
--- a/lib/classes/eventsmanager/notify/order.class.php
+++ b/lib/classes/eventsmanager/notify/order.class.php
@@ -17,263 +17,241 @@
*/
class eventsmanager_notify_order extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__NEW_ORDER__');
- /**
- *
- * @var string
- */
- public $events = array('__NEW_ORDER__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/user.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return Void
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'usr_id' => ''
- , 'order_id' => array()
- );
-
- $params = array_merge($default, $params);
- $order_id = $params['order_id'];
-
- $users = array();
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $sql = 'SELECT DISTINCT e.base_id
- FROM order_elements e
- WHERE e.order_id = :order_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':order_id' => $order_id));
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $base_ids = array();
- foreach ($rs as $row)
- {
- $base_ids[] = $row['base_id'];
- }
-
- $query = new User_Query($this->appbox);
- $users = $query->on_base_ids($base_ids)
- ->who_have_right(array('order_master'))
- ->execute()->get_results();
-
- }
- catch (Exception $e)
- {
-
+ return '/skins/icons/user.png';
}
- if (count($users) == 0)
-
- return;
-
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $usr_id_dom = $dom_xml->createElement('usr_id');
- $order_id_dom = $dom_xml->createElement('order_id');
-
- $usr_id_dom->appendChild($dom_xml->createTextNode($params['usr_id']));
-
- $order_id_dom->appendChild($dom_xml->createTextNode($order_id));
-
-
- $root->appendChild($usr_id_dom);
- $root->appendChild($order_id_dom);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- foreach ($users as $user)
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return Void
+ */
+ public function fire($event, $params, &$object)
{
- $usr_id = $user->get_id();
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
- if ($send_notif)
- {
- $dest = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
-
- $to = array('email' => $user->get_email(), 'name' => $dest);
- $from = array(
- 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
- 'name' => $this->registry->get('GV_homeTitle')
+ $default = array(
+ 'usr_id' => ''
+ , 'order_id' => array()
);
- if (self::mail($to, $from, $datas))
- {
- $mailed = true;
+ $params = array_merge($default, $params);
+ $order_id = $params['order_id'];
+
+ $users = array();
+
+ try {
+ $sql = 'SELECT DISTINCT e.base_id
+ FROM order_elements e
+ WHERE e.order_id = :order_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':order_id' => $order_id));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $base_ids = array();
+ foreach ($rs as $row) {
+ $base_ids[] = $row['base_id'];
+ }
+
+ $query = new User_Query($this->appbox);
+ $users = $query->on_base_ids($base_ids)
+ ->who_have_right(array('order_master'))
+ ->execute()->get_results();
+ } catch (Exception $e) {
+
}
- }
- $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ if (count($users) == 0)
+ return;
+
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $usr_id_dom = $dom_xml->createElement('usr_id');
+ $order_id_dom = $dom_xml->createElement('order_id');
+
+ $usr_id_dom->appendChild($dom_xml->createTextNode($params['usr_id']));
+
+ $order_id_dom->appendChild($dom_xml->createTextNode($order_id));
+
+
+ $root->appendChild($usr_id_dom);
+ $root->appendChild($order_id_dom);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ foreach ($users as $user) {
+ $usr_id = $user->get_id();
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
+ if ($send_notif) {
+ $dest = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+
+ $to = array('email' => $user->get_email(), 'name' => $dest);
+ $from = array(
+ 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
+ 'name' => $this->registry->get('GV_homeTitle')
+ );
+
+ if (self::mail($to, $from, $datas)) {
+ $mailed = true;
+ }
+ }
+
+ $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ }
+
+ return;
}
- return;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return string
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $usr_id = (string) $sx->usr_id;
- $order_id = (string) $sx->order_id;
-
- try
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return string
+ */
+ public function datas($datas, $unread)
{
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
- }
+ $sx = simplexml_load_string($datas);
- $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+ $usr_id = (string) $sx->usr_id;
+ $order_id = (string) $sx->order_id;
- $ret = array(
- 'text' => sprintf(_('%1$s a passe une %2$scommande%3$s')
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return array();
+ }
+
+ $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+
+ $ret = array(
+ 'text' => sprintf(_('%1$s a passe une %2$scommande%3$s')
, $sender
, '
'
, ' ')
- , 'class' => ''
- );
+ , 'class' => ''
+ );
- return $ret;
- }
+ return $ret;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Nouvelle commande');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Nouvelle commande');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'un utilisateur commande des documents');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Recevoir des notifications lorsqu\'un utilisateur commande des documents');
+ }
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param Array $datas
- * @return boolean
- */
- function mail($to, $from, $datas)
- {
- $subject = sprintf(_('admin::register: Nouvelle commande sur %s')
- , $this->registry->get('GV_homeTitle'));
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param Array $datas
+ * @return boolean
+ */
+ function mail($to, $from, $datas)
+ {
+ $subject = sprintf(_('admin::register: Nouvelle commande sur %s')
+ , $this->registry->get('GV_homeTitle'));
- $body = "
"
+ $body = "
"
. _('admin::register: un utilisateur a commande des documents')
. "
\n";
- $sx = simplexml_load_string($datas);
+ $sx = simplexml_load_string($datas);
- $usr_id = (string) $sx->usr_id;
+ $usr_id = (string) $sx->usr_id;
- try
- {
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
- $body .= "
\n
Login : "
+ $body .= "
\n
Login : "
. $registered_user->get_login() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur nom')
+ $body .= "
" . _('admin::compte-utilisateur nom')
. " : " . $registered_user->get_firstname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur prenom')
+ $body .= "
" . _('admin::compte-utilisateur prenom')
. " : " . $registered_user->get_lastname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur email')
+ $body .= "
" . _('admin::compte-utilisateur email')
. " : " . $registered_user->get_email() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur adresse')
+ $body .= "
" . _('admin::compte-utilisateur adresse')
. " : " . $registered_user->get_address() . "
\n";
- $body .= "
" . $registered_user->get_city()
+ $body .= "
" . $registered_user->get_city()
. " " . $registered_user->get_zipcode() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur telephone')
+ $body .= "
" . _('admin::compte-utilisateur telephone')
. " : " . $registered_user->get_tel() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur fax')
+ $body .= "
" . _('admin::compte-utilisateur fax')
. " : " . $registered_user->get_fax() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur poste')
+ $body .= "
" . _('admin::compte-utilisateur poste')
. "/" . _('admin::compte-utilisateur societe')
. " " . $registered_user->get_job()
. " " . $registered_user->get_company() . "
\n";
- $base_ids = $sx->base_ids;
+ $base_ids = $sx->base_ids;
- $body .= "
\n
"
+ $body .= "
\n
"
. _('Retrouvez son bon de commande dans l\'interface')
. "
\n";
- return mail::send_mail($subject, $body, $to, $from);
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- $bool = false;
- $session = $this->appbox->get_session();
- if (!$session->is_authenticated())
-
- return false;
-
- try
- {
- $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
+ return mail::send_mail($subject, $body, $to, $from);
}
- if ($user->ACL()->has_right('order_master'))
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
{
- $bool = true;
+ $bool = false;
+ $session = $this->appbox->get_session();
+ if ( ! $session->is_authenticated())
+ return false;
+
+ try {
+ $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ if ($user->ACL()->has_right('order_master')) {
+ $bool = true;
+ }
+
+ return $bool;
}
-
- return $bool;
- }
-
}
diff --git a/lib/classes/eventsmanager/notify/orderdeliver.class.php b/lib/classes/eventsmanager/notify/orderdeliver.class.php
index 529c13fd34..ee66c85a40 100644
--- a/lib/classes/eventsmanager/notify/orderdeliver.class.php
+++ b/lib/classes/eventsmanager/notify/orderdeliver.class.php
@@ -17,224 +17,205 @@
*/
class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__ORDER_DELIVER__');
- /**
- *
- * @var string
- */
- public $events = array('__ORDER_DELIVER__');
-
- /**
- *
- * @return notify_orderdeliver
- */
- function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->group = _('Commande');
- parent::__construct($appbox, $core, $broker);
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/prod/000000/images/disktt_history.gif';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param Array $object
- * @return boolean
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'ssel_id' => ''
- , 'n' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $ssel_id = $dom_xml->createElement('ssel_id');
- $n = $dom_xml->createElement('n');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
- $n->appendChild($dom_xml->createTextNode($params['n']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($ssel_id);
- $root->appendChild($n);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
- if ($send_notif)
+ /**
+ *
+ * @return notify_orderdeliver
+ */
+ function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{
- try
- {
- $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
- $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ $this->group = _('Commande');
+ parent::__construct($appbox, $core, $broker);
- $to = array(
- 'email' => $user_to->get_email(),
- 'name' => $user_to->get_display_name()
- );
- $from = array(
- 'email' => $user_from->get_email(),
- 'name' => $user_from->get_display_name()
- );
-
- if (self::mail($to, $from, $params['ssel_id'], $params['n']))
- $mailed = true;
+ return $this;
}
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return string
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
- $ssel_id = (string) $sx->ssel_id;
- $n = (int) $sx->n;
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
+ return '/skins/prod/000000/images/disktt_history.gif';
}
- $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
-
- try
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param Array $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$object)
{
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'ssel_id' => ''
+ , 'n' => ''
+ );
- $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $ssel_id = $dom_xml->createElement('ssel_id');
+ $n = $dom_xml->createElement('n');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
+ $n->appendChild($dom_xml->createTextNode($params['n']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($ssel_id);
+ $root->appendChild($n);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+ if ($send_notif) {
+ try {
+ $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
+ $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ $to = array(
+ 'email' => $user_to->get_email(),
+ 'name' => $user_to->get_display_name()
+ );
+ $from = array(
+ 'email' => $user_from->get_email(),
+ 'name' => $user_from->get_display_name()
+ );
+
+ if (self::mail($to, $from, $params['ssel_id'], $params['n']))
+ $mailed = true;
+ }
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
}
- catch (Exception $e)
+
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return string
+ */
+ public function datas($datas, $unread)
{
- return array();
- }
- $ret = array(
- 'text' => sprintf(
- _('%1$s vous a delivre %2$d document(s) pour votre commande %3$s'),
- $sender, $n,
- '
ssel_id . '/" target="_blank">'
. $basket->getName() . ' '
- )
- , 'class' => ''
- );
+ )
+ , 'class' => ''
+ );
- return $ret;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Reception de commande');
- }
-
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Reception d\'une commande');
- }
-
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param int $ssel_id
- * @return boolean
- */
- function mail($to, $from, $ssel_id)
- {
- try
- {
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- $basket = $repository->findOneBy(array(
- 'id' => $ssel_id
- , 'pusher_id' => $this->core->getAuthenticatedUser()->get_id()
- )
- );
+ return $ret;
}
- catch (Exception $e)
- {
- return false;
- }
- $subject = sprintf(
- _('push::mail:: Reception de votre commande %s'),
- $basket->getName()
- );
- $body = "
"
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Reception de commande');
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Reception d\'une commande');
+ }
+
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param int $ssel_id
+ * @return boolean
+ */
+ function mail($to, $from, $ssel_id)
+ {
+ try {
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ $basket = $repository->findOneBy(array(
+ 'id' => $ssel_id
+ , 'pusher_id' => $this->core->getAuthenticatedUser()->get_id()
+ )
+ );
+ } catch (Exception $e) {
+ return false;
+ }
+ $subject = sprintf(
+ _('push::mail:: Reception de votre commande %s'), $basket->getName()
+ );
+
+ $body = "
"
. sprintf(
- _('%s vous a delivre votre commande, consultez la en ligne a l\'adresse suivante'),
- $from['name']
+ _('%s vous a delivre votre commande, consultez la en ligne a l\'adresse suivante'), $from['name']
) . "
\n";
- $body .= "
\n" . $this->registry->get('GV_ServerName') . 'lightbox/validate/' . $ssel_id;
+ $body .= "
\n" . $this->registry->get('GV_ServerName') . 'lightbox/validate/' . $ssel_id;
- return mail::send_mail($subject, $body, $to, $from, array());
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ return mail::send_mail($subject, $body, $to, $from, array());
+ }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notify/ordernotdelivered.class.php b/lib/classes/eventsmanager/notify/ordernotdelivered.class.php
index a1e737983e..762d994934 100644
--- a/lib/classes/eventsmanager/notify/ordernotdelivered.class.php
+++ b/lib/classes/eventsmanager/notify/ordernotdelivered.class.php
@@ -17,147 +17,138 @@
*/
class eventsmanager_notify_ordernotdelivered extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__ORDER_NOT_DELIVERED__');
- /**
- *
- * @var string
- */
- public $events = array('__ORDER_NOT_DELIVERED__');
-
- function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->group = _('Commande');
- parent::__construct($appbox, $core, $broker);
-
- return $this;
- }
-
- public function icon_url()
- {
- return '/skins/prod/000000/images/disktt_history.gif';
- }
-
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'n' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $n = $dom_xml->createElement('n');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $n->appendChild($dom_xml->createTextNode($params['n']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($n);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
- if ($send_notif)
+ function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{
- try
- {
- $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
- $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ $this->group = _('Commande');
+ parent::__construct($appbox, $core, $broker);
- $to = array(
- 'email' => $user_to->get_email(),
- 'name' => $user_to->get_display_name()
- );
- $from = array(
- 'email' => $user_from->get_email(),
- 'name' => $user_from->get_display_name()
- );
-
- if (self::mail($to, $from, $params['n']))
- $mailed = true;
+ return $this;
}
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
- $n = (int) $sx->n;
-
- try
+ public function icon_url()
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
+ return '/skins/prod/000000/images/disktt_history.gif';
}
- $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
+ public function fire($event, $params, &$object)
+ {
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'n' => ''
+ );
- $ret = array(
- 'text' => sprintf(
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $n = $dom_xml->createElement('n');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $n->appendChild($dom_xml->createTextNode($params['n']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($n);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+ if ($send_notif) {
+ try {
+ $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
+ $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ $to = array(
+ 'email' => $user_to->get_email(),
+ 'name' => $user_to->get_display_name()
+ );
+ $from = array(
+ 'email' => $user_from->get_email(),
+ 'name' => $user_from->get_display_name()
+ );
+
+ if (self::mail($to, $from, $params['n']))
+ $mailed = true;
+ }
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
+ }
+
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
+
+ $from = (string) $sx->from;
+ $n = (int) $sx->n;
+
+ try {
+ $registered_user = User_Adapter::getInstance($from, $this->appbox);
+ } catch (Exception $e) {
+ return array();
+ }
+
+ $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
+
+ $ret = array(
+ 'text' => sprintf(
_('%1$s a refuse la livraison de %2$d document(s) pour votre commande'), $sender, $n
- )
- , 'class' => ''
- );
+ )
+ , 'class' => ''
+ );
- return $ret;
- }
+ return $ret;
+ }
- public function get_name()
- {
- return _('Refus d\'elements de commande');
- }
+ public function get_name()
+ {
+ return _('Refus d\'elements de commande');
+ }
- public function get_description()
- {
- return _('Refus d\'elements de commande');
- }
+ public function get_description()
+ {
+ return _('Refus d\'elements de commande');
+ }
- function mail($to, $from, $n)
- {
- $subject = sprintf(_('push::mail:: Refus d\'elements de votre commande'));
+ function mail($to, $from, $n)
+ {
+ $subject = sprintf(_('push::mail:: Refus d\'elements de votre commande'));
- $body = "
"
+ $body = "
"
. sprintf(
- _('%s a refuse %d elements de votre commande'), $from['name'], $n
+ _('%s a refuse %d elements de votre commande'), $from['name'], $n
) . "
\n";
- return mail::send_mail($subject, $body, $to, $from, array());
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ return mail::send_mail($subject, $body, $to, $from, array());
+ }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notify/push.class.php b/lib/classes/eventsmanager/notify/push.class.php
index 533e767005..d577157b3f 100644
--- a/lib/classes/eventsmanager/notify/push.class.php
+++ b/lib/classes/eventsmanager/notify/push.class.php
@@ -17,180 +17,172 @@
*/
class eventsmanager_notify_push extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__PUSH_DATAS__');
- /**
- *
- * @var string
- */
- public $events = array('__PUSH_DATAS__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/push16.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return boolean
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'message' => ''
- , 'ssel_id' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $message = $dom_xml->createElement('message');
- $ssel_id = $dom_xml->createElement('ssel_id');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $message->appendChild($dom_xml->createTextNode($params['message']));
- $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($message);
- $root->appendChild($ssel_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
- if ($send_notif)
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $email = array(
- 'email' => $params['to_email'],
- 'name' => $params['to_name']
- );
- $from = array(
- 'email' => $params['from_email'],
- 'name' => $params['from_email']
- );
- $message = $params['message'];
- $url = $params['url'];
- $accuse = $params['accuse'];
-
- if (self::mail($email, $from, $message, $url, $accuse))
- $mailed = true;
+ return '/skins/icons/push16.png';
}
-
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
-
- try
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$object)
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'message' => ''
+ , 'ssel_id' => ''
+ );
+
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $message = $dom_xml->createElement('message');
+ $ssel_id = $dom_xml->createElement('ssel_id');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $message->appendChild($dom_xml->createTextNode($params['message']));
+ $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($message);
+ $root->appendChild($ssel_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+ if ($send_notif) {
+ $email = array(
+ 'email' => $params['to_email'],
+ 'name' => $params['to_name']
+ );
+ $from = array(
+ 'email' => $params['from_email'],
+ 'name' => $params['from_email']
+ );
+ $message = $params['message'];
+ $url = $params['url'];
+ $accuse = $params['accuse'];
+
+ if (self::mail($email, $from, $message, $url, $accuse))
+ $mailed = true;
+ }
+
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
}
- $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
- $ret = array(
- 'text' => sprintf(
- _('%1$s vous a envoye un %2$spanier%3$s'),
- $sender,
- '
', ' ')
- , 'class' => ($unread == 1 ? 'reload_baskets' : '')
- );
+ , 'class' => ($unread == 1 ? 'reload_baskets' : '')
+ );
- return $ret;
- }
+ return $ret;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Push');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Push');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'on me push quelque chose');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Recevoir des notifications lorsqu\'on me push quelque chose');
+ }
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param string $message
- * @param string $url
- * @param boolean $accuse
- * @return boolean
- */
- function mail($to, $from, $message, $url, $accuse)
- {
- $subject = _('push::mail:: Reception de documents');
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param string $message
+ * @param string $url
+ * @param boolean $accuse
+ * @return boolean
+ */
+ function mail($to, $from, $message, $url, $accuse)
+ {
+ $subject = _('push::mail:: Reception de documents');
- $body = "
"
+ $body = "
"
. _('push::Vous pouvez vous connecter a l\'adresse suivante afin de retrouver votre panier, voir les previews, les descriptions, le telecharger, etc.')
. "
\n";
- $body .= '
\n";
+ $body .= '
\n";
- $body .= "
";
+ $body .= "
";
- $body .= $message;
+ $body .= $message;
- $body .= "
\n
\n
\n"
+ $body .= "
\n
\n
\n"
. _('push::atention: ce lien est unique et son contenu confidentiel, ne divulguez pas');
- return mail::send_mail($subject, $body, $to, $from, array(), $accuse);
- }
-
+ return mail::send_mail($subject, $body, $to, $from, array(), $accuse);
+ }
}
diff --git a/lib/classes/eventsmanager/notify/register.class.php b/lib/classes/eventsmanager/notify/register.class.php
index a92e9dd502..cbad8faf06 100644
--- a/lib/classes/eventsmanager/notify/register.class.php
+++ b/lib/classes/eventsmanager/notify/register.class.php
@@ -17,48 +17,45 @@
*/
class eventsmanager_notify_register extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__REGISTER_APPROVAL__');
- /**
- *
- * @var string
- */
- public $events = array('__REGISTER_APPROVAL__');
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/user.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return Void
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'usr_id' => ''
- , 'demand' => array()
- );
-
- $params = array_merge($default, $params);
- $base_ids = $params['demand'];
-
- if (count($base_ids) == 0)
-
- return;
-
- $mailColl = array();
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $sql = 'SELECT u.usr_id, b.base_id
+ return '/skins/icons/user.png';
+ }
+
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return Void
+ */
+ public function fire($event, $params, &$object)
+ {
+ $default = array(
+ 'usr_id' => ''
+ , 'demand' => array()
+ );
+
+ $params = array_merge($default, $params);
+ $base_ids = $params['demand'];
+
+ if (count($base_ids) == 0)
+ return;
+
+ $mailColl = array();
+
+ try {
+ $sql = 'SELECT u.usr_id, b.base_id
FROM usr u, basusr b
WHERE u.usr_id = b.usr_id
AND b.base_id
@@ -68,247 +65,221 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract
AND b.actif="1"
AND u.usr_login NOT LIKE "(#deleted%"';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- if (!isset($mailColl[$row['usr_id']]))
- $mailColl[$row['usr_id']] = array();
+ foreach ($rs as $row) {
+ if ( ! isset($mailColl[$row['usr_id']]))
+ $mailColl[$row['usr_id']] = array();
- $mailColl[$row['usr_id']][] = $row['base_id'];
- }
- }
- catch (Exception $e)
- {
+ $mailColl[$row['usr_id']][] = $row['base_id'];
+ }
+ } catch (Exception $e) {
- }
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $usr_id = $dom_xml->createElement('usr_id');
- $base_ids = $dom_xml->createElement('base_ids');
-
- $usr_id->appendChild($dom_xml->createTextNode($params['usr_id']));
-
- foreach ($params['demand'] as $base_id => $is_ok)
- {
- $base_id_node = $dom_xml->createElement('base_id');
- $base_id_node->appendChild($dom_xml->createTextNode($base_id));
- $base_ids->appendChild($base_id_node);
- }
-
-
- $root->appendChild($usr_id);
- $root->appendChild($base_ids);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- foreach ($mailColl as $usr_id => $base_ids)
- {
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
- if ($send_notif)
- {
- try
- {
- $admin_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- continue;
}
- $dest = $admin_user->get_email();
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
- $dest = $admin_user->get_display_name();
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
- $to = array('email' => $admin_user->get_email(), 'name' => $dest);
- $from = array(
- 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
- 'name' => $this->registry->get('GV_homeTitle')
+ $root = $dom_xml->createElement('datas');
+
+ $usr_id = $dom_xml->createElement('usr_id');
+ $base_ids = $dom_xml->createElement('base_ids');
+
+ $usr_id->appendChild($dom_xml->createTextNode($params['usr_id']));
+
+ foreach ($params['demand'] as $base_id => $is_ok) {
+ $base_id_node = $dom_xml->createElement('base_id');
+ $base_id_node->appendChild($dom_xml->createTextNode($base_id));
+ $base_ids->appendChild($base_id_node);
+ }
+
+
+ $root->appendChild($usr_id);
+ $root->appendChild($base_ids);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ foreach ($mailColl as $usr_id => $base_ids) {
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $usr_id) != '0');
+ if ($send_notif) {
+ try {
+ $admin_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ continue;
+ }
+
+ $dest = $admin_user->get_email();
+
+ $dest = $admin_user->get_display_name();
+
+ $to = array('email' => $admin_user->get_email(), 'name' => $dest);
+ $from = array(
+ 'email' => $this->registry->get('GV_defaulmailsenderaddr'),
+ 'name' => $this->registry->get('GV_homeTitle')
+ );
+
+ if (self::mail($to, $from, $datas))
+ $mailed = true;
+ }
+
+
+ $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ }
+
+ return;
+ }
+
+ /**
+ *
+ * @param Array $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
+ {
+ $sx = simplexml_load_string($datas);
+
+ $usr_id = (string) $sx->usr_id;
+
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return array();
+ }
+
+ $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+
+ $ret = array(
+ 'text' => sprintf(
+ _('%1$s demande votre approbation sur une ou plusieurs %2$scollections%3$s'), $sender, '
', ' '
+ )
+ , 'class' => ''
);
- if (self::mail($to, $from, $datas))
- $mailed = true;
- }
-
-
- $this->broker->notify($usr_id, __CLASS__, $datas, $mailed);
+ return $ret;
}
- return;
- }
-
- /**
- *
- * @param Array $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $usr_id = (string) $sx->usr_id;
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
{
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ return _('Register approbation');
}
- catch (Exception $e)
+
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
{
- return array();
+ return _('Recevoir des notifications lorsqu\'un utilisateur demande une inscription necessitant mon approbation');
}
- $sender = User_Adapter::getInstance($usr_id, $this->appbox)->get_display_name();
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param string $datas
+ * @return boolean
+ */
+ function mail($to, $from, $datas)
+ {
+ $subject = sprintf(
+ _('admin::register: demande d\'inscription sur %s'), $this->registry->get('GV_homeTitle')
+ );
- $ret = array(
- 'text' => sprintf(
- _('%1$s demande votre approbation sur une ou plusieurs %2$scollections%3$s'),
- $sender,
- '
',
- ' '
- )
- , 'class' => ''
- );
-
- return $ret;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Register approbation');
- }
-
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'un utilisateur demande une inscription necessitant mon approbation');
- }
-
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param string $datas
- * @return boolean
- */
- function mail($to, $from, $datas)
- {
- $subject = sprintf(
- _('admin::register: demande d\'inscription sur %s'),
- $this->registry->get('GV_homeTitle')
- );
-
- $body = "
"
+ $body = "
"
. _('admin::register: un utilisateur a fait une demande d\'inscription')
. "
\n";
- $sx = simplexml_load_string($datas);
+ $sx = simplexml_load_string($datas);
- $usr_id = (string) $sx->usr_id;
+ $usr_id = (string) $sx->usr_id;
- try
- {
- $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ try {
+ $registered_user = User_Adapter::getInstance($usr_id, $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
- $body .= "
\n
Login : "
+ $body .= "
\n
Login : "
. $registered_user->get_login() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur nom')
+ $body .= "
" . _('admin::compte-utilisateur nom')
. " : " . $registered_user->get_firstname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur prenom')
+ $body .= "
" . _('admin::compte-utilisateur prenom')
. " : " . $registered_user->get_lastname() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur email')
+ $body .= "
" . _('admin::compte-utilisateur email')
. " : " . $registered_user->get_email() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur adresse')
+ $body .= "
" . _('admin::compte-utilisateur adresse')
. " : " . $registered_user->get_address() . "
\n";
- $body .= "
" . $registered_user->get_city()
+ $body .= "
" . $registered_user->get_city()
. " " . $registered_user->get_zipcode() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur telephone')
+ $body .= "
" . _('admin::compte-utilisateur telephone')
. " : " . $registered_user->get_tel() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur fax')
+ $body .= "
" . _('admin::compte-utilisateur fax')
. " : " . $registered_user->get_fax() . "
\n";
- $body .= "
" . _('admin::compte-utilisateur poste')
+ $body .= "
" . _('admin::compte-utilisateur poste')
. "/" . _('admin::compte-utilisateur societe')
. " " . $registered_user->get_job()
. " " . $registered_user->get_company() . "
\n";
- $base_ids = $sx->base_ids;
+ $base_ids = $sx->base_ids;
- $body .= "
\n
"
+ $body .= "
\n
"
. _('admin::register: les demandes de l\'utilisateur portent sur les bases suivantes')
. "
\n";
- $body .= "
\n";
+ $body .= "\n";
- foreach ($base_ids->base_id as $base_id)
- {
- $body .= ""
- . phrasea::sbas_names(phrasea::sbasFromBas((string) $base_id))
- . ' - '
- . phrasea::bas_names((string) $base_id) . " \n";
- }
+ foreach ($base_ids->base_id as $base_id) {
+ $body .= ""
+ . phrasea::sbas_names(phrasea::sbasFromBas((string) $base_id))
+ . ' - '
+ . phrasea::bas_names((string) $base_id) . " \n";
+ }
- $body .= " \n";
+ $body .= " \n";
- $body .= "
\n
\n";
- return mail::send_mail($subject, $body, $to, $from);
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- $bool = false;
-
- $session = $this->appbox->get_session();
- if (!$session->is_authenticated() || !login::register_enabled())
-
- return false;
-
- try
- {
- $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
+ return mail::send_mail($subject, $body, $to, $from);
}
- if ($user->ACL()->has_right('manageusers'))
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
{
- $bool = true;
+ $bool = false;
+
+ $session = $this->appbox->get_session();
+ if ( ! $session->is_authenticated() || ! login::register_enabled())
+ return false;
+
+ try {
+ $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ if ($user->ACL()->has_right('manageusers')) {
+ $bool = true;
+ }
+
+ return $bool;
}
-
- return $bool;
- }
-
}
diff --git a/lib/classes/eventsmanager/notify/validate.class.php b/lib/classes/eventsmanager/notify/validate.class.php
index 550086d281..8c7c8b3a5f 100644
--- a/lib/classes/eventsmanager/notify/validate.class.php
+++ b/lib/classes/eventsmanager/notify/validate.class.php
@@ -17,211 +17,201 @@
*/
class eventsmanager_notify_validate extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__PUSH_VALIDATION__');
- /**
- *
- * @var string
- */
- public $events = array('__PUSH_VALIDATION__');
-
- /**
- *
- * @return notify_validate
- */
- function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->group = _('Validation');
- parent::__construct($appbox, $core, $broker);
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/push16.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return boolean
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'message' => ''
- , 'ssel_id' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $message = $dom_xml->createElement('message');
- $ssel_id = $dom_xml->createElement('ssel_id');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $message->appendChild($dom_xml->createTextNode($params['message']));
- $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($message);
- $root->appendChild($ssel_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
- if ($send_notif)
+ /**
+ *
+ * @return notify_validate
+ */
+ function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{
- $to = array(
- 'email' => $params['to_email'],
- 'name' => $params['to_name']
- );
- $from = array(
- 'email' => $params['from_email'],
- 'name' => $params['from_email']
- );
- $message = $params['message'];
- $url = $params['url'];
- $accuse = $params['accuse'];
+ $this->group = _('Validation');
+ parent::__construct($appbox, $core, $broker);
- if (self::mail($to, $from, $message, $url, $accuse))
- $mailed = true;
+ return $this;
}
-
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- /**
- *
- * @param string $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
- $ssel_id = (string) $sx->ssel_id;
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
+ return '/skins/icons/push16.png';
}
- $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
-
- try
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$object)
{
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'message' => ''
+ , 'ssel_id' => ''
+ );
- $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
+ $params = array_merge($default, $params);
- $basket_name = trim($basket->getName()) ?: _('Une selection');
- }
- catch (Exception $e)
- {
- $basket_name = _('Une selection');
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $message = $dom_xml->createElement('message');
+ $ssel_id = $dom_xml->createElement('ssel_id');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $message->appendChild($dom_xml->createTextNode($params['message']));
+ $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($message);
+ $root->appendChild($ssel_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+ if ($send_notif) {
+ $to = array(
+ 'email' => $params['to_email'],
+ 'name' => $params['to_name']
+ );
+ $from = array(
+ 'email' => $params['from_email'],
+ 'name' => $params['from_email']
+ );
+ $message = $params['message'];
+ $url = $params['url'];
+ $accuse = $params['accuse'];
+
+ if (self::mail($to, $from, $message, $url, $accuse))
+ $mailed = true;
+ }
+
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
}
- $bask_link = '
registry->get('GV_ServerName') . 'lightbox/validate/'
. (string) $sx->ssel_id . '/" target="_blank">'
. $basket_name . ' ';
- $ret = array(
- 'text' => sprintf(
+ $ret = array(
+ 'text' => sprintf(
_('%1$s vous demande de valider %2$s')
, $sender, $bask_link
- )
- , 'class' => ($unread == 1 ? 'reload_baskets' : '')
- );
+ )
+ , 'class' => ($unread == 1 ? 'reload_baskets' : '')
+ );
- return $ret;
- }
+ return $ret;
+ }
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Validation');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Validation');
+ }
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Recevoir des notifications lorsqu\'on me demande une validation');
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Recevoir des notifications lorsqu\'on me demande une validation');
+ }
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param string $message
- * @param string $url
- * @param boolean $accuse
- * @return boolean
- */
- function mail($to, $from, $message, $url, $accuse)
- {
- $subject = _('push::mail:: Demande de validation de documents');
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param string $message
+ * @param string $url
+ * @param boolean $accuse
+ * @return boolean
+ */
+ function mail($to, $from, $message, $url, $accuse)
+ {
+ $subject = _('push::mail:: Demande de validation de documents');
- $body = '
' . sprintf(
- _('Le lien suivant vous propose de valider une selection faite par %s'),
- $from['name']
+ $body = '
' . sprintf(
+ _('Le lien suivant vous propose de valider une selection faite par %s'), $from['name']
)
. "
\n";
- $body .= "
\n";
- $body .= '
\n";
+ $body .= '
\n" . $message;
- $body .= "
\n
\n
\n"
+ $body .= "
\n
\n
\n"
. _('push::atention: ce lien est unique et son contenu confidentiel, ne divulguez pas');
- return mail::send_mail($subject, $body, $to, $from, array(), $accuse);
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- return true;
- }
+ return mail::send_mail($subject, $body, $to, $from, array(), $accuse);
+ }
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notify/validationdone.class.php b/lib/classes/eventsmanager/notify/validationdone.class.php
index 2d10376233..9e403f79f9 100644
--- a/lib/classes/eventsmanager/notify/validationdone.class.php
+++ b/lib/classes/eventsmanager/notify/validationdone.class.php
@@ -17,239 +17,214 @@
*/
class eventsmanager_notify_validationdone extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__VALIDATION_DONE__');
- /**
- *
- * @var string
- */
- public $events = array('__VALIDATION_DONE__');
-
- /**
- *
- * @return notify_validationdone
- */
- function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->group = _('Validation');
- parent::__construct($appbox, $core, $broker);
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/push16.png';
- }
-
- /**
- *
- * @param Array $event
- * @param Array $params
- * @param mixed content $object
- * @return boolean
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'ssel_id' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $ssel_id = $dom_xml->createElement('ssel_id');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($ssel_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
-
- if ($send_notif)
+ /**
+ *
+ * @return notify_validationdone
+ */
+ function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{
- try
- {
- $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
- $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
- }
+ $this->group = _('Validation');
+ parent::__construct($appbox, $core, $broker);
- $to = array(
- 'email' => $user_to->get_email(),
- 'name' => $user_to->get_display_name()
- );
- $from = array(
- 'email' => $user_from->get_email(),
- 'name' => $user_from->get_display_name()
- );
-
- if (self::mail($to, $from, $params['ssel_id'], $params['url']))
- $mailed = true;
+ return $this;
}
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- /**
- *
- * @param string $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
- $ssel_id = (string) $sx->ssel_id;
-
- try
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
+ return '/skins/icons/push16.png';
}
- $sender = $registered_user->get_display_name();
-
- try
+ /**
+ *
+ * @param Array $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$object)
{
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'ssel_id' => ''
+ );
- $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
- }
- catch (Exception $e)
- {
- return array();
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $ssel_id = $dom_xml->createElement('ssel_id');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($ssel_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+
+ if ($send_notif) {
+ try {
+ $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
+ $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ $to = array(
+ 'email' => $user_to->get_email(),
+ 'name' => $user_to->get_display_name()
+ );
+ $from = array(
+ 'email' => $user_from->get_email(),
+ 'name' => $user_from->get_display_name()
+ );
+
+ if (self::mail($to, $from, $params['ssel_id'], $params['url']))
+ $mailed = true;
+ }
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
}
- $ret = array(
- 'text' => sprintf(
- _('%1$s a envoye son rapport de validation de %2$s'),
- $sender,
- '
ssel_id . '/" target="_blank">'
. $basket->getName() . ' '
- )
- , 'class' => ''
- );
+ )
+ , 'class' => ''
+ );
- return $ret;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Rapport de Validation');
- }
-
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Reception d\'un rapport de validation');
- }
-
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param int $ssel_id
- * @return boolean
- */
- function mail($to, $from, $ssel_id, $url)
- {
- try
- {
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
-
- $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
- }
- catch (Exception $e)
- {
- return false;
+ return $ret;
}
- $subject = sprintf(
- _('push::mail:: Rapport de validation de %1$s pour %2$s'),
- $from['name'],
- $basket->getName()
- );
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Rapport de Validation');
+ }
- $body = "
" . sprintf(
- _('%s a rendu son rapport, consulter le en ligne a l\'adresse suivante'),
- $from['name']
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Reception d\'un rapport de validation');
+ }
+
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param int $ssel_id
+ * @return boolean
+ */
+ function mail($to, $from, $ssel_id, $url)
+ {
+ try {
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
+
+ $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ $subject = sprintf(
+ _('push::mail:: Rapport de validation de %1$s pour %2$s'), $from['name'], $basket->getName()
+ );
+
+ $body = "
" . sprintf(
+ _('%s a rendu son rapport, consulter le en ligne a l\'adresse suivante'), $from['name']
) . "
\n";
- $body .= "
\n" . $url;
+ $body .= "
\n" . $url;
- return mail::send_mail($subject, $body, $to, $from, array());
- }
-
- /**
- *
- * @return boolean
- */
- function is_available()
- {
- $bool = false;
-
- $session = $this->appbox->get_session();
- if (!$session->is_authenticated())
-
- return false;
-
- try
- {
- $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
+ return mail::send_mail($subject, $body, $to, $from, array());
}
- if ($user->ACL()->has_right('push'))
+ /**
+ *
+ * @return boolean
+ */
+ function is_available()
{
- $bool = true;
+ $bool = false;
+
+ $session = $this->appbox->get_session();
+ if ( ! $session->is_authenticated())
+ return false;
+
+ try {
+ $user = User_Adapter::getInstance($session->get_usr_id(), $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ if ($user->ACL()->has_right('push')) {
+ $bool = true;
+ }
+
+ return $bool;
}
-
- return $bool;
- }
-
}
diff --git a/lib/classes/eventsmanager/notify/validationreminder.class.php b/lib/classes/eventsmanager/notify/validationreminder.class.php
index 13622a8500..1949bfe039 100644
--- a/lib/classes/eventsmanager/notify/validationreminder.class.php
+++ b/lib/classes/eventsmanager/notify/validationreminder.class.php
@@ -17,231 +17,215 @@
*/
class eventsmanager_notify_validationreminder extends eventsmanager_notifyAbstract
{
+ /**
+ *
+ * @var string
+ */
+ public $events = array('__VALIDATION_REMINDER__');
- /**
- *
- * @var string
- */
- public $events = array('__VALIDATION_REMINDER__');
-
- /**
- *
- * @return notify_validationreminder
- */
- function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
- {
- $this->group = _('Validation');
- parent::__construct($appbox, $core, $broker);
-
- return $this;
- }
-
- /**
- *
- * @return string
- */
- public function icon_url()
- {
- return '/skins/icons/push16.png';
- }
-
- /**
- *
- * @param string $event
- * @param Array $params
- * @param mixed content $object
- * @return boolean
- */
- public function fire($event, $params, &$object)
- {
- $default = array(
- 'from' => ''
- , 'to' => ''
- , 'ssel_id' => ''
- , 'url' => ''
- );
-
- $params = array_merge($default, $params);
-
- $dom_xml = new DOMDocument('1.0', 'UTF-8');
-
- $dom_xml->preserveWhiteSpace = false;
- $dom_xml->formatOutput = true;
-
- $root = $dom_xml->createElement('datas');
-
- $from = $dom_xml->createElement('from');
- $to = $dom_xml->createElement('to');
- $ssel_id = $dom_xml->createElement('ssel_id');
-
- $from->appendChild($dom_xml->createTextNode($params['from']));
- $to->appendChild($dom_xml->createTextNode($params['to']));
- $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
-
- $root->appendChild($from);
- $root->appendChild($to);
- $root->appendChild($ssel_id);
-
- $dom_xml->appendChild($root);
-
- $datas = $dom_xml->saveXml();
-
- $mailed = false;
-
- try
+ /**
+ *
+ * @return notify_validationreminder
+ */
+ function __construct(appbox &$appbox, \Alchemy\Phrasea\Core $core, eventsmanager_broker &$broker)
{
- $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
- $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
- }
- catch (Exception $e)
- {
- return false;
+ $this->group = _('Validation');
+ parent::__construct($appbox, $core, $broker);
+
+ return $this;
}
- $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
- if ($send_notif)
+ /**
+ *
+ * @return string
+ */
+ public function icon_url()
{
- $to = array(
- 'email' => $user_to->get_email(),
- 'name' => $user_to->get_display_name()
- );
- $from = array(
- 'email' => $user_from->get_email(),
- 'name' => $user_from->get_display_name()
- );
- $url = $params['url'];
-
- if (self::mail($to, $from, $url))
- $mailed = true;
+ return '/skins/icons/push16.png';
}
- try
- {
- $sql = 'UPDATE validate SET last_reminder=NOW() WHERE id = :validate_id';
- $stmt = $this->appbox->get_connection()->prepare($sql);
- $stmt->execute(array(':validate_id' => $params['validate_id']));
- $stmt->closeCursor();
- }
- catch (Exception $e)
+ /**
+ *
+ * @param string $event
+ * @param Array $params
+ * @param mixed content $object
+ * @return boolean
+ */
+ public function fire($event, $params, &$object)
{
+ $default = array(
+ 'from' => ''
+ , 'to' => ''
+ , 'ssel_id' => ''
+ , 'url' => ''
+ );
+ $params = array_merge($default, $params);
+
+ $dom_xml = new DOMDocument('1.0', 'UTF-8');
+
+ $dom_xml->preserveWhiteSpace = false;
+ $dom_xml->formatOutput = true;
+
+ $root = $dom_xml->createElement('datas');
+
+ $from = $dom_xml->createElement('from');
+ $to = $dom_xml->createElement('to');
+ $ssel_id = $dom_xml->createElement('ssel_id');
+
+ $from->appendChild($dom_xml->createTextNode($params['from']));
+ $to->appendChild($dom_xml->createTextNode($params['to']));
+ $ssel_id->appendChild($dom_xml->createTextNode($params['ssel_id']));
+
+ $root->appendChild($from);
+ $root->appendChild($to);
+ $root->appendChild($ssel_id);
+
+ $dom_xml->appendChild($root);
+
+ $datas = $dom_xml->saveXml();
+
+ $mailed = false;
+
+ try {
+ $user_from = User_Adapter::getInstance($params['from'], $this->appbox);
+ $user_to = User_Adapter::getInstance($params['to'], $this->appbox);
+ } catch (Exception $e) {
+ return false;
+ }
+
+ $send_notif = ($this->get_prefs(__CLASS__, $params['to']) != '0');
+ if ($send_notif) {
+ $to = array(
+ 'email' => $user_to->get_email(),
+ 'name' => $user_to->get_display_name()
+ );
+ $from = array(
+ 'email' => $user_from->get_email(),
+ 'name' => $user_from->get_display_name()
+ );
+ $url = $params['url'];
+
+ if (self::mail($to, $from, $url))
+ $mailed = true;
+ }
+
+ try {
+ $sql = 'UPDATE validate SET last_reminder=NOW() WHERE id = :validate_id';
+ $stmt = $this->appbox->get_connection()->prepare($sql);
+ $stmt->execute(array(':validate_id' => $params['validate_id']));
+ $stmt->closeCursor();
+ } catch (Exception $e) {
+
+ }
+
+ return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
}
- return $this->broker->notify($params['to'], __CLASS__, $datas, $mailed);
- }
-
- /**
- *
- * @param string $datas
- * @param boolean $unread
- * @return Array
- */
- public function datas($datas, $unread)
- {
- $sx = simplexml_load_string($datas);
-
- $from = (string) $sx->from;
- $ssel_id = (string) $sx->ssel_id;
-
- try
+ /**
+ *
+ * @param string $datas
+ * @param boolean $unread
+ * @return Array
+ */
+ public function datas($datas, $unread)
{
- $registered_user = User_Adapter::getInstance($from, $this->appbox);
- }
- catch (Exception $e)
- {
- return array();
- }
+ $sx = simplexml_load_string($datas);
- $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
+ $from = (string) $sx->from;
+ $ssel_id = (string) $sx->ssel_id;
- try
- {
- $em = $this->core->getEntityManager();
- $repository = $em->getRepository('\Entities\Basket');
+ try {
+ $registered_user = User_Adapter::getInstance($from, $this->appbox);
+ } catch (Exception $e) {
+ return array();
+ }
- $basket = $repository->findUserBasket($ssel_id, $this->core->getAuthenticatedUser(), false);
+ $sender = User_Adapter::getInstance($from, $this->appbox)->get_display_name();
- $basket_name = trim($basket->getName()) ? : _('Une selection');
- }
- catch (Exception $e)
- {
- $basket_name = _('Une selection');
- }
+ try {
+ $em = $this->core->getEntityManager();
+ $repository = $em->getRepository('\Entities\Basket');
- $bask_link = '
'
. $basket_name . ' ';
- $ret = array(
- 'text' => sprintf(
+ $ret = array(
+ 'text' => sprintf(
_('Rappel : Il vous reste %1$d jours pour valider %2$s de %3$s'), $this->registry->get('GV_validation_reminder'), $bask_link, $sender
- )
- , 'class' => ($unread == 1 ? 'reload_baskets' : '')
- );
+ )
+ , 'class' => ($unread == 1 ? 'reload_baskets' : '')
+ );
- return $ret;
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return _('Validation');
- }
-
- /**
- *
- * @return string
- */
- public function get_description()
- {
- return _('Rappel pour une demande de validation');
- }
-
- /**
- *
- * @param Array $to
- * @param Array $from
- * @param string $url
- * @return boolean
- */
- function mail($to, $from, $url)
- {
- $subject = _('push::mail:: Rappel de demande de validation de documents');
-
- $body = "
"
- . sprintf(
- _('Il ne vous reste plus que %d jours pour terminer votre validation'), $this->registry->get('GV_validation_reminder'))
- . "
\n";
-
- if (trim($url) != '')
- {
- $body = '
'
- . sprintf(
- _('Le lien suivant vous propose de valider une selection faite par %s'), $from['name']
- ) . "
\n";
-
- $body .= "
\n";
-
- $body .= '
\n";
+ return $ret;
}
- $body .= "
\n
\n
\n"
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return _('Validation');
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_description()
+ {
+ return _('Rappel pour une demande de validation');
+ }
+
+ /**
+ *
+ * @param Array $to
+ * @param Array $from
+ * @param string $url
+ * @return boolean
+ */
+ function mail($to, $from, $url)
+ {
+ $subject = _('push::mail:: Rappel de demande de validation de documents');
+
+ $body = "
"
+ . sprintf(
+ _('Il ne vous reste plus que %d jours pour terminer votre validation'), $this->registry->get('GV_validation_reminder'))
+ . "
\n";
+
+ if (trim($url) != '') {
+ $body = '
'
+ . sprintf(
+ _('Le lien suivant vous propose de valider une selection faite par %s'), $from['name']
+ ) . "
\n";
+
+ $body .= "
\n";
+
+ $body .= '
\n";
+ }
+
+ $body .= "
\n
\n
\n"
. _('push::atention: ce lien est unique et son contenu confidentiel, ne divulguez pas');
- return mail::send_mail($subject, $body, $to, $from, array());
- }
-
- /**
- *
- * @return string
- */
- function is_available()
- {
- return true;
- }
+ return mail::send_mail($subject, $body, $to, $from, array());
+ }
+ /**
+ *
+ * @return string
+ */
+ function is_available()
+ {
+ return true;
+ }
}
diff --git a/lib/classes/eventsmanager/notifyAbstract.class.php b/lib/classes/eventsmanager/notifyAbstract.class.php
index 88bf6c0336..7e7cd31c55 100644
--- a/lib/classes/eventsmanager/notifyAbstract.class.php
+++ b/lib/classes/eventsmanager/notifyAbstract.class.php
@@ -2,33 +2,31 @@
abstract class eventsmanager_notifyAbstract extends eventsmanager_eventAbstract
{
+ protected $events = array('__EVENT__');
- protected $events = array('__EVENT__');
+ function fire($event, $params, &$object)
+ {
- function fire($event, $params, &$object)
- {
+ }
- }
+ abstract function datas($datas, $unread);
- abstract function datas($datas, $unread);
+ function is_available()
+ {
+ return true;
+ }
- function is_available()
- {
- return true;
- }
+ function email()
+ {
+ return true;
+ }
- function email()
- {
- return true;
- }
+ abstract function icon_url();
- abstract function icon_url();
-
- protected function get_prefs($class, $usr_id)
- {
- $user = User_Adapter::getInstance($usr_id, appbox::get_instance(\bootstrap::getCore()));
-
- return $user->getPrefs('notification_' . $class);
- }
+ protected function get_prefs($class, $usr_id)
+ {
+ $user = User_Adapter::getInstance($usr_id, appbox::get_instance(\bootstrap::getCore()));
+ return $user->getPrefs('notification_' . $class);
+ }
}
diff --git a/lib/classes/exiftool.class.php b/lib/classes/exiftool.class.php
index 309051e83b..740402e2e8 100644
--- a/lib/classes/exiftool.class.php
+++ b/lib/classes/exiftool.class.php
@@ -3,114 +3,97 @@
class exiftool
{
- public static function get_fields($filename, $fields)
- {
- $system = system_server::get_platform();
- $registry = registry::get_instance();
-
- $ret = array();
-
- if (in_array($system, array('DARWIN', 'LINUX')))
+ public static function get_fields($filename, $fields)
{
- $cmd = $registry->get('GV_exiftool') . ' ' . escapeshellarg($filename) . '';
- }
- else
- {
- if (chdir($registry->get('GV_RootPath') . 'tmp/'))
- {
- $cmd = 'start /B /LOW ' . $registry->get('GV_exiftool') . ' ' . escapeshellarg($filename) . '';
- }
- }
- if ($cmd)
- {
- $s = @shell_exec($cmd);
- if (trim($s) != '')
- {
- $lines = explode("\n", $s);
+ $system = system_server::get_platform();
+ $registry = registry::get_instance();
- foreach ($lines as $line)
- {
- $cells = explode(':', $line);
+ $ret = array();
- if (count($cells) < 2)
- continue;
-
- $cell_1 = trim(array_shift($cells));
- $cell_2 = trim(implode(':', $cells));
-
- if (in_array($cell_1, $fields))
- $ret[$cell_1] = $cell_2;
+ if (in_array($system, array('DARWIN', 'LINUX'))) {
+ $cmd = $registry->get('GV_exiftool') . ' ' . escapeshellarg($filename) . '';
+ } else {
+ if (chdir($registry->get('GV_RootPath') . 'tmp/')) {
+ $cmd = 'start /B /LOW ' . $registry->get('GV_exiftool') . ' ' . escapeshellarg($filename) . '';
+ }
}
- }
- }
+ if ($cmd) {
+ $s = @shell_exec($cmd);
+ if (trim($s) != '') {
+ $lines = explode("\n", $s);
- foreach ($fields as $field)
+ foreach ($lines as $line) {
+ $cells = explode(':', $line);
+
+ if (count($cells) < 2)
+ continue;
+
+ $cell_1 = trim(array_shift($cells));
+ $cell_2 = trim(implode(':', $cells));
+
+ if (in_array($cell_1, $fields))
+ $ret[$cell_1] = $cell_2;
+ }
+ }
+ }
+
+ foreach ($fields as $field) {
+ if ( ! isset($ret[$field]))
+ $ret[$field] = false;
+ }
+
+ return $ret;
+ }
+ const EXTRACT_XML_RDF = 0;
+ const EXTRACT_TEXT = 1;
+
+ protected static $extracts = array();
+
+ public static function extract_metadatas(system_file $file, $extract_type = null)
{
- if (!isset($ret[$field]))
- $ret[$field] = false;
+
+ if (isset(self::$extracts[$file->getPathname()]) && isset(self::$extracts[$file->getPathname()][$extract_type])) {
+ return self::$extracts[$file->getPathname()][$extract_type];
+ }
+
+ $registry = registry::get_instance();
+ $system = system_server::get_platform();
+
+ $options = '';
+ switch ($extract_type) {
+ case self::EXTRACT_TEXT:
+ default:
+
+ break;
+ case self::EXTRACT_XML_RDF:
+ $options .= ' -X -n -fast ';
+ break;
+ }
+
+
+
+ if (in_array($system, array('DARWIN', 'LINUX'))) {
+ $cmd = $registry->get('GV_exiftool') . $options . escapeshellarg($file->getPathname()) . '';
+ } else {
+ if (chdir($registry->get('GV_RootPath') . 'tmp/')) {
+ $cmd = 'start /B /LOW ' . $registry->get('GV_exiftool') . $options . escapeshellarg($file->getPathname()) . '';
+ }
+ }
+
+ $s = shell_exec($cmd);
+
+ if ($s) {
+ self::$extracts[$file->getPathname()][$extract_type] = $s;
+ }
+
+ return self::$extracts[$file->getPathname()][$extract_type];
}
- return $ret;
- }
-
- const EXTRACT_XML_RDF = 0;
- const EXTRACT_TEXT = 1;
-
- protected static $extracts = array();
-
- public static function extract_metadatas(system_file $file, $extract_type = null)
- {
-
- if (isset(self::$extracts[$file->getPathname()]) && isset(self::$extracts[$file->getPathname()][$extract_type]))
+ public static function flush_extracts(system_file $file)
{
- return self::$extracts[$file->getPathname()][$extract_type];
+ if (isset(self::$extracts[$file->getPathname()]))
+ unset(self::$extracts[$file->getPathname()]);
+
+ return;
}
-
- $registry = registry::get_instance();
- $system = system_server::get_platform();
-
- $options = '';
- switch ($extract_type)
- {
- case self::EXTRACT_TEXT:
- default:
-
- break;
- case self::EXTRACT_XML_RDF:
- $options .= ' -X -n -fast ';
- break;
- }
-
-
-
- if (in_array($system, array('DARWIN', 'LINUX')))
- {
- $cmd = $registry->get('GV_exiftool') . $options . escapeshellarg($file->getPathname()) . '';
- }
- else
- {
- if (chdir($registry->get('GV_RootPath') . 'tmp/'))
- {
- $cmd = 'start /B /LOW ' . $registry->get('GV_exiftool') . $options . escapeshellarg($file->getPathname()) . '';
- }
- }
-
- $s = shell_exec($cmd);
-
- if ($s)
- {
- self::$extracts[$file->getPathname()][$extract_type] = $s;
- }
-
- return self::$extracts[$file->getPathname()][$extract_type];
- }
-
- public static function flush_extracts(system_file $file)
- {
- if (isset(self::$extracts[$file->getPathname()]))
- unset(self::$extracts[$file->getPathname()]);
-
- return;
- }
-
}
diff --git a/lib/classes/format.class.php b/lib/classes/format.class.php
index 936674d8ca..63d883d829 100644
--- a/lib/classes/format.class.php
+++ b/lib/classes/format.class.php
@@ -3,77 +3,59 @@
class format
{
- static public function arr_to_csv_line($arr, $tri_column = false)
- {
- $line = array();
- $tmp = array();
- foreach ($arr as $v)
+ static public function arr_to_csv_line($arr, $tri_column = false)
{
- if (is_array($v))
- {
- $line[] = self::arr_to_csv_line($v);
- }
- elseif ($tri_column)
- {
- $key = array_search($v, $arr);
- unset($arr[$key]);
+ $line = array();
+ $tmp = array();
+ foreach ($arr as $v) {
+ if (is_array($v)) {
+ $line[] = self::arr_to_csv_line($v);
+ } elseif ($tri_column) {
+ $key = array_search($v, $arr);
+ unset($arr[$key]);
- if (array_key_exists($key, $tri_column))
- {
- $tmp[$key] = $v;
+ if (array_key_exists($key, $tri_column)) {
+ $tmp[$key] = $v;
+ }
+ }
+ else
+ $line[] = '"' . str_replace('"', '""', strip_tags($v)) . '"';
}
- }
- else
- $line[] = '"' . str_replace('"', '""', strip_tags($v)) . '"';
- }
- if ($tri_column)
- {
- foreach ($tri_column as $key => $value)
- {
- foreach ($tmp as $k => $v)
- {
- if ($key == $k)
- {
- $line[] = '"' . str_replace('"', '""', strip_tags($v)) . '"';
- }
+ if ($tri_column) {
+ foreach ($tri_column as $key => $value) {
+ foreach ($tmp as $k => $v) {
+ if ($key == $k) {
+ $line[] = '"' . str_replace('"', '""', strip_tags($v)) . '"';
+ }
+ }
+ }
}
- }
+
+ if ($tri_column && count($tri_column) == count($line)) {
+ return implode(",", $line);
+ } elseif (count($arr) == count($line)) {
+ return implode(",", $line);
+ }
+ else
+ throw new Exception('CSV failed');
}
- if($tri_column && count($tri_column) == count($line))
+ static public function arr_to_csv($arr, $tri_column = false)
{
- return implode(",", $line);
+ $lines = array();
+
+ if ($tri_column) {
+ $title = "";
+ foreach ($tri_column as $v) {
+ if (isset($v['title']))
+ $title .= ( empty($title) ? "" : ",") . '"' . str_replace('"', '""', strip_tags($v['title'])) . '"';
+ }
+ ! empty($title) ? $lines[] = $title : "";
+ }
+ foreach ($arr as $v) {
+ $lines[] = self::arr_to_csv_line($v, $tri_column);
+ }
+
+ return implode("\n", $lines);
}
- elseif(count($arr) == count($line))
- {
- return implode(",", $line);
- }
- else
- throw new Exception('CSV failed');
-
-
- }
-
- static public function arr_to_csv($arr, $tri_column = false)
- {
- $lines = array();
-
- if ($tri_column)
- {
- $title = "";
- foreach ($tri_column as $v)
- {
- if (isset($v['title']))
- $title .= ( empty($title) ? "" : ",") . '"' . str_replace('"', '""', strip_tags($v['title'])) . '"';
- }
- !empty($title) ? $lines[] = $title : "";
- }
- foreach ($arr as $v)
- {
- $lines[] = self::arr_to_csv_line($v, $tri_column);
- }
-
- return implode("\n", $lines);
- }
-
}
diff --git a/lib/classes/ftpclient.class.php b/lib/classes/ftpclient.class.php
index e366749f9b..b9417b90e4 100644
--- a/lib/classes/ftpclient.class.php
+++ b/lib/classes/ftpclient.class.php
@@ -2,435 +2,393 @@
class ftpclient
{
+ protected $connexion;
+ protected $proxy;
+ protected $host;
+ protected $cached_dirs = array();
+ protected $debug = false;
- protected $connexion;
- protected $proxy;
- protected $host;
- protected $cached_dirs = array();
- protected $debug = false;
-
- public function __construct($host, $port = 21, $timeout = 90, $ssl = false, $proxy = false, $proxyport = false)
- {
- $host = mb_substr($host, -1, 1) == '/' ? mb_substr($host, 0, (mb_strlen($host) - 1)) : $host;
-
- if (($p = mb_strpos($host, 'ftp://')) !== false)
- $host = mb_substr($host, 6);
-
- $host = $proxy ? $proxy : $host;
- $port = $proxyport ? $proxyport : $port;
-
- if ($this->debug && $proxy)
- echo "Utilisation du proxy $proxy\n
";
-
- if ($this->debug && $proxyport)
- echo "Utilisation du port proxy $proxyport\n
";
-
- $this->proxy = $proxy;
- $this->host = $host;
-
- if ($this->debug)
- echo "Ouverture de connection vers $host:$port timeout $timeout et proxy $proxy:$proxyport\n
";
-
- if (trim($host) == '')
+ public function __construct($host, $port = 21, $timeout = 90, $ssl = false, $proxy = false, $proxyport = false)
{
- throw new Exception('Nom d\'hote incorrect ' . $host);
+ $host = mb_substr($host, -1, 1) == '/' ? mb_substr($host, 0, (mb_strlen($host) - 1)) : $host;
+
+ if (($p = mb_strpos($host, 'ftp://')) !== false)
+ $host = mb_substr($host, 6);
+
+ $host = $proxy ? $proxy : $host;
+ $port = $proxyport ? $proxyport : $port;
+
+ if ($this->debug && $proxy)
+ echo "Utilisation du proxy $proxy\n
";
+
+ if ($this->debug && $proxyport)
+ echo "Utilisation du port proxy $proxyport\n
";
+
+ $this->proxy = $proxy;
+ $this->host = $host;
+
+ if ($this->debug)
+ echo "Ouverture de connection vers $host:$port timeout $timeout et proxy $proxy:$proxyport\n
";
+
+ if (trim($host) == '') {
+ throw new Exception('Nom d\'hote incorrect ' . $host);
+ }
+
+ if ($ssl === true) {
+ if (($this->connexion = ftp_ssl_connect($host, $port, $timeout)) === false) {
+ throw new Exception('Impossible de se connecter au serveur FTP en SSL');
+ }
+ } else {
+ if (($this->connexion = ftp_connect($host, $port, $timeout)) === false) {
+ throw new Exception('Impossible de se connecter au serveur FTP ' . $host . ":$port $timeout");
+ }
+ }
+
+ return $this;
}
- if ($ssl === true)
+ public function __destruct()
{
- if (($this->connexion = ftp_ssl_connect($host, $port, $timeout)) === false)
- {
- throw new Exception('Impossible de se connecter au serveur FTP en SSL');
- }
- }
- else
- {
- if (($this->connexion = ftp_connect($host, $port, $timeout)) === false)
- {
- throw new Exception('Impossible de se connecter au serveur FTP ' . $host . ":$port $timeout");
- }
+ if ($this->connexion)
+ $this->close();
+
+ return;
}
- return $this;
- }
-
- public function __destruct()
- {
- if ($this->connexion)
- $this->close();
-
- return;
- }
-
- public function login($username, $password)
- {
- $username = $this->proxy ? $username . "@" . $this->host : $username;
-
- $retry = 3;
- $done = false;
-
- if ($this->debug)
- echo "tentative de login avec $username, $password\n
";
-
- while ($retry > 0)
+ public function login($username, $password)
{
- if ((ftp_login($this->connexion, $username, $password)) === false)
- {
- $retry--;
- }
- else
- {
- $retry = 0;
- $done = true;
- }
- }
- if (!$done)
- {
- throw new Exception('Impossible de s\'authentifier sur le serveur FTP');
+ $username = $this->proxy ? $username . "@" . $this->host : $username;
+
+ $retry = 3;
+ $done = false;
+
+ if ($this->debug)
+ echo "tentative de login avec $username, $password\n
";
+
+ while ($retry > 0) {
+ if ((ftp_login($this->connexion, $username, $password)) === false) {
+ $retry --;
+ } else {
+ $retry = 0;
+ $done = true;
+ }
+ }
+ if ( ! $done) {
+ throw new Exception('Impossible de s\'authentifier sur le serveur FTP');
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function passive($boolean)
- {
- $boolean = !!$boolean;
-
- if ($this->debug)
- echo ($boolean ? 'des' : '') . "activation du mode passif\n
";
-
- if ((ftp_pasv($this->connexion, $boolean)) === false)
+ public function passive($boolean)
{
- throw new Exception('Impossible de changer le mode passif');
+ $boolean = ! ! $boolean;
+
+ if ($this->debug)
+ echo ($boolean ? 'des' : '') . "activation du mode passif\n
";
+
+ if ((ftp_pasv($this->connexion, $boolean)) === false) {
+ throw new Exception('Impossible de changer le mode passif');
+ }
+
+ return $this;
}
- return $this;
- }
-
- public function pwd()
- {
-
- if ($this->debug)
- echo "Recuperation du path working directory\n
";
-
- if (($pwd = ftp_pwd($this->connexion)) === false)
+ public function pwd()
{
- throw new Exception('Impossible de recuperer le path working directory');
- }
- $this->cached_dirs[$pwd] = $pwd;
- return $pwd;
- }
+ if ($this->debug)
+ echo "Recuperation du path working directory\n
";
- public function chdir($directory)
- {
- $directory = $this->get_absolute_path($directory);
- if ($this->debug)
- echo "Changement de dossier vers $directory\n
";
+ if (($pwd = ftp_pwd($this->connexion)) === false) {
+ throw new Exception('Impossible de recuperer le path working directory');
+ }
+ $this->cached_dirs[$pwd] = $pwd;
- if ((ftp_chdir($this->connexion, $directory)) === false)
- {
- throw new Exception('Impossible de changer de dossier');
- }
- $this->pwd();
-
- return $this;
- }
-
- public function rmdir($remote_directory)
- {
- $remote_directory = $this->get_absolute_path($remote_directory);
- if ($this->debug)
- echo "Suppression du dossier $remote_directory\n
";
-
- if ((ftp_rmdir($this->connexion, $remote_directory)) === false)
- {
- throw new Exception('Impossible de supprimer le dossier');
+ return $pwd;
}
- unset($this->cached_dirs[$remote_directory]);
-
- return $this;
- }
-
- public function unlink($filepath)
- {
- $filepath = $this->get_absolute_path($filepath);
- if ($this->debug)
- echo "Suppression du fichier $filepath \n
";
-
- if ((ftp_delete($this->connexion, $filepath)) === false)
+ public function chdir($directory)
{
- throw new Exception('Impossible de supprimer le fichier');
+ $directory = $this->get_absolute_path($directory);
+ if ($this->debug)
+ echo "Changement de dossier vers $directory\n
";
+
+ if ((ftp_chdir($this->connexion, $directory)) === false) {
+ throw new Exception('Impossible de changer de dossier');
+ }
+ $this->pwd();
+
+ return $this;
}
- return $this;
- }
-
- public function rename($oldname, $newname)
- {
- $oldname = $this->get_absolute_path($oldname);
- $newname = $this->get_absolute_path($newname);
- if ($this->debug)
- echo "Renommage de $oldname en $newname\n
";
-
- if ((ftp_rename($this->connexion, $oldname, $newname)) === false)
+ public function rmdir($remote_directory)
{
- throw new Exception('Impossible de renommer le dossier ou le fichier');
+ $remote_directory = $this->get_absolute_path($remote_directory);
+ if ($this->debug)
+ echo "Suppression du dossier $remote_directory\n
";
+
+ if ((ftp_rmdir($this->connexion, $remote_directory)) === false) {
+ throw new Exception('Impossible de supprimer le dossier');
+ }
+
+ unset($this->cached_dirs[$remote_directory]);
+
+ return $this;
}
- unset($this->cached_dirs[$oldname]);
-
- return $this;
- }
-
- public function mkdir($remote_directory)
- {
- $remote_directory = $this->get_absolute_path($remote_directory);
- if (isset($this->cached_dirs[$remote_directory]))
-
- return $this;
-
- if ($this->debug)
- echo "Creation du dossier $remote_directory\n
";
-
- if ((ftp_mkdir($this->connexion, $remote_directory)) === false)
+ public function unlink($filepath)
{
- throw new Exception('Impossible de creer le dossier');
- }
- $this->cached_dirs[$remote_directory] = $remote_directory;
+ $filepath = $this->get_absolute_path($filepath);
+ if ($this->debug)
+ echo "Suppression du fichier $filepath \n
";
- return $this;
- }
+ if ((ftp_delete($this->connexion, $filepath)) === false) {
+ throw new Exception('Impossible de supprimer le fichier');
+ }
- public function put($remotefile, $localfile)
- {
- $remotefile = $this->get_absolute_path($remotefile);
- if ($this->debug)
- echo "Envoi du fichier par AUTORESUME $localfile vers $remotefile de taille " . filesize($localfile) . "\n
";
-
- $ret = $this->nb_put($remotefile, $localfile);
-
- if ($this->debug)
- echo "APRES ESSAI EN AUTORESUME ON A retour:" . $ret . "\n
";
-
- if ($ret == FTP_FAILED)
- {
- if ($this->debug)
- echo "Resume seems not to be supported, try again from scratch\n
";
- try
- {
- $this->unlink($remotefile);
- }
- catch (Exception $e)
- {
- echo $e;
- }
- $ret = $this->nb_put($remotefile, $localfile, 0);
-
- if ($this->debug)
- echo "On doit avoir a la fin $remotefile de size " . filesize($localfile) . "\n
";
- }
- if ($ret != FTP_FINISHED)
- {
- throw new Exception('Erreur lors du transfert de fichier');
+ return $this;
}
- return $this;
- }
-
- protected function nb_put($remotefile, $localfile, $start = FTP_AUTORESUME)
- {
- $ret = ftp_nb_put($this->connexion, $remotefile, $localfile, FTP_BINARY, $start);
-
- while ($ret == FTP_MOREDATA)
+ public function rename($oldname, $newname)
{
- set_time_limit(20);
- $ret = ftp_nb_continue($this->connexion);
+ $oldname = $this->get_absolute_path($oldname);
+ $newname = $this->get_absolute_path($newname);
+ if ($this->debug)
+ echo "Renommage de $oldname en $newname\n
";
+
+ if ((ftp_rename($this->connexion, $oldname, $newname)) === false) {
+ throw new Exception('Impossible de renommer le dossier ou le fichier');
+ }
+
+ unset($this->cached_dirs[$oldname]);
+
+ return $this;
}
- return $ret;
- }
-
- public function get($localfile, $remotefile)
- {
- $remotefile = $this->get_absolute_path($remotefile);
- if ($this->debug)
- echo "Reception du fichier par AUTORESUME $remotefile vers $localfile \n
";
-
- $ret = $this->nb_get($localfile, $remotefile);
-
- if ($this->debug)
- echo "APRES ESSAI EN AUTORESUME ON A retour:" . $ret . "\n
";
-
- if ($ret == FTP_FAILED)
+ public function mkdir($remote_directory)
{
- if ($this->debug)
- echo "Resume seems not to be supported, try again from scratch\n
";
- try
- {
- $this->unlink($localfile);
- }
- catch (Exception $e)
- {
- echo $e;
- }
- $ret = $this->nb_get($localfile, $remotefile, 0);
+ $remote_directory = $this->get_absolute_path($remote_directory);
+ if (isset($this->cached_dirs[$remote_directory]))
+ return $this;
+
+ if ($this->debug)
+ echo "Creation du dossier $remote_directory\n
";
+
+ if ((ftp_mkdir($this->connexion, $remote_directory)) === false) {
+ throw new Exception('Impossible de creer le dossier');
+ }
+ $this->cached_dirs[$remote_directory] = $remote_directory;
+
+ return $this;
+ }
+
+ public function put($remotefile, $localfile)
+ {
+ $remotefile = $this->get_absolute_path($remotefile);
+ if ($this->debug)
+ echo "Envoi du fichier par AUTORESUME $localfile vers $remotefile de taille " . filesize($localfile) . "\n
";
+
+ $ret = $this->nb_put($remotefile, $localfile);
+
+ if ($this->debug)
+ echo "APRES ESSAI EN AUTORESUME ON A retour:" . $ret . "\n
";
+
+ if ($ret == FTP_FAILED) {
+ if ($this->debug)
+ echo "Resume seems not to be supported, try again from scratch\n
";
+ try {
+ $this->unlink($remotefile);
+ } catch (Exception $e) {
+ echo $e;
+ }
+ $ret = $this->nb_put($remotefile, $localfile, 0);
+
+ if ($this->debug)
+ echo "On doit avoir a la fin $remotefile de size " . filesize($localfile) . "\n
";
+ }
+ if ($ret != FTP_FINISHED) {
+ throw new Exception('Erreur lors du transfert de fichier');
+ }
+
+ return $this;
+ }
+
+ protected function nb_put($remotefile, $localfile, $start = FTP_AUTORESUME)
+ {
+ $ret = ftp_nb_put($this->connexion, $remotefile, $localfile, FTP_BINARY, $start);
+
+ while ($ret == FTP_MOREDATA) {
+ set_time_limit(20);
+ $ret = ftp_nb_continue($this->connexion);
+ }
+
+ return $ret;
+ }
+
+ public function get($localfile, $remotefile)
+ {
+ $remotefile = $this->get_absolute_path($remotefile);
+ if ($this->debug)
+ echo "Reception du fichier par AUTORESUME $remotefile vers $localfile \n
";
+
+ $ret = $this->nb_get($localfile, $remotefile);
+
+ if ($this->debug)
+ echo "APRES ESSAI EN AUTORESUME ON A retour:" . $ret . "\n
";
+
+ if ($ret == FTP_FAILED) {
+ if ($this->debug)
+ echo "Resume seems not to be supported, try again from scratch\n
";
+ try {
+ $this->unlink($localfile);
+ } catch (Exception $e) {
+ echo $e;
+ }
+ $ret = $this->nb_get($localfile, $remotefile, 0);
// if($this->debug)
// echo "On doit avoir a la fin $remotefile de size ".filesize($localfile)."\n
";
+ }
+ if ($ret != FTP_FINISHED) {
+ throw new Exception('Erreur lors du transfert de fichier');
+ }
+
+ return $this;
}
- if ($ret != FTP_FINISHED)
+
+ public function delete($filepath)
{
- throw new Exception('Erreur lors du transfert de fichier');
+ if ( ! ftp_delete($this->connexion, $filepath))
+ throw new Exception('Impossible de supprimer le fichier');
+
+ return $this;
}
- return $this;
- }
-
- public function delete($filepath)
- {
- if (!ftp_delete($this->connexion, $filepath))
- throw new Exception('Impossible de supprimer le fichier');
-
- return $this;
- }
-
- protected function nb_get($localfile, $remotefile, $start = FTP_AUTORESUME)
- {
- clearstatcache();
- if (!file_exists($localfile))
- $start = 0;
-
- $ret = ftp_nb_get($this->connexion, $localfile, $remotefile, FTP_BINARY, $start);
-
- while ($ret == FTP_MOREDATA)
+ protected function nb_get($localfile, $remotefile, $start = FTP_AUTORESUME)
{
- set_time_limit(20);
- $ret = ftp_nb_continue($this->connexion);
+ clearstatcache();
+ if ( ! file_exists($localfile))
+ $start = 0;
+
+ $ret = ftp_nb_get($this->connexion, $localfile, $remotefile, FTP_BINARY, $start);
+
+ while ($ret == FTP_MOREDATA) {
+ set_time_limit(20);
+ $ret = ftp_nb_continue($this->connexion);
+ }
+
+ return $ret;
}
- return $ret;
- }
-
- public function system_type()
- {
-
- if ($this->debug)
- echo "Recuperation du type de systeme distant\n
";
-
- if (($systype = ftp_systype($this->connexion)) === false)
+ public function system_type()
{
- throw new Exception('Impossible de recuperer le type de systeme');
+
+ if ($this->debug)
+ echo "Recuperation du type de systeme distant\n
";
+
+ if (($systype = ftp_systype($this->connexion)) === false) {
+ throw new Exception('Impossible de recuperer le type de systeme');
+ }
+
+ return $systype;
}
- return $systype;
- }
-
- public function filesize($remotefile)
- {
- $remotefile = $this->get_absolute_path($remotefile);
- if ($this->debug)
- echo "Recuperation de la taille du fichier $remotefile\n
";
-
- if (($size = ftp_size($this->connexion, $remotefile)) === false)
+ public function filesize($remotefile)
{
- throw new Exception('Impossible de recuperer la taille du fichier');
+ $remotefile = $this->get_absolute_path($remotefile);
+ if ($this->debug)
+ echo "Recuperation de la taille du fichier $remotefile\n
";
+
+ if (($size = ftp_size($this->connexion, $remotefile)) === false) {
+ throw new Exception('Impossible de recuperer la taille du fichier');
+ }
+
+ return $size;
}
- return $size;
- }
-
- public function close()
- {
- if ($this->debug)
- echo "Fermeture de la connexion\n
";
- if (!$this->connexion)
-
- return $this;
- if ((ftp_close($this->connexion)) === false)
+ public function close()
{
- throw new Exception('Impossible de fermer la connexion');
+ if ($this->debug)
+ echo "Fermeture de la connexion\n
";
+ if ( ! $this->connexion)
+ return $this;
+ if ((ftp_close($this->connexion)) === false) {
+ throw new Exception('Impossible de fermer la connexion');
+ }
+ $this->connexion = null;
+
+ return $this;
}
- $this->connexion = null;
- return $this;
- }
-
- protected function is_absolute_path($path)
- {
- $absolute = false;
-
- if (substr($path, 0, 1) == '/')
- $absolute = true;
-
- return $absolute;
- }
-
- protected function get_absolute_path($file)
- {
- $file = str_replace('//', '/', $file);
- if ($this->is_absolute_path($file))
-
- return $file;
-
- $pwd = $this->add_end_slash($this->pwd());
-
- return $pwd . $file;
- }
-
- public function add_end_slash($path)
- {
- $path = trim($path);
-
- if ($path == "" || $path == '/' || $path == '//')
-
- return("/");
-
- if (substr($path, -1, 1) != "/")
- $path .= "/";
-
- return($path);
- }
-
- public function list_directory($recursive = false)
- {
- $current_dir = $this->pwd();
- $contents = ftp_rawlist($this->connexion, $current_dir, !!$recursive);
-
- $list = array();
-
- foreach ($contents as $content)
+ protected function is_absolute_path($path)
{
- if ($content == '')
- continue;
+ $absolute = false;
- $info = preg_split("/[\s]+/", $content, 9);
+ if (substr($path, 0, 1) == '/')
+ $absolute = true;
- $is_dir = $info[0]{0} == 'd';
- if ($is_dir)
- continue;
- if ($content[0] == '/')
- {
- $current_dir = str_replace(':', '', $content);
- continue;
- }
-
- $file = $this->add_end_slash($current_dir) . $info[8];
-
- $date = strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]);
- if (!$date)
- {
- $date = strtotime($info[6] . ' ' . $info[5] . ' ' . date('Y') . ' ' . $info[7]);
- }
-
- $list[$file] = array(
- 'date' => $date
- );
+ return $absolute;
}
- return $list;
- }
+ protected function get_absolute_path($file)
+ {
+ $file = str_replace('//', '/', $file);
+ if ($this->is_absolute_path($file))
+ return $file;
+ $pwd = $this->add_end_slash($this->pwd());
+
+ return $pwd . $file;
+ }
+
+ public function add_end_slash($path)
+ {
+ $path = trim($path);
+
+ if ($path == "" || $path == '/' || $path == '//')
+ return("/");
+
+ if (substr($path, -1, 1) != "/")
+ $path .= "/";
+
+ return($path);
+ }
+
+ public function list_directory($recursive = false)
+ {
+ $current_dir = $this->pwd();
+ $contents = ftp_rawlist($this->connexion, $current_dir, ! ! $recursive);
+
+ $list = array();
+
+ foreach ($contents as $content) {
+ if ($content == '')
+ continue;
+
+ $info = preg_split("/[\s]+/", $content, 9);
+
+ $is_dir = $info[0]{0} == 'd';
+ if ($is_dir)
+ continue;
+ if ($content[0] == '/') {
+ $current_dir = str_replace(':', '', $content);
+ continue;
+ }
+
+ $file = $this->add_end_slash($current_dir) . $info[8];
+
+ $date = strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]);
+ if ( ! $date) {
+ $date = strtotime($info[6] . ' ' . $info[5] . ' ' . date('Y') . ' ' . $info[7]);
+ }
+
+ $list[$file] = array(
+ 'date' => $date
+ );
+ }
+
+ return $list;
+ }
}
diff --git a/lib/classes/gatekeeper.class.php b/lib/classes/gatekeeper.class.php
index eb997d6836..2703dea0f3 100644
--- a/lib/classes/gatekeeper.class.php
+++ b/lib/classes/gatekeeper.class.php
@@ -17,334 +17,290 @@
*/
class gatekeeper
{
+ /**
+ *
+ * @var string
+ */
+ protected $_directory;
- /**
- *
- * @var string
- */
- protected $_directory;
+ /**
+ *
+ * @var string
+ */
+ protected $_script_name;
- /**
- *
- * @var string
- */
- protected $_script_name;
+ /**
+ *
+ * @var string
+ */
+ protected $_PHP_SELF;
- /**
- *
- * @var string
- */
- protected $_PHP_SELF;
+ /**
+ *
+ * @var gatekeeper
+ */
+ protected static $_instance;
+ protected $Core;
- /**
- *
- * @var gatekeeper
- */
- protected static $_instance;
- protected $Core;
-
- /**
- *
- * @return gatekeeper
- */
- public static function getInstance(\Alchemy\Phrasea\Core $Core)
- {
- if (!(self::$_instance instanceof self))
- self::$_instance = new self($Core);
-
- return self::$_instance;
- }
-
- /**
- *
- * @return gatekeeper
- */
- function __construct(\Alchemy\Phrasea\Core $Core)
- {
- $this->Core = $Core;
-
- return $this;
- }
-
- /**
- * Check the current sub_directory on the domain name
- * Redirect if access is denied
- *
- * @return Void
- */
- function check_directory()
- {
- $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
- $appbox = appbox::get_instance($this->Core);
- $session = $appbox->get_session();
-
- if (http_request::is_command_line())
-
- return;
-
- if (isset($_SERVER['PHP_SELF']) && trim($_SERVER['PHP_SELF']))
+ /**
+ *
+ * @return gatekeeper
+ */
+ public static function getInstance(\Alchemy\Phrasea\Core $Core)
{
- $this->_PHP_SELF = $_SERVER['PHP_SELF'];
+ if ( ! (self::$_instance instanceof self))
+ self::$_instance = new self($Core);
- $php_script = explode('/', $_SERVER['PHP_SELF']);
-
- if (trim($php_script[0]) == 0)
- array_shift($php_script);
-
- if (count($php_script) > 1)
- $this->_directory = $php_script[0];
- else
- $this->_directory = '';
- $this->_script_name = array_pop($php_script);
+ return self::$_instance;
}
- if (!$session->is_authenticated())
+ /**
+ *
+ * @return gatekeeper
+ */
+ function __construct(\Alchemy\Phrasea\Core $Core)
{
- try
- {
- $cookie = Session_Handler::get_cookie('persistent');
- $auth = new Session_Authentication_PersistentCookie($appbox, $cookie);
- $session->restore($auth->get_user(), $auth->get_ses_id());
- }
- catch (Exception $e)
- {
+ $this->Core = $Core;
- }
+ return $this;
}
- if (!$session->is_authenticated())
+ /**
+ * Check the current sub_directory on the domain name
+ * Redirect if access is denied
+ *
+ * @return Void
+ */
+ function check_directory()
{
- switch ($this->_directory)
- {
- case 'prod':
- case 'client':
- $this->give_guest_access();
- if ($request->isXmlHttpRequest())
- {
- phrasea::headers(404);
- }
- else
- {
- phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
- }
- break;
- case 'thesaurus2':
- if ($this->_PHP_SELF == '/thesaurus2/xmlhttp/getterm.x.php'
- || $this->_PHP_SELF == '/thesaurus2/xmlhttp/searchcandidate.x.php'
- || $this->_PHP_SELF == '/thesaurus2/xmlhttp/getsy.x.php')
+ $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
+ $appbox = appbox::get_instance($this->Core);
+ $session = $appbox->get_session();
+ if (http_request::is_command_line())
return;
- phrasea::redirect('/login/?redirect=/thesaurus2');
- break;
- case 'report':
- phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
- break;
- case 'admin':
- if ($this->_script_name === 'runscheduler.php')
+ if (isset($_SERVER['PHP_SELF']) && trim($_SERVER['PHP_SELF'])) {
+ $this->_PHP_SELF = $_SERVER['PHP_SELF'];
+
+ $php_script = explode('/', $_SERVER['PHP_SELF']);
+
+ if (trim($php_script[0]) == 0)
+ array_shift($php_script);
+
+ if (count($php_script) > 1)
+ $this->_directory = $php_script[0];
+ else
+ $this->_directory = '';
+ $this->_script_name = array_pop($php_script);
+ }
+
+ if ( ! $session->is_authenticated()) {
+ try {
+ $cookie = Session_Handler::get_cookie('persistent');
+ $auth = new Session_Authentication_PersistentCookie($appbox, $cookie);
+ $session->restore($auth->get_user(), $auth->get_ses_id());
+ } catch (Exception $e) {
+
+ }
+ }
+
+ if ( ! $session->is_authenticated()) {
+ switch ($this->_directory) {
+ case 'prod':
+ case 'client':
+ $this->give_guest_access();
+ if ($request->isXmlHttpRequest()) {
+ phrasea::headers(404);
+ } else {
+ phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
+ }
+ break;
+ case 'thesaurus2':
+ if ($this->_PHP_SELF == '/thesaurus2/xmlhttp/getterm.x.php'
+ || $this->_PHP_SELF == '/thesaurus2/xmlhttp/searchcandidate.x.php'
+ || $this->_PHP_SELF == '/thesaurus2/xmlhttp/getsy.x.php')
+ return;
+ phrasea::redirect('/login/?redirect=/thesaurus2');
+ break;
+ case 'report':
+ phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
+ break;
+ case 'admin':
+ if ($this->_script_name === 'runscheduler.php')
+ return;
+ phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
+ break;
+ case 'login':
+ if ($appbox->need_major_upgrade()) {
+ phrasea::redirect("/setup/");
+ }
+
+ return;
+ break;
+ case 'api':
+ return;
+ break;
+ case 'include':
+ case '':
+ return;
+ case 'setup':
+ if ($appbox->upgradeavailable())
+ return;
+ else
+ phrasea::redirect('/login/');
+ break;
+ default:
+ phrasea::redirect('/login/');
+ break;
+ case 'lightbox':
+ $this->token_access();
+ if ( ! $session->is_authenticated()) {
+ phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
+ }
+ break;
+ }
+ } elseif ($_SERVER['PHP_SELF'] === '/login/logout.php') {
return;
- phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
- break;
- case 'login':
- if ($appbox->need_major_upgrade())
- {
- phrasea::redirect("/setup/");
- }
-
- return;
- break;
- case 'api':
- return;
- break;
- case 'include':
- case '':
- return;
- case 'setup':
- if ($appbox->upgradeavailable())
-
- return;
- else
- phrasea::redirect('/login/');
- break;
- default:
- phrasea::redirect('/login/');
- break;
- case 'lightbox':
- $this->token_access();
- if (!$session->is_authenticated())
- {
- phrasea::redirect('/login/?redirect=' . $_SERVER['REQUEST_URI']);
- }
- break;
- }
- }
- elseif ($_SERVER['PHP_SELF'] === '/login/logout.php')
- {
- return;
- }
-
- try
- {
- $session->open_phrasea_session();
- }
- catch (Exception $e)
- {
- phrasea::redirect('/login/logout.php?app=' . $this->_directory);
- }
-
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- switch ($this->_directory)
- {
- case 'admin':
- case 'taskmanager':
- if (!$user->ACL()->has_access_to_module('admin'))
- {
- phrasea::headers(403);
}
- break;
- case 'thesaurus2':
- if (!$user->ACL()->has_access_to_module('thesaurus'))
- {
- phrasea::headers(403);
+
+ try {
+ $session->open_phrasea_session();
+ } catch (Exception $e) {
+ phrasea::redirect('/login/logout.php?app=' . $this->_directory);
}
- break;
- case 'client':
- case 'prod':
- case 'lightbox':
- $this->token_access();
- break;
- case 'upload':
- if (!$user->ACL()->has_right('addrecord'))
- {
- phrasea::headers(403);
+
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+
+ switch ($this->_directory) {
+ case 'admin':
+ case 'taskmanager':
+ if ( ! $user->ACL()->has_access_to_module('admin')) {
+ phrasea::headers(403);
+ }
+ break;
+ case 'thesaurus2':
+ if ( ! $user->ACL()->has_access_to_module('thesaurus')) {
+ phrasea::headers(403);
+ }
+ break;
+ case 'client':
+ case 'prod':
+ case 'lightbox':
+ $this->token_access();
+ break;
+ case 'upload':
+ if ( ! $user->ACL()->has_right('addrecord')) {
+ phrasea::headers(403);
+ }
+ break;
+ case 'report':
+ if ( ! $user->ACL()->has_right('report')) {
+ phrasea::headers(403);
+ }
+ break;
+ default:
+ break;
}
- break;
- case 'report':
- if (!$user->ACL()->has_right('report'))
- {
- phrasea::headers(403);
+
+ return;
+ }
+
+ /**
+ * Redirect to the correct guest location
+ *
+ * @return gatekeeper
+ */
+ protected function give_guest_access()
+ {
+ $appbox = appbox::get_instance($this->Core);
+ $request = http_request::getInstance();
+ $session = $appbox->get_session();
+
+ $parm = $request->get_parms('nolog', 'redirect');
+
+ if ( ! is_null($parm['nolog']) && phrasea::guest_allowed()) {
+ try {
+ $auth = new Session_Authentication_Guest($appbox);
+ $session->authenticate($auth);
+ } catch (Exception $e) {
+ $url = '/login/?redirect=' . $parm['redirect']
+ . '&error=' . urlencode($e->getMessage());
+ phrasea::redirect($url);
+ }
+ phrasea::redirect('/' . $this->_directory . '/');
}
- break;
- default:
- break;
+
+ return $this;
}
- return;
- }
-
- /**
- * Redirect to the correct guest location
- *
- * @return gatekeeper
- */
- protected function give_guest_access()
- {
- $appbox = appbox::get_instance($this->Core);
- $request = http_request::getInstance();
- $session = $appbox->get_session();
-
- $parm = $request->get_parms('nolog', 'redirect');
-
- if (!is_null($parm['nolog']) && phrasea::guest_allowed())
+ /**
+ * If token is present in URL, sign on and redirect
+ *
+ * @return gatekeeper
+ */
+ protected function token_access()
{
- try
- {
- $auth = new Session_Authentication_Guest($appbox);
- $session->authenticate($auth);
- }
- catch (Exception $e)
- {
- $url = '/login/?redirect=' . $parm['redirect']
- . '&error=' . urlencode($e->getMessage());
- phrasea::redirect($url);
- }
- phrasea::redirect('/' . $this->_directory . '/');
+ $appbox = appbox::get_instance($this->Core);
+ $request = new http_request();
+ $session = $appbox->get_session();
+ $parm = $request->get_parms('LOG');
+
+ if (is_null($parm["LOG"]))
+ return $this;
+
+ try {
+ if ($session->is_authenticated())
+ $session->logout();
+ $auth = new Session_Authentication_Token($appbox, $parm['LOG']);
+ $session->authenticate($auth);
+ } catch (Exception $e) {
+ return phrasea::redirect("/login/?error=" . urlencode($e->getMessage()));
+ }
+
+ try {
+ $datas = random::helloToken($parm['LOG']);
+
+ switch ($datas['type']) {
+ default:
+ return $this;
+ break;
+ case \random::TYPE_FEED_ENTRY:
+ return phrasea::redirect("/lightbox/feeds/entry/" . $datas['datas'] . "/");
+ break;
+ case \random::TYPE_VALIDATE:
+ case \random::TYPE_VIEW:
+ return phrasea::redirect("/lightbox/validate/" . $datas['datas'] . "/");
+ break;
+ }
+ } catch (Exception_NotFound $e) {
+
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- * If token is present in URL, sign on and redirect
- *
- * @return gatekeeper
- */
- protected function token_access()
- {
- $appbox = appbox::get_instance($this->Core);
- $request = new http_request();
- $session = $appbox->get_session();
- $parm = $request->get_parms('LOG');
-
- if (is_null($parm["LOG"]))
-
- return $this;
-
- try
+ /**
+ * Checks if session is open
+ * Redirect if session is missing
+ *
+ * @return Void
+ */
+ public function require_session()
{
- if ($session->is_authenticated())
- $session->logout();
- $auth = new Session_Authentication_Token($appbox, $parm['LOG']);
- $session->authenticate($auth);
+ $appbox = appbox::get_instance($this->Core);
+ $session = $appbox->get_session();
+ if ($session->is_authenticated()) {
+ try {
+ $session->open_phrasea_session();
+ } catch (Exception $e) {
+ phrasea::redirect('/login/logout.php');
+ }
+
+ return true;
+ }
+ phrasea::headers(403);
+
+ return;
}
- catch (Exception $e)
- {
- return phrasea::redirect("/login/?error=" . urlencode($e->getMessage()));
- }
-
- try
- {
- $datas = random::helloToken($parm['LOG']);
-
- switch ($datas['type'])
- {
- default:
- return $this;
- break;
- case \random::TYPE_FEED_ENTRY:
- return phrasea::redirect("/lightbox/feeds/entry/" . $datas['datas'] . "/");
- break;
- case \random::TYPE_VALIDATE:
- case \random::TYPE_VIEW:
- return phrasea::redirect("/lightbox/validate/" . $datas['datas'] . "/");
- break;
- }
- }
- catch (Exception_NotFound $e)
- {
-
- }
-
- return $this;
- }
-
- /**
- * Checks if session is open
- * Redirect if session is missing
- *
- * @return Void
- */
- public function require_session()
- {
- $appbox = appbox::get_instance($this->Core);
- $session = $appbox->get_session();
- if ($session->is_authenticated())
- {
- try
- {
- $session->open_phrasea_session();
- }
- catch (Exception $e)
- {
- phrasea::redirect('/login/logout.php');
- }
-
- return true;
- }
- phrasea::headers(403);
-
- return;
- }
-
}
diff --git a/lib/classes/geonames.class.php b/lib/classes/geonames.class.php
index bd3d494677..787e1b8d57 100644
--- a/lib/classes/geonames.class.php
+++ b/lib/classes/geonames.class.php
@@ -2,180 +2,164 @@
class geonames
{
+ protected static $NamesFromId = array();
+ protected static $CountryFromId = array();
+ protected static $CountryCodeFromId = array();
+ protected static $GeonameFromIp = array();
+ protected static $Searches = array();
- protected static $NamesFromId = array();
- protected static $CountryFromId = array();
- protected static $CountryCodeFromId = array();
- protected static $GeonameFromIp = array();
- protected static $Searches = array();
-
- public function name_from_id($geonameid)
- {
- $registry = registry::get_instance();
- $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
- . 'get_name.php?geonameid='
- . $geonameid;
-
- $ret = '';
-
- $xml = http_query::getUrl($url);
- if ($xml)
+ public function name_from_id($geonameid)
{
+ $registry = registry::get_instance();
+ $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
+ . 'get_name.php?geonameid='
+ . $geonameid;
- $sxe = simplexml_load_string($xml);
+ $ret = '';
- if ($sxe && ($geoname = $sxe->geoname))
- {
- $ret = (string) $geoname->city . ', ' . (string) $geoname->country;
- }
+ $xml = http_query::getUrl($url);
+ if ($xml) {
+
+ $sxe = simplexml_load_string($xml);
+
+ if ($sxe && ($geoname = $sxe->geoname)) {
+ $ret = (string) $geoname->city . ', ' . (string) $geoname->country;
+ }
+ }
+
+ return $ret;
}
- return $ret;
- }
-
- public function get_country($geonameid)
- {
- if (trim($geonameid) === '' || trim($geonameid) <= 0)
+ public function get_country($geonameid)
{
- return '';
+ if (trim($geonameid) === '' || trim($geonameid) <= 0) {
+ return '';
+ }
+
+ $registry = registry::get_instance();
+ $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
+ . 'get_name.php?geonameid='
+ . $geonameid;
+
+ $ret = '';
+ $xml = http_query::getUrl($url);
+ if ($xml) {
+ $sxe = simplexml_load_string($xml);
+
+ if ($sxe && ($geoname = $sxe->geoname)) {
+ $ret = (string) $geoname->country;
+ }
+ }
+
+ return $ret;
}
- $registry = registry::get_instance();
- $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
- . 'get_name.php?geonameid='
- . $geonameid;
-
- $ret = '';
- $xml = http_query::getUrl($url);
- if ($xml)
+ public function get_country_code($geonameid)
{
- $sxe = simplexml_load_string($xml);
+ $registry = registry::get_instance();
+ $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
+ . 'get_name.php?geonameid='
+ . $geonameid;
- if ($sxe && ($geoname = $sxe->geoname))
- {
- $ret = (string) $geoname->country;
- }
+ $ret = '';
+
+ $xml = http_query::getUrl($url);
+ if ($xml) {
+ $sxe = simplexml_load_string($xml);
+
+ if ($sxe && ($geoname = $sxe->geoname)) {
+ $ret = (string) $geoname->country_code;
+ }
+ }
+
+ return $ret;
}
- return $ret;
- }
-
- public function get_country_code($geonameid)
- {
- $registry = registry::get_instance();
- $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
- . 'get_name.php?geonameid='
- . $geonameid;
-
- $ret = '';
-
- $xml = http_query::getUrl($url);
- if ($xml)
+ protected static function clean_input($input)
{
- $sxe = simplexml_load_string($xml);
-
- if ($sxe && ($geoname = $sxe->geoname))
- {
- $ret = (string) $geoname->country_code;
- }
+ return strip_tags(trim($input));
}
- return $ret;
- }
-
- protected static function clean_input($input)
- {
- return strip_tags(trim($input));
- }
-
- protected static function highlight($title, $length)
- {
- return '
' . mb_substr($title, 0, $length) . ' '
- . mb_substr($title, $length);
- }
-
- public function find_city($cityName)
- {
- $output = array();
- $cityName = self::clean_input($cityName);
-
- if (strlen($cityName) === 0)
-
- return $output;
-
- $registry = registry::get_instance();
- $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
- . 'find_city.php?city='
- . urlencode($cityName) . '&maxResult=30';
-
- $sxe = simplexml_load_string(http_query::getUrl($url));
-
- foreach ($sxe->geoname as $geoname)
+ protected static function highlight($title, $length)
{
- $length = mb_strlen($geoname->title_match);
-
- $title_highlight = self::highlight($geoname->title, $length);
-
- $country_highlight = (string) $geoname->country;
- if (trim($geoname->country_match) !== '')
- {
- $length = mb_strlen($geoname->country_match);
- $country_highlight = self::highlight($geoname->country, $length);
- }
-
- $output[] = array(
- 'title_highlighted' => $title_highlight
- , 'title' => (string) $geoname->title
- , 'country_highlighted' => $country_highlight
- , 'country' => (string) $geoname->country
- , 'geoname_id' => (int) $geoname->geonameid
- , 'region' => (string) $geoname->region
- );
+ return '
' . mb_substr($title, 0, $length) . ' '
+ . mb_substr($title, $length);
}
- return $output;
- }
-
- protected $cache_ips = array();
-
- public function find_geoname_from_ip($ip)
- {
- if (array_key_exists($ip, $this->cache_ips))
-
- return $this->cache_ips[$ip];
-
- $output = array(
- 'city' => '',
- 'country_code' => '',
- 'country' => '',
- 'fips' => '',
- 'longitude' => '',
- 'latitude' => ''
- );
-
- $registry = registry::get_instance();
- $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
- . 'geoip.php?ip='
- . urlencode($ip);
-
- $xml = http_query::getUrl($url);
- if ($xml)
+ public function find_city($cityName)
{
- $sxe = simplexml_load_string($xml);
- if ($sxe && $sxe->geoname)
- {
- $output['city'] = (string) $sxe->geoname->city;
- $output['country_code'] = (string) $sxe->geoname->country_code;
- $output['country'] = (string) $sxe->geoname->country;
- $output['fips'] = (string) $sxe->geoname->fips;
- $output['longitude'] = (string) $sxe->geoname->longitude;
- $output['latitude'] = (string) $sxe->geoname->latitude;
- }
+ $output = array();
+ $cityName = self::clean_input($cityName);
+
+ if (strlen($cityName) === 0)
+ return $output;
+
+ $registry = registry::get_instance();
+ $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
+ . 'find_city.php?city='
+ . urlencode($cityName) . '&maxResult=30';
+
+ $sxe = simplexml_load_string(http_query::getUrl($url));
+
+ foreach ($sxe->geoname as $geoname) {
+ $length = mb_strlen($geoname->title_match);
+
+ $title_highlight = self::highlight($geoname->title, $length);
+
+ $country_highlight = (string) $geoname->country;
+ if (trim($geoname->country_match) !== '') {
+ $length = mb_strlen($geoname->country_match);
+ $country_highlight = self::highlight($geoname->country, $length);
+ }
+
+ $output[] = array(
+ 'title_highlighted' => $title_highlight
+ , 'title' => (string) $geoname->title
+ , 'country_highlighted' => $country_highlight
+ , 'country' => (string) $geoname->country
+ , 'geoname_id' => (int) $geoname->geonameid
+ , 'region' => (string) $geoname->region
+ );
+ }
+
+ return $output;
}
- $this->cache_ips[$ip] = $output;
+ protected $cache_ips = array();
+
+ public function find_geoname_from_ip($ip)
+ {
+ if (array_key_exists($ip, $this->cache_ips))
+ return $this->cache_ips[$ip];
+
+ $output = array(
+ 'city' => '',
+ 'country_code' => '',
+ 'country' => '',
+ 'fips' => '',
+ 'longitude' => '',
+ 'latitude' => ''
+ );
+
+ $registry = registry::get_instance();
+ $url = $registry->get('GV_i18n_service', 'http://localization.webservice.alchemyasp.com/')
+ . 'geoip.php?ip='
+ . urlencode($ip);
+
+ $xml = http_query::getUrl($url);
+ if ($xml) {
+ $sxe = simplexml_load_string($xml);
+ if ($sxe && $sxe->geoname) {
+ $output['city'] = (string) $sxe->geoname->city;
+ $output['country_code'] = (string) $sxe->geoname->country_code;
+ $output['country'] = (string) $sxe->geoname->country;
+ $output['fips'] = (string) $sxe->geoname->fips;
+ $output['longitude'] = (string) $sxe->geoname->longitude;
+ $output['latitude'] = (string) $sxe->geoname->latitude;
+ }
+ }
+ $this->cache_ips[$ip] = $output;
- return $output;
- }
-
+ return $output;
+ }
}
diff --git a/lib/classes/http/query.class.php b/lib/classes/http/query.class.php
index 86f6a8a9e1..718baa5ec0 100644
--- a/lib/classes/http/query.class.php
+++ b/lib/classes/http/query.class.php
@@ -18,100 +18,92 @@
class http_query
{
- /**
- *
- * @param string $url
- * @return int
- */
- public static function getHttpCodeFromUrl($url)
- {
- if (!is_scalar($url))
-
- return null;
-
- if (trim($url) === '')
-
- return null;
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
- curl_setopt($ch, CURLOPT_NOBODY, true);
- curl_setopt($ch, CURLOPT_HEADER, true);
-
- curl_exec($ch);
- $result = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
-
- curl_close($ch);
-
- return $result;
- }
-
- public static function getHttpHeaders($url)
- {
- if (!is_scalar($url))
-
- return null;
-
- if (trim($url) === '')
-
- return null;
- $ch = curl_init();
-
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
- curl_setopt($ch, CURLOPT_NOBODY, true);
- curl_setopt($ch, CURLOPT_HEADER, true);
-
- curl_exec($ch);
- $result = curl_getinfo($ch);
- curl_close($ch);
-
- return $result;
- }
-
- /**
- *
- * @param string $url
- * @param array $post_data
- * @return string
- */
- public static function getUrl($url, $post_data = false)
- {
- if (!is_scalar($url))
-
- return null;
-
- if (trim($url) === '')
-
- return null;
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, false);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
- curl_setopt($ch, CURLOPT_FAILONERROR, 1);
-
- if ($post_data)
+ /**
+ *
+ * @param string $url
+ * @return int
+ */
+ public static function getHttpCodeFromUrl($url)
{
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
+ if ( ! is_scalar($url))
+ return null;
+
+ if (trim($url) === '')
+ return null;
+
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
+ curl_setopt($ch, CURLOPT_NOBODY, true);
+ curl_setopt($ch, CURLOPT_HEADER, true);
+
+ curl_exec($ch);
+ $result = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+ curl_close($ch);
+
+ return $result;
}
- $result = (curl_exec($ch));
- curl_close($ch);
+ public static function getHttpHeaders($url)
+ {
+ if ( ! is_scalar($url))
+ return null;
- return $result;
- }
+ if (trim($url) === '')
+ return null;
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+ curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
+ curl_setopt($ch, CURLOPT_NOBODY, true);
+ curl_setopt($ch, CURLOPT_HEADER, true);
+
+ curl_exec($ch);
+ $result = curl_getinfo($ch);
+ curl_close($ch);
+
+ return $result;
+ }
+
+ /**
+ *
+ * @param string $url
+ * @param array $post_data
+ * @return string
+ */
+ public static function getUrl($url, $post_data = false)
+ {
+ if ( ! is_scalar($url))
+ return null;
+
+ if (trim($url) === '')
+ return null;
+
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_HEADER, false);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
+ curl_setopt($ch, CURLOPT_FAILONERROR, 1);
+
+ if ($post_data) {
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
+ }
+
+ $result = (curl_exec($ch));
+ curl_close($ch);
+
+ return $result;
+ }
}
diff --git a/lib/classes/http/request.class.php b/lib/classes/http/request.class.php
index 622228dc60..015bcc3d4a 100644
--- a/lib/classes/http/request.class.php
+++ b/lib/classes/http/request.class.php
@@ -17,9 +17,9 @@
*/
class http_request
{
- /**
- * @todo enable filters
- */
+ /**
+ * @todo enable filters
+ */
// private static $_FILTER_IMPLEMENTED = extension_loaded;
//
// const VALIDATE_BOOLEAN = FILTER_VALIDATE_BOOLEAN;
@@ -34,242 +34,226 @@ class http_request
// const SANITIZE_ENCODED = FILTER_SANITIZE_ENCODED;
// const SANITIZE_MAGIC_QUOTES = FILTER_SANITIZE_MAGIC_QUOTES;
// const SANITIZE_NUMBER_FLOAT = FILTER_SANITIZE_NUMBER_FLOAT;
- const SANITIZE_NUMBER_INT = 'int';
+ const SANITIZE_NUMBER_INT = 'int';
// const SANITIZE_SPECIAL_CHARS = FILTER_SANITIZE_SPECIAL_CHARS;
- const SANITIZE_STRING = 'string';
+ const SANITIZE_STRING = 'string';
+
// const SANITIZE_STRIPPED = FILTER_SANITIZE_STRIPPED;
// const SANITIZE_URL = FILTER_SANITIZE_URL;
+ /**
+ *
+ * @var
+ */
+ private static $_instance;
- /**
- *
- * @var
- */
- private static $_instance;
+ /**
+ *
+ * @var boolean
+ */
+ protected static $_cli_usage;
- /**
- *
- * @var boolean
- */
- protected static $_cli_usage;
+ /**
+ *
+ * @var
+ */
+ protected $code;
- /**
- *
- * @var
- */
- protected $code;
-
- /**
- *
- * @return http_request
- */
- public static function getInstance()
- {
- if (!(self::$_instance instanceof self))
+ /**
+ *
+ * @return http_request
+ */
+ public static function getInstance()
{
- self::$_instance = new self();
+ if ( ! (self::$_instance instanceof self)) {
+ self::$_instance = new self();
+ }
+
+ return self::$_instance;
}
- return self::$_instance;
- }
+ /**
+ *
+ * @return http_request
+ */
+ function __construct()
+ {
+ return $this;
+ }
- /**
- *
- * @return http_request
- */
- function __construct()
- {
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_ajax()
- {
- if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
+ /**
+ *
+ * @return boolean
+ */
+ public function is_ajax()
+ {
+ if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
-
- return true;
- return false;
- }
-
- public function is_secure()
- {
- return (
- isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == 1)
- );
- }
-
- public function comes_from_flash()
- {
- return (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/\bflash\b/i', $_SERVER['HTTP_USER_AGENT']) > 0);
- }
-
- /**
- *
- * @return int
- */
- public function get_code()
- {
- if (is_null($this->code) && isset($_SERVER['REDIRECT_STATUS']))
- {
- $this->code = $_SERVER['REDIRECT_STATUS'];
+ return true;
+ return false;
}
- return $this->code;
- }
-
- /**
- *
- * @param int $code
- * @return http_request
- */
- public function set_code($code)
- {
- $this->code = (int) $code;
-
- return $this;
- }
-
- /**
- *
- * @return Array
- */
- public function get_parms()
- {
- $parm = array();
- $nargs = func_num_args();
-
- if ($nargs == 1 && is_array(func_get_arg(0)))
+ public function is_secure()
{
- foreach (func_get_arg(0) as $key => $nom)
- {
- if (is_string($key))
- {
- $value = isset($_GET[$key]) ?
- $_GET[$key] : (isset($_POST[$key]) ? $_POST[$key] : NULL);
- switch ($nom)
- {
- case self::SANITIZE_NUMBER_INT:
- $value = (int) $value;
- break;
- case self::SANITIZE_STRING:
- $value = trim((string) $value);
- break;
- default:
- break;
- }
- $parm[$key] = $value;
+ return (
+ isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == 1)
+ );
+ }
+
+ public function comes_from_flash()
+ {
+ return (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/\bflash\b/i', $_SERVER['HTTP_USER_AGENT']) > 0);
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_code()
+ {
+ if (is_null($this->code) && isset($_SERVER['REDIRECT_STATUS'])) {
+ $this->code = $_SERVER['REDIRECT_STATUS'];
}
- else
- {
- $parm[$nom] = isset($_GET[$nom]) ?
- $_GET[$nom] : (isset($_POST[$nom]) ? $_POST[$nom] : NULL);
+
+ return $this->code;
+ }
+
+ /**
+ *
+ * @param int $code
+ * @return http_request
+ */
+ public function set_code($code)
+ {
+ $this->code = (int) $code;
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return Array
+ */
+ public function get_parms()
+ {
+ $parm = array();
+ $nargs = func_num_args();
+
+ if ($nargs == 1 && is_array(func_get_arg(0))) {
+ foreach (func_get_arg(0) as $key => $nom) {
+ if (is_string($key)) {
+ $value = isset($_GET[$key]) ?
+ $_GET[$key] : (isset($_POST[$key]) ? $_POST[$key] : NULL);
+ switch ($nom) {
+ case self::SANITIZE_NUMBER_INT:
+ $value = (int) $value;
+ break;
+ case self::SANITIZE_STRING:
+ $value = trim((string) $value);
+ break;
+ default:
+ break;
+ }
+ $parm[$key] = $value;
+ } else {
+ $parm[$nom] = isset($_GET[$nom]) ?
+ $_GET[$nom] : (isset($_POST[$nom]) ? $_POST[$nom] : NULL);
+ }
+ }
+ } else {
+ for ($i = 0; $i < $nargs; $i ++ ) {
+ $nom = func_get_arg($i);
+ $parm[$nom] = isset($_GET[$nom]) ?
+ $_GET[$nom] : (isset($_POST[$nom]) ? $_POST[$nom] : NULL);
+ }
}
- }
+
+ return($parm);
}
- else
+
+ /**
+ *
+ * @param array $indexes
+ * @param string $serializeds_datas_index
+ * @return array
+ */
+ public function get_parms_from_serialized_datas(Array $indexes, $serializeds_datas_index)
{
- for ($i = 0; $i < $nargs; $i++)
- {
- $nom = func_get_arg($i);
- $parm[$nom] = isset($_GET[$nom]) ?
- $_GET[$nom] : (isset($_POST[$nom]) ? $_POST[$nom] : NULL);
- }
+ $parm = array();
+ $tmp_parms = array();
+
+ if (isset($_GET[$serializeds_datas_index]))
+ parse_str($_GET[$serializeds_datas_index], $tmp_parms);
+ elseif (isset($_POST[$serializeds_datas_index]))
+ parse_str($_POST[$serializeds_datas_index], $tmp_parms);
+
+ if (count($tmp_parms) > 0) {
+ foreach ($indexes as $nom) {
+ $parm[$nom] = isset($tmp_parms[$nom]) ? $tmp_parms[$nom] : NULL;
+ }
+ }
+
+ return $parm;
}
- return($parm);
- }
-
- /**
- *
- * @param array $indexes
- * @param string $serializeds_datas_index
- * @return array
- */
- public function get_parms_from_serialized_datas(Array $indexes, $serializeds_datas_index)
- {
- $parm = array();
- $tmp_parms = array();
-
- if (isset($_GET[$serializeds_datas_index]))
- parse_str($_GET[$serializeds_datas_index], $tmp_parms);
- elseif (isset($_POST[$serializeds_datas_index]))
- parse_str($_POST[$serializeds_datas_index], $tmp_parms);
-
- if (count($tmp_parms) > 0)
+ /**
+ *
+ * @return boolean
+ */
+ public function has_post_datas()
{
- foreach ($indexes as $nom)
- {
- $parm[$nom] = isset($tmp_parms[$nom]) ? $tmp_parms[$nom] : NULL;
- }
+ return ! empty($_POST);
}
- return $parm;
- }
-
- /**
- *
- * @return boolean
- */
- public function has_post_datas()
- {
- return!empty($_POST);
- }
-
- /**
- *
- * @return Array
- */
- public function get_post_datas()
- {
- return $_POST;
- }
-
- /**
- *
- * @return boolean
- */
- public function has_get_datas()
- {
- return!empty($_GET);
- }
-
- /**
- *
- * @return boolean
- */
- public function has_datas()
- {
- return ($this->has_post_datas() || $this->has_get_datas());
- }
-
- /**
- *
- * @param mixed content $data
- * @param const $filter
- * @return mixed content
- */
- public function filter($data, $filter)
- {
- return filter_var($data, $filter);
- }
-
- /**
- * Tells wheter or not it's command line script
- *
- * @return boolean
- */
- public static function is_command_line()
- {
- if (self::$_cli_usage === null)
+ /**
+ *
+ * @return Array
+ */
+ public function get_post_datas()
{
- $sapi_name = strtolower(substr(php_sapi_name(), 0, 3));
- self::$_cli_usage = ($sapi_name == 'cli');
+ return $_POST;
}
- return self::$_cli_usage;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function has_get_datas()
+ {
+ return ! empty($_GET);
+ }
+ /**
+ *
+ * @return boolean
+ */
+ public function has_datas()
+ {
+ return ($this->has_post_datas() || $this->has_get_datas());
+ }
+
+ /**
+ *
+ * @param mixed content $data
+ * @param const $filter
+ * @return mixed content
+ */
+ public function filter($data, $filter)
+ {
+ return filter_var($data, $filter);
+ }
+
+ /**
+ * Tells wheter or not it's command line script
+ *
+ * @return boolean
+ */
+ public static function is_command_line()
+ {
+ if (self::$_cli_usage === null) {
+ $sapi_name = strtolower(substr(php_sapi_name(), 0, 3));
+ self::$_cli_usage = ($sapi_name == 'cli');
+ }
+
+ return self::$_cli_usage;
+ }
}
diff --git a/lib/classes/lazaret.class.php b/lib/classes/lazaret.class.php
index c5b1accb97..d3f28f722e 100644
--- a/lib/classes/lazaret.class.php
+++ b/lib/classes/lazaret.class.php
@@ -18,153 +18,142 @@
class lazaret extends set_abstract
{
- /**
- * Constructor
- *
- * @return lazaret
- */
- function __construct()
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $registry = $appbox->get_registry();
- $conn = $appbox->get_connection();
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
+ /**
+ * Constructor
+ *
+ * @return lazaret
+ */
+ function __construct()
+ {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $registry = $appbox->get_registry();
+ $conn = $appbox->get_connection();
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
- $base_ids = array_keys($user->ACL()->get_granted_base(array('canaddrecord')));
+ $base_ids = array_keys($user->ACL()->get_granted_base(array('canaddrecord')));
- if (count($base_ids) == 0)
+ if (count($base_ids) == 0)
+ return $this;
- return $this;
-
- $sql = "SELECT id, filepath, filename, base_id,
+ $sql = "SELECT id, filepath, filename, base_id,
uuid, errors, created_on, usr_id
FROM lazaret WHERE base_id IN (" . implode(', ', $base_ids) . ")
ORDER BY uuid, id DESC";
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $lazaret_group = array();
-
- foreach ($rs as $row)
- {
- $sbas_id = phrasea::sbasFromBas($row['base_id']);
-
- $row['uuid'] =
- trim($row['uuid']) !== '' ? $row['uuid'] : mt_rand(1000000, 9999999);
-
- $key = $row['uuid'] . '__' . $sbas_id;
-
- $pathfile = $registry->get('GV_RootPath') . 'tmp/lazaret/' . $row['filepath'];
-
- if (!file_exists($pathfile))
- {
- $sql = 'DELETE FROM lazaret WHERE id = :id';
$stmt = $conn->prepare($sql);
- $stmt->execute(array(':id' => $row['id']));
- $stmt->closeCursor();
-
- if (file_exists($pathfile . '_thumbnail.jpg'))
- unlink($pathfile . '_thumbnail.jpg');
- continue;
- }
- if (!isset($lazaret_group[$key]))
- $lazaret_group[$key] = array(
- 'candidates' => array(),
- 'potentials' => array()
- );
-
- $pathfile_thumbnail = $pathfile . '_thumbnail.jpg';
-
- if (is_file($pathfile_thumbnail)
- && $gis = @getimagesize($pathfile_thumbnail))
- $is = $gis;
- else
- $is = array(80, 80);
-
- $thumbnail = new media_adapter(
- '/upload/lazaret_image.php?id=' . $row['id'],
- $is[0],
- $is[1]
- );
-
- $row['created_on'] = new DateTime($row['created_on']);
-
- if ($row['usr_id'])
- $row['usr_id'] = User_Adapter::getInstance($row['usr_id'], $appbox)->get_display_name();
- else
- $row['usr_id'] = _('tache d\'archivage');
-
- $lazaret_group[$key]['candidates'][$row['id']] = array_merge(
- array(
- 'thumbnail' => $thumbnail,
- 'title' => $row['filename'],
- 'caption' => '',
- 'potential_relationship' => array()
- ), $row
- );
- }
-
- foreach ($lazaret_group as $key_group => $lazaret)
- {
- $infos = explode('__', $key_group);
-
- $uuid = $infos[0];
- $sbas_id = $infos[1];
-
- try
- {
- $connbas = connection::getPDOConnection($sbas_id);
-
- $sql = "SELECT record_id, coll_id FROM record WHERE uuid = :uuid";
-
- $stmt = $connbas->prepare($sql);
- $stmt->execute(array(':uuid' => $uuid));
+ $stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- foreach ($rs as $row)
- {
- $lazaret_group[$key_group]['potentials'][$row['record_id']] =
- new record_adapter($sbas_id, $row['record_id'], FALSE);
+ $lazaret_group = array();
+
+ foreach ($rs as $row) {
+ $sbas_id = phrasea::sbasFromBas($row['base_id']);
+
+ $row['uuid'] =
+ trim($row['uuid']) !== '' ? $row['uuid'] : mt_rand(1000000, 9999999);
+
+ $key = $row['uuid'] . '__' . $sbas_id;
+
+ $pathfile = $registry->get('GV_RootPath') . 'tmp/lazaret/' . $row['filepath'];
+
+ if ( ! file_exists($pathfile)) {
+ $sql = 'DELETE FROM lazaret WHERE id = :id';
+ $stmt = $conn->prepare($sql);
+ $stmt->execute(array(':id' => $row['id']));
+ $stmt->closeCursor();
+
+ if (file_exists($pathfile . '_thumbnail.jpg'))
+ unlink($pathfile . '_thumbnail.jpg');
+ continue;
+ }
+ if ( ! isset($lazaret_group[$key]))
+ $lazaret_group[$key] = array(
+ 'candidates' => array(),
+ 'potentials' => array()
+ );
+
+ $pathfile_thumbnail = $pathfile . '_thumbnail.jpg';
+
+ if (is_file($pathfile_thumbnail)
+ && $gis = @getimagesize($pathfile_thumbnail))
+ $is = $gis;
+ else
+ $is = array(80, 80);
+
+ $thumbnail = new media_adapter(
+ '/upload/lazaret_image.php?id=' . $row['id'],
+ $is[0],
+ $is[1]
+ );
+
+ $row['created_on'] = new DateTime($row['created_on']);
+
+ if ($row['usr_id'])
+ $row['usr_id'] = User_Adapter::getInstance($row['usr_id'], $appbox)->get_display_name();
+ else
+ $row['usr_id'] = _('tache d\'archivage');
+
+ $lazaret_group[$key]['candidates'][$row['id']] = array_merge(
+ array(
+ 'thumbnail' => $thumbnail,
+ 'title' => $row['filename'],
+ 'caption' => '',
+ 'potential_relationship' => array()
+ ), $row
+ );
}
- }
- catch (Exception $e)
- {
- continue;
- }
- foreach ($lazaret['candidates'] as $lazaret_id => $lazaret_item)
- {
- foreach ($lazaret_group[$key_group]['potentials']
- as $record_id => $record)
- {
- $can_substitute = false;
+ foreach ($lazaret_group as $key_group => $lazaret) {
+ $infos = explode('__', $key_group);
- $potential_base_id = $record->get_base_id();
+ $uuid = $infos[0];
+ $sbas_id = $infos[1];
- if (
- $user->ACL()->has_right_on_base($potential_base_id, 'canaddrecord') &&
- $user->ACL()->has_right_on_base($potential_base_id, 'candeleterecord')
- )
- $can_substitute = false;
+ try {
+ $connbas = connection::getPDOConnection($sbas_id);
- $lazaret_group[$key_group]['candidates']
- [$lazaret_id]['potential_relationship'][$record_id] =
- array(
- 'can_substitute' => $can_substitute,
- 'same_coll' => ($potential_base_id == $lazaret_item['base_id']),
- 'title' => $record->get_title()
- );
+ $sql = "SELECT record_id, coll_id FROM record WHERE uuid = :uuid";
+
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute(array(':uuid' => $uuid));
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs as $row) {
+ $lazaret_group[$key_group]['potentials'][$row['record_id']] =
+ new record_adapter($sbas_id, $row['record_id'], FALSE);
+ }
+ } catch (Exception $e) {
+ continue;
+ }
+
+ foreach ($lazaret['candidates'] as $lazaret_id => $lazaret_item) {
+ foreach ($lazaret_group[$key_group]['potentials']
+ as $record_id => $record) {
+ $can_substitute = false;
+
+ $potential_base_id = $record->get_base_id();
+
+ if (
+ $user->ACL()->has_right_on_base($potential_base_id, 'canaddrecord') &&
+ $user->ACL()->has_right_on_base($potential_base_id, 'candeleterecord')
+ )
+ $can_substitute = false;
+
+ $lazaret_group[$key_group]['candidates']
+ [$lazaret_id]['potential_relationship'][$record_id] =
+ array(
+ 'can_substitute' => $can_substitute,
+ 'same_coll' => ($potential_base_id == $lazaret_item['base_id']),
+ 'title' => $record->get_title()
+ );
+ }
+ }
}
- }
+ $this->elements = $lazaret_group;
+
+ return $this;
}
- $this->elements = $lazaret_group;
-
- return $this;
- }
-
}
diff --git a/lib/classes/lazaretFile.class.php b/lib/classes/lazaretFile.class.php
index b7342e3f6f..e938d62f66 100644
--- a/lib/classes/lazaretFile.class.php
+++ b/lib/classes/lazaretFile.class.php
@@ -11,7 +11,6 @@
class lazaretFile
{
-
protected $storage = array();
/**
@@ -29,7 +28,7 @@ class lazaretFile
$stmt = $conn->prepare($sql);
$stmt->execute(array(':lazaret_id' => $lazaret_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ( ! $row)
@@ -58,7 +57,7 @@ class lazaretFile
$file = new system_file($registry->get('GV_RootPath') . 'tmp/lazaret/' . $this->filepath);
if (($record_id = p4file::archiveFile(
- $file, $this->base_id, false, $this->filename)) === false)
+ $file, $this->base_id, false, $this->filename)) === false)
throw new Exception(_('Impossible dajouter le fichier a la base'));
$sbas_id = phrasea::sbasFromBas($this->base_id);
@@ -83,24 +82,21 @@ class lazaretFile
*/
public function delete()
{
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
$registry = registry::get_instance();
- try
- {
- $sql = 'DELETE FROM lazaret WHERE id = :lazaret_id';
+ try {
+ $sql = 'DELETE FROM lazaret WHERE id = :lazaret_id';
$stmt = $conn->prepare($sql);
$stmt->execute(array(':lazaret_id' => $this->id));
$stmt->closeCursor();
- $file = $registry->get('GV_RootPath') . 'tmp/lazaret/' . $this->filepath;
+ $file = $registry->get('GV_RootPath') . 'tmp/lazaret/' . $this->filepath;
$thumbnail = $file . '_thumbnail.jpg';
@unlink($thumbnail);
@unlink($file);
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
@@ -126,7 +122,7 @@ class lazaretFile
$stmt = $connbas->prepare($sql);
$stmt->execute(array(':record_id' => $record_id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ( ! $row)
@@ -146,35 +142,33 @@ class lazaretFile
public static function move_uploaded_to_lazaret(system_file $system_file, $base_id, $filename, $errors = '', $status = false)
{
- $Core = \bootstrap::getCore();
- $appbox = appbox::get_instance($Core);
- $session = $appbox->get_session();
+ $Core = \bootstrap::getCore();
+ $appbox = appbox::get_instance($Core);
+ $session = $appbox->get_session();
$registry = $appbox->get_registry();
- $conn = $appbox->get_connection();
+ $conn = $appbox->get_connection();
- if ( ! $status)
- {
+ if ( ! $status) {
$status = '0';
}
$usr_id = $session->is_authenticated() ? $session->get_usr_id() : false;
$lazaret_root = $registry->get('GV_RootPath') . 'tmp/lazaret/';
- $pathinfo = pathinfo($filename);
+ $pathinfo = pathinfo($filename);
$tmp_filename = $filename;
$n = 1;
- while (file_exists($lazaret_root . $tmp_filename))
- {
+ while (file_exists($lazaret_root . $tmp_filename)) {
$tmp_filename = $pathinfo['filename']
- . '-' . $n . '.' . $pathinfo['extension'];
+ . '-' . $n . '.' . $pathinfo['extension'];
$n ++;
}
$pathfile = $lazaret_root . $tmp_filename;
- $uuid = $system_file->read_uuid();
- $sha256 = $system_file->get_sha256();
+ $uuid = $system_file->read_uuid();
+ $sha256 = $system_file->get_sha256();
rename($system_file->getPathname(), $pathfile);
unset($system_file);
@@ -182,23 +176,19 @@ class lazaretFile
$system_file = new system_file($pathfile);
$system_file->chmod();
- try
- {
+ try {
$spec = new MediaAlchemyst\Specification\Image();
$spec->setDimensions(200, 200);
$Core['media-alchemyst']
- ->open($pathfile)
- ->turnInto($spec, $pathfile . "_thumbnail.jpg")
- ->close();
- }
- catch (\MediaAlchemyst\Exception\RuntimeException $e)
- {
+ ->open($pathfile)
+ ->turnInto($spec, $pathfile . "_thumbnail.jpg")
+ ->close();
+ } catch (\MediaAlchemyst\Exception\RuntimeException $e) {
}
- try
- {
+ try {
$sql = 'INSERT INTO lazaret
(id, filename, filepath, base_id, uuid, sha256,
@@ -207,14 +197,14 @@ class lazaretFile
:uuid, :sha256, :errors, 0b' . $status . ', NOW(), :usr_id )';
$params = array(
- ':filename' => $filename
- , ':filepath' => $tmp_filename
- , ':base_id' => $base_id
- , ':uuid' => $uuid
- , ':sha256' => $sha256
- , ':errors' => $errors
- , ':usr_id' => ($usr_id ? $usr_id : null
- )
+ ':filename' => $filename
+ , ':filepath' => $tmp_filename
+ , ':base_id' => $base_id
+ , ':uuid' => $uuid
+ , ':sha256' => $sha256
+ , ':errors' => $errors
+ , ':usr_id' => ($usr_id ? $usr_id : null
+ )
);
$stmt = $conn->prepare($sql);
@@ -222,9 +212,7 @@ class lazaretFile
$stmt->closeCursor();
return true;
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
}
@@ -233,27 +221,25 @@ class lazaretFile
public static function stream_thumbnail($id)
{
- $conn = connection::getPDOConnection();
+ $conn = connection::getPDOConnection();
$registry = registry::get_instance();
- $sql = "SELECT filepath FROM lazaret WHERE id = :lazaret_id";
+ $sql = "SELECT filepath FROM lazaret WHERE id = :lazaret_id";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':lazaret_id' => $id));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
- if ($row)
- {
+ if ($row) {
$pathfile = $registry->get('GV_RootPath') . 'tmp/lazaret/'
- . $row['filepath'] . '_thumbnail.jpg';
+ . $row['filepath'] . '_thumbnail.jpg';
$response = set_export::stream_file(
- $pathfile, basename($pathfile), 'image/jpeg', 'inline'
+ $pathfile, basename($pathfile), 'image/jpeg', 'inline'
);
$response->send();
}
return false;
}
-
}
diff --git a/lib/classes/liste.class.php b/lib/classes/liste.class.php
index bdcc2459c9..568568b7e2 100644
--- a/lib/classes/liste.class.php
+++ b/lib/classes/liste.class.php
@@ -3,71 +3,62 @@
class liste
{
- public static function filter($lst)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- if (!is_array($lst))
- explode(';', $lst);
-
- $okbrec = array();
-
- $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
-
- foreach ($lst as $basrec)
+ public static function filter($lst)
{
- $basrec = explode("_", $basrec);
- if (!$basrec || count($basrec) != 2)
- {
- continue;
- }
- try
- {
- $record = new record_adapter($basrec[0], $basrec[1]);
- }
- catch(Exception $e)
- {
- continue;
- }
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
- if ($user->ACL()->has_hd_grant($record))
- {
- $okbrec[] = implode('_', $basrec);;
- continue;
- }
- if ($user->ACL()->has_preview_grant($record))
- {
- $okbrec[] = implode('_', $basrec);;
- continue;
- }
+ if ( ! is_array($lst))
+ explode(';', $lst);
- if (!$user->ACL()->has_access_to_base($record->get_base_id()))
- continue;
+ $okbrec = array();
- try
- {
- $connsbas = connection::getPDOConnection($basrec[0]);
+ $user = User_Adapter::getInstance($session->get_usr_id(), $appbox);
- $sql = 'SELECT record_id FROM record WHERE ((status ^ ' . $user->ACL()->get_mask_xor($record->get_base_id()) . ')
+ foreach ($lst as $basrec) {
+ $basrec = explode("_", $basrec);
+ if ( ! $basrec || count($basrec) != 2) {
+ continue;
+ }
+ try {
+ $record = new record_adapter($basrec[0], $basrec[1]);
+ } catch (Exception $e) {
+ continue;
+ }
+
+ if ($user->ACL()->has_hd_grant($record)) {
+ $okbrec[] = implode('_', $basrec);
+ ;
+ continue;
+ }
+ if ($user->ACL()->has_preview_grant($record)) {
+ $okbrec[] = implode('_', $basrec);
+ ;
+ continue;
+ }
+
+ if ( ! $user->ACL()->has_access_to_base($record->get_base_id()))
+ continue;
+
+ try {
+ $connsbas = connection::getPDOConnection($basrec[0]);
+
+ $sql = 'SELECT record_id FROM record WHERE ((status ^ ' . $user->ACL()->get_mask_xor($record->get_base_id()) . ')
& ' . $user->ACL()->get_mask_and($record->get_base_id()) . ')=0' .
- ' AND record_id = :record_id';
+ ' AND record_id = :record_id';
- $stmt = $connsbas->prepare($sql);
- $stmt->execute(array(':record_id' => $basrec[1]));
+ $stmt = $connsbas->prepare($sql);
+ $stmt->execute(array(':record_id' => $basrec[1]));
- if ($stmt->rowCount() > 0)
- $okbrec[] = implode('_', $basrec);
+ if ($stmt->rowCount() > 0)
+ $okbrec[] = implode('_', $basrec);
- $stmt->closeCursor();
- }
- catch (Exception $e)
- {
+ $stmt->closeCursor();
+ } catch (Exception $e) {
- }
+ }
+ }
+
+ return $okbrec;
}
-
- return $okbrec;
- }
-
}
diff --git a/lib/classes/login.class.php b/lib/classes/login.class.php
index 93b0444d80..0047507c84 100644
--- a/lib/classes/login.class.php
+++ b/lib/classes/login.class.php
@@ -3,54 +3,48 @@
class login
{
- public function get_cgus()
- {
- return databox_cgu::getHome();
- }
-
- public function register_enabled()
- {
- $registry = registry::get_instance();
- require_once $registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php';
-
- $bases = giveMeBases();
-
- if ($bases)
+ public function get_cgus()
{
- foreach ($bases as $base)
- {
- if ($base['inscript'])
- {
- return true;
+ return databox_cgu::getHome();
+ }
+
+ public function register_enabled()
+ {
+ $registry = registry::get_instance();
+ require_once $registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php';
+
+ $bases = giveMeBases();
+
+ if ($bases) {
+ foreach ($bases as $base) {
+ if ($base['inscript']) {
+ return true;
+ }
+ }
}
- }
+
+ return false;
}
- return false;
- }
-
- public function get_register_link()
- {
- $demandLinkBox = '';
-
- if (self::register_enabled())
+ public function get_register_link()
{
- $demandLinkBox = '' . _('login:: register') . ' ';
+ $demandLinkBox = '';
+
+ if (self::register_enabled()) {
+ $demandLinkBox = '' . _('login:: register') . ' ';
+ }
+
+ return $demandLinkBox;
}
- return $demandLinkBox;
- }
-
- public function get_guest_link()
- {
- $inviteBox = '';
-
- if (phrasea::guest_allowed())
+ public function get_guest_link()
{
- $inviteBox = '' . _('login:: guest Access') . ' ';
+ $inviteBox = '';
+
+ if (phrasea::guest_allowed()) {
+ $inviteBox = '' . _('login:: guest Access') . ' ';
+ }
+
+ return $inviteBox;
}
-
- return $inviteBox;
- }
-
}
diff --git a/lib/classes/logs.class.php b/lib/classes/logs.class.php
index 73a93cd8fe..719523d76b 100644
--- a/lib/classes/logs.class.php
+++ b/lib/classes/logs.class.php
@@ -2,37 +2,32 @@
class logs
{
+ static $_last_check = array();
- static $_last_check = array();
-
- static function rotate($filepath)
- {
- $limit = (1024 * 1024 * 20);
-
- $date_obj = new DateTime('-3 min');
- $check_time = $date_obj->format('U');
-
- if (!isset(self::$_last_check[$filepath]) || self::$_last_check[$filepath] < $check_time)
+ static function rotate($filepath)
{
- clearstatcache();
+ $limit = (1024 * 1024 * 20);
- if (file_exists($filepath) && filesize($filepath) > $limit)
- {
- $n = 1;
- while (file_exists($filepath . '.' . $n))
- $n++;
- if (copy($filepath, $filepath . '.' . $n))
- {
- $handle = fopen($filepath, 'r+');
- ftruncate($handle, 0);
- fclose($handle);
+ $date_obj = new DateTime('-3 min');
+ $check_time = $date_obj->format('U');
+
+ if ( ! isset(self::$_last_check[$filepath]) || self::$_last_check[$filepath] < $check_time) {
+ clearstatcache();
+
+ if (file_exists($filepath) && filesize($filepath) > $limit) {
+ $n = 1;
+ while (file_exists($filepath . '.' . $n))
+ $n ++;
+ if (copy($filepath, $filepath . '.' . $n)) {
+ $handle = fopen($filepath, 'r+');
+ ftruncate($handle, 0);
+ fclose($handle);
+ }
+ }
+
+ self::$_last_check[$filepath] = $check_time;
}
- }
- self::$_last_check[$filepath] = $check_time;
+ return;
}
-
- return;
- }
-
}
diff --git a/lib/classes/mail.class.php b/lib/classes/mail.class.php
index 53c13a9fb4..b1f331487c 100644
--- a/lib/classes/mail.class.php
+++ b/lib/classes/mail.class.php
@@ -3,279 +3,261 @@
class mail
{
- public static function mail_test($email)
- {
- $registry = registry::get_instance();
- $from = array('email' => $registry->get('GV_defaulmailsenderaddr'), 'name' => $registry->get('GV_defaulmailsenderaddr'));
+ public static function mail_test($email)
+ {
+ $registry = registry::get_instance();
+ $from = array('email' => $registry->get('GV_defaulmailsenderaddr'), 'name' => $registry->get('GV_defaulmailsenderaddr'));
- $subject = _('mail:: test d\'envoi d\'email');
+ $subject = _('mail:: test d\'envoi d\'email');
- $message = sprintf(_('Ce mail est un test d\'envoi de mail depuis %s'), $registry->get('GV_ServerName'));
+ $message = sprintf(_('Ce mail est un test d\'envoi de mail depuis %s'), $registry->get('GV_ServerName'));
- $to = array('email' => $email, 'name' => $email);
+ $to = array('email' => $email, 'name' => $email);
- return self::send_mail($subject, $message, $to, $from);
- }
+ return self::send_mail($subject, $message, $to, $from);
+ }
- public static function send_validation_results($email, $subject, $from, $message)
- {
- $to = array('email' => $email, 'name' => $email);
+ public static function send_validation_results($email, $subject, $from, $message)
+ {
+ $to = array('email' => $email, 'name' => $email);
- return self::send_mail($subject, $message, $to, $from);
- }
+ return self::send_mail($subject, $message, $to, $from);
+ }
- public static function ftp_sent($email, $subject, $body)
- {
- $to = array('email' => $email, 'name' => $email);
+ public static function ftp_sent($email, $subject, $body)
+ {
+ $to = array('email' => $email, 'name' => $email);
- return self::send_mail($subject, $body, $to);
- }
+ return self::send_mail($subject, $body, $to);
+ }
- public static function ftp_receive($email, $body)
- {
- $subject = _("task::ftp:Someone has sent some files onto FTP server");
+ public static function ftp_receive($email, $body)
+ {
+ $subject = _("task::ftp:Someone has sent some files onto FTP server");
- $to = array('email' => $email, 'name' => $email);
+ $to = array('email' => $email, 'name' => $email);
- return self::send_mail($subject, $body, $to);
- }
+ return self::send_mail($subject, $body, $to);
+ }
- public static function send_documents($email, $url, $from, $endate_obj, $message='', $accuse)
- {
- $subject = _('export::vous avez recu des documents');
+ public static function send_documents($email, $url, $from, $endate_obj, $message = '', $accuse)
+ {
+ $subject = _('export::vous avez recu des documents');
- $body = '' . _('Vous avez recu des documents, vous pourrez les telecharger a ladresse suivante ') . "
\n";
- $body .= "" . $url . " \n";
+ $body = '' . _('Vous avez recu des documents, vous pourrez les telecharger a ladresse suivante ') . "
\n";
+ $body .= "" . $url . " \n";
- $body .= '' .
+ $body .= '
' .
sprintf(
- _('Attention, ce lien lien est valable jusqu\'au %s'),
- phraseadate::getDate($endate_obj) . ' ' . phraseadate::getTime($endate_obj)
+ _('Attention, ce lien lien est valable jusqu\'au %s'), phraseadate::getDate($endate_obj) . ' ' . phraseadate::getTime($endate_obj)
)
. '
';
- if ($message != '')
- {
- $body .= "
---------------------------------------------------
\n" . $message;
- }
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to, $from, array(), $accuse);
- }
-
- public static function forgot_passord($email, $login, $url)
- {
- $subject = _('login:: Forgot your password'); // Registration order on .
-
- $body = "
" . _('login:: Quelqu\'un a demande a reinitialiser le mode passe correspondant au login suivant : ') . "
\n\n" . $login . "
\n\n";
- $body .= "
" . _('login:: Visitez le lien suivant et suivez les instructions pour continuer, sinon ignorez cet email et il ne se passera rien') . "
\n\n";
- $body .= "
\n";
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function register_confirm($email, $accept, $deny)
- {
- $registry = registry::get_instance();
- $subject = sprintf(_('login::register:email: Votre compte %s'), $registry->get('GV_homeTitle'));
-
- $body = '
' . _('login::register:email: Voici un compte rendu du traitement de vos demandes d\'acces :') . "
\n";
-
- if ($accept != '')
- {
- $body .= "
\n
" . _('login::register:email: Vous avez ete accepte sur les collections suivantes : ') . "
\n
\n";
- }
- if ($deny != '')
- {
- $body .= "
\n
" . _('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . "
\n
\n";
- }
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function register_user($email, $auto, $others)
- {
- $registry = registry::get_instance();
- $subject = sprintf(_('login::register:email: Votre compte %s'), $registry->get('GV_homeTitle'));
-
-
- $body = "
" . _('login::register:Votre inscription a ete prise en compte') . "
\n";
-
- if ($auto != '')
- {
- $body .= "
\n
" . _('login::register: vous avez des a present acces aux collections suivantes : ') . "
\n
\n";
- }
-
- if ($others != '')
- {
- $body .= "
\n
" . _('login::register: vos demandes concernat les collections suivantes sont sujettes a approbation d\'un administrateur') . "
\n
\n";
- $body .= "
\n
" . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . "
\n";
- }
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function reset_email($email, $usr_id)
- {
- $registry = registry::get_instance();
- $date = new DateTime('1 day');
- $token = random::getUrlToken(\random::TYPE_EMAIL, $usr_id, $date, $email);
-
- $url = $registry->get('GV_ServerName') . 'login/reset-email.php?token=' . $token;
-
- $subject = _('login::register: sujet email : confirmation de votre adresse email');
-
- $body = "
" . _('admin::compte-utilisateur: email changement de mot d\'email Bonjour, nous avons bien recu votre demande de changement d\'adresse e-mail. Pour la confirmer, veuillez suivre le lien qui suit. SI vous recevez ce mail sans l\'avoir sollicite, merci de le detruire et de l\'ignorer.') . "
\n";
- $body .= "
\n";
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function mail_confirm_registered($email)
- {
- $registry = \registry::get_instance();
-
- $subject = _('login::register: sujet email : confirmation de votre adresse email');
-
- $body = "
" . _('login::register: merci d\'avoir confirme votre adresse email') . "
\n";
- $body .= "
" . _('login::register: vous pouvez maintenant vous connecter a l\'adresse suivante : ') . "
\n";
- $body .= "
\n";
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function mail_confirm_unregistered($email, $others)
- {
-
- $subject = _('login::register: sujet email : confirmation de votre adresse email');
-
- $body = "
" . _('login::register: merci d\'avoir confirme votre adresse email') . "
\n";
- $body .= "
\n
" . _('login::register: vous devez attendre la confirmation d\'un administrateur ; vos demandes sur les collections suivantes sont toujours en attente : ') . "
\n
\n";
- $body .= "
\n
" . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . "
\n";
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function mail_confirmation($email, $usr_id)
- {
- $registry = registry::get_instance();
- $expire = new DateTime('+3 days');
- $token = random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $expire, $email);
-
- $subject = _('login::register: sujet email : confirmation de votre adresse email');
-
- $body = "
" . _('login::register: email confirmation email Pour valider votre inscription a la base de donnees, merci de confirmer votre e-mail en suivant le lien ci-dessous.') . "
\n";
- $body .= "
\n
\n";
-
- $to = array('email' => $email, 'name' => $email);
-
- return self::send_mail($subject, $body, $to);
- }
-
- public static function validateEmail($email)
- {
- return PHPMailer::ValidateAddress($email);
- }
-
- public static function send_mail($subject, $body, $to, $from=false, $files=array(), $reading_confirm_to=false)
- {
-
- $registry = registry::get_instance();
-
- if (!isset($to['email']) || !PHPMailer::ValidateAddress($to['email']))
-
- return false;
-
- $mail = new PHPMailer();
-
- $body = eregi_replace("[\]", '', $body);
-
- $body .= "
\n\n\n\n";
- $body .= '
'._('si cet email contient des liens non cliquables copiez/collez ces liens dans votre navigateur.').'
';
- $body .= "
\n";
- $body .= '
' . _('phraseanet::signature automatique des notifications par mail, infos a l\'url suivante') . "
\n";
- $body .= '
\n";
- $body = '' . $body . '';
-
- $body = str_replace('https://', 'http://', $body);
-
- try
- {
- $mail->CharSet = 'utf-8';
- $mail->Encoding = 'base64'; //'quoted-printable';
-
- $registry = registry::get_instance();
-
- if ($registry->get('GV_smtp'))
- {
- $mail->IsSMTP();
- if ($registry->get('GV_smtp_host') != '')
- $mail->Host = $registry->get('GV_smtp_host');
-// $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
- if ($registry->get('GV_smtp_auth'))
- {
- $mail->SMTPAuth = true;
-
- if ($registry->get('GV_smtp_secure') === true)
- {
- $mail->SMTPSecure = "ssl";
- }
- $mail->Host = $registry->get('GV_smtp_host');
- $mail->Port = $registry->get('GV_smtp_port');
- $mail->Username = $registry->get('GV_smtp_user');
- $mail->Password = $registry->get('GV_smtp_password');
+ if ($message != '') {
+ $body .= "
---------------------------------------------------
\n" . $message;
}
- }
- if ($from && trim($from['email']) != '')
- $mail->AddReplyTo($from['email'], $from['name']);
+ $to = array('email' => $email, 'name' => $email);
- $mail->AddAddress($to['email'], $to['name']);
-
- $mail->SetFrom($registry->get('GV_defaulmailsenderaddr'), $registry->get('GV_homeTitle'));
-
- $mail->Subject = $subject;
-
- $mail->AltBody = html_entity_decode(strip_tags($body), ENT_QUOTES, 'UTF-8');
-
- if ($reading_confirm_to)
- {
- $mail->ConfirmReadingTo = $reading_confirm_to;
- }
-
- $mail->MsgHTML(strip_tags($body, '
'));
-
- foreach ($files as $f)
- {
- $mail->AddAttachment($f); // attachment
- }
-
- $mail->Send();
-
- return true;
+ return self::send_mail($subject, $body, $to, $from, array(), $accuse);
}
- catch (phpmailerException $e)
+
+ public static function forgot_passord($email, $login, $url)
{
- return $e->errorMessage();
- }
- catch (Exception $e)
- {
- return $e->getMessage();
- }
- }
+ $subject = _('login:: Forgot your password'); // Registration order on .
+ $body = "" . _('login:: Quelqu\'un a demande a reinitialiser le mode passe correspondant au login suivant : ') . "
\n\n" . $login . "
\n\n";
+ $body .= "" . _('login:: Visitez le lien suivant et suivez les instructions pour continuer, sinon ignorez cet email et il ne se passera rien') . "
\n\n";
+ $body .= "\n";
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function register_confirm($email, $accept, $deny)
+ {
+ $registry = registry::get_instance();
+ $subject = sprintf(_('login::register:email: Votre compte %s'), $registry->get('GV_homeTitle'));
+
+ $body = '' . _('login::register:email: Voici un compte rendu du traitement de vos demandes d\'acces :') . "
\n";
+
+ if ($accept != '') {
+ $body .= " \n" . _('login::register:email: Vous avez ete accepte sur les collections suivantes : ') . "
\n\n";
+ }
+ if ($deny != '') {
+ $body .= " \n" . _('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . "
\n\n";
+ }
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function register_user($email, $auto, $others)
+ {
+ $registry = registry::get_instance();
+ $subject = sprintf(_('login::register:email: Votre compte %s'), $registry->get('GV_homeTitle'));
+
+
+ $body = "" . _('login::register:Votre inscription a ete prise en compte') . "
\n";
+
+ if ($auto != '') {
+ $body .= " \n" . _('login::register: vous avez des a present acces aux collections suivantes : ') . "
\n\n";
+ }
+
+ if ($others != '') {
+ $body .= " \n" . _('login::register: vos demandes concernat les collections suivantes sont sujettes a approbation d\'un administrateur') . "
\n\n";
+ $body .= " \n" . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . "
\n";
+ }
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function reset_email($email, $usr_id)
+ {
+ $registry = registry::get_instance();
+ $date = new DateTime('1 day');
+ $token = random::getUrlToken(\random::TYPE_EMAIL, $usr_id, $date, $email);
+
+ $url = $registry->get('GV_ServerName') . 'login/reset-email.php?token=' . $token;
+
+ $subject = _('login::register: sujet email : confirmation de votre adresse email');
+
+ $body = "" . _('admin::compte-utilisateur: email changement de mot d\'email Bonjour, nous avons bien recu votre demande de changement d\'adresse e-mail. Pour la confirmer, veuillez suivre le lien qui suit. SI vous recevez ce mail sans l\'avoir sollicite, merci de le detruire et de l\'ignorer.') . "
\n";
+ $body .= "\n";
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function mail_confirm_registered($email)
+ {
+ $registry = \registry::get_instance();
+
+ $subject = _('login::register: sujet email : confirmation de votre adresse email');
+
+ $body = "" . _('login::register: merci d\'avoir confirme votre adresse email') . "
\n";
+ $body .= "" . _('login::register: vous pouvez maintenant vous connecter a l\'adresse suivante : ') . "
\n";
+ $body .= "\n";
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function mail_confirm_unregistered($email, $others)
+ {
+
+ $subject = _('login::register: sujet email : confirmation de votre adresse email');
+
+ $body = "" . _('login::register: merci d\'avoir confirme votre adresse email') . "
\n";
+ $body .= " \n" . _('login::register: vous devez attendre la confirmation d\'un administrateur ; vos demandes sur les collections suivantes sont toujours en attente : ') . "
\n\n";
+ $body .= " \n" . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . "
\n";
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function mail_confirmation($email, $usr_id)
+ {
+ $registry = registry::get_instance();
+ $expire = new DateTime('+3 days');
+ $token = random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $expire, $email);
+
+ $subject = _('login::register: sujet email : confirmation de votre adresse email');
+
+ $body = "" . _('login::register: email confirmation email Pour valider votre inscription a la base de donnees, merci de confirmer votre e-mail en suivant le lien ci-dessous.') . "
\n";
+ $body .= " \n\n";
+
+ $to = array('email' => $email, 'name' => $email);
+
+ return self::send_mail($subject, $body, $to);
+ }
+
+ public static function validateEmail($email)
+ {
+ return PHPMailer::ValidateAddress($email);
+ }
+
+ public static function send_mail($subject, $body, $to, $from = false, $files = array(), $reading_confirm_to = false)
+ {
+
+ $registry = registry::get_instance();
+
+ if ( ! isset($to['email']) || ! PHPMailer::ValidateAddress($to['email']))
+ return false;
+
+ $mail = new PHPMailer();
+
+ $body = eregi_replace("[\]", '', $body);
+
+ $body .= " \n\n\n\n";
+ $body .= '' . _('si cet email contient des liens non cliquables copiez/collez ces liens dans votre navigateur.') . '
';
+ $body .= " \n";
+ $body .= '' . _('phraseanet::signature automatique des notifications par mail, infos a l\'url suivante') . "
\n";
+ $body .= '\n";
+ $body = '' . $body . '';
+
+ $body = str_replace('https://', 'http://', $body);
+
+ try {
+ $mail->CharSet = 'utf-8';
+ $mail->Encoding = 'base64'; //'quoted-printable';
+
+ $registry = registry::get_instance();
+
+ if ($registry->get('GV_smtp')) {
+ $mail->IsSMTP();
+ if ($registry->get('GV_smtp_host') != '')
+ $mail->Host = $registry->get('GV_smtp_host');
+// $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
+ if ($registry->get('GV_smtp_auth')) {
+ $mail->SMTPAuth = true;
+
+ if ($registry->get('GV_smtp_secure') === true) {
+ $mail->SMTPSecure = "ssl";
+ }
+ $mail->Host = $registry->get('GV_smtp_host');
+ $mail->Port = $registry->get('GV_smtp_port');
+ $mail->Username = $registry->get('GV_smtp_user');
+ $mail->Password = $registry->get('GV_smtp_password');
+ }
+ }
+
+ if ($from && trim($from['email']) != '')
+ $mail->AddReplyTo($from['email'], $from['name']);
+
+ $mail->AddAddress($to['email'], $to['name']);
+
+ $mail->SetFrom($registry->get('GV_defaulmailsenderaddr'), $registry->get('GV_homeTitle'));
+
+ $mail->Subject = $subject;
+
+ $mail->AltBody = html_entity_decode(strip_tags($body), ENT_QUOTES, 'UTF-8');
+
+ if ($reading_confirm_to) {
+ $mail->ConfirmReadingTo = $reading_confirm_to;
+ }
+
+ $mail->MsgHTML(strip_tags($body, ' '));
+
+ foreach ($files as $f) {
+ $mail->AddAttachment($f); // attachment
+ }
+
+ $mail->Send();
+
+ return true;
+ } catch (phpmailerException $e) {
+ return $e->errorMessage();
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+ }
}
diff --git a/lib/classes/media/Permalink/Adapter.class.php b/lib/classes/media/Permalink/Adapter.class.php
index 9022fb67b1..c6786378c9 100644
--- a/lib/classes/media/Permalink/Adapter.class.php
+++ b/lib/classes/media/Permalink/Adapter.class.php
@@ -17,344 +17,344 @@
*/
class media_Permalink_Adapter implements media_Permalink_Interface, cache_cacheableInterface
{
+ /**
+ *
+ * @var databox
+ */
+ protected $databox;
- /**
- *
- * @var databox
- */
- protected $databox;
- /**
- *
- * @var media_subdef
- */
- protected $media_subdef;
- /**
- *
- * @var int
- */
- protected $id;
- /**
- *
- * @var string
- */
- protected $token;
- /**
- *
- * @var boolean
- */
- protected $is_activated;
- /**
- *
- * @var DateTime
- */
- protected $created_on;
- /**
- *
- * @var DateTime
- */
- protected $last_modified;
- /**
- *
- * @var string
- */
- protected $label;
+ /**
+ *
+ * @var media_subdef
+ */
+ protected $media_subdef;
- /**
- *
- * @param databox $databox
- * @param media_subdef $media_subdef
- * @return media_Permalink_Adapter
- */
- protected function __construct(databox &$databox, media_subdef &$media_subdef)
- {
+ /**
+ *
+ * @var int
+ */
+ protected $id;
- $this->databox = $databox;
- $this->media_subdef = $media_subdef;
+ /**
+ *
+ * @var string
+ */
+ protected $token;
- $this->load();
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_activated;
- return $this;
- }
+ /**
+ *
+ * @var DateTime
+ */
+ protected $created_on;
- /**
- *
- * @return int
- */
- public function get_id()
- {
- return $this->id;
- }
+ /**
+ *
+ * @var DateTime
+ */
+ protected $last_modified;
- /**
- *
- * @return string
- */
- public function get_token()
- {
- return $this->token;
- }
+ /**
+ *
+ * @var string
+ */
+ protected $label;
- /**
- *
- * @return boolean
- */
- public function get_is_activated()
- {
- return $this->is_activated;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_created_on()
- {
- return $this->created_on;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_last_modified()
- {
- return $this->last_modified;
- }
-
- /**
- *
- * @return string
- */
- public function get_label()
- {
- return $this->label;
- }
-
- /**
- *
- * @return string
- */
- public function get_url()
- {
- $registry = registry::get_instance();
-
- return sprintf('%spermalink/v1/%s/%d/%d/%s/%s/'
- , $registry->get('GV_ServerName')
- , $this->get_label()
- , $this->media_subdef->get_sbas_id()
- , $this->media_subdef->get_record_id()
- , $this->get_token()
- , $this->media_subdef->get_name()
- );
- }
-
- /**
- *
- * @param registryInterface $registry
- * @return string
- */
- public function get_page(registryInterface $registry)
- {
- return sprintf('%spermalink/v1/%s/%d/%d/%s/%s/view/'
- , $registry->get('GV_ServerName')
- , $this->get_label()
- , $this->media_subdef->get_sbas_id()
- , $this->media_subdef->get_record_id()
- , $this->get_token()
- , $this->media_subdef->get_name()
- );
- }
-
- /**
- *
- * @param string $token
- * @return media_Permalink_Adapter
- */
- protected function set_token($token)
- {
- $this->token = $token;
-
- $sql = 'UPDATE permalinks SET token = :token, last_modified = NOW()
- WHERE id = :id';
- $stmt = $this->databox->get_connection()->prepare($sql);
- $stmt->execute(array(':token' => $this->token, ':id' => $this->get_id()));
- $stmt->closeCursor();
-
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- *
- * @param string $is_activated
- * @return media_Permalink_Adapter
- */
- public function set_is_activated($is_activated)
- {
- $this->is_activated = !!$is_activated;
-
- $sql = 'UPDATE permalinks SET activated = :activated, last_modified = NOW()
- WHERE id = :id';
- $stmt = $this->databox->get_connection()->prepare($sql);
-
- $params = array(
- ':activated' => $this->is_activated,
- ':id' => $this->get_id()
- );
-
- $stmt->execute($params);
- $stmt->closeCursor();
-
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- *
- * @param string $label
- * @return media_Permalink_Adapter
- */
- public function set_label($label)
- {
- $unicode_processor = new unicode();
-
- $label = trim($label);
- while (strpos($label, ' ') !== false)
- $label = str_replace(' ', ' ', $label);
-
- $this->label = $unicode_processor->remove_nonazAZ09(
- str_replace(' ', '-', $label)
- );
-
- $sql = 'UPDATE permalinks SET label = :label, last_modified = NOW()
- WHERE id = :id';
- $stmt = $this->databox->get_connection()->prepare($sql);
- $stmt->execute(array(':label' => $this->label, ':id' => $this->get_id()));
- $stmt->closeCursor();
-
- $this->delete_data_from_cache();
-
- return $this;
- }
-
- /**
- *
- * @return media_Permalink_Adapter
- */
- protected function load()
- {
- try
- {
- $datas = $this->get_data_from_cache();
- $this->id = $datas['id'];
- $this->token = $datas['token'];
- $this->is_activated = $datas['is_activated'];
- $this->created_on = $datas['created_on'];
- $this->last_modified = $datas['last_modified'];
- $this->label = $datas['label'];
-
- return $this;
- }
- catch (Exception $e)
+ /**
+ *
+ * @param databox $databox
+ * @param media_subdef $media_subdef
+ * @return media_Permalink_Adapter
+ */
+ protected function __construct(databox &$databox, media_subdef &$media_subdef)
{
+ $this->databox = $databox;
+ $this->media_subdef = $media_subdef;
+
+ $this->load();
+
+ return $this;
}
- $sql = 'SELECT p.id, p.token, p.activated, p.created_on, p.last_modified
+ /**
+ *
+ * @return int
+ */
+ public function get_id()
+ {
+ return $this->id;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_token()
+ {
+ return $this->token;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function get_is_activated()
+ {
+ return $this->is_activated;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_created_on()
+ {
+ return $this->created_on;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_last_modified()
+ {
+ return $this->last_modified;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_label()
+ {
+ return $this->label;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ $registry = registry::get_instance();
+
+ return sprintf('%spermalink/v1/%s/%d/%d/%s/%s/'
+ , $registry->get('GV_ServerName')
+ , $this->get_label()
+ , $this->media_subdef->get_sbas_id()
+ , $this->media_subdef->get_record_id()
+ , $this->get_token()
+ , $this->media_subdef->get_name()
+ );
+ }
+
+ /**
+ *
+ * @param registryInterface $registry
+ * @return string
+ */
+ public function get_page(registryInterface $registry)
+ {
+ return sprintf('%spermalink/v1/%s/%d/%d/%s/%s/view/'
+ , $registry->get('GV_ServerName')
+ , $this->get_label()
+ , $this->media_subdef->get_sbas_id()
+ , $this->media_subdef->get_record_id()
+ , $this->get_token()
+ , $this->media_subdef->get_name()
+ );
+ }
+
+ /**
+ *
+ * @param string $token
+ * @return media_Permalink_Adapter
+ */
+ protected function set_token($token)
+ {
+ $this->token = $token;
+
+ $sql = 'UPDATE permalinks SET token = :token, last_modified = NOW()
+ WHERE id = :id';
+ $stmt = $this->databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':token' => $this->token, ':id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $is_activated
+ * @return media_Permalink_Adapter
+ */
+ public function set_is_activated($is_activated)
+ {
+ $this->is_activated = ! ! $is_activated;
+
+ $sql = 'UPDATE permalinks SET activated = :activated, last_modified = NOW()
+ WHERE id = :id';
+ $stmt = $this->databox->get_connection()->prepare($sql);
+
+ $params = array(
+ ':activated' => $this->is_activated,
+ ':id' => $this->get_id()
+ );
+
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @param string $label
+ * @return media_Permalink_Adapter
+ */
+ public function set_label($label)
+ {
+ $unicode_processor = new unicode();
+
+ $label = trim($label);
+ while (strpos($label, ' ') !== false)
+ $label = str_replace(' ', ' ', $label);
+
+ $this->label = $unicode_processor->remove_nonazAZ09(
+ str_replace(' ', '-', $label)
+ );
+
+ $sql = 'UPDATE permalinks SET label = :label, last_modified = NOW()
+ WHERE id = :id';
+ $stmt = $this->databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':label' => $this->label, ':id' => $this->get_id()));
+ $stmt->closeCursor();
+
+ $this->delete_data_from_cache();
+
+ return $this;
+ }
+
+ /**
+ *
+ * @return media_Permalink_Adapter
+ */
+ protected function load()
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+ $this->id = $datas['id'];
+ $this->token = $datas['token'];
+ $this->is_activated = $datas['is_activated'];
+ $this->created_on = $datas['created_on'];
+ $this->last_modified = $datas['last_modified'];
+ $this->label = $datas['label'];
+
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $sql = 'SELECT p.id, p.token, p.activated, p.created_on, p.last_modified
, p.label
FROM permalinks p
WHERE p.subdef_id = :subdef_id';
- $stmt = $this->databox->get_connection()->prepare($sql);
- $stmt->execute(array(':subdef_id' => $this->media_subdef->get_subdef_id()));
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $this->databox->get_connection()->prepare($sql);
+ $stmt->execute(array(':subdef_id' => $this->media_subdef->get_subdef_id()));
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- if (!$row)
- throw new Exception_Media_SubdefNotFound ();
+ if ( ! $row)
+ throw new Exception_Media_SubdefNotFound ();
- $this->id = (int) $row['id'];
- $this->token = $row['token'];
- $this->is_activated = !!$row['activated'];
- $this->created_on = new DateTime($row['created_on']);
- $this->last_modified = new DateTime($row['last_modified']);
- $this->label = $row['label'];
+ $this->id = (int) $row['id'];
+ $this->token = $row['token'];
+ $this->is_activated = ! ! $row['activated'];
+ $this->created_on = new DateTime($row['created_on']);
+ $this->last_modified = new DateTime($row['last_modified']);
+ $this->label = $row['label'];
- $datas = array(
- 'id' => $this->id
- , 'token' => $this->token
- , 'is_activated' => $this->is_activated
- , 'created_on' => $this->created_on
- , 'last_modified' => $this->last_modified
- , 'label' => $this->label
- );
+ $datas = array(
+ 'id' => $this->id
+ , 'token' => $this->token
+ , 'is_activated' => $this->is_activated
+ , 'created_on' => $this->created_on
+ , 'last_modified' => $this->last_modified
+ , 'label' => $this->label
+ );
- $this->set_data_to_cache($datas);
-
- return $this;
- }
-
- /**
- *
- * @param databox $databox
- * @param media_subdef $media_subdef
- * @return media_Permalink_Adapter
- */
- public static function getPermalink(databox &$databox, media_subdef &$media_subdef)
- {
- try
- {
- return new self($databox, $media_subdef);
- }
- catch (Exception $e)
- {
+ $this->set_data_to_cache($datas);
+ return $this;
}
- return self::create($databox, $media_subdef);
- }
+ /**
+ *
+ * @param databox $databox
+ * @param media_subdef $media_subdef
+ * @return media_Permalink_Adapter
+ */
+ public static function getPermalink(databox &$databox, media_subdef &$media_subdef)
+ {
+ try {
+ return new self($databox, $media_subdef);
+ } catch (Exception $e) {
- /**
- *
- * @param databox $databox
- * @param media_subdef $media_subdef
- * @return media_Permalink_Adapter
- */
- public static function create(databox &$databox, media_subdef &$media_subdef)
- {
- $sql = 'INSERT INTO permalinks
+ }
+
+ return self::create($databox, $media_subdef);
+ }
+
+ /**
+ *
+ * @param databox $databox
+ * @param media_subdef $media_subdef
+ * @return media_Permalink_Adapter
+ */
+ public static function create(databox &$databox, media_subdef &$media_subdef)
+ {
+ $sql = 'INSERT INTO permalinks
(id, subdef_id, token, activated, created_on, last_modified, label)
VALUES (null, :subdef_id, :token, :activated, NOW(), NOW(), "")';
- $params = array(
- ':subdef_id' => $media_subdef->get_subdef_id()
- , ':token' => random::generatePassword(8, random::LETTERS_AND_NUMBERS)
- , ':activated' => '1'
- );
+ $params = array(
+ ':subdef_id' => $media_subdef->get_subdef_id()
+ , ':token' => random::generatePassword(8, random::LETTERS_AND_NUMBERS)
+ , ':activated' => '1'
+ );
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ unset($stmt);
- $permalink = self::getPermalink($databox, $media_subdef);
- $permalink->set_label(strip_tags($media_subdef->get_record()->get_title()));
+ $permalink = self::getPermalink($databox, $media_subdef);
+ $permalink->set_label(strip_tags($media_subdef->get_record()->get_title()));
- return $permalink;
- }
+ return $permalink;
+ }
- /**
- *
- * @param databox $databox
- * @param string $token
- * @param int $record_id
- * @param string $name
- * @return record_adapter
- */
- public static function challenge_token(databox &$databox, $token, $record_id, $name)
- {
- $sql = 'SELECT p.id
+ /**
+ *
+ * @param databox $databox
+ * @param string $token
+ * @param int $record_id
+ * @param string $name
+ * @return record_adapter
+ */
+ public static function challenge_token(databox &$databox, $token, $record_id, $name)
+ {
+ $sql = 'SELECT p.id
FROM permalinks p, subdef s
WHERE s.record_id = :record_id
AND s.name = :name
@@ -362,46 +362,44 @@ class media_Permalink_Adapter implements media_Permalink_Interface, cache_cachea
AND activated = "1"
AND token = :token';
- $params = array(
- ':record_id' => $record_id
- , ':token' => $token
- , ':name' => $name
- );
+ $params = array(
+ ':record_id' => $record_id
+ , ':token' => $token
+ , ':name' => $name
+ );
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute($params);
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- unset($stmt);
+ $stmt->closeCursor();
+ unset($stmt);
- if ($row)
- {
- return new record_adapter($databox->get_sbas_id(), $record_id);
+ if ($row) {
+ return new record_adapter($databox->get_sbas_id(), $record_id);
+ }
+
+ return null;
}
- return null;
- }
+ public function get_cache_key($option = null)
+ {
+ return 'permalink_' . $this->media_subdef->get_subdef_id() . ($option ? '_' . $option : '');
+ }
- public function get_cache_key($option = null)
- {
- return 'permalink_' . $this->media_subdef->get_subdef_id() . ($option ? '_' . $option : '');
- }
+ public function get_data_from_cache($option = null)
+ {
+ return $this->databox->get_data_from_cache($this->get_cache_key($option));
+ }
- public function get_data_from_cache($option = null)
- {
- return $this->databox->get_data_from_cache($this->get_cache_key($option));
- }
-
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
-
- public function delete_data_from_cache($option = null)
- {
- return $this->databox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ return $this->databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
+ public function delete_data_from_cache($option = null)
+ {
+ return $this->databox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/media/Permalink/Interface.class.php b/lib/classes/media/Permalink/Interface.class.php
index 1027acff2d..5e986c5d4d 100644
--- a/lib/classes/media/Permalink/Interface.class.php
+++ b/lib/classes/media/Permalink/Interface.class.php
@@ -17,27 +17,28 @@
*/
interface media_Permalink_Interface
{
- public function get_url();
- public function get_page(registryInterface $registry);
+ public function get_url();
- public function get_id();
+ public function get_page(registryInterface $registry);
- public function get_token();
+ public function get_id();
- public function get_is_activated();
+ public function get_token();
- public function get_created_on();
+ public function get_is_activated();
- public function get_last_modified();
+ public function get_created_on();
- public function get_label();
+ public function get_last_modified();
- public function set_is_activated($is_activated);
+ public function get_label();
- public function set_label($label);
+ public function set_is_activated($is_activated);
- public static function getPermalink(databox &$databox, media_subdef &$media_subdef);
+ public function set_label($label);
- public static function create(databox &$databox, media_subdef &$media_subdef);
+ public static function getPermalink(databox &$databox, media_subdef &$media_subdef);
+
+ public static function create(databox &$databox, media_subdef &$media_subdef);
}
diff --git a/lib/classes/media/abstract.class.php b/lib/classes/media/abstract.class.php
index a8f215f6f8..991e65a558 100644
--- a/lib/classes/media/abstract.class.php
+++ b/lib/classes/media/abstract.class.php
@@ -17,117 +17,115 @@
*/
abstract class media_abstract
{
+ /**
+ *
+ * @var string
+ */
+ protected $url;
- /**
- *
- * @var string
- */
- protected $url;
- /**
- *
- * @var int
- */
- protected $height;
- /**
- *
- * @var int
- */
- protected $width;
+ /**
+ *
+ * @var int
+ */
+ protected $height;
- const PORTRAIT = 'PORTRAIT';
- const PAYSAGE = 'LANDSCAPE';
+ /**
+ *
+ * @var int
+ */
+ protected $width;
- /**
- *
- * @param string $url
- * @param int $width
- * @param int $height
- * @return media
- */
- function __construct($url, $width, $height)
- {
- $this->url = $url;
- $this->height = (int) $height;
- $this->width = (int) $width;
+ const PORTRAIT = 'PORTRAIT';
+ const PAYSAGE = 'LANDSCAPE';
- return $this;
- }
+ /**
+ *
+ * @param string $url
+ * @param int $width
+ * @param int $height
+ * @return media
+ */
+ function __construct($url, $width, $height)
+ {
+ $this->url = $url;
+ $this->height = (int) $height;
+ $this->width = (int) $width;
- /**
- *
- * @return string
- */
- public function get_random()
- {
- return md5(time() . mt_rand(100000, 999999));
- }
+ return $this;
+ }
- /**
- *
- * @return string
- */
- public function get_url()
- {
- return $this->url;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_random()
+ {
+ return md5(time() . mt_rand(100000, 999999));
+ }
- /**
- *
- * @return int
- */
- public function get_width()
- {
- return $this->width;
- }
+ /**
+ *
+ * @return string
+ */
+ public function get_url()
+ {
+ return $this->url;
+ }
- /**
- *
- * @return int
- */
- public function get_height()
- {
- return $this->height;
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_width()
+ {
+ return $this->width;
+ }
- /**
- *
- * @return string
- */
- public function get_type()
- {
- return 'image';
- }
+ /**
+ *
+ * @return int
+ */
+ public function get_height()
+ {
+ return $this->height;
+ }
- /**
- *
- * @return string
- */
- public function get_orientation()
- {
- if ($this->width > $this->height)
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ return 'image';
+ }
- return self::PAYSAGE;
- else
+ /**
+ *
+ * @return string
+ */
+ public function get_orientation()
+ {
+ if ($this->width > $this->height)
+ return self::PAYSAGE;
+ else
+ return self::PORTRAIT;
+ }
- return self::PORTRAIT;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_paysage()
- {
- return $this->get_orientation() == self::PAYSAGE;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_portrait()
- {
- return $this->get_orientation() == self::PORTRAIT;
- }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_paysage()
+ {
+ return $this->get_orientation() == self::PAYSAGE;
+ }
+ /**
+ *
+ * @return boolean
+ */
+ public function is_portrait()
+ {
+ return $this->get_orientation() == self::PORTRAIT;
+ }
}
diff --git a/lib/classes/media/subdef.class.php b/lib/classes/media/subdef.class.php
index 143762525b..f883f02b60 100644
--- a/lib/classes/media/subdef.class.php
+++ b/lib/classes/media/subdef.class.php
@@ -17,616 +17,599 @@
*/
class media_subdef extends media_abstract implements cache_cacheableInterface
{
+ /**
+ *
+ * @var string
+ */
+ protected $mime;
- /**
- *
- * @var string
- */
- protected $mime;
- /**
- *
- * @var string
- */
- protected $baseurl;
- /**
- *
- * @var string
- */
- protected $file;
- /**
- *
- * @var string
- */
- protected $path;
- /**
- *
- * @var record_adapter
- */
- protected $record;
- /**
- *
- * @var media_Permalink_Adapter
- */
- protected $permalink;
- /**
- *
- * @var boolean
- */
- protected $is_substituted = false;
- /**
- *
- * @var string
- */
- protected $pathfile;
- /**
- *
- * @var int
- */
- protected $subdef_id;
- /**
- *
- * @var string
- */
- protected $name;
- /**
- *
- * @var DateTime
- */
- protected $creation_date;
- /**
- *
- * @var DateTime
- */
- protected $modification_date;
- /**
- *
- * @var boolean
- */
- protected $is_physically_present = true;
+ /**
+ *
+ * @var string
+ */
+ protected $baseurl;
- const TYPE_VIDEO_MP4 = 'VIDEO_MP4';
- const TYPE_VIDEO_FLV = 'VIDEO_FLV';
- const TYPE_FLEXPAPER = 'FLEXPAPER';
- const TYPE_AUDIO_MP3 = 'AUDIO_MP3';
- const TYPE_IMAGE = 'IMAGE';
- const TYPE_NO_PLAYER = 'UNKNOWN';
+ /**
+ *
+ * @var string
+ */
+ protected $file;
- /**
- * @todo the presence of file is checked on constructor, it would be better
- * to check it when needed (stop disk access)
- *
- * @param record_adapter $record
- * @param type $name
- * @param type $substitute
- * @return media_subdef
- */
- function __construct(record_adapter &$record, $name, $substitute = false)
- {
- $this->name = $name;
- $this->record = $record;
- $this->load($substitute);
- $this->pathfile = $this->path . $this->file;
+ /**
+ *
+ * @var string
+ */
+ protected $path;
- $nowtime = new DateTime('-3 days');
- $random = $record->get_modification_date() > $nowtime;
+ /**
+ *
+ * @var record_adapter
+ */
+ protected $record;
- $this->generate_url($random);
+ /**
+ *
+ * @var media_Permalink_Adapter
+ */
+ protected $permalink;
- return $this;
- }
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_substituted = false;
- /**
- *
- * @param boolean $substitute
- * @return media_subdef
- */
- protected function load($substitute)
- {
- try
+ /**
+ *
+ * @var string
+ */
+ protected $pathfile;
+
+ /**
+ *
+ * @var int
+ */
+ protected $subdef_id;
+
+ /**
+ *
+ * @var string
+ */
+ protected $name;
+
+ /**
+ *
+ * @var DateTime
+ */
+ protected $creation_date;
+
+ /**
+ *
+ * @var DateTime
+ */
+ protected $modification_date;
+
+ /**
+ *
+ * @var boolean
+ */
+ protected $is_physically_present = true;
+
+ const TYPE_VIDEO_MP4 = 'VIDEO_MP4';
+ const TYPE_VIDEO_FLV = 'VIDEO_FLV';
+ const TYPE_FLEXPAPER = 'FLEXPAPER';
+ const TYPE_AUDIO_MP3 = 'AUDIO_MP3';
+ const TYPE_IMAGE = 'IMAGE';
+ const TYPE_NO_PLAYER = 'UNKNOWN';
+
+ /**
+ * @todo the presence of file is checked on constructor, it would be better
+ * to check it when needed (stop disk access)
+ *
+ * @param record_adapter $record
+ * @param type $name
+ * @param type $substitute
+ * @return media_subdef
+ */
+ function __construct(record_adapter &$record, $name, $substitute = false)
{
- $datas = $this->get_data_from_cache();
- $this->mime = $datas['mime'];
- $this->width = $datas['width'];
- $this->height = $datas['height'];
- $this->baseurl = $datas['baseurl'];
- $this->path = $datas['path'];
- $this->file = $datas['file'];
- $this->is_physically_present = $datas['physically_present'];
- $this->is_substituted = $datas['is_substituted'];
- $this->subdef_id = $datas['subdef_id'];
- $this->modification_date = $datas['modification_date'];
- $this->creation_date = $datas['creation_date'];
+ $this->name = $name;
+ $this->record = $record;
+ $this->load($substitute);
+ $this->pathfile = $this->path . $this->file;
- return $this;
- }
- catch (Exception $e)
- {
+ $nowtime = new DateTime('-3 days');
+ $random = $record->get_modification_date() > $nowtime;
+ $this->generate_url($random);
+
+ return $this;
}
- $connbas = $this->record->get_databox()->get_connection();
+ /**
+ *
+ * @param boolean $substitute
+ * @return media_subdef
+ */
+ protected function load($substitute)
+ {
+ try {
+ $datas = $this->get_data_from_cache();
+ $this->mime = $datas['mime'];
+ $this->width = $datas['width'];
+ $this->height = $datas['height'];
+ $this->baseurl = $datas['baseurl'];
+ $this->path = $datas['path'];
+ $this->file = $datas['file'];
+ $this->is_physically_present = $datas['physically_present'];
+ $this->is_substituted = $datas['is_substituted'];
+ $this->subdef_id = $datas['subdef_id'];
+ $this->modification_date = $datas['modification_date'];
+ $this->creation_date = $datas['creation_date'];
- $sql = 'SELECT subdef_id, name, baseurl, file, width, height, mime,
+ return $this;
+ } catch (Exception $e) {
+
+ }
+
+ $connbas = $this->record->get_databox()->get_connection();
+
+ $sql = 'SELECT subdef_id, name, baseurl, file, width, height, mime,
path, size, substit, created_on, updated_on
FROM subdef
WHERE name = :name AND record_id = :record_id';
- $params = array(
- ':record_id' => $this->record->get_record_id(),
- ':name' => $this->name
- );
+ $params = array(
+ ':record_id' => $this->record->get_record_id(),
+ ':name' => $this->name
+ );
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $registry = $this->record->get_databox()->get_registry();
+ $registry = $this->record->get_databox()->get_registry();
- if ($row)
- {
- $this->width = (int) $row['width'];
- $this->height = (int) $row['height'];
- $this->mime = $row['mime'];
- $this->baseurl = trim($row['baseurl']);
- $this->file = $row['file'];
- $this->path = p4string::addEndSlash($row['path']);
- $this->is_substituted = !!$row['substit'];
- $this->subdef_id = (int) $row['subdef_id'];
+ if ($row) {
+ $this->width = (int) $row['width'];
+ $this->height = (int) $row['height'];
+ $this->mime = $row['mime'];
+ $this->baseurl = trim($row['baseurl']);
+ $this->file = $row['file'];
+ $this->path = p4string::addEndSlash($row['path']);
+ $this->is_substituted = ! ! $row['substit'];
+ $this->subdef_id = (int) $row['subdef_id'];
- if ($row['updated_on'])
- $this->modification_date = new DateTime($row['updated_on']);
- if ($row['created_on'])
- $this->creation_date = new DateTime($row['created_on']);
- }
- elseif ($substitute === false)
- {
- throw new Exception_Media_SubdefNotFound($this->name . ' not found');
- }
- else
- {
- $this->mime = 'image/png';
- $this->width = 256;
- $this->height = 256;
- $this->baseurl = 'skins/icons/';
- $this->path = $registry->get('GV_RootPath') . 'www/skins/icons/';
- $this->file = 'deleted.png';
- $this->is_physically_present = false;
- $this->is_substituted = true;
- }
- if (!$row || !file_exists($this->path . $this->file))
- {
- if ($this->record->is_grouping())
- {
- $this->mime = 'image/png';
- $this->width = 256;
- $this->height = 256;
- $this->baseurl = 'skins/icons/substitution/';
- $this->path = $registry->get('GV_RootPath')
- . 'www/skins/icons/substitution/';
- $this->file = 'regroup_thumb.png';
- $this->is_substituted = true;
- }
- else
- {
- $mime = $this->record->get_mime();
- $mime = trim($mime) != '' ? str_replace('/', '_', $mime) : 'application_octet-stream';
+ if ($row['updated_on'])
+ $this->modification_date = new DateTime($row['updated_on']);
+ if ($row['created_on'])
+ $this->creation_date = new DateTime($row['created_on']);
+ }
+ elseif ($substitute === false) {
+ throw new Exception_Media_SubdefNotFound($this->name . ' not found');
+ } else {
+ $this->mime = 'image/png';
+ $this->width = 256;
+ $this->height = 256;
+ $this->baseurl = 'skins/icons/';
+ $this->path = $registry->get('GV_RootPath') . 'www/skins/icons/';
+ $this->file = 'deleted.png';
+ $this->is_physically_present = false;
+ $this->is_substituted = true;
+ }
+ if ( ! $row || ! file_exists($this->path . $this->file)) {
+ if ($this->record->is_grouping()) {
+ $this->mime = 'image/png';
+ $this->width = 256;
+ $this->height = 256;
+ $this->baseurl = 'skins/icons/substitution/';
+ $this->path = $registry->get('GV_RootPath')
+ . 'www/skins/icons/substitution/';
+ $this->file = 'regroup_thumb.png';
+ $this->is_substituted = true;
+ } else {
+ $mime = $this->record->get_mime();
+ $mime = trim($mime) != '' ? str_replace('/', '_', $mime) : 'application_octet-stream';
- $this->mime = 'image/png';
- $this->width = 256;
- $this->height = 256;
- $this->baseurl = 'skins/icons/substitution/';
- $this->path = $registry->get('GV_RootPath')
- . 'www/skins/icons/substitution/';
- $this->file = str_replace('+', '%20', $mime) . '.png';
- $this->is_substituted = true;
- }
- $this->is_physically_present = false;
- if (!file_exists($this->path . $this->file))
- {
- $this->baseurl = 'skins/icons/';
- $this->path = $registry->get('GV_RootPath')
- . 'www/skins/icons/';
- $this->file = 'substitution.png';
- $this->is_substituted = true;
- }
- }
+ $this->mime = 'image/png';
+ $this->width = 256;
+ $this->height = 256;
+ $this->baseurl = 'skins/icons/substitution/';
+ $this->path = $registry->get('GV_RootPath')
+ . 'www/skins/icons/substitution/';
+ $this->file = str_replace('+', '%20', $mime) . '.png';
+ $this->is_substituted = true;
+ }
+ $this->is_physically_present = false;
+ if ( ! file_exists($this->path . $this->file)) {
+ $this->baseurl = 'skins/icons/';
+ $this->path = $registry->get('GV_RootPath')
+ . 'www/skins/icons/';
+ $this->file = 'substitution.png';
+ $this->is_substituted = true;
+ }
+ }
- $datas = array(
- 'mime' => $this->mime
- , 'width' => $this->width
- , 'height' => $this->height
- , 'baseurl' => $this->baseurl
- , 'path' => $this->path
- , 'file' => $this->file
- , 'physically_present' => $this->is_physically_present
- , 'is_substituted' => $this->is_substituted
- , 'subdef_id' => $this->subdef_id
- , 'modification_date' => $this->modification_date
- , 'creation_date' => $this->creation_date
- );
+ $datas = array(
+ 'mime' => $this->mime
+ , 'width' => $this->width
+ , 'height' => $this->height
+ , 'baseurl' => $this->baseurl
+ , 'path' => $this->path
+ , 'file' => $this->file
+ , 'physically_present' => $this->is_physically_present
+ , 'is_substituted' => $this->is_substituted
+ , 'subdef_id' => $this->subdef_id
+ , 'modification_date' => $this->modification_date
+ , 'creation_date' => $this->creation_date
+ );
- $this->set_data_to_cache($datas);
+ $this->set_data_to_cache($datas);
- return $this;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_physically_present()
- {
- return $this->is_physically_present;
- }
-
- /**
- *
- * @return record_adapter
- */
- public function get_record()
- {
- return $this->record;
- }
-
- /**
- *
- * @return media_Permalink_Adapter
- */
- public function get_permalink()
- {
- if (!$this->permalink && $this->is_physically_present)
- $this->permalink = media_Permalink_Adapter::getPermalink($this->record->get_databox(), $this);
-
- return $this->permalink;
- }
-
- /**
- *
- * @return int
- */
- public function get_record_id()
- {
- return $this->record->get_record_id();
- }
-
- /**
- *
- * @return int
- */
- public function get_sbas_id()
- {
- return $this->record->get_sbas_id();
- }
-
- /**
- *
- * @return string
- */
- public function get_type()
- {
- switch ($this->mime)
- {
- case 'video/mp4':
- $type = self::TYPE_VIDEO_MP4;
- break;
- case 'video/x-flv':
- $type = self::TYPE_VIDEO_FLV;
- break;
- case 'application/x-shockwave-flash':
- $type = self::TYPE_FLEXPAPER;
- break;
- case 'audio/mpeg':
- $type = self::TYPE_AUDIO_MP3;
- break;
- case 'image/jpeg':
- case 'image/png':
- case 'image/gif':
- $type = self::TYPE_IMAGE;
- break;
- default:
- $type = self::TYPE_NO_PLAYER;
- break;
- }
-
- return $type;
- }
-
- /**
- *
- * @return string
- */
- public function get_mime()
- {
- return $this->mime;
- }
-
- /**
- *
- * @return string
- */
- public function get_path()
- {
- return $this->path;
- }
-
- /**
- *
- * @return string
- */
- public function get_baseurl()
- {
- return $this->baseurl;
- }
-
- /**
- *
- * @return string
- */
- public function get_file()
- {
- return $this->file;
- }
-
- /**
- *
- * @return int
- */
- public function get_size()
- {
- try
- {
- $system_file = new system_file($this->path . $this->file);
-
- return $system_file->getSize();
- }
- catch (Exception $e)
- {
- return 0;
- }
- }
-
- /**
- *
- * @return string
- */
- public function get_name()
- {
- return $this->name;
- }
-
- /**
- *
- * @return id
- */
- public function get_subdef_id()
- {
- return $this->subdef_id;
- }
-
- /**
- *
- * @return boolean
- */
- public function is_substituted()
- {
- return $this->is_substituted;
- }
-
- /**
- *
- * @return string
- */
- public function get_pathfile()
- {
- return $this->pathfile;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_modification_date()
- {
- return $this->modification_date;
- }
-
- /**
- *
- * @return DateTime
- */
- public function get_creation_date()
- {
- return $this->creation_date;
- }
-
- /**
- *
- * @return string
- */
- public function renew_url()
- {
- $this->generate_url();
-
- return $this->get_url();
- }
-
- /**
- *
- * @param registryInterface $registry
- * @param int $angle
- * @return media_subdef
- */
- public function rotate(registryInterface $registry, $angle)
- {
- $Core = \bootstrap::getCore();
-
- $specs = new MediaAlchemyst\Specification\Image();
- $specs->setRotationAngle($angle);
-
- try
- {
- $Core['media-alchemyst']->open($this->get_pathfile())
- ->turnInto($this->get_pathfile(), $specs)
- ->close();
- }
- catch(\MediaAlchemyst\Exception\Exception $e)
- {
return $this;
}
- $result = new system_file($this->get_pathfile());
-
- $tc_datas = $result->get_technical_datas();
- if ($tc_datas[system_file::TC_DATAS_WIDTH] && $tc_datas[system_file::TC_DATAS_HEIGHT])
+ /**
+ *
+ * @return boolean
+ */
+ public function is_physically_present()
{
+ return $this->is_physically_present;
+ }
- $sql = "UPDATE subdef
+ /**
+ *
+ * @return record_adapter
+ */
+ public function get_record()
+ {
+ return $this->record;
+ }
+
+ /**
+ *
+ * @return media_Permalink_Adapter
+ */
+ public function get_permalink()
+ {
+ if ( ! $this->permalink && $this->is_physically_present)
+ $this->permalink = media_Permalink_Adapter::getPermalink($this->record->get_databox(), $this);
+
+ return $this->permalink;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_record_id()
+ {
+ return $this->record->get_record_id();
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_sbas_id()
+ {
+ return $this->record->get_sbas_id();
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_type()
+ {
+ switch ($this->mime) {
+ case 'video/mp4':
+ $type = self::TYPE_VIDEO_MP4;
+ break;
+ case 'video/x-flv':
+ $type = self::TYPE_VIDEO_FLV;
+ break;
+ case 'application/x-shockwave-flash':
+ $type = self::TYPE_FLEXPAPER;
+ break;
+ case 'audio/mpeg':
+ $type = self::TYPE_AUDIO_MP3;
+ break;
+ case 'image/jpeg':
+ case 'image/png':
+ case 'image/gif':
+ $type = self::TYPE_IMAGE;
+ break;
+ default:
+ $type = self::TYPE_NO_PLAYER;
+ break;
+ }
+
+ return $type;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_mime()
+ {
+ return $this->mime;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_path()
+ {
+ return $this->path;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_baseurl()
+ {
+ return $this->baseurl;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_file()
+ {
+ return $this->file;
+ }
+
+ /**
+ *
+ * @return int
+ */
+ public function get_size()
+ {
+ try {
+ $system_file = new system_file($this->path . $this->file);
+
+ return $system_file->getSize();
+ } catch (Exception $e) {
+ return 0;
+ }
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_name()
+ {
+ return $this->name;
+ }
+
+ /**
+ *
+ * @return id
+ */
+ public function get_subdef_id()
+ {
+ return $this->subdef_id;
+ }
+
+ /**
+ *
+ * @return boolean
+ */
+ public function is_substituted()
+ {
+ return $this->is_substituted;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function get_pathfile()
+ {
+ return $this->pathfile;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_modification_date()
+ {
+ return $this->modification_date;
+ }
+
+ /**
+ *
+ * @return DateTime
+ */
+ public function get_creation_date()
+ {
+ return $this->creation_date;
+ }
+
+ /**
+ *
+ * @return string
+ */
+ public function renew_url()
+ {
+ $this->generate_url();
+
+ return $this->get_url();
+ }
+
+ /**
+ *
+ * @param registryInterface $registry
+ * @param int $angle
+ * @return media_subdef
+ */
+ public function rotate(registryInterface $registry, $angle)
+ {
+ $Core = \bootstrap::getCore();
+
+ $specs = new MediaAlchemyst\Specification\Image();
+ $specs->setRotationAngle($angle);
+
+ try {
+ $Core['media-alchemyst']->open($this->get_pathfile())
+ ->turnInto($this->get_pathfile(), $specs)
+ ->close();
+ } catch (\MediaAlchemyst\Exception\Exception $e) {
+ return $this;
+ }
+
+ $result = new system_file($this->get_pathfile());
+
+ $tc_datas = $result->get_technical_datas();
+ if ($tc_datas[system_file::TC_DATAS_WIDTH] && $tc_datas[system_file::TC_DATAS_HEIGHT]) {
+
+ $sql = "UPDATE subdef
SET height = :height , width = :width, updated_on = NOW()
WHERE record_id = :record_id AND name = :name";
- $params = array(
- ':width' => $tc_datas[system_file::TC_DATAS_WIDTH]
- , ':height' => $tc_datas[system_file::TC_DATAS_HEIGHT]
- , ':record_id' => $this->get_record_id()
- , ':name' => $this->get_name()
- );
+ $params = array(
+ ':width' => $tc_datas[system_file::TC_DATAS_WIDTH]
+ , ':height' => $tc_datas[system_file::TC_DATAS_HEIGHT]
+ , ':record_id' => $this->get_record_id()
+ , ':name' => $this->get_name()
+ );
- $stmt = $this->record->get_databox()->get_connection()->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
- $this->delete_data_from_cache();
+ $stmt = $this->record->get_databox()->get_connection()->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+ $this->delete_data_from_cache();
+ }
+
+ return $this;
}
- return $this;
- }
-
- /**
- *
- * @param record_Interface $record
- * @param string $name
- * @param system_file $system_file
- * @param string $baseurl
- * @return media_subdef
- */
- public static function create(record_Interface $record, $name, system_file $system_file, $baseurl='')
- {
- $databox = $record->get_databox();
- $connbas = $databox->get_connection();
-
- $path = $system_file->getPath();
- $newname = $system_file->getFilename();
-
- $datas = $system_file->get_technical_datas();
-
- $params = array(
- ':path' => $path,
- ':file' => $newname,
- ':baseurl' => $baseurl,
- ':width' => isset($datas[system_file::TC_DATAS_WIDTH]) ? $datas[system_file::TC_DATAS_WIDTH] : '',
- ':height' => isset($datas[system_file::TC_DATAS_HEIGHT]) ? $datas[system_file::TC_DATAS_HEIGHT] : '',
- ':mime' => $system_file->get_mime(),
- ':size' => $system_file->getSize(),
- ':dispatched' => 1,
- );
-
- try
+ /**
+ *
+ * @param record_Interface $record
+ * @param string $name
+ * @param system_file $system_file
+ * @param string $baseurl
+ * @return media_subdef
+ */
+ public static function create(record_Interface $record, $name, system_file $system_file, $baseurl = '')
{
- $subdef = new self($record, $name);
+ $databox = $record->get_databox();
+ $connbas = $databox->get_connection();
- if(!$subdef->is_physically_present())
- {
- throw new \Exception_Media_SubdefNotFound('Require the real one');
- }
+ $path = $system_file->getPath();
+ $newname = $system_file->getFilename();
- $sql = "UPDATE subdef
+ $datas = $system_file->get_technical_datas();
+
+ $params = array(
+ ':path' => $path,
+ ':file' => $newname,
+ ':baseurl' => $baseurl,
+ ':width' => isset($datas[system_file::TC_DATAS_WIDTH]) ? $datas[system_file::TC_DATAS_WIDTH] : '',
+ ':height' => isset($datas[system_file::TC_DATAS_HEIGHT]) ? $datas[system_file::TC_DATAS_HEIGHT] : '',
+ ':mime' => $system_file->get_mime(),
+ ':size' => $system_file->getSize(),
+ ':dispatched' => 1,
+ );
+
+ try {
+ $subdef = new self($record, $name);
+
+ if ( ! $subdef->is_physically_present()) {
+ throw new \Exception_Media_SubdefNotFound('Require the real one');
+ }
+
+ $sql = "UPDATE subdef
SET path = :path, file = :file, baseurl = :baseurl
, width = :width , height = :height, mime = :mime
, size = :size, dispatched = :dispatched, updated_on = NOW()
WHERE subdef_id = :subdef_id";
- $params[':subdef_id'] = $subdef->get_subdef_id();
- }
- catch (\Exception_Media_SubdefNotFound $e)
- {
- $sql = "INSERT INTO subdef
+ $params[':subdef_id'] = $subdef->get_subdef_id();
+ } catch (\Exception_Media_SubdefNotFound $e) {
+ $sql = "INSERT INTO subdef
(record_id, name, path, file, baseurl, width
, height, mime, size, dispatched, created_on, updated_on)
VALUES (:record_id, :name, :path, :file, :baseurl, :width, :height
, :mime, :size, :dispatched, NOW(), NOW())";
- $params[':record_id'] = $record->get_record_id();
- $params[':name'] = $name;
+ $params[':record_id'] = $record->get_record_id();
+ $params[':name'] = $name;
+ }
+
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute($params);
+ $stmt->closeCursor();
+
+ return new self($record, $name);
}
- $stmt = $connbas->prepare($sql);
- $stmt->execute($params);
- $stmt->closeCursor();
-
- return new self($record, $name);
- }
-
- /**
- *
- * @param boolean $random
- * @return string
- */
- protected function generate_url($random = false)
- {
- if ($this->baseurl !== '')
+ /**
+ *
+ * @param boolean $random
+ * @return string
+ */
+ protected function generate_url($random = false)
{
- $registry = registry::get_instance();
- $this->url = $registry->get('GV_STATIC_URL')
- . '/' . p4string::addEndSlash($this->baseurl)
- . $this->file . ($random ? '?rand=' . mt_rand(10000, 99999) : '');
+ if ($this->baseurl !== '') {
+ $registry = registry::get_instance();
+ $this->url = $registry->get('GV_STATIC_URL')
+ . '/' . p4string::addEndSlash($this->baseurl)
+ . $this->file . ($random ? '?rand=' . mt_rand(10000, 99999) : '');
- return;
- }
+ return;
+ }
- if (in_array($this->mime, array('video/mp4')))
- {
- $token = p4file::apache_tokenize($this->pathfile);
- if ($token)
- {
- $this->url = $token;
+ if (in_array($this->mime, array('video/mp4'))) {
+ $token = p4file::apache_tokenize($this->pathfile);
+ if ($token) {
+ $this->url = $token;
- return;
- }
- }
- $this->url = "/datafiles/" . $this->record->get_sbas_id()
+ return;
+ }
+ }
+ $this->url = "/datafiles/" . $this->record->get_sbas_id()
. "/" . $this->record->get_record_id() . "/"
. $this->get_name() . "/"
. ($random ? '?' . mt_rand(10000, 99999) : '');
- return;
- }
+ return;
+ }
- public function get_cache_key($option = null)
- {
- return 'subdef_' . $this->get_record()->get_serialize_key()
- . '_' . $this->name . ($option ? '_' . $option : '');
- }
+ public function get_cache_key($option = null)
+ {
+ return 'subdef_' . $this->get_record()->get_serialize_key()
+ . '_' . $this->name . ($option ? '_' . $option : '');
+ }
- public function get_data_from_cache($option = null)
- {
- $databox = $this->get_record()->get_databox();
+ public function get_data_from_cache($option = null)
+ {
+ $databox = $this->get_record()->get_databox();
- return $databox->get_data_from_cache($this->get_cache_key($option));
- }
+ return $databox->get_data_from_cache($this->get_cache_key($option));
+ }
- public function set_data_to_cache($value, $option = null, $duration = 0)
- {
- $databox = $this->get_record()->get_databox();
+ public function set_data_to_cache($value, $option = null, $duration = 0)
+ {
+ $databox = $this->get_record()->get_databox();
- return $databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
- }
+ return $databox->set_data_to_cache($value, $this->get_cache_key($option), $duration);
+ }
- public function delete_data_from_cache($option = null)
- {
- $databox = $this->get_record()->get_databox();
-
- return $databox->delete_data_from_cache($this->get_cache_key($option));
- }
+ public function delete_data_from_cache($option = null)
+ {
+ $databox = $this->get_record()->get_databox();
+ return $databox->delete_data_from_cache($this->get_cache_key($option));
+ }
}
diff --git a/lib/classes/metadata/Abstract.class.php b/lib/classes/metadata/Abstract.class.php
index f4cba16685..c46bea8510 100644
--- a/lib/classes/metadata/Abstract.class.php
+++ b/lib/classes/metadata/Abstract.class.php
@@ -17,129 +17,128 @@
*/
abstract class metadata_Abstract
{
- const MULTI = false;
- const MIN_LENGTH = 0;
- const DEPRECATED = false;
- const SOURCE = null;
- const NAME_SPACE = null;
- const TAGNAME = null;
- const MAX_LENGTH = null;
- const TYPE = null;
- const READONLY = false;
- const MANDATORY = false;
+ const MULTI = false;
+ const MIN_LENGTH = 0;
+ const DEPRECATED = false;
+ const SOURCE = null;
+ const NAME_SPACE = null;
+ const TAGNAME = null;
+ const MAX_LENGTH = null;
+ const TYPE = null;
+ const READONLY = false;
+ const MANDATORY = false;
- /**
- * Tells if the metadata source is MultiValued
- *
- * @return boolean
- */
- public static function is_multi()
- {
- return static::MULTI;
- }
+ /**
+ * Tells if the metadata source is MultiValued
+ *
+ * @return boolean
+ */
+ public static function is_multi()
+ {
+ return static::MULTI;
+ }
- /**
- * Returns the minimum character required for the metadata
- * Returns 0 if not minimal length
- *
- * @return int
- */
- public static function minLength()
- {
- return static::MIN_LENGTH;
- }
+ /**
+ * Returns the minimum character required for the metadata
+ * Returns 0 if not minimal length
+ *
+ * @return int
+ */
+ public static function minLength()
+ {
+ return static::MIN_LENGTH;
+ }
- /**
- * Tells if the metadata is deprecated
- *
- * @return boolean
- */
- public static function is_deprecated()
- {
- return static::DEPRECATED;
- }
+ /**
+ * Tells if the metadata is deprecated
+ *
+ * @return boolean
+ */
+ public static function is_deprecated()
+ {
+ return static::DEPRECATED;
+ }
- /**
- * Return the source value as an xpath value like
- * /rdf:RDF/rdf:Description/NAMESPACE:tagname
- *
- * @return string
- */
- public static function get_source()
- {
- return static::SOURCE;
- }
+ /**
+ * Return the source value as an xpath value like
+ * /rdf:RDF/rdf:Description/NAMESPACE:tagname
+ *
+ * @return string
+ */
+ public static function get_source()
+ {
+ return static::SOURCE;
+ }
- /**
- * Retuns the namespace of the metadata
- *
- * @return string
- */
- public static function get_namespace()
- {
- return static::NAME_SPACE;
- }
+ /**
+ * Retuns the namespace of the metadata
+ *
+ * @return string
+ */
+ public static function get_namespace()
+ {
+ return static::NAME_SPACE;
+ }
- /**
- * Returns the tagname of the metadata
- *
- * @return string
- */
- public static function get_tagname()
- {
- return static::TAGNAME;
- }
+ /**
+ * Returns the tagname of the metadata
+ *
+ * @return string
+ */
+ public static function get_tagname()
+ {
+ return static::TAGNAME;
+ }
- /**
- * Returns the maximum character required for the metadata
- * Returns 0 if not maximal length
- *
- * @return int
- */
- public static function maxlength()
- {
- return static::MAX_LENGTH;
- }
+ /**
+ * Returns the maximum character required for the metadata
+ * Returns 0 if not maximal length
+ *
+ * @return int
+ */
+ public static function maxlength()
+ {
+ return static::MAX_LENGTH;
+ }
- /**
- * Returns the type, one of the metadata_interface::TYPE_* values
- *
- * @return string
- */
- public static function get_type()
- {
- return static::TYPE;
- }
+ /**
+ * Returns the type, one of the metadata_interface::TYPE_* values
+ *
+ * @return string
+ */
+ public static function get_type()
+ {
+ return static::TYPE;
+ }
- /**
- * Returns an associative array of the avalaible values :
- * Keys are values and values are filled with the actual meaning of the value
- *
- * @return Array
- */
- public static function available_values()
- {
- return array();
- }
+ /**
+ * Returns an associative array of the avalaible values :
+ * Keys are values and values are filled with the actual meaning of the value
+ *
+ * @return Array
+ */
+ public static function available_values()
+ {
+ return array();
+ }
- /**
- * Returns true is the value is readonly
- *
- * @return boolean
- */
- public static function is_readonly()
- {
- return static::READONLY;
- }
-
- /**
- * Returns true if the value is mandatory
- *
- * @return boolean
- */
- public static function is_mandatory()
- {
- return static::MANDATORY;
- }
+ /**
+ * Returns true is the value is readonly
+ *
+ * @return boolean
+ */
+ public static function is_readonly()
+ {
+ return static::READONLY;
+ }
+ /**
+ * Returns true if the value is mandatory
+ *
+ * @return boolean
+ */
+ public static function is_mandatory()
+ {
+ return static::MANDATORY;
+ }
}
diff --git a/lib/classes/metadata/Interface.class.php b/lib/classes/metadata/Interface.class.php
index 15fe2ae29f..97668f4f2b 100644
--- a/lib/classes/metadata/Interface.class.php
+++ b/lib/classes/metadata/Interface.class.php
@@ -17,41 +17,41 @@
*/
interface metadata_Interface
{
- const TYPE_STRING = 'string';
- const TYPE_DIGITS = 'digits';
- const TYPE_RATIONAL64 = 'rational64';
- const TYPE_BINARY = 'binary';
- const TYPE_INT8U = 'int8u';
- const TYPE_DATETIME = 'datetime';
- const TYPE_DATE = 'date';
- const TYPE_TIME = 'time';
- const TYPE_BOOLEAN = 'boolean';
- const TYPE_FLOAT = 'float';
- const TYPE_INT16U = 'int16u';
- const TYPE_INT32U = 'int32u';
- const TYPE_INTEGER = 'integer';
- const TYPE_LANGALT = 'langalt';
- const TYPE_REAL = 'real';
+ const TYPE_STRING = 'string';
+ const TYPE_DIGITS = 'digits';
+ const TYPE_RATIONAL64 = 'rational64';
+ const TYPE_BINARY = 'binary';
+ const TYPE_INT8U = 'int8u';
+ const TYPE_DATETIME = 'datetime';
+ const TYPE_DATE = 'date';
+ const TYPE_TIME = 'time';
+ const TYPE_BOOLEAN = 'boolean';
+ const TYPE_FLOAT = 'float';
+ const TYPE_INT16U = 'int16u';
+ const TYPE_INT32U = 'int32u';
+ const TYPE_INTEGER = 'integer';
+ const TYPE_LANGALT = 'langalt';
+ const TYPE_REAL = 'real';
- public static function get_source();
+ public static function get_source();
- public static function get_namespace();
+ public static function get_namespace();
- public static function get_tagname();
+ public static function get_tagname();
- public static function is_multi();
+ public static function is_multi();
- public static function maxlength();
+ public static function maxlength();
- public static function minlength();
+ public static function minlength();
- public static function get_type();
+ public static function get_type();
- public static function is_deprecated();
+ public static function is_deprecated();
- public static function available_values();
+ public static function available_values();
- public static function is_readonly();
+ public static function is_readonly();
- public static function is_mandatory();
+ public static function is_mandatory();
}
diff --git a/lib/classes/module/admin.class.php b/lib/classes/module/admin.class.php
index d8c71da1fe..c38c707a4a 100644
--- a/lib/classes/module/admin.class.php
+++ b/lib/classes/module/admin.class.php
@@ -18,71 +18,63 @@
class module_admin
{
- function getTree($position=false)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
-
- $usr_id = $session->get_usr_id();
-
- $user = User_Adapter::getInstance($usr_id, $appbox);
-
- $available = array(
- 'connected'
- , 'registrations'
- , 'taskmanager'
- , 'base'
- , 'bases'
- , 'collection'
- , 'user'
- , 'users'
- );
-
- $feature = 'connected';
- $featured = false;
- $position = explode(':', $position);
- if (count($position) > 0)
+ function getTree($position = false)
{
- if (in_array($position[0], $available))
- {
- $feature = $position[0];
- if (isset($position[1]))
- $featured = $position[1];
- }
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+
+ $usr_id = $session->get_usr_id();
+
+ $user = User_Adapter::getInstance($usr_id, $appbox);
+
+ $available = array(
+ 'connected'
+ , 'registrations'
+ , 'taskmanager'
+ , 'base'
+ , 'bases'
+ , 'collection'
+ , 'user'
+ , 'users'
+ );
+
+ $feature = 'connected';
+ $featured = false;
+ $position = explode(':', $position);
+ 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;
+
+ $connbas = $databox->get_connection();
+ } catch (Exception $e) {
+ $off_databoxes[] = $databox;
+ continue;
+ }
+ $databoxes[] = $databox;
+ }
+
+ $params = array(
+ 'feature' => $feature
+ , 'featured' => $featured
+ , 'databoxes' => $databoxes
+ , 'off_databoxes' => $off_databoxes
+ );
+
+
+ $core = \bootstrap::getCore();
+ $twig = $core->getTwig();
+
+ return $twig->render('admin/tree.html.twig', $params);
}
-
- $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();
- }
- catch (Exception $e)
- {
- $off_databoxes[] = $databox;
- continue;
- }
- $databoxes[] = $databox;
- }
-
- $params = array(
- 'feature' => $feature
- , 'featured' => $featured
- , 'databoxes' => $databoxes
- , 'off_databoxes' => $off_databoxes
- );
-
-
- $core = \bootstrap::getCore();
- $twig = $core->getTwig();
-
- return $twig->render('admin/tree.html.twig', $params);
-
- }
-
}
diff --git a/lib/classes/module/client.class.php b/lib/classes/module/client.class.php
index 0e9945e2c8..7af4bc08e5 100644
--- a/lib/classes/module/client.class.php
+++ b/lib/classes/module/client.class.php
@@ -18,25 +18,24 @@
class module_client
{
- public function getLanguage($lng)
- {
- $registry = registry::get_instance();
- $out = array();
- $out['createWinInvite'] = _('paniers:: Quel nom souhaitez vous donner a votre panier ?');
- $out['chuNameEmpty'] = _('paniers:: Quel nom souhaitez vous donner a votre panier ?');
- $out['noDLok'] = _('export:: aucun document n\'est disponible au telechargement');
- $out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez');
- $out['serverName'] = $registry->get('GV_ServerName');
- $out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
- $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['confirmDelBasket'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?');
- $out['annuler'] = _('boutton::annuler');
- $out['fermer'] = _('boutton::fermer');
- $out['renewRss'] = _('boutton::renouveller');
-
- return p4string::jsonencode($out);
- }
+ public function getLanguage($lng)
+ {
+ $registry = registry::get_instance();
+ $out = array();
+ $out['createWinInvite'] = _('paniers:: Quel nom souhaitez vous donner a votre panier ?');
+ $out['chuNameEmpty'] = _('paniers:: Quel nom souhaitez vous donner a votre panier ?');
+ $out['noDLok'] = _('export:: aucun document n\'est disponible au telechargement');
+ $out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez');
+ $out['serverName'] = $registry->get('GV_ServerName');
+ $out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique');
+ $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['confirmDelBasket'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?');
+ $out['annuler'] = _('boutton::annuler');
+ $out['fermer'] = _('boutton::fermer');
+ $out['renewRss'] = _('boutton::renouveller');
+ return p4string::jsonencode($out);
+ }
}
diff --git a/lib/classes/module/console/aboutAuthors.class.php b/lib/classes/module/console/aboutAuthors.class.php
index 212e090a37..038969e793 100644
--- a/lib/classes/module/console/aboutAuthors.class.php
+++ b/lib/classes/module/console/aboutAuthors.class.php
@@ -26,20 +26,19 @@ use Symfony\Component\Console\Command\Command;
class module_console_aboutAuthors extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('List authors and contributors');
+ $this->setDescription('List authors and contributors');
- return $this;
- }
+ return $this;
+ }
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $output->writeln(file_get_contents(__DIR__ . '/../../../../AUTHORS'));
-
- return 0;
- }
+ public function execute(InputInterface $input, OutputInterface $output)
+ {
+ $output->writeln(file_get_contents(__DIR__ . '/../../../../AUTHORS'));
+ return 0;
+ }
}
diff --git a/lib/classes/module/console/aboutLicense.class.php b/lib/classes/module/console/aboutLicense.class.php
index 57df72cc13..8287e9ac3c 100644
--- a/lib/classes/module/console/aboutLicense.class.php
+++ b/lib/classes/module/console/aboutLicense.class.php
@@ -26,20 +26,19 @@ use Symfony\Component\Console\Command\Command;
class module_console_aboutLicense extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('This program license');
+ $this->setDescription('This program license');
- return $this;
- }
+ return $this;
+ }
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $output->writeln(file_get_contents(__DIR__ . '/../../../../LICENSE'));
-
- return 0;
- }
+ public function execute(InputInterface $input, OutputInterface $output)
+ {
+ $output->writeln(file_get_contents(__DIR__ . '/../../../../LICENSE'));
+ return 0;
+ }
}
diff --git a/lib/classes/module/console/checkExtension.class.php b/lib/classes/module/console/checkExtension.class.php
index f96b761720..39bbc75823 100644
--- a/lib/classes/module/console/checkExtension.class.php
+++ b/lib/classes/module/console/checkExtension.class.php
@@ -25,233 +25,202 @@ use Symfony\Component\Console\Command\Command;
class module_console_checkExtension extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Delete a documentation field from a Databox');
-
- $this->addOption('usr_id', 'u', InputOption::VALUE_OPTIONAL, 'Usr_id to use. If no user, get the first available');
-
- $this->addOption('query', '', InputOption::VALUE_OPTIONAL, 'The query', 'last');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
-
- if (!extension_loaded('phrasea2'))
- printf("Missing Extension php-phrasea");
-
- $appbox = \appbox::get_instance(\bootstrap::getCore());
- $registry = $appbox->get_registry();
-
- $usr_id = $input->getOption('usr_id');
-
- try
+ public function __construct($name = null)
{
- $TestUser = \User_Adapter::getInstance($usr_id, $appbox);
- }
- catch (\Exception $e)
- {
- $output->writeln("Wrong user ! ");
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Delete a documentation field from a Databox');
+
+ $this->addOption('usr_id', 'u', InputOption::VALUE_OPTIONAL, 'Usr_id to use. If no user, get the first available');
+
+ $this->addOption('query', '', InputOption::VALUE_OPTIONAL, 'The query', 'last');
+
+ return $this;
}
- $output->writeln(
- sprintf(
- "\nWill do the check with user %s (%s)\n"
- , $TestUser->get_display_name()
- , $TestUser->get_email()
- )
- );
-
- $output->writeln("PHRASEA FUNCTIONS");
-
- foreach (get_extension_funcs("phrasea2") as $function)
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $output->writeln("$function ");
+
+ if ( ! extension_loaded('phrasea2'))
+ printf("Missing Extension php-phrasea");
+
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
+ $registry = $appbox->get_registry();
+
+ $usr_id = $input->getOption('usr_id');
+
+ try {
+ $TestUser = \User_Adapter::getInstance($usr_id, $appbox);
+ } catch (\Exception $e) {
+ $output->writeln("Wrong user ! ");
+
+ return 1;
+ }
+
+ $output->writeln(
+ sprintf(
+ "\nWill do the check with user %s (%s)\n"
+ , $TestUser->get_display_name()
+ , $TestUser->get_email()
+ )
+ );
+
+ $output->writeln("PHRASEA FUNCTIONS");
+
+ foreach (get_extension_funcs("phrasea2") as $function) {
+ $output->writeln("$function ");
+ }
+
+ $Core = \bootstrap::getCore();
+ $configuration = $Core->getConfiguration();
+ $choosenConnection = $configuration->getPhraseanet()->get('database');
+ $connexion = $configuration->getConnexion($choosenConnection);
+ $hostname = $connexion->get('host');
+ $port = $connexion->get('port');
+ $user = $connexion->get('user');
+ $password = $connexion->get('password');
+ $dbname = $connexion->get('dbname');
+
+ $output->writeln("\n-- phrasea_conn --");
+
+ if (phrasea_conn($hostname, $port, $user, $password, $dbname) !== true) {
+ $output->writeln("Failed ! got no connection");
+
+ return 1;
+ } else {
+ $output->writeln("Succes ! got connection");
+ }
+
+ $output->writeln("");
+
+ $output->writeln("\n-- phrasea_info --");
+
+ foreach (phrasea_info() as $key => $value) {
+ $output->writeln("\t$key => $value");
+ }
+
+
+ $output->writeln("");
+
+ $output->writeln("\n-- phrasea_create_session --");
+
+ $sessid = phrasea_create_session((string) $TestUser->get_id());
+
+ if (ctype_digit((string) $sessid)) {
+ $output->writeln("Succes ! got session id $sessid");
+ } else {
+ $output->writeln("Failed ! got no session id");
+
+ return 1;
+ }
+
+ $output->writeln("\n-- phrasea_open_session --");
+
+ $ph_session = phrasea_open_session($sessid, $usr_id);
+
+ if ($ph_session) {
+ $output->writeln("Succes ! got session ");
+ } else {
+ $output->writeln("Failed ! got no session ");
+
+ return 1;
+ }
+
+ $output->writeln("\n-- phrasea_clear_cache --");
+
+ $ret = phrasea_clear_cache($sessid);
+
+ if ($sessid) {
+ $output->writeln("Succes ! got session ");
+ } else {
+ $output->writeln("Failed ! got no session ");
+
+ return 1;
+ }
+
+ $tbases = array();
+
+ foreach ($ph_session["bases"] as $phbase) {
+ $tcoll = array();
+ foreach ($phbase["collections"] as $coll) {
+ $tcoll[] = 0 + $coll["base_id"];
+ }
+ if (sizeof($tcoll) > 0) {
+ $kbase = "S" . $phbase["sbas_id"];
+ $tbases[$kbase] = array();
+ $tbases[$kbase]["sbas_id"] = $phbase["sbas_id"];
+ $tbases[$kbase]["searchcoll"] = $tcoll;
+ $tbases[$kbase]["mask_xor"] = $tbases[$kbase]["mask_and"] = 0;
+
+ $qp = new searchEngine_adapter_phrasea_queryParser();
+ $treeq = $qp->parsequery($input->getOption('query'));
+ $arrayq = $qp->makequery($treeq);
+
+ $tbases[$kbase]["arrayq"] = $arrayq;
+ }
+ }
+
+
+ $output->writeln("\n-- phrasea_query --");
+
+ $nbanswers = 0;
+ foreach ($tbases as $kb => $base) {
+ $tbases[$kb]["results"] = NULL;
+
+ $ret = phrasea_query2(
+ $ph_session["session_id"]
+ , $base["sbas_id"]
+ , $base["searchcoll"]
+ , $base["arrayq"]
+ , $registry->get('GV_sit')
+ , $usr_id
+ , FALSE
+ , PHRASEA_MULTIDOC_DOCONLY
+ , ''
+ , array()
+ );
+
+
+ if ($ret) {
+ $output->writeln("Succes ! got result on sbas_id " . $base["sbas_id"]);
+ } else {
+ $output->writeln("Failed ! No results on sbas_id " . $base["sbas_id"]);
+
+ return 1;
+ }
+
+ $tbases[$kb]["results"] = $ret;
+
+ $nbanswers += $tbases[$kb]["results"]["nbanswers"];
+ }
+
+
+ $output->writeln("Got a total of $nbanswers answers");
+
+ $output->writeln("\n-- phrasea_fetch_results --");
+
+ $rs = phrasea_fetch_results($sessid, $usr_id, 1, true, '[[em]]', '[[/em]]');
+
+ if ($rs) {
+ $output->writeln("Succes ! got result ");
+ } else {
+ $output->writeln("Failed ! got no result ");
+
+ return 1;
+ }
+
+ $output->writeln("\n-- phrasea_close_session --");
+
+ $rs = phrasea_close_session($sessid);
+
+ if ($rs) {
+ $output->writeln("Succes ! closed ! ");
+ } else {
+ $output->writeln("Failed ! not closed ");
+
+ return 1;
+ }
+
+ return 0;
}
-
- $Core = \bootstrap::getCore();
- $configuration = $Core->getConfiguration();
- $choosenConnection = $configuration->getPhraseanet()->get('database');
- $connexion = $configuration->getConnexion($choosenConnection);
- $hostname = $connexion->get('host');
- $port = $connexion->get('port');
- $user = $connexion->get('user');
- $password = $connexion->get('password');
- $dbname = $connexion->get('dbname');
-
- $output->writeln("\n-- phrasea_conn --");
-
- if (phrasea_conn($hostname, $port, $user, $password, $dbname) !== true)
- {
- $output->writeln("Failed ! got no connection");
-
- return 1;
- }
- else
- {
- $output->writeln("Succes ! got connection");
- }
-
- $output->writeln("");
-
- $output->writeln("\n-- phrasea_info --");
-
- foreach (phrasea_info() as $key => $value)
- {
- $output->writeln("\t$key => $value");
- }
-
-
- $output->writeln("");
-
- $output->writeln("\n-- phrasea_create_session --");
-
- $sessid = phrasea_create_session((string) $TestUser->get_id());
-
- if (ctype_digit((string) $sessid))
- {
- $output->writeln("Succes ! got session id $sessid");
- }
- else
- {
- $output->writeln("Failed ! got no session id");
-
- return 1;
- }
-
- $output->writeln("\n-- phrasea_open_session --");
-
- $ph_session = phrasea_open_session($sessid, $usr_id);
-
- if ($ph_session)
- {
- $output->writeln("Succes ! got session ");
- }
- else
- {
- $output->writeln("Failed ! got no session ");
-
- return 1;
- }
-
- $output->writeln("\n-- phrasea_clear_cache --");
-
- $ret = phrasea_clear_cache($sessid);
-
- if ($sessid)
- {
- $output->writeln("Succes ! got session ");
- }
- else
- {
- $output->writeln("Failed ! got no session ");
-
- return 1;
- }
-
- $tbases = array();
-
- foreach ($ph_session["bases"] as $phbase)
- {
- $tcoll = array();
- foreach ($phbase["collections"] as $coll)
- {
- $tcoll[] = 0 + $coll["base_id"];
- }
- if (sizeof($tcoll) > 0)
- {
- $kbase = "S" . $phbase["sbas_id"];
- $tbases[$kbase] = array();
- $tbases[$kbase]["sbas_id"] = $phbase["sbas_id"];
- $tbases[$kbase]["searchcoll"] = $tcoll;
- $tbases[$kbase]["mask_xor"] = $tbases[$kbase]["mask_and"] = 0;
-
- $qp = new searchEngine_adapter_phrasea_queryParser();
- $treeq = $qp->parsequery($input->getOption('query'));
- $arrayq = $qp->makequery($treeq);
-
- $tbases[$kbase]["arrayq"] = $arrayq;
- }
- }
-
-
- $output->writeln("\n-- phrasea_query --");
-
- $nbanswers = 0;
- foreach ($tbases as $kb => $base)
- {
- $tbases[$kb]["results"] = NULL;
-
- $ret = phrasea_query2(
- $ph_session["session_id"]
- , $base["sbas_id"]
- , $base["searchcoll"]
- , $base["arrayq"]
- , $registry->get('GV_sit')
- , $usr_id
- , FALSE
- , PHRASEA_MULTIDOC_DOCONLY
- , ''
- , array()
- );
-
-
- if ($ret)
- {
- $output->writeln("Succes ! got result on sbas_id " . $base["sbas_id"]);
- }
- else
- {
- $output->writeln("Failed ! No results on sbas_id " . $base["sbas_id"]);
-
- return 1;
- }
-
- $tbases[$kb]["results"] = $ret;
-
- $nbanswers += $tbases[$kb]["results"]["nbanswers"];
- }
-
-
- $output->writeln("Got a total of $nbanswers answers");
-
- $output->writeln("\n-- phrasea_fetch_results --");
-
- $rs = phrasea_fetch_results($sessid, $usr_id, 1, true, '[[em]]', '[[/em]]');
-
- if ($rs)
- {
- $output->writeln("Succes ! got result ");
- }
- else
- {
- $output->writeln("Failed ! got no result ");
-
- return 1;
- }
-
- $output->writeln("\n-- phrasea_close_session --");
-
- $rs = phrasea_close_session($sessid);
-
- if ($rs)
- {
- $output->writeln("Succes ! closed ! ");
- }
- else
- {
- $output->writeln("Failed ! not closed ");
-
- return 1;
- }
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/fieldsDelete.class.php b/lib/classes/module/console/fieldsDelete.class.php
index b94f70c366..4041ef52d0 100644
--- a/lib/classes/module/console/fieldsDelete.class.php
+++ b/lib/classes/module/console/fieldsDelete.class.php
@@ -25,74 +25,66 @@ use Symfony\Component\Console\Command\Command;
class module_console_fieldsDelete extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Delete a documentation field from a Databox');
-
- $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
-
- $this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
-
- if (!$input->getOption('sbas_id'))
- throw new \Exception('Missing argument sbas_id');
-
- if (!$input->getOption('meta_struct_id'))
- throw new \Exception('Missing argument meta_struct_id');
-
- try
+ public function __construct($name = null)
{
- $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
- }
- catch (\Exception $e)
- {
- $output->writeln("Invalid databox id ");
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Delete a documentation field from a Databox');
+
+ $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
+
+ $this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
+
+ return $this;
}
- try
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $field = $databox->get_meta_structure()->get_element((int) $input->getOption('meta_struct_id'));
+
+ if ( ! $input->getOption('sbas_id'))
+ throw new \Exception('Missing argument sbas_id');
+
+ if ( ! $input->getOption('meta_struct_id'))
+ throw new \Exception('Missing argument meta_struct_id');
+
+ try {
+ $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
+ } catch (\Exception $e) {
+ $output->writeln("Invalid databox id ");
+
+ return 1;
+ }
+
+ try {
+ $field = $databox->get_meta_structure()->get_element((int) $input->getOption('meta_struct_id'));
+ } catch (\Exception $e) {
+ $output->writeln("Invalid meta struct id ");
+
+ return 1;
+ }
+
+
+ $dialog = $this->getHelperSet()->get('dialog');
+ $continue = mb_strtolower(
+ $dialog->ask(
+ $output
+ , "About to delete " . $field->get_name() . " (y/N) "
+ , 'n'
+ )
+ );
+
+ if ($continue != 'y') {
+ $output->writeln("Request canceled by user");
+
+ return 1;
+ }
+
+ $output->writeln("Deleting ... ");
+
+ $field->delete();
+
+ $output->writeln("Done with success !");
+
+ return 0;
}
- catch (\Exception $e)
- {
- $output->writeln("Invalid meta struct id ");
-
- return 1;
- }
-
-
- $dialog = $this->getHelperSet()->get('dialog');
- $continue = mb_strtolower(
- $dialog->ask(
- $output
- , "About to delete " . $field->get_name() . " (y/N) "
- , 'n'
- )
- );
-
- if($continue != 'y')
- {
- $output->writeln("Request canceled by user");
-
- return 1;
- }
-
- $output->writeln("Deleting ... ");
-
- $field->delete();
-
- $output->writeln("Done with success !");
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/fieldsList.class.php b/lib/classes/module/console/fieldsList.class.php
index b1a5e14be5..db557fed9a 100644
--- a/lib/classes/module/console/fieldsList.class.php
+++ b/lib/classes/module/console/fieldsList.class.php
@@ -25,46 +25,43 @@ use Symfony\Component\Console\Command\Command;
class module_console_fieldsList extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('List all databox fields');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
-
- $appbox = \appbox::get_instance(\bootstrap::getCore());
-
- foreach ($appbox->get_databoxes() as $databox)
+ public function __construct($name = null)
{
- /* @var $databox \databox */
- $output->writeln(
- sprintf(
- "\n ---------------- \nOn databox %s (sbas_id %d) :\n"
- , $databox->get_viewname()
- , $databox->get_sbas_id()
- )
- );
+ parent::__construct($name);
- foreach ($databox->get_meta_structure()->get_elements() as $field)
- {
- $output->writeln(
- sprintf(
- " %2d - %s (%s) %s"
- , $field->get_id()
- , $field->get_name()
- , $field->get_type()
- , ($field->is_multi() ? 'multi ' : '')
- )
- );
- }
+ $this->setDescription('List all databox fields');
+
+ return $this;
}
- return 0;
- }
+ public function execute(InputInterface $input, OutputInterface $output)
+ {
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
+
+ foreach ($appbox->get_databoxes() as $databox) {
+ /* @var $databox \databox */
+ $output->writeln(
+ sprintf(
+ "\n ---------------- \nOn databox %s (sbas_id %d) :\n"
+ , $databox->get_viewname()
+ , $databox->get_sbas_id()
+ )
+ );
+
+ foreach ($databox->get_meta_structure()->get_elements() as $field) {
+ $output->writeln(
+ sprintf(
+ " %2d - %s (%s) %s"
+ , $field->get_id()
+ , $field->get_name()
+ , $field->get_type()
+ , ($field->is_multi() ? 'multi ' : '')
+ )
+ );
+ }
+ }
+
+ return 0;
+ }
}
diff --git a/lib/classes/module/console/fieldsMerge.class.php b/lib/classes/module/console/fieldsMerge.class.php
index d3042a4732..17bcb3af31 100644
--- a/lib/classes/module/console/fieldsMerge.class.php
+++ b/lib/classes/module/console/fieldsMerge.class.php
@@ -25,260 +25,227 @@ use Symfony\Component\Console\Command\Command;
class module_console_fieldsMerge extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Merge databox structure fields');
-
- $this->addOption(
- 'source'
- , 'f'
- , InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
- , 'Metadata structure ids for source'
- , array()
- );
-
- $this->addOption(
- 'destination'
- , 'd'
- , InputOption::VALUE_REQUIRED
- , 'Metadata structure id destination'
- );
-
- $this->addOption(
- 'sbas_id'
- , 's'
- , InputOption::VALUE_REQUIRED
- , 'Databox sbas_id'
- );
-
- $this->addOption(
- 'separator'
- , ''
- , InputOption::VALUE_OPTIONAL
- , 'Separator for concatenation (if destination is monovalued)'
- , ';'
- );
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $output->writeln("");
-
- if (!$input->getOption('sbas_id'))
- throw new \Exception('Missing argument sbas_id');
-
- try
+ public function __construct($name = null)
{
- $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
- }
- catch (\Exception $e)
- {
- $output->writeln("Invalid databox id ");
+ parent::__construct($name);
- return 1;
- }
+ $this->setDescription('Merge databox structure fields');
- $sources = array();
-
- foreach ($input->getOption('source') as $source_id)
- {
- $sources[] = $databox->get_meta_structure()->get_element($source_id);
- }
-
- if (count($sources) === 0)
- throw new \Exception('No sources to proceed');
-
- if (!$input->getOption('destination'))
- throw new \Exception('Missing argument destination');
-
- $separator = ' ' . $input->getOption('separator') . ' ';
-
- $destination = $databox->get_meta_structure()->get_element($input->getOption('destination'));
-
- $types = $multis = array();
-
- foreach ($sources as $source)
- {
- array_push($types, $source->get_type());
- array_push($multis, $source->is_multi());
- }
-
- $types = array_unique($types);
- $multis = array_unique($multis);
-
- if (count(array_unique($types)) > 1)
- {
- $output->writeln(
- sprintf("Warning, trying to merge inconsistent types : %s \n"
- , implode(', ', $types)
- )
- );
- }
-
- if (count(array_unique($multis)) > 1)
- {
- $output->writeln(
- sprintf(
- "Warning, trying to merge mono and multi values fields\n"
- )
- );
- }
-
- $field_names = array();
- foreach ($sources as $source)
- {
- $field_names[] = $source->get_name();
- }
-
- if (count($multis) == 1)
- {
- if ($multis[0] === false && !$destination->is_multi())
- {
- $output->writeln(
- sprintf(
- "You are going to merge mono valued fields in a "
- . "monovalued field , fields will be "
- . "concatenated in the following order : %s"
- , implode($separator, $field_names)
- )
+ $this->addOption(
+ 'source'
+ , 'f'
+ , InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
+ , 'Metadata structure ids for source'
+ , array()
);
- $this->displayHelpConcatenation($output);
- }
- elseif ($multis[0] === true && !$destination->is_multi())
- {
- $output->writeln(
- sprintf(
- "You are going to merge multi valued fields in a "
- . "monovalued field , fields will be "
- . "concatenated in the following order : %s"
- , implode(' ', $field_names)
- )
+
+ $this->addOption(
+ 'destination'
+ , 'd'
+ , InputOption::VALUE_REQUIRED
+ , 'Metadata structure id destination'
);
- $this->displayHelpConcatenation($output);
- }
- elseif ($multis[0] === false && $destination->is_multi())
- {
- $output->writeln(
- sprintf(
- "You are going to merge mono valued fields in a "
- . "multivalued field "
- )
+
+ $this->addOption(
+ 'sbas_id'
+ , 's'
+ , InputOption::VALUE_REQUIRED
+ , 'Databox sbas_id'
);
- }
- elseif ($multis[0] === true && $destination->is_multi())
- {
- $output->writeln(
- sprintf(
- "You are going to merge multi valued fields in a "
- . "multivalued field "
- )
+
+ $this->addOption(
+ 'separator'
+ , ''
+ , InputOption::VALUE_OPTIONAL
+ , 'Separator for concatenation (if destination is monovalued)'
+ , ';'
);
- }
- }
- elseif ($destination->is_multi())
- {
- $output->writeln(
- sprintf(
- "You are going to merge mixed valued fields in a "
- . "multivalued field"
- )
- );
- }
- else
- {
- $output->writeln(
- sprintf(
- "You are going to merge mixed valued fields in a "
- . "monovalued field , fields will be "
- . "concatenated in the following order : %s"
- , implode($separator, $field_names)
- )
- );
- $this->displayHelpConcatenation($output);
+
+ return $this;
}
- $start = 0;
- $quantity = 100;
-
- do
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $sql = 'SELECT record_id FROM record
+ $output->writeln("");
+
+ if ( ! $input->getOption('sbas_id'))
+ throw new \Exception('Missing argument sbas_id');
+
+ try {
+ $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
+ } catch (\Exception $e) {
+ $output->writeln("Invalid databox id ");
+
+ return 1;
+ }
+
+ $sources = array();
+
+ foreach ($input->getOption('source') as $source_id) {
+ $sources[] = $databox->get_meta_structure()->get_element($source_id);
+ }
+
+ if (count($sources) === 0)
+ throw new \Exception('No sources to proceed');
+
+ if ( ! $input->getOption('destination'))
+ throw new \Exception('Missing argument destination');
+
+ $separator = ' ' . $input->getOption('separator') . ' ';
+
+ $destination = $databox->get_meta_structure()->get_element($input->getOption('destination'));
+
+ $types = $multis = array();
+
+ foreach ($sources as $source) {
+ array_push($types, $source->get_type());
+ array_push($multis, $source->is_multi());
+ }
+
+ $types = array_unique($types);
+ $multis = array_unique($multis);
+
+ if (count(array_unique($types)) > 1) {
+ $output->writeln(
+ sprintf("Warning, trying to merge inconsistent types : %s \n"
+ , implode(', ', $types)
+ )
+ );
+ }
+
+ if (count(array_unique($multis)) > 1) {
+ $output->writeln(
+ sprintf(
+ "Warning, trying to merge mono and multi values fields\n"
+ )
+ );
+ }
+
+ $field_names = array();
+ foreach ($sources as $source) {
+ $field_names[] = $source->get_name();
+ }
+
+ if (count($multis) == 1) {
+ if ($multis[0] === false && ! $destination->is_multi()) {
+ $output->writeln(
+ sprintf(
+ "You are going to merge mono valued fields in a "
+ . "monovalued field , fields will be "
+ . "concatenated in the following order : %s"
+ , implode($separator, $field_names)
+ )
+ );
+ $this->displayHelpConcatenation($output);
+ } elseif ($multis[0] === true && ! $destination->is_multi()) {
+ $output->writeln(
+ sprintf(
+ "You are going to merge multi valued fields in a "
+ . "monovalued field , fields will be "
+ . "concatenated in the following order : %s"
+ , implode(' ', $field_names)
+ )
+ );
+ $this->displayHelpConcatenation($output);
+ } elseif ($multis[0] === false && $destination->is_multi()) {
+ $output->writeln(
+ sprintf(
+ "You are going to merge mono valued fields in a "
+ . "multivalued field "
+ )
+ );
+ } elseif ($multis[0] === true && $destination->is_multi()) {
+ $output->writeln(
+ sprintf(
+ "You are going to merge multi valued fields in a "
+ . "multivalued field "
+ )
+ );
+ }
+ } elseif ($destination->is_multi()) {
+ $output->writeln(
+ sprintf(
+ "You are going to merge mixed valued fields in a "
+ . "multivalued field"
+ )
+ );
+ } else {
+ $output->writeln(
+ sprintf(
+ "You are going to merge mixed valued fields in a "
+ . "monovalued field , fields will be "
+ . "concatenated in the following order : %s"
+ , implode($separator, $field_names)
+ )
+ );
+ $this->displayHelpConcatenation($output);
+ }
+
+ $start = 0;
+ $quantity = 100;
+
+ do {
+ $sql = 'SELECT record_id FROM record
ORDER BY record_id LIMIT ' . $start . ', ' . $quantity;
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute();
- $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($results as $row)
- {
- $record = $databox->get_record($row['record_id']);
+ foreach ($results as $row) {
+ $record = $databox->get_record($row['record_id']);
- $datas = array();
+ $datas = array();
- foreach ($sources as $source)
- {
- try
- {
- $value = $record->get_caption()->get_field($source->get_name())->get_value();
- }
- catch (\Exception $e)
- {
- $value = array();
- }
- if (!is_array($value))
- {
- $value = array($value);
- }
+ foreach ($sources as $source) {
+ try {
+ $value = $record->get_caption()->get_field($source->get_name())->get_value();
+ } catch (\Exception $e) {
+ $value = array();
+ }
+ if ( ! is_array($value)) {
+ $value = array($value);
+ }
- $datas = array_merge($datas, $value);
- }
+ $datas = array_merge($datas, $value);
+ }
- $datas = array_unique($datas);
+ $datas = array_unique($datas);
- if (!$destination->is_multi())
- {
- $datas = array(implode($separator, $datas));
- }
+ if ( ! $destination->is_multi()) {
+ $datas = array(implode($separator, $datas));
+ }
- try
- {
- $record->get_caption()->get_field($destination->get_name())->set_value($datas);
- }
- catch (\Exception $e)
- {
- $record->set_metadatas(
- array(
- array(
- 'meta_struct_id' => $destination->get_id()
- , 'meta_id' => null
- , 'value' => $datas
- )
- )
- , true
- );
- }
- unset($record);
- }
+ try {
+ $record->get_caption()->get_field($destination->get_name())->set_value($datas);
+ } catch (\Exception $e) {
+ $record->set_metadatas(
+ array(
+ array(
+ 'meta_struct_id' => $destination->get_id()
+ , 'meta_id' => null
+ , 'value' => $datas
+ )
+ )
+ , true
+ );
+ }
+ unset($record);
+ }
- $start += $quantity;
+ $start += $quantity;
+ } while (count($results) > 0);
+
+ return 0;
}
- while (count($results) > 0);
- return 0;
- }
+ protected function displayHelpConcatenation(OutputInterface $output)
+ {
- protected function displayHelpConcatenation(OutputInterface $output)
- {
-
- $output->writeln("\nYou can choose the concatenation order in the "
- . "commandline (first option is first value) and set a separator "
- . "with the --separator option)");
-
- return $this;
- }
+ $output->writeln("\nYou can choose the concatenation order in the "
+ . "commandline (first option is first value) and set a separator "
+ . "with the --separator option)");
+ return $this;
+ }
}
diff --git a/lib/classes/module/console/fieldsRename.class.php b/lib/classes/module/console/fieldsRename.class.php
index adc1a691f3..944992ae11 100644
--- a/lib/classes/module/console/fieldsRename.class.php
+++ b/lib/classes/module/console/fieldsRename.class.php
@@ -25,82 +25,74 @@ use Symfony\Component\Console\Command\Command;
class module_console_fieldsRename extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Rename a documentation field from a Databox');
-
- $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
-
- $this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
-
- $this->addOption('name', 'n', InputOption::VALUE_REQUIRED, 'The new name');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
-
- if (!$input->getOption('sbas_id'))
- throw new \Exception('Missing argument sbas_id');
-
- if (!$input->getOption('meta_struct_id'))
- throw new \Exception('Missing argument meta_struct_id');
-
- if (!$input->getOption('name'))
- throw new \Exception('Missing argument name');
-
- $new_name = $input->getOption('name');
-
- try
+ public function __construct($name = null)
{
- $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
- }
- catch (\Exception $e)
- {
- $output->writeln("Invalid databox id ");
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Rename a documentation field from a Databox');
+
+ $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED, 'Databox sbas_id');
+
+ $this->addOption('meta_struct_id', 'm', InputOption::VALUE_REQUIRED, 'Databox meta structure Id');
+
+ $this->addOption('name', 'n', InputOption::VALUE_REQUIRED, 'The new name');
+
+ return $this;
}
- try
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $field = $databox->get_meta_structure()->get_element((int) $input->getArgument('meta_struct_id'));
+
+ if ( ! $input->getOption('sbas_id'))
+ throw new \Exception('Missing argument sbas_id');
+
+ if ( ! $input->getOption('meta_struct_id'))
+ throw new \Exception('Missing argument meta_struct_id');
+
+ if ( ! $input->getOption('name'))
+ throw new \Exception('Missing argument name');
+
+ $new_name = $input->getOption('name');
+
+ try {
+ $databox = \databox::get_instance((int) $input->getOption('sbas_id'));
+ } catch (\Exception $e) {
+ $output->writeln("Invalid databox id ");
+
+ return 1;
+ }
+
+ try {
+ $field = $databox->get_meta_structure()->get_element((int) $input->getArgument('meta_struct_id'));
+ } catch (\Exception $e) {
+ $output->writeln("Invalid meta struct id ");
+
+ return 1;
+ }
+
+
+ $dialog = $this->getHelperSet()->get('dialog');
+ $continue = mb_strtolower(
+ $dialog->ask(
+ $output
+ , "About to rename " . $field->get_name() . " into " . $new_name . " (y/N) "
+ , 'n'
+ )
+ );
+
+ if ($continue != 'y') {
+ $output->writeln("Request canceled by user");
+
+ return 1;
+ }
+
+ $output->writeln("Renaming ... ");
+
+ $field->set_name($new_name);
+ $field->save();
+
+ $output->writeln("Done with success !");
+
+ return 0;
}
- catch (\Exception $e)
- {
- $output->writeln("Invalid meta struct id ");
-
- return 1;
- }
-
-
- $dialog = $this->getHelperSet()->get('dialog');
- $continue = mb_strtolower(
- $dialog->ask(
- $output
- , "About to rename " . $field->get_name() . " into ".$new_name." (y/N) "
- , 'n'
- )
- );
-
- if($continue != 'y')
- {
- $output->writeln("Request canceled by user");
-
- return 1;
- }
-
- $output->writeln("Renaming ... ");
-
- $field->set_name($new_name);
- $field->save();
-
- $output->writeln("Done with success !");
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/fileEnsureDevSetting.class.php b/lib/classes/module/console/fileEnsureDevSetting.class.php
index 01e8cf8056..b79976af61 100644
--- a/lib/classes/module/console/fileEnsureDevSetting.class.php
+++ b/lib/classes/module/console/fileEnsureDevSetting.class.php
@@ -26,897 +26,756 @@ use Symfony\Component\Yaml;
*/
class module_console_fileEnsureDevSetting extends Command
{
+ const ALERT = 1;
+ const ERROR = 0;
- const ALERT = 1;
- const ERROR = 0;
+ /**
+ *
+ * @var \Alchemy\Phrasea\Core\Configuration
+ */
+ protected $configuration;
+ protected $testSuite = array(
+ 'checkPhraseanetScope'
+ , 'checkDatabaseScope'
+ , 'checkTeamplateEngineService'
+ , 'checkOrmService'
+ , 'checkCacheService'
+ , 'checkOpcodeCacheService'
+ );
+ protected $errors = 0;
+ protected $alerts = 0;
- /**
- *
- * @var \Alchemy\Phrasea\Core\Configuration
- */
- protected $configuration;
- protected $testSuite = array(
- 'checkPhraseanetScope'
- , 'checkDatabaseScope'
- , 'checkTeamplateEngineService'
- , 'checkOrmService'
- , 'checkCacheService'
- , 'checkOpcodeCacheService'
- );
- protected $errors = 0;
- protected $alerts = 0;
-
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Ensure development settings');
-
- $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
- $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
-
- $environnement = $input->getArgument('conf');
-
- $this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
-
- if (!$this->configuration->isInstalled())
+ public function __construct($name = null)
{
- $output->writeln(sprintf("\nPhraseanet is not installed\n"));
+ parent::__construct($name);
+
+ $this->setDescription('Ensure development settings');
+
+ $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
+ $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
+
+ return $this;
}
- $this->checkParse($output);
- $output->writeln(sprintf("Will Ensure Production Settings on %s ", $this->configuration->getEnvironnement()));
-
- $this->runTests($output);
-
- $retval = $this->errors;
- if ($input->getOption('strict'))
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $retval += $this->alerts;
- }
+ $specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
- if ($retval > 0)
- {
- $output->writeln("\nSome errors found in your conf ");
- }
- else
- {
- $output->writeln("\nYour dev settings are setted correctly ! Enjoy ");
- }
- $output->writeln('End');
+ $environnement = $input->getArgument('conf');
- return $retval;
- }
+ $this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
- private function runTests(OutputInterface $output)
- {
- foreach ($this->testSuite as $test)
- {
- $display = "";
- switch ($test)
- {
- case 'checkPhraseanetScope' :
- $display = "Phraseanet Configuration";
- break;
- case 'checkDatabaseScope' :
- $display = "Database";
- break;
- case 'checkTeamplateEngineService' :
- $display = "Template Engine";
- break;
- case 'checkOrmService' :
- $display = "ORM";
- break;
- case 'checkCacheService' :
- $display = "Cache";
- break;
- case 'checkOpcodeCacheService' :
- $display = "Opcode";
- break;
- default:
- throw new \Exception('Unknown test');
- break;
- }
-
- $output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
-
- call_user_func(array($this, $test), $output);
- }
- }
-
- private function checkParse(OutputInterface $output)
- {
-
- if (!$this->configuration->getConfigurations())
- {
- throw new \Exception("Unable to load configurations\n");
- }
- if (!$this->configuration->getConnexions())
- {
- throw new \Exception("Unable to load connexions\n");
- }
- if (!$this->configuration->getServices())
- {
- throw new \Exception("Unable to load services\n");
- }
-
- return;
- }
-
- private function checkCacheService(OutputInterface $output)
- {
- $cache = $this->configuration->getCache();
-
-
- if ($this->probeCacheService($output, $cache))
- {
- if ($this->recommendedCacheService($output, $cache, true))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'Cache server recommended ';
- $this->alerts++;
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message);
-
-
- $this->printConf($output, "\t" . 'service', $cache, false, $verification);
- $this->verifyCacheOptions($output, $cache);
- }
-
- private function checkOpcodeCacheService(OutputInterface $output)
- {
- $cache = $this->configuration->getOpcodeCache();
-
-
- if ($this->probeCacheService($output, $cache))
- {
- if ($this->recommendedCacheService($output, $cache, false))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'No cache required ';
- $this->errors++;
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message);
-
-
- $this->printConf($output, "\t" . 'service', $cache, false, $verification);
- $this->verifyCacheOptions($output, $cache);
- }
-
- private function checkPhraseanetScope(OutputInterface $output)
- {
- $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
-
- $phraseanet = $this->configuration->getPhraseanet();
-
- foreach ($phraseanet->all() as $conf => $value)
- {
- switch ($conf)
- {
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- case 'servername':
- $url = $value;
- $required = array_diff($required, array($conf));
-
- $parseUrl = parse_url($url);
-
- if (empty($url))
- {
- $message = "should not be empty ";
- $this->errors++;
- }
- elseif ($url == 'http://sub.domain.tld/')
- {
- $this->alerts++;
- $message = "may be wrong ";
- }
- elseif (!filter_var($url, FILTER_VALIDATE_URL))
- {
- $message = "not valid ";
- $this->errors++;
- }
- else
- {
- $message = "OK ";
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'maintenance':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== false)
- {
- $message = 'Should be true ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'debug':
- case 'display_errors':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== true)
- {
- $message = 'Should be true ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'database':
- $required = array_diff($required, array($conf));
- try
- {
- $service = $this->configuration->getConnexion($value);
- if ($this->verifyDatabaseConnexion($service))
- {
- $message = 'OK ';
- }
- else
- {
- $message = 'Connection not available ';
- $this->errors++;
- }
- }
- catch (\Exception $e)
- {
- $message = 'Unknown connection ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- private function checkDatabaseScope(OutputInterface $output)
- {
- $connexionName = $this->configuration->getPhraseanet()->get('database');
- $connexion = $this->configuration->getConnexion($connexionName);
-
- try
- {
- if ($this->verifyDatabaseConnexion($connexion))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
- }
- catch (\Exception $e)
- {
-
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message));
-
- $required = array('driver');
-
- if (!$connexion->has('driver'))
- {
- $output->writeln("\nConnection has no driver ");
- $this->errors++;
- }
- elseif ($connexion->get('driver') == 'pdo_mysql')
- {
- $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
- }
- elseif ($connexion->get('driver') == 'pdo_sqlite')
- {
- $required = array('driver', 'path', 'charset');
- }
- else
- {
- $output->writeln("\nYour driver is not managed ");
- $this->errors++;
- }
-
- foreach ($connexion->all() as $conf => $value)
- {
- switch ($conf)
- {
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- case 'charset':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
- if ($value !== 'UTF8')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'path':
- $required = array_diff($required, array($conf));
- $message = is_writable(dirname($value)) ? 'OK ' : 'Not writeable ';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'dbname':
- case 'user':
- case 'host':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'port':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!ctype_digit($value))
- {
- $message = 'Should be ctype_digit ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'password':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $value = '***********';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'driver':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== 'pdo_mysql')
- {
- $message = 'MySQL recommended ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
- {
- try
- {
- $config = new \Doctrine\DBAL\Configuration();
- $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
-
- return true;
- }
- catch (\Exception $e)
- {
-
- }
-
- return false;
- }
-
- private function checkTeamplateEngineService(OutputInterface $output)
- {
- $templateEngineName = $this->configuration->getTemplating();
- $configuration = $this->configuration->getService($templateEngineName);
-
- try
- {
- Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
- $work_message = 'Works ! ';
- }
- catch (\Exception $e)
- {
- $work_message = 'Failed - could not load template engine ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message));
-
- if (!$configuration->has('type'))
- {
- $output->writeln("\nConfiguration has no type ");
- $this->errors++;
- }
- elseif ($configuration->get('type') == 'TemplateEngine\\Twig')
- {
- $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
- }
- else
- {
- $output->writeln("\nYour type is not managed ");
- $this->errors++;
- }
-
-
-
- foreach ($configuration->all() as $conf => $value)
- {
- switch ($conf)
- {
- case 'type':
- $message = 'OK ';
-
- if ($value !== 'TemplateEngine\\Twig')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'options':
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
- break;
- }
- }
-
- foreach ($configuration->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'debug';
- case 'strict_variables';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== true)
- {
- $message = 'Should be false ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- case 'autoescape';
- case 'optimizer';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== true)
- {
- $message = 'Should be true ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- case 'charset';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== 'utf-8')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized ');
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- private function checkOrmService(OutputInterface $output)
- {
- $ormName = $this->configuration->getOrm();
- $configuration = $this->configuration->getService($ormName);
-
- try
- {
- $service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
- $work_message = 'Works ! ';
- }
- catch (\Exception $e)
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message));
-
-
-
- if (!$configuration->has('type'))
- {
- $output->writeln("\nConfiguration has no type ");
- $this->errors++;
- }
- elseif ($configuration->get('type') == 'Orm\\Doctrine')
- {
- $required = array('debug', 'dbal', 'cache');
- }
- else
- {
- $output->writeln("\nYour type is not managed ");
- $this->errors++;
- }
-
-
-
- foreach ($configuration->all() as $conf => $value)
- {
- switch ($conf)
- {
- case 'type':
- $message = $value == 'Orm\\Doctrine' ? 'OK ' : 'Not recognized ';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'options':
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
- break;
- }
- }
-
-
- foreach ($configuration->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'log':
- $message = 'OK ';
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'cache':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be Array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
-
- $required_caches = array('query', 'result', 'metadata');
- foreach ($value as $name => $cache_type)
- {
- $required_caches = array_diff($required_caches, array($name));
-
- foreach ($cache_type as $key_cache => $value_cache)
- {
- switch ($key_cache)
- {
- case 'service':
- if ($this->probeCacheService($output, $value_cache))
- {
- $server = $name === 'result';
- if ($this->recommendedCacheService($output, $value_cache, $server))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $this->errors++;
- $work_message = 'No cache required ';
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", $name, $work_message);
-
-
- $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
- $this->verifyCacheOptions($output, $value_cache);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized ');
- break;
- }
- if (!isset($cache_type['service']))
- {
- $output->writeln('Miss service for %s ', $cache_type);
- $this->errors++;
- }
- }
- }
-
- if (count($required_caches) > 0)
- {
- $output->writeln(sprintf('Miss required caches %s ', implode(', ', $required_caches)));
- $this->errors++;
- }
- break;
- case 'debug':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== true)
- {
- $message = 'Should be true ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'dbal':
- $required = array_diff($required, array($conf));
- try
- {
- $connexion = $this->configuration->getConnexion($value);
- $this->verifyDatabaseConnexion($connexion);
- $message = 'OK ';
- }
- catch (\Exception $e)
- {
- $message = 'Failed ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
- {
- try
- {
- $conf = $this->configuration->getService($ServiceName);
-
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $conf
- );
- }
- catch (\Exception $e)
- {
- return false;
- }
-
- $required_options = array();
-
- switch ($Service->getType())
- {
- default:
- break;
- case 'memcache':
- $required_options = array('host', 'port');
- break;
- }
-
- if ($required_options)
- {
- foreach ($conf->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'host';
- $required_options = array_diff($required_options, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t\t" . $conf, $value, false, $message);
- break;
- case 'port';
- $required_options = array_diff($required_options, array($conf));
- $message = 'OK ';
-
- if (!ctype_digit($value))
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, "\t\t" . $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized ');
- break;
+ if ( ! $this->configuration->isInstalled()) {
+ $output->writeln(sprintf("\nPhraseanet is not installed\n"));
}
- }
+
+ $this->checkParse($output);
+ $output->writeln(sprintf("Will Ensure Production Settings on %s ", $this->configuration->getEnvironnement()));
+
+ $this->runTests($output);
+
+ $retval = $this->errors;
+ if ($input->getOption('strict')) {
+ $retval += $this->alerts;
+ }
+
+ if ($retval > 0) {
+ $output->writeln("\nSome errors found in your conf ");
+ } else {
+ $output->writeln("\nYour dev settings are setted correctly ! Enjoy ");
+ }
+ $output->writeln('End');
+
+ return $retval;
}
- if (count($required_options) > 0)
+ private function runTests(OutputInterface $output)
{
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required_options)));
- $this->errors++;
- }
- }
+ foreach ($this->testSuite as $test) {
+ $display = "";
+ switch ($test) {
+ case 'checkPhraseanetScope' :
+ $display = "Phraseanet Configuration";
+ break;
+ case 'checkDatabaseScope' :
+ $display = "Database";
+ break;
+ case 'checkTeamplateEngineService' :
+ $display = "Template Engine";
+ break;
+ case 'checkOrmService' :
+ $display = "ORM";
+ break;
+ case 'checkCacheService' :
+ $display = "Cache";
+ break;
+ case 'checkOpcodeCacheService' :
+ $display = "Opcode";
+ break;
+ default:
+ throw new \Exception('Unknown test');
+ break;
+ }
- protected function probeCacheService(OutputInterface $output, $ServiceName)
- {
- try
- {
- $originalConfiguration = $this->configuration->getService($ServiceName);
+ $output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $originalConfiguration
- );
- }
- catch (\Exception $e)
- {
- return false;
+ call_user_func(array($this, $test), $output);
+ }
}
- if ($Service->getDriver()->isServer())
+ private function checkParse(OutputInterface $output)
{
- switch ($Service->getType())
- {
- default:
- return false;
- break;
- case 'memcache':
- if (!@memcache_connect($Service->getHost(), $Service->getPort()))
- {
+
+ if ( ! $this->configuration->getConfigurations()) {
+ throw new \Exception("Unable to load configurations\n");
+ }
+ if ( ! $this->configuration->getConnexions()) {
+ throw new \Exception("Unable to load connexions\n");
+ }
+ if ( ! $this->configuration->getServices()) {
+ throw new \Exception("Unable to load services\n");
+ }
+
+ return;
+ }
+
+ private function checkCacheService(OutputInterface $output)
+ {
+ $cache = $this->configuration->getCache();
+
+
+ if ($this->probeCacheService($output, $cache)) {
+ if ($this->recommendedCacheService($output, $cache, true)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'Cache server recommended ';
+ $this->alerts ++;
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message);
+
+
+ $this->printConf($output, "\t" . 'service', $cache, false, $verification);
+ $this->verifyCacheOptions($output, $cache);
+ }
+
+ private function checkOpcodeCacheService(OutputInterface $output)
+ {
+ $cache = $this->configuration->getOpcodeCache();
+
+
+ if ($this->probeCacheService($output, $cache)) {
+ if ($this->recommendedCacheService($output, $cache, false)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'No cache required ';
+ $this->errors ++;
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message);
+
+
+ $this->printConf($output, "\t" . 'service', $cache, false, $verification);
+ $this->verifyCacheOptions($output, $cache);
+ }
+
+ private function checkPhraseanetScope(OutputInterface $output)
+ {
+ $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
+
+ $phraseanet = $this->configuration->getPhraseanet();
+
+ foreach ($phraseanet->all() as $conf => $value) {
+ switch ($conf) {
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ case 'servername':
+ $url = $value;
+ $required = array_diff($required, array($conf));
+
+ $parseUrl = parse_url($url);
+
+ if (empty($url)) {
+ $message = "should not be empty ";
+ $this->errors ++;
+ } elseif ($url == 'http://sub.domain.tld/') {
+ $this->alerts ++;
+ $message = "may be wrong ";
+ } elseif ( ! filter_var($url, FILTER_VALIDATE_URL)) {
+ $message = "not valid ";
+ $this->errors ++;
+ } else {
+ $message = "OK ";
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'maintenance':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== false) {
+ $message = 'Should be true ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'debug':
+ case 'display_errors':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== true) {
+ $message = 'Should be true ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'database':
+ $required = array_diff($required, array($conf));
+ try {
+ $service = $this->configuration->getConnexion($value);
+ if ($this->verifyDatabaseConnexion($service)) {
+ $message = 'OK ';
+ } else {
+ $message = 'Connection not available ';
+ $this->errors ++;
+ }
+ } catch (\Exception $e) {
+ $message = 'Unknown connection ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ private function checkDatabaseScope(OutputInterface $output)
+ {
+ $connexionName = $this->configuration->getPhraseanet()->get('database');
+ $connexion = $this->configuration->getConnexion($connexionName);
+
+ try {
+ if ($this->verifyDatabaseConnexion($connexion)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+ } catch (\Exception $e) {
+
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message));
+
+ $required = array('driver');
+
+ if ( ! $connexion->has('driver')) {
+ $output->writeln("\nConnection has no driver ");
+ $this->errors ++;
+ } elseif ($connexion->get('driver') == 'pdo_mysql') {
+ $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
+ } elseif ($connexion->get('driver') == 'pdo_sqlite') {
+ $required = array('driver', 'path', 'charset');
+ } else {
+ $output->writeln("\nYour driver is not managed ");
+ $this->errors ++;
+ }
+
+ foreach ($connexion->all() as $conf => $value) {
+ switch ($conf) {
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ case 'charset':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+ if ($value !== 'UTF8') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'path':
+ $required = array_diff($required, array($conf));
+ $message = is_writable(dirname($value)) ? 'OK ' : 'Not writeable ';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'dbname':
+ case 'user':
+ case 'host':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'port':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! ctype_digit($value)) {
+ $message = 'Should be ctype_digit ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'password':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $value = '***********';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'driver':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== 'pdo_mysql') {
+ $message = 'MySQL recommended ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
+ {
+ try {
+ $config = new \Doctrine\DBAL\Configuration();
+ $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
+
+ return true;
+ } catch (\Exception $e) {
+
+ }
+
+ return false;
+ }
+
+ private function checkTeamplateEngineService(OutputInterface $output)
+ {
+ $templateEngineName = $this->configuration->getTemplating();
+ $configuration = $this->configuration->getService($templateEngineName);
+
+ try {
+ Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
+ $work_message = 'Works ! ';
+ } catch (\Exception $e) {
+ $work_message = 'Failed - could not load template engine ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message));
+
+ if ( ! $configuration->has('type')) {
+ $output->writeln("\nConfiguration has no type ");
+ $this->errors ++;
+ } elseif ($configuration->get('type') == 'TemplateEngine\\Twig') {
+ $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
+ } else {
+ $output->writeln("\nYour type is not managed ");
+ $this->errors ++;
+ }
+
+
+
+ foreach ($configuration->all() as $conf => $value) {
+ switch ($conf) {
+ case 'type':
+ $message = 'OK ';
+
+ if ($value !== 'TemplateEngine\\Twig') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'options':
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
+ break;
+ }
+ }
+
+ foreach ($configuration->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'debug';
+ case 'strict_variables';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== true) {
+ $message = 'Should be false ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ case 'autoescape';
+ case 'optimizer';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== true) {
+ $message = 'Should be true ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ case 'charset';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== 'utf-8') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ private function checkOrmService(OutputInterface $output)
+ {
+ $ormName = $this->configuration->getOrm();
+ $configuration = $this->configuration->getService($ormName);
+
+ try {
+ $service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
+ $work_message = 'Works ! ';
+ } catch (\Exception $e) {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message));
+
+
+
+ if ( ! $configuration->has('type')) {
+ $output->writeln("\nConfiguration has no type ");
+ $this->errors ++;
+ } elseif ($configuration->get('type') == 'Orm\\Doctrine') {
+ $required = array('debug', 'dbal', 'cache');
+ } else {
+ $output->writeln("\nYour type is not managed ");
+ $this->errors ++;
+ }
+
+
+
+ foreach ($configuration->all() as $conf => $value) {
+ switch ($conf) {
+ case 'type':
+ $message = $value == 'Orm\\Doctrine' ? 'OK ' : 'Not recognized ';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'options':
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
+ break;
+ }
+ }
+
+
+ foreach ($configuration->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'log':
+ $message = 'OK ';
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'cache':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be Array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+
+ $required_caches = array('query', 'result', 'metadata');
+ foreach ($value as $name => $cache_type) {
+ $required_caches = array_diff($required_caches, array($name));
+
+ foreach ($cache_type as $key_cache => $value_cache) {
+ switch ($key_cache) {
+ case 'service':
+ if ($this->probeCacheService($output, $value_cache)) {
+ $server = $name === 'result';
+ if ($this->recommendedCacheService($output, $value_cache, $server)) {
+ $work_message = 'Works ! ';
+ } else {
+ $this->errors ++;
+ $work_message = 'No cache required ';
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", $name, $work_message);
+
+
+ $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
+ $this->verifyCacheOptions($output, $value_cache);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized ');
+ break;
+ }
+ if ( ! isset($cache_type['service'])) {
+ $output->writeln('Miss service for %s ', $cache_type);
+ $this->errors ++;
+ }
+ }
+ }
+
+ if (count($required_caches) > 0) {
+ $output->writeln(sprintf('Miss required caches %s ', implode(', ', $required_caches)));
+ $this->errors ++;
+ }
+ break;
+ case 'debug':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== true) {
+ $message = 'Should be true ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'dbal':
+ $required = array_diff($required, array($conf));
+ try {
+ $connexion = $this->configuration->getConnexion($value);
+ $this->verifyDatabaseConnexion($connexion);
+ $message = 'OK ';
+ } catch (\Exception $e) {
+ $message = 'Failed ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
+ {
+ try {
+ $conf = $this->configuration->getService($ServiceName);
+
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $conf
+ );
+ } catch (\Exception $e) {
return false;
- }
- break;
- }
+ }
+
+ $required_options = array();
+
+ switch ($Service->getType()) {
+ default:
+ break;
+ case 'memcache':
+ $required_options = array('host', 'port');
+ break;
+ }
+
+ if ($required_options) {
+ foreach ($conf->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'host';
+ $required_options = array_diff($required_options, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t\t" . $conf, $value, false, $message);
+ break;
+ case 'port';
+ $required_options = array_diff($required_options, array($conf));
+ $message = 'OK ';
+
+ if ( ! ctype_digit($value)) {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, "\t\t" . $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+ }
+
+ if (count($required_options) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required_options)));
+ $this->errors ++;
+ }
}
- return true;
- }
-
- protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
- {
- try
+ protected function probeCacheService(OutputInterface $output, $ServiceName)
{
- $originalConfiguration = $this->configuration->getService($ServiceName);
+ try {
+ $originalConfiguration = $this->configuration->getService($ServiceName);
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $originalConfiguration
- );
- }
- catch (\Exception $e)
- {
- return false;
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $originalConfiguration
+ );
+ } catch (\Exception $e) {
+ return false;
+ }
+
+ if ($Service->getDriver()->isServer()) {
+ switch ($Service->getType()) {
+ default:
+ return false;
+ break;
+ case 'memcache':
+ if ( ! @memcache_connect($Service->getHost(), $Service->getPort())) {
+ return false;
+ }
+ break;
+ }
+ }
+
+ return true;
}
- return $Service->getType() === 'array';
- }
+ protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
+ {
+ try {
+ $originalConfiguration = $this->configuration->getService($ServiceName);
- private function printConf($output, $scope, $value, $scopage = false, $message = '')
- {
- if (is_array($value))
- {
- foreach ($value as $key => $val)
- {
- if ($scopage)
- $key = $scope . ":" . $key;
- $this->printConf($output, $key, $val, $scopage, '');
- }
- }
- elseif (is_bool($value))
- {
- if ($value === false)
- {
- $value = 'false';
- }
- elseif ($value === true)
- {
- $value = 'true';
- }
- $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
- }
- elseif (!empty($value))
- {
- $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
- }
- }
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $originalConfiguration
+ );
+ } catch (\Exception $e) {
+ return false;
+ }
+ return $Service->getType() === 'array';
+ }
+
+ private function printConf($output, $scope, $value, $scopage = false, $message = '')
+ {
+ if (is_array($value)) {
+ foreach ($value as $key => $val) {
+ if ($scopage)
+ $key = $scope . ":" . $key;
+ $this->printConf($output, $key, $val, $scopage, '');
+ }
+ }
+ elseif (is_bool($value)) {
+ if ($value === false) {
+ $value = 'false';
+ } elseif ($value === true) {
+ $value = 'true';
+ }
+ $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
+ } elseif ( ! empty($value)) {
+ $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
+ }
+ }
}
diff --git a/lib/classes/module/console/fileEnsureProductionSetting.class.php b/lib/classes/module/console/fileEnsureProductionSetting.class.php
index 3716bb6972..907e434357 100644
--- a/lib/classes/module/console/fileEnsureProductionSetting.class.php
+++ b/lib/classes/module/console/fileEnsureProductionSetting.class.php
@@ -26,909 +26,762 @@ use Symfony\Component\Yaml;
*/
class module_console_fileEnsureProductionSetting extends Command
{
+ const ALERT = 1;
+ const ERROR = 0;
- const ALERT = 1;
- const ERROR = 0;
+ /**
+ *
+ * @var \Alchemy\Phrasea\Core\Configuration
+ */
+ protected $configuration;
+ protected $testSuite = array(
+ 'checkPhraseanetScope'
+ , 'checkDatabaseScope'
+ , 'checkTeamplateEngineService'
+ , 'checkOrmService'
+ , 'checkCacheService'
+ , 'checkOpcodeCacheService'
+ );
+ protected $errors = 0;
+ protected $alerts = 0;
- /**
- *
- * @var \Alchemy\Phrasea\Core\Configuration
- */
- protected $configuration;
- protected $testSuite = array(
- 'checkPhraseanetScope'
- , 'checkDatabaseScope'
- , 'checkTeamplateEngineService'
- , 'checkOrmService'
- , 'checkCacheService'
- , 'checkOpcodeCacheService'
- );
- protected $errors = 0;
- protected $alerts = 0;
-
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Ensure production settings');
-
- $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
- $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
-
- $environnement = $input->getArgument('conf');
-
- $this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
-
- if (!$this->configuration->isInstalled())
+ public function __construct($name = null)
{
- $output->writeln(sprintf("\nPhraseanet is not installed\n"));
+ parent::__construct($name);
+
+ $this->setDescription('Ensure production settings');
+
+ $this->addArgument('conf', InputArgument::OPTIONAL, 'The file to check', null);
+ $this->addOption('strict', 's', InputOption::VALUE_NONE, 'Wheter to fail on alerts or not');
+
+ return $this;
}
- $this->checkParse($output);
- $output->writeln(sprintf("Will Ensure Production Settings on %s ", $this->configuration->getEnvironnement()));
-
- $this->runTests($output);
-
- $retval = $this->errors;
- if ($input->getOption('strict'))
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $retval += $this->alerts;
- }
+ $specifications = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification();
- if ($retval > 0)
- {
- $output->writeln("\nSome errors found in your conf ");
- }
- else
- {
- $output->writeln("\nYour production settings are setted correctly ! Enjoy ");
- }
- $output->writeln('End');
+ $environnement = $input->getArgument('conf');
- return $retval;
- }
+ $this->configuration = \Alchemy\Phrasea\Core\Configuration::build($specifications, $environnement);
- private function runTests(OutputInterface $output)
- {
- foreach ($this->testSuite as $test)
- {
- $display = "";
- switch ($test)
- {
- case 'checkPhraseanetScope' :
- $display = "Phraseanet Configuration";
- break;
- case 'checkDatabaseScope' :
- $display = "Database";
- break;
- case 'checkTeamplateEngineService' :
- $display = "Template Engine";
- break;
- case 'checkOrmService' :
- $display = "ORM";
- break;
- case 'checkCacheService' :
- $display = "Cache";
- break;
- case 'checkOpcodeCacheService' :
- $display = "Opcode";
- break;
- default:
- throw new \Exception('Unknown test');
- break;
- }
-
- $output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
-
- call_user_func(array($this, $test), $output);
- }
- }
-
- private function checkParse(OutputInterface $output)
- {
-
- if (!$this->configuration->getConfigurations())
- {
- throw new \Exception("Unable to load configurations\n");
- }
- if (!$this->configuration->getConnexions())
- {
- throw new \Exception("Unable to load connexions\n");
- }
- if (!$this->configuration->getServices())
- {
- throw new \Exception("Unable to load services\n");
- }
-
- return;
- }
-
- private function checkCacheService(OutputInterface $output)
- {
- $cache = $this->configuration->getCache();
-
-
- if ($this->probeCacheService($output, $cache))
- {
- if ($this->recommendedCacheService($output, $cache, true))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'Cache server recommended ';
- $this->alerts++;
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message);
-
-
- $this->printConf($output, "\t" . 'service', $cache, false, $verification);
- $this->verifyCacheOptions($output, $cache);
- }
-
- private function checkOpcodeCacheService(OutputInterface $output)
- {
- $cache = $this->configuration->getOpcodeCache();
-
-
- if ($this->probeCacheService($output, $cache))
- {
- if ($this->recommendedCacheService($output, $cache, false))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'Opcode recommended ';
- $this->alerts++;
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message);
-
-
- $this->printConf($output, "\t" . 'service', $cache, false, $verification);
- $this->verifyCacheOptions($output, $cache);
- }
-
- private function checkPhraseanetScope(OutputInterface $output)
- {
- $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
-
- $phraseanet = $this->configuration->getPhraseanet();
-
- foreach ($phraseanet->all() as $conf => $value)
- {
- switch ($conf)
- {
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- case 'servername':
- $url = $value;
- $required = array_diff($required, array($conf));
-
- $parseUrl = parse_url($url);
-
- if (empty($url))
- {
- $message = "should not be empty ";
- $this->errors++;
- }
- elseif ($url == 'http://sub.domain.tld/')
- {
- $this->alerts++;
- $message = "may be wrong ";
- }
- elseif (!filter_var($url, FILTER_VALIDATE_URL))
- {
- $message = "not valid ";
- $this->errors++;
- }
- elseif ($parseUrl["scheme"] !== "https")
- {
- $this->alerts++;
- $message = "should be https ";
- }
- else
- {
- $message = "OK ";
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'maintenance':
- case 'debug':
- case 'display_errors':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== false)
- {
- $message = 'Should be false ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'database':
- $required = array_diff($required, array($conf));
- try
- {
- $service = $this->configuration->getConnexion($value);
- if ($this->verifyDatabaseConnexion($service))
- {
- $message = 'OK ';
- }
- else
- {
- $message = 'Connection not available ';
- $this->errors++;
- }
- }
- catch (\Exception $e)
- {
- $message = 'Unknown connection ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- private function checkDatabaseScope(OutputInterface $output)
- {
- $connexionName = $this->configuration->getPhraseanet()->get('database');
- $connexion = $this->configuration->getConnexion($connexionName);
-
- try
- {
- if ($this->verifyDatabaseConnexion($connexion))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
- }
- catch (\Exception $e)
- {
-
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message));
-
- $required = array('driver');
-
- if (!$connexion->has('driver'))
- {
- $output->writeln("\nConnection has no driver ");
- $this->errors++;
- }
- elseif ($connexion->get('driver') == 'pdo_mysql')
- {
- $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
- }
- elseif ($connexion->get('driver') == 'pdo_sqlite')
- {
- $required = array('driver', 'path', 'charset');
- }
- else
- {
- $output->writeln("\nYour driver is not managed ");
- $this->errors++;
- }
-
- foreach ($connexion->all() as $conf => $value)
- {
- switch ($conf)
- {
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- case 'charset':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
- if ($value !== 'UTF8')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'path':
- $required = array_diff($required, array($conf));
- $message = is_writable(dirname($value)) ? 'OK ' : 'Not writeable ';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'dbname':
- case 'user':
- case 'host':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'port':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!ctype_digit($value))
- {
- $message = 'Should be ctype_digit ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'password':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $value = '***********';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'driver':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== 'pdo_mysql')
- {
- $message = 'MySQL recommended ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
- {
- try
- {
- $config = new \Doctrine\DBAL\Configuration();
- $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
-
- return true;
- }
- catch (\Exception $e)
- {
-
- }
-
- return false;
- }
-
- private function checkTeamplateEngineService(OutputInterface $output)
- {
- $templateEngineName = $this->configuration->getTemplating();
- $configuration = $this->configuration->getService($templateEngineName);
-
- try
- {
- Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
- $work_message = 'Works ! ';
- }
- catch (\Exception $e)
- {
- $work_message = 'Failed - could not load template engine ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message));
-
- if (!$configuration->has('type'))
- {
- $output->writeln("\nConfiguration has no type ");
- $this->errors++;
- }
- elseif ($configuration->get('type') == 'TemplateEngine\\Twig')
- {
- $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
- }
- else
- {
- $output->writeln("\nYour type is not managed ");
- $this->errors++;
- }
-
-
-
- foreach ($configuration->all() as $conf => $value)
- {
- switch ($conf)
- {
- case 'type':
- $message = 'OK ';
-
- if($value !== 'TemplateEngine\\Twig')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'options':
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
- break;
- }
- }
-
- foreach ($configuration->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'debug';
- case 'strict_variables';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== false)
- {
- $message = 'Should be false ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- case 'autoescape';
- case 'optimizer';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== true)
- {
- $message = 'Should be true ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- case 'charset';
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== 'utf-8')
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, "\t" . $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized ');
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- private function checkOrmService(OutputInterface $output)
- {
- $ormName = $this->configuration->getOrm();
- $configuration = $this->configuration->getService($ormName);
-
- try
- {
- $service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
- $work_message = 'Works ! ';
- }
- catch (\Exception $e)
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message));
-
-
-
- if (!$configuration->has('type'))
- {
- $output->writeln("\nConfiguration has no type ");
- $this->errors++;
- }
- elseif ($configuration->get('type') == 'Orm\\Doctrine')
- {
- $required = array('debug', 'dbal', 'cache');
- }
- else
- {
- $output->writeln("\nYour type is not managed ");
- $this->errors++;
- }
-
-
-
- foreach ($configuration->all() as $conf => $value)
- {
- switch ($conf)
- {
- case 'type':
- $message = $value == 'Orm\\Doctrine' ? 'OK ' : 'Not recognized ';
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'options':
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
- break;
- }
- }
-
-
- foreach ($configuration->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'log':
- $message = 'OK ';
-
- if ($value !== false)
- {
- $message = 'Should be deactivated ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'cache':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if (!is_array($value))
- {
- $message = 'Should be Array ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, 'array()', false, $message);
-
- $required_caches = array('query', 'result', 'metadata');
- foreach ($value as $name => $cache_type)
- {
- $required_caches = array_diff($required_caches, array($name));
-
- foreach ($cache_type as $key_cache => $value_cache)
- {
- switch ($key_cache)
- {
- case 'service':
- if ($this->probeCacheService($output, $value_cache))
- {
- $server = $name === 'result';
- if ($this->recommendedCacheService($output, $value_cache, $server))
- {
- $work_message = 'Works ! ';
- }
- else
- {
- $this->alerts++;
- if ($server)
- {
- $work_message = 'Cache server recommended ';
- }
- else
- {
- $work_message = 'Opcode cache recommended ';
- }
- }
- }
- else
- {
- $work_message = 'Failed - could not connect ! ';
- $this->errors++;
- }
-
- $verification = sprintf("\t--> Verify %s : %s", $name, $work_message);
-
-
- $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
- $this->verifyCacheOptions($output, $value_cache);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized ');
- break;
- }
- if (!isset($cache_type['service']))
- {
- $output->writeln('Miss service for %s ', $cache_type);
- $this->errors++;
- }
- }
- }
-
- if (count($required_caches) > 0)
- {
- $output->writeln(sprintf('Miss required caches %s ', implode(', ', $required_caches)));
- $this->errors++;
- }
- break;
- case 'debug':
- $required = array_diff($required, array($conf));
- $message = 'OK ';
-
- if ($value !== false)
- {
- $message = 'Should be false ';
- $this->errors++;
- }
-
- $this->printConf($output, $conf, $value, false, $message);
- break;
- case 'dbal':
- $required = array_diff($required, array($conf));
- try
- {
- $connexion = $this->configuration->getConnexion($value);
- $this->verifyDatabaseConnexion($connexion);
- $message = 'OK ';
- }
- catch (\Exception $e)
- {
- $message = 'Failed ';
- $this->errors++;
- }
- $this->printConf($output, $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, $conf, $value, false, 'Not recognized ');
- break;
- }
- }
-
- if (count($required) > 0)
- {
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
- $this->errors++;
- }
-
- return;
- }
-
- protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
- {
- try
- {
- $conf = $this->configuration->getService($ServiceName);
-
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $conf
- );
- }
- catch (\Exception $e)
- {
- return false;
- }
-
- $required_options = array();
-
- switch ($Service->getType())
- {
- default:
- break;
- case 'memcache':
- $required_options = array('host', 'port');
- break;
- }
-
- if ($required_options)
- {
- foreach ($conf->get('options') as $conf => $value)
- {
- switch ($conf)
- {
- case 'host';
- $required_options = array_diff($required_options, array($conf));
- $message = 'OK ';
-
- if (!is_scalar($value))
- {
- $message = 'Should be scalar ';
- $this->errors++;
- }
-
- $this->printConf($output, "\t\t" . $conf, $value, false, $message);
- break;
- case 'port';
- $required_options = array_diff($required_options, array($conf));
- $message = 'OK ';
-
- if (!ctype_digit($value))
- {
- $message = 'Not recognized ';
- $this->alerts++;
- }
-
- $this->printConf($output, "\t\t" . $conf, $value, false, $message);
- break;
- default:
- $this->alerts++;
- $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized ');
- break;
+ if ( ! $this->configuration->isInstalled()) {
+ $output->writeln(sprintf("\nPhraseanet is not installed\n"));
}
- }
+
+ $this->checkParse($output);
+ $output->writeln(sprintf("Will Ensure Production Settings on %s ", $this->configuration->getEnvironnement()));
+
+ $this->runTests($output);
+
+ $retval = $this->errors;
+ if ($input->getOption('strict')) {
+ $retval += $this->alerts;
+ }
+
+ if ($retval > 0) {
+ $output->writeln("\nSome errors found in your conf ");
+ } else {
+ $output->writeln("\nYour production settings are setted correctly ! Enjoy ");
+ }
+ $output->writeln('End');
+
+ return $retval;
}
- if (count($required_options) > 0)
+ private function runTests(OutputInterface $output)
{
- $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required_options)));
- $this->errors++;
- }
- }
+ foreach ($this->testSuite as $test) {
+ $display = "";
+ switch ($test) {
+ case 'checkPhraseanetScope' :
+ $display = "Phraseanet Configuration";
+ break;
+ case 'checkDatabaseScope' :
+ $display = "Database";
+ break;
+ case 'checkTeamplateEngineService' :
+ $display = "Template Engine";
+ break;
+ case 'checkOrmService' :
+ $display = "ORM";
+ break;
+ case 'checkCacheService' :
+ $display = "Cache";
+ break;
+ case 'checkOpcodeCacheService' :
+ $display = "Opcode";
+ break;
+ default:
+ throw new \Exception('Unknown test');
+ break;
+ }
- protected function probeCacheService(OutputInterface $output, $ServiceName)
- {
- try
- {
- $originalConfiguration = $this->configuration->getService($ServiceName);
+ $output->writeln(sprintf("\n||| %s", mb_strtoupper($display)));
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $originalConfiguration
- );
- }
- catch (\Exception $e)
- {
- return false;
+ call_user_func(array($this, $test), $output);
+ }
}
- if ($Service->getDriver()->isServer())
+ private function checkParse(OutputInterface $output)
{
- switch ($Service->getType())
- {
- default:
- return false;
- break;
- case 'memcache':
- if (!@memcache_connect($Service->getHost(), $Service->getPort()))
- {
+
+ if ( ! $this->configuration->getConfigurations()) {
+ throw new \Exception("Unable to load configurations\n");
+ }
+ if ( ! $this->configuration->getConnexions()) {
+ throw new \Exception("Unable to load connexions\n");
+ }
+ if ( ! $this->configuration->getServices()) {
+ throw new \Exception("Unable to load services\n");
+ }
+
+ return;
+ }
+
+ private function checkCacheService(OutputInterface $output)
+ {
+ $cache = $this->configuration->getCache();
+
+
+ if ($this->probeCacheService($output, $cache)) {
+ if ($this->recommendedCacheService($output, $cache, true)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'Cache server recommended ';
+ $this->alerts ++;
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", 'MainCache', $work_message);
+
+
+ $this->printConf($output, "\t" . 'service', $cache, false, $verification);
+ $this->verifyCacheOptions($output, $cache);
+ }
+
+ private function checkOpcodeCacheService(OutputInterface $output)
+ {
+ $cache = $this->configuration->getOpcodeCache();
+
+
+ if ($this->probeCacheService($output, $cache)) {
+ if ($this->recommendedCacheService($output, $cache, false)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'Opcode recommended ';
+ $this->alerts ++;
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", 'OpcodeCache', $work_message);
+
+
+ $this->printConf($output, "\t" . 'service', $cache, false, $verification);
+ $this->verifyCacheOptions($output, $cache);
+ }
+
+ private function checkPhraseanetScope(OutputInterface $output)
+ {
+ $required = array('servername', 'maintenance', 'debug', 'display_errors', 'database');
+
+ $phraseanet = $this->configuration->getPhraseanet();
+
+ foreach ($phraseanet->all() as $conf => $value) {
+ switch ($conf) {
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ case 'servername':
+ $url = $value;
+ $required = array_diff($required, array($conf));
+
+ $parseUrl = parse_url($url);
+
+ if (empty($url)) {
+ $message = "should not be empty ";
+ $this->errors ++;
+ } elseif ($url == 'http://sub.domain.tld/') {
+ $this->alerts ++;
+ $message = "may be wrong ";
+ } elseif ( ! filter_var($url, FILTER_VALIDATE_URL)) {
+ $message = "not valid ";
+ $this->errors ++;
+ } elseif ($parseUrl["scheme"] !== "https") {
+ $this->alerts ++;
+ $message = "should be https ";
+ } else {
+ $message = "OK ";
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'maintenance':
+ case 'debug':
+ case 'display_errors':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== false) {
+ $message = 'Should be false ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'database':
+ $required = array_diff($required, array($conf));
+ try {
+ $service = $this->configuration->getConnexion($value);
+ if ($this->verifyDatabaseConnexion($service)) {
+ $message = 'OK ';
+ } else {
+ $message = 'Connection not available ';
+ $this->errors ++;
+ }
+ } catch (\Exception $e) {
+ $message = 'Unknown connection ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ private function checkDatabaseScope(OutputInterface $output)
+ {
+ $connexionName = $this->configuration->getPhraseanet()->get('database');
+ $connexion = $this->configuration->getConnexion($connexionName);
+
+ try {
+ if ($this->verifyDatabaseConnexion($connexion)) {
+ $work_message = 'Works ! ';
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+ } catch (\Exception $e) {
+
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify connection %s : %s", $connexionName, $work_message));
+
+ $required = array('driver');
+
+ if ( ! $connexion->has('driver')) {
+ $output->writeln("\nConnection has no driver ");
+ $this->errors ++;
+ } elseif ($connexion->get('driver') == 'pdo_mysql') {
+ $required = array('driver', 'dbname', 'charset', 'password', 'user', 'port', 'host');
+ } elseif ($connexion->get('driver') == 'pdo_sqlite') {
+ $required = array('driver', 'path', 'charset');
+ } else {
+ $output->writeln("\nYour driver is not managed ");
+ $this->errors ++;
+ }
+
+ foreach ($connexion->all() as $conf => $value) {
+ switch ($conf) {
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ case 'charset':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+ if ($value !== 'UTF8') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'path':
+ $required = array_diff($required, array($conf));
+ $message = is_writable(dirname($value)) ? 'OK ' : 'Not writeable ';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'dbname':
+ case 'user':
+ case 'host':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'port':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! ctype_digit($value)) {
+ $message = 'Should be ctype_digit ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'password':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $value = '***********';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'driver':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== 'pdo_mysql') {
+ $message = 'MySQL recommended ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ protected function verifyDatabaseConnexion(\Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $connexion)
+ {
+ try {
+ $config = new \Doctrine\DBAL\Configuration();
+ $conn = \Doctrine\DBAL\DriverManager::getConnection($connexion->all(), $config);
+
+ return true;
+ } catch (\Exception $e) {
+
+ }
+
+ return false;
+ }
+
+ private function checkTeamplateEngineService(OutputInterface $output)
+ {
+ $templateEngineName = $this->configuration->getTemplating();
+ $configuration = $this->configuration->getService($templateEngineName);
+
+ try {
+ Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
+ $work_message = 'Works ! ';
+ } catch (\Exception $e) {
+ $work_message = 'Failed - could not load template engine ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify Template engine %s : %s", $templateEngineName, $work_message));
+
+ if ( ! $configuration->has('type')) {
+ $output->writeln("\nConfiguration has no type ");
+ $this->errors ++;
+ } elseif ($configuration->get('type') == 'TemplateEngine\\Twig') {
+ $required = array('debug', 'charset', 'strict_variables', 'autoescape', 'optimizer');
+ } else {
+ $output->writeln("\nYour type is not managed ");
+ $this->errors ++;
+ }
+
+
+
+ foreach ($configuration->all() as $conf => $value) {
+ switch ($conf) {
+ case 'type':
+ $message = 'OK ';
+
+ if ($value !== 'TemplateEngine\\Twig') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'options':
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
+ break;
+ }
+ }
+
+ foreach ($configuration->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'debug';
+ case 'strict_variables';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== false) {
+ $message = 'Should be false ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ case 'autoescape';
+ case 'optimizer';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== true) {
+ $message = 'Should be true ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ case 'charset';
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== 'utf-8') {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, "\t" . $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t" . $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ private function checkOrmService(OutputInterface $output)
+ {
+ $ormName = $this->configuration->getOrm();
+ $configuration = $this->configuration->getService($ormName);
+
+ try {
+ $service = Core\Service\Builder::create(\bootstrap::getCore(), $configuration);
+ $work_message = 'Works ! ';
+ } catch (\Exception $e) {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $output->writeln(sprintf("\t--> Verify ORM engine %s : %s", $ormName, $work_message));
+
+
+
+ if ( ! $configuration->has('type')) {
+ $output->writeln("\nConfiguration has no type ");
+ $this->errors ++;
+ } elseif ($configuration->get('type') == 'Orm\\Doctrine') {
+ $required = array('debug', 'dbal', 'cache');
+ } else {
+ $output->writeln("\nYour type is not managed ");
+ $this->errors ++;
+ }
+
+
+
+ foreach ($configuration->all() as $conf => $value) {
+ switch ($conf) {
+ case 'type':
+ $message = $value == 'Orm\\Doctrine' ? 'OK ' : 'Not recognized ';
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'options':
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, 'unknown', false, 'Not recognized ');
+ break;
+ }
+ }
+
+
+ foreach ($configuration->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'log':
+ $message = 'OK ';
+
+ if ($value !== false) {
+ $message = 'Should be deactivated ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'cache':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_array($value)) {
+ $message = 'Should be Array ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, 'array()', false, $message);
+
+ $required_caches = array('query', 'result', 'metadata');
+ foreach ($value as $name => $cache_type) {
+ $required_caches = array_diff($required_caches, array($name));
+
+ foreach ($cache_type as $key_cache => $value_cache) {
+ switch ($key_cache) {
+ case 'service':
+ if ($this->probeCacheService($output, $value_cache)) {
+ $server = $name === 'result';
+ if ($this->recommendedCacheService($output, $value_cache, $server)) {
+ $work_message = 'Works ! ';
+ } else {
+ $this->alerts ++;
+ if ($server) {
+ $work_message = 'Cache server recommended ';
+ } else {
+ $work_message = 'Opcode cache recommended ';
+ }
+ }
+ } else {
+ $work_message = 'Failed - could not connect ! ';
+ $this->errors ++;
+ }
+
+ $verification = sprintf("\t--> Verify %s : %s", $name, $work_message);
+
+
+ $this->printConf($output, "\t" . $key_cache, $value_cache, false, $verification);
+ $this->verifyCacheOptions($output, $value_cache);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t" . $key_cache, $value_cache, false, 'Not recognized ');
+ break;
+ }
+ if ( ! isset($cache_type['service'])) {
+ $output->writeln('Miss service for %s ', $cache_type);
+ $this->errors ++;
+ }
+ }
+ }
+
+ if (count($required_caches) > 0) {
+ $output->writeln(sprintf('Miss required caches %s ', implode(', ', $required_caches)));
+ $this->errors ++;
+ }
+ break;
+ case 'debug':
+ $required = array_diff($required, array($conf));
+ $message = 'OK ';
+
+ if ($value !== false) {
+ $message = 'Should be false ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ case 'dbal':
+ $required = array_diff($required, array($conf));
+ try {
+ $connexion = $this->configuration->getConnexion($value);
+ $this->verifyDatabaseConnexion($connexion);
+ $message = 'OK ';
+ } catch (\Exception $e) {
+ $message = 'Failed ';
+ $this->errors ++;
+ }
+ $this->printConf($output, $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+
+ if (count($required) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required)));
+ $this->errors ++;
+ }
+
+ return;
+ }
+
+ protected function verifyCacheOptions(OutputInterface $output, $ServiceName)
+ {
+ try {
+ $conf = $this->configuration->getService($ServiceName);
+
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $conf
+ );
+ } catch (\Exception $e) {
return false;
- }
- break;
- }
+ }
+
+ $required_options = array();
+
+ switch ($Service->getType()) {
+ default:
+ break;
+ case 'memcache':
+ $required_options = array('host', 'port');
+ break;
+ }
+
+ if ($required_options) {
+ foreach ($conf->get('options') as $conf => $value) {
+ switch ($conf) {
+ case 'host';
+ $required_options = array_diff($required_options, array($conf));
+ $message = 'OK ';
+
+ if ( ! is_scalar($value)) {
+ $message = 'Should be scalar ';
+ $this->errors ++;
+ }
+
+ $this->printConf($output, "\t\t" . $conf, $value, false, $message);
+ break;
+ case 'port';
+ $required_options = array_diff($required_options, array($conf));
+ $message = 'OK ';
+
+ if ( ! ctype_digit($value)) {
+ $message = 'Not recognized ';
+ $this->alerts ++;
+ }
+
+ $this->printConf($output, "\t\t" . $conf, $value, false, $message);
+ break;
+ default:
+ $this->alerts ++;
+ $this->printConf($output, "\t\t" . $conf, $value, false, 'Not recognized ');
+ break;
+ }
+ }
+ }
+
+ if (count($required_options) > 0) {
+ $output->writeln(sprintf('Miss required keys %s ', implode(', ', $required_options)));
+ $this->errors ++;
+ }
}
- return true;
- }
-
- protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
- {
- try
+ protected function probeCacheService(OutputInterface $output, $ServiceName)
{
- $originalConfiguration = $this->configuration->getService($ServiceName);
+ try {
+ $originalConfiguration = $this->configuration->getService($ServiceName);
- $Service = Core\Service\Builder::create(
- \bootstrap::getCore(), $originalConfiguration
- );
- }
- catch (\Exception $e)
- {
- return false;
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $originalConfiguration
+ );
+ } catch (\Exception $e) {
+ return false;
+ }
+
+ if ($Service->getDriver()->isServer()) {
+ switch ($Service->getType()) {
+ default:
+ return false;
+ break;
+ case 'memcache':
+ if ( ! @memcache_connect($Service->getHost(), $Service->getPort())) {
+ return false;
+ }
+ break;
+ }
+ }
+
+ return true;
}
- if ($Service->getType() === 'array')
+ protected function recommendedCacheService(OutputInterface $output, $ServiceName, $server)
{
- return false;
+ try {
+ $originalConfiguration = $this->configuration->getService($ServiceName);
+
+ $Service = Core\Service\Builder::create(
+ \bootstrap::getCore(), $originalConfiguration
+ );
+ } catch (\Exception $e) {
+ return false;
+ }
+
+ if ($Service->getType() === 'array') {
+ return false;
+ }
+
+ return $server === $Service->getDriver()->isServer();
}
- return $server === $Service->getDriver()->isServer();
- }
-
- private function printConf($output, $scope, $value, $scopage = false, $message = '')
- {
- if (is_array($value))
+ private function printConf($output, $scope, $value, $scopage = false, $message = '')
{
- foreach ($value as $key => $val)
- {
- if ($scopage)
- $key = $scope . ":" . $key;
- $this->printConf($output, $key, $val, $scopage, '');
- }
+ if (is_array($value)) {
+ foreach ($value as $key => $val) {
+ if ($scopage)
+ $key = $scope . ":" . $key;
+ $this->printConf($output, $key, $val, $scopage, '');
+ }
+ }
+ elseif (is_bool($value)) {
+ if ($value === false) {
+ $value = 'false';
+ } elseif ($value === true) {
+ $value = 'true';
+ }
+ $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
+ } elseif ( ! empty($value)) {
+ $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
+ }
}
- elseif (is_bool($value))
- {
- if ($value === false)
- {
- $value = 'false';
- }
- elseif ($value === true)
- {
- $value = 'true';
- }
- $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
- }
- elseif (!empty($value))
- {
- $output->writeln(sprintf("\t%s: %s %s", $scope, $value, $message));
- }
- }
-
}
diff --git a/lib/classes/module/console/schedulerStart.class.php b/lib/classes/module/console/schedulerStart.class.php
index 39616efa37..fd98db85bf 100644
--- a/lib/classes/module/console/schedulerStart.class.php
+++ b/lib/classes/module/console/schedulerStart.class.php
@@ -25,57 +25,52 @@ use Symfony\Component\Console\Command\Command;
class module_console_schedulerStart extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('Start the scheduler');
- $this->addOption(
+ $this->setDescription('Start the scheduler');
+ $this->addOption(
'nolog'
, NULL
, 1 | InputOption::VALUE_NONE
, 'do not log (scheduler) to logfile'
, NULL
- );
- $this->addOption(
+ );
+ $this->addOption(
'notasklog'
, NULL
, 1 | InputOption::VALUE_NONE
, 'do not log (tasks) to logfiles'
, NULL
- );
- $this->setHelp(
+ );
+ $this->setHelp(
"You should use launch the command and finish it with `&`"
. " to return to the console\n\n"
. "\tie : bin/console scheduler:start & "
- );
+ );
- return $this;
- }
-
- public function execute(InputInterface $zinput, OutputInterface $output)
- {
- if (!setup::is_installed())
- {
- $output->writeln('Phraseanet is not set up');
-
- return 1;
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- $scheduler = new task_Scheduler();
- $scheduler->run($zinput, $output); //, !$input->getOption('nolog'), !$input->getOption('notasklog'));
-
- try
+ public function execute(InputInterface $zinput, OutputInterface $output)
{
- $scheduler = new task_Scheduler();
- $scheduler->run($output, true);
- }
- catch (\Exception $e)
- {
- return 1;
- }
- }
+ if ( ! setup::is_installed()) {
+ $output->writeln('Phraseanet is not set up');
+ return 1;
+ }
+
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
+
+ $scheduler = new task_Scheduler();
+ $scheduler->run($zinput, $output); //, !$input->getOption('nolog'), !$input->getOption('notasklog'));
+
+ try {
+ $scheduler = new task_Scheduler();
+ $scheduler->run($output, true);
+ } catch (\Exception $e) {
+ return 1;
+ }
+ }
}
diff --git a/lib/classes/module/console/schedulerState.class.php b/lib/classes/module/console/schedulerState.class.php
index 78507b1bc3..cb6363e67c 100644
--- a/lib/classes/module/console/schedulerState.class.php
+++ b/lib/classes/module/console/schedulerState.class.php
@@ -25,54 +25,46 @@ use Symfony\Component\Console\Command\Command;
class module_console_schedulerState extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Get scheduler state');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!setup::is_installed())
+ public function __construct($name = null)
{
- $output->writeln('Phraseanet is not set up');
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Get scheduler state');
+
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- try
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $task_manager = new task_manager($appbox);
+ if ( ! setup::is_installed()) {
+ $output->writeln('Phraseanet is not set up');
- $state = $task_manager->get_scheduler_state();
+ return 1;
+ }
- if ($state['status'] == 'started')
- {
- $output->writeln(sprintf(
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
+
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $task_manager = new task_manager($appbox);
+
+ $state = $task_manager->get_scheduler_state();
+
+ if ($state['status'] == 'started') {
+ $output->writeln(sprintf(
'Scheduler is %s on pid %d'
, $state['schedstatus']
, $state['schedpid']
- ));
- }
- else
- {
- $output->writeln(sprintf('Scheduler is %s', $state['status']));
- }
+ ));
+ } else {
+ $output->writeln(sprintf('Scheduler is %s', $state['status']));
+ }
- return 0;
+ return 0;
+ } catch (\Exception $e) {
+ return 1;
+ }
+
+ return 0;
}
- catch(\Exception $e)
- {
- return 1;
- }
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/schedulerStop.class.php b/lib/classes/module/console/schedulerStop.class.php
index 333403cde0..b1fdf188d0 100644
--- a/lib/classes/module/console/schedulerStop.class.php
+++ b/lib/classes/module/console/schedulerStop.class.php
@@ -25,40 +25,35 @@ use Symfony\Component\Console\Command\Command;
class module_console_schedulerStop extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Stop the scheduler');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!setup::is_installed())
+ public function __construct($name = null)
{
- $output->writeln('Phraseanet is not set up');
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Stop the scheduler');
+
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- try
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $task_manager = new task_manager($appbox);
- $task_manager->set_sched_status(task_manager::STATUS_SCHED_TOSTOP);
+ if ( ! setup::is_installed()) {
+ $output->writeln('Phraseanet is not set up');
- return 0;
+ return 1;
+ }
+
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
+
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $task_manager = new task_manager($appbox);
+ $task_manager->set_sched_status(task_manager::STATUS_SCHED_TOSTOP);
+
+ return 0;
+ } catch (\Exception $e) {
+ return 1;
+ }
+
+ return 0;
}
- catch (\Exception $e)
- {
- return 1;
- }
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/sphinxGenerateSuggestion.class.php b/lib/classes/module/console/sphinxGenerateSuggestion.class.php
index 40133e3559..54dcc23be0 100644
--- a/lib/classes/module/console/sphinxGenerateSuggestion.class.php
+++ b/lib/classes/module/console/sphinxGenerateSuggestion.class.php
@@ -25,138 +25,126 @@ use Symfony\Component\Console\Command\Command;
class module_console_sphinxGenerateSuggestion extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Generate suggestions for Sphinx Search Engine');
-
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- define('FREQ_THRESHOLD', 10);
- define('SUGGEST_DEBUG', 0);
-
- $appbox = \appbox::get_instance(\bootstrap::getCore());
- $registry = $appbox->get_registry();
-
- $params = phrasea::sbas_params();
-
- foreach ($params as $sbas_id => $p)
+ public function __construct($name = null)
{
- $index = crc32(
- str_replace(
- array('.', '%')
- , '_'
- , sprintf('%s_%s_%s_%s', $p['host'], $p['port'], $p['user'], $p['dbname'])
- )
- );
+ parent::__construct($name);
- $tmp_file = $registry->get('GV_RootPath') . 'tmp/dict' . $index . '.txt';
+ $this->setDescription('Generate suggestions for Sphinx Search Engine');
- $databox = databox::get_instance($sbas_id);
- $output->writeln("process Databox " . $databox->get_viewname() . " / $index\n");
-
- if(!is_executable("/usr/local/bin/indexer"))
- {
- $output->writeln("'/usr/local/bin/indexer' is not executable ");
-
- return 1;
- }
-
- if(!file_exists($tmp_file))
- {
- $output->writeln(" file '".$tmp_file."' does not exist ");
-
- return 1;
- }
-
- $cmd = '/usr/local/bin/indexer metadatas' . $index . ' --buildstops ' . $tmp_file . ' 1000000 --buildfreqs';
- exec($cmd);
-
- try
- {
- $connbas = connection::getPDOConnection($sbas_id);
- }
- catch (Exception $e)
- {
- continue;
- }
-
- $sql = 'TRUNCATE suggest';
- $stmt = $connbas->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
-
- $sql = $this->BuildDictionarySQL($output, file_get_contents($tmp_file));
-
- if (trim($sql) !== '')
- {
- $stmt = $connbas->prepare($sql);
- $stmt->execute();
- $stmt->closeCursor();
- }
-
- unlink($tmp_file);
+ return $this;
}
- return 0;
- }
-
- protected function BuildTrigrams($keyword)
- {
- $t = "__" . $keyword . "__";
-
- $trigrams = "";
- for ($i = 0; $i < strlen($t) - 2; $i++)
- $trigrams .= substr($t, $i, 3) . " ";
-
- return $trigrams;
- }
-
- protected function BuildDictionarySQL(OutputInterface $output, $in)
- {
- $out = '';
-
- $n = 0;
- $lines = explode("\n", $in);
- foreach ($lines as $line)
+ public function execute(InputInterface $input, OutputInterface $output)
{
- if (trim($line) === '')
- continue;
- list ( $keyword, $freq ) = explode(" ", trim($line));
+ define('FREQ_THRESHOLD', 10);
+ define('SUGGEST_DEBUG', 0);
- if ($freq < FREQ_THRESHOLD || strstr($keyword, "_") !== false || strstr($keyword, "'") !== false)
- continue;
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
+ $registry = $appbox->get_registry();
- if (ctype_digit($keyword))
- {
- continue;
- }
- if (mb_strlen($keyword) < 3)
- {
- continue;
- }
+ $params = phrasea::sbas_params();
- $trigrams = $this->BuildTrigrams($keyword);
+ foreach ($params as $sbas_id => $p) {
+ $index = crc32(
+ str_replace(
+ array('.', '%')
+ , '_'
+ , sprintf('%s_%s_%s_%s', $p['host'], $p['port'], $p['user'], $p['dbname'])
+ )
+ );
- if ($n++)
- $out .= ",\n";
- $out .= "( $n, '$keyword', '$trigrams', $freq )";
+ $tmp_file = $registry->get('GV_RootPath') . 'tmp/dict' . $index . '.txt';
+
+ $databox = databox::get_instance($sbas_id);
+
+ $output->writeln("process Databox " . $databox->get_viewname() . " / $index\n");
+
+ if ( ! is_executable("/usr/local/bin/indexer")) {
+ $output->writeln("'/usr/local/bin/indexer' is not executable ");
+
+ return 1;
+ }
+
+ if ( ! file_exists($tmp_file)) {
+ $output->writeln(" file '" . $tmp_file . "' does not exist ");
+
+ return 1;
+ }
+
+ $cmd = '/usr/local/bin/indexer metadatas' . $index . ' --buildstops ' . $tmp_file . ' 1000000 --buildfreqs';
+ exec($cmd);
+
+ try {
+ $connbas = connection::getPDOConnection($sbas_id);
+ } catch (Exception $e) {
+ continue;
+ }
+
+ $sql = 'TRUNCATE suggest';
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+
+ $sql = $this->BuildDictionarySQL($output, file_get_contents($tmp_file));
+
+ if (trim($sql) !== '') {
+ $stmt = $connbas->prepare($sql);
+ $stmt->execute();
+ $stmt->closeCursor();
+ }
+
+ unlink($tmp_file);
+ }
+
+ return 0;
}
- if (trim($out) !== '')
+ protected function BuildTrigrams($keyword)
{
- $out = "INSERT INTO suggest VALUES " . $out . ";";
+ $t = "__" . $keyword . "__";
+
+ $trigrams = "";
+ for ($i = 0; $i < strlen($t) - 2; $i ++ )
+ $trigrams .= substr($t, $i, 3) . " ";
+
+ return $trigrams;
}
- $output->writeln(sprintf("Generated %d suggestions", $n));
+ protected function BuildDictionarySQL(OutputInterface $output, $in)
+ {
+ $out = '';
- return $out;
- }
+ $n = 0;
+ $lines = explode("\n", $in);
+ foreach ($lines as $line) {
+ if (trim($line) === '')
+ continue;
+ list ( $keyword, $freq ) = explode(" ", trim($line));
+ if ($freq < FREQ_THRESHOLD || strstr($keyword, "_") !== false || strstr($keyword, "'") !== false)
+ continue;
+
+ if (ctype_digit($keyword)) {
+ continue;
+ }
+ if (mb_strlen($keyword) < 3) {
+ continue;
+ }
+
+ $trigrams = $this->BuildTrigrams($keyword);
+
+ if ($n ++)
+ $out .= ",\n";
+ $out .= "( $n, '$keyword', '$trigrams', $freq )";
+ }
+
+ if (trim($out) !== '') {
+ $out = "INSERT INTO suggest VALUES " . $out . ";";
+ }
+
+ $output->writeln(sprintf("Generated %d suggestions", $n));
+
+ return $out;
+ }
}
diff --git a/lib/classes/module/console/systemBackupDB.class.php b/lib/classes/module/console/systemBackupDB.class.php
index 5f437c8369..14424d5843 100644
--- a/lib/classes/module/console/systemBackupDB.class.php
+++ b/lib/classes/module/console/systemBackupDB.class.php
@@ -25,63 +25,61 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemBackupDB extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $dir = sprintf(
+ $dir = sprintf(
'%s/config/'
, dirname(dirname(dirname(dirname(__DIR__))))
- );
+ );
- $this->setDescription('Backup Phraseanet Databases');
+ $this->setDescription('Backup Phraseanet Databases');
- $this->addArgument('directory', null, 'The directory where to backup', $dir);
+ $this->addArgument('directory', null, 'The directory where to backup', $dir);
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!setup::is_installed())
- {
- $output->writeln('Argument must be an Id.');
-
- return 1;
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- $output->write('Phraseanet is going to be backup...', true);
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
-
- $ok = true;
-
- $ok = $this->dump_base($appbox, $input, $output) && $ok;
-
- foreach ($appbox->get_databoxes() as $databox)
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $ok = $this->dump_base($databox, $input, $output) && $ok;
+ if ( ! setup::is_installed()) {
+ $output->writeln('Argument must be an Id.');
+
+ return 1;
+ }
+
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
+
+ $output->write('Phraseanet is going to be backup...', true);
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+
+ $ok = true;
+
+ $ok = $this->dump_base($appbox, $input, $output) && $ok;
+
+ foreach ($appbox->get_databoxes() as $databox) {
+ $ok = $this->dump_base($databox, $input, $output) && $ok;
+ }
+
+ return (int) ! $ok;
}
- return (int) !$ok;
- }
+ protected function dump_base(base $base, InputInterface $input, OutputInterface $output)
+ {
+ $date_obj = new DateTime();
- protected function dump_base(base $base, InputInterface $input, OutputInterface $output)
- {
- $date_obj = new DateTime();
-
- $filename = sprintf(
+ $filename = sprintf(
'%s%s_%s.sql'
, p4string::addEndSlash($input->getArgument('directory'))
, $base->get_dbname()
, $date_obj->format('Y_m_d_H_i_s')
- );
+ );
- $output->write(sprintf('Generating %s ... ', $filename));
+ $output->write(sprintf('Generating %s ... ', $filename));
- $command = sprintf(
+ $command = sprintf(
'mysqldump --host %s --port %s --user %s --password=%s'
. ' --database %s --default-character-set=utf8 > %s'
, $base->get_host()
@@ -90,24 +88,18 @@ class module_console_systemBackupDB extends Command
, $base->get_passwd()
, $base->get_dbname()
, escapeshellarg($filename)
- );
+ );
- system($command);
+ system($command);
- if (file_exists($filename) && filesize($filename) > 0)
- {
- $output->writeln('OK');
+ if (file_exists($filename) && filesize($filename) > 0) {
+ $output->writeln('OK');
- return true;
+ return true;
+ } else {
+ $output->writeln('Failed ');
+
+ return false;
+ }
}
- else
- {
- $output->writeln('Failed ');
-
- return false;
- }
-
-
- }
-
}
diff --git a/lib/classes/module/console/systemClearCache.class.php b/lib/classes/module/console/systemClearCache.class.php
index ebb853dcd0..f631dffd30 100644
--- a/lib/classes/module/console/systemClearCache.class.php
+++ b/lib/classes/module/console/systemClearCache.class.php
@@ -26,20 +26,20 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemClearCache extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('Empty cache directories, clear Memcached, Redis if avalaible');
+ $this->setDescription('Empty cache directories, clear Memcached, Redis if avalaible');
- return $this;
- }
+ return $this;
+ }
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $files = $dirs = array();
- $finder = new Finder();
- $finder
+ public function execute(InputInterface $input, OutputInterface $output)
+ {
+ $files = $dirs = array();
+ $finder = new Finder();
+ $finder
->files()
->exclude('.git')
->exclude('.svn')
@@ -48,15 +48,14 @@ class module_console_systemClearCache extends Command
, __DIR__ . '/../../../../tmp/cache_twig/'
));
- $count = 1;
- foreach ($finder as $file)
- {
- $files[$file->getPathname()] = $file->getPathname();
- $count++;
- }
+ $count = 1;
+ foreach ($finder as $file) {
+ $files[$file->getPathname()] = $file->getPathname();
+ $count ++;
+ }
- $finder = new Finder();
- $finder
+ $finder = new Finder();
+ $finder
->directories()
->in(array(
__DIR__ . '/../../../../tmp/cache_minify'
@@ -65,31 +64,26 @@ class module_console_systemClearCache extends Command
->exclude('.git')
->exclude('.svn');
- foreach ($finder as $file)
- {
- $dirs[$file->getPathname()] = $file->getPathname();
- printf('%4d) %s' . PHP_EOL, $count, $file->getPathname());
- $count++;
+ foreach ($finder as $file) {
+ $dirs[$file->getPathname()] = $file->getPathname();
+ printf('%4d) %s' . PHP_EOL, $count, $file->getPathname());
+ $count ++;
+ }
+
+ foreach ($files as $file) {
+ unlink($file);
+ }
+ foreach ($dirs as $dir) {
+ rmdir($dir);
+ }
+
+ if (setup::is_installed()) {
+ $Core = \bootstrap::getCore();
+ $Core['CacheService']->flushAll();
+ }
+
+ $output->write('Finished !', true);
+
+ return 0;
}
-
- foreach ($files as $file)
- {
- unlink($file);
- }
- foreach ($dirs as $dir)
- {
- rmdir($dir);
- }
-
- if(setup::is_installed())
- {
- $Core = \bootstrap::getCore();
- $Core['CacheService']->flushAll();
- }
-
- $output->write('Finished !', true);
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/systemConfigCheck.class.php b/lib/classes/module/console/systemConfigCheck.class.php
index 8242dd7e59..275c48c295 100644
--- a/lib/classes/module/console/systemConfigCheck.class.php
+++ b/lib/classes/module/console/systemConfigCheck.class.php
@@ -26,101 +26,89 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemConfigCheck extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Check the configuration');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!function_exists('_'))
+ public function __construct($name = null)
{
- $output->writeln('YOU MUST ENABLE GETTEXT SUPPORT TO USE PHRASEANET ');
- $output->writeln('Canceled');
+ parent::__construct($name);
- return 1;
+ $this->setDescription('Check the configuration');
+
+ return $this;
}
- $ok = true;
-
- if (setup::is_installed())
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $registry = registry::get_instance();
+ if ( ! function_exists('_')) {
+ $output->writeln('YOU MUST ENABLE GETTEXT SUPPORT TO USE PHRASEANET ');
+ $output->writeln('Canceled');
- $output->writeln(_('*** CHECK BINARY CONFIGURATION ***'));
- $ok = $this->processConstraints(setup::check_binaries($registry), $output) && $ok;
- $output->writeln("");
- }
- else
- {
- $registry = new Setup_Registry();
+ return 1;
+ }
+
+ $ok = true;
+
+ if (setup::is_installed()) {
+ $registry = registry::get_instance();
+
+ $output->writeln(_('*** CHECK BINARY CONFIGURATION ***'));
+ $ok = $this->processConstraints(setup::check_binaries($registry), $output) && $ok;
+ $output->writeln("");
+ } else {
+ $registry = new Setup_Registry();
+ }
+
+
+
+ $output->writeln(_('*** FILESYSTEM CONFIGURATION ***'));
+ $ok = $this->processConstraints(setup::check_writability($registry), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK CACHE OPCODE ***'));
+ $ok = $this->processConstraints(setup::check_cache_opcode(), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK CACHE SERVER ***'));
+ $ok = $this->processConstraints(setup::check_cache_server(), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK PHP CONFIGURATION ***'));
+ $ok = $this->processConstraints(setup::check_php_configuration(), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK PHP EXTENSIONS ***'));
+ $ok = $this->processConstraints(setup::check_php_extension(), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK PHRASEA ***'));
+ $ok = $this->processConstraints(setup::check_phrasea(), $output) && $ok;
+ $output->writeln("");
+ $output->writeln(_('*** CHECK SYSTEM LOCALES ***'));
+ $ok = $this->processConstraints(setup::check_system_locales(), $output) && $ok;
+ $output->writeln("");
+
+ $output->write('Finished !', true);
+
+ return (int) ! $ok;
}
-
-
- $output->writeln(_('*** FILESYSTEM CONFIGURATION ***'));
- $ok = $this->processConstraints(setup::check_writability($registry), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK CACHE OPCODE ***'));
- $ok = $this->processConstraints(setup::check_cache_opcode(), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK CACHE SERVER ***'));
- $ok = $this->processConstraints(setup::check_cache_server(), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK PHP CONFIGURATION ***'));
- $ok = $this->processConstraints(setup::check_php_configuration(), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK PHP EXTENSIONS ***'));
- $ok = $this->processConstraints(setup::check_php_extension(), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK PHRASEA ***'));
- $ok = $this->processConstraints(setup::check_phrasea(), $output) && $ok;
- $output->writeln("");
- $output->writeln(_('*** CHECK SYSTEM LOCALES ***'));
- $ok = $this->processConstraints(setup::check_system_locales(), $output) && $ok;
- $output->writeln("");
-
- $output->write('Finished !', true);
-
- return (int)!$ok;
- }
-
- protected function processConstraints(Setup_ConstraintsIterator $constraints, OutputInterface &$output)
- {
- $hasError = false;
- foreach ($constraints as $constraint)
+ protected function processConstraints(Setup_ConstraintsIterator $constraints, OutputInterface &$output)
{
- if (!$hasError && !$this->processConstraint($constraint, $output))
- {
- $hasError = true;
- }
+ $hasError = false;
+ foreach ($constraints as $constraint) {
+ if ( ! $hasError && ! $this->processConstraint($constraint, $output)) {
+ $hasError = true;
+ }
+ }
+
+ return ! $hasError;
}
- return !$hasError;
- }
-
- protected function processConstraint(Setup_Constraint $constraint, OutputInterface &$output)
- {
- $ok = true;
- if ($constraint->is_ok())
+ protected function processConstraint(Setup_Constraint $constraint, OutputInterface &$output)
{
- $output->writeln("\t\t" . $constraint->get_message() . ' ');
- }
- elseif ($constraint->is_blocker())
- {
- $output->writeln("\t!!!\t" . $constraint->get_message() . ' ');
- $ok = false;
- }
- else
- {
- $output->writeln("\t/!\\\t" . $constraint->get_message() . ' ');
- }
-
- return $ok;
- }
+ $ok = true;
+ if ($constraint->is_ok()) {
+ $output->writeln("\t\t" . $constraint->get_message() . ' ');
+ } elseif ($constraint->is_blocker()) {
+ $output->writeln("\t!!!\t" . $constraint->get_message() . ' ');
+ $ok = false;
+ } else {
+ $output->writeln("\t/!\\\t" . $constraint->get_message() . ' ');
+ }
+ return $ok;
+ }
}
diff --git a/lib/classes/module/console/systemExport.class.php b/lib/classes/module/console/systemExport.class.php
index b532c3b81a..f704f48b35 100644
--- a/lib/classes/module/console/systemExport.class.php
+++ b/lib/classes/module/console/systemExport.class.php
@@ -25,288 +25,259 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemExport extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('Export all phraseanet records to a directory');
+ $this->setDescription('Export all phraseanet records to a directory');
- /**
- * To implement
- */
+ /**
+ * To implement
+ */
// $this->addOption('useoriginalname', 'o', InputOption::VALUE_OPTIONAL
// , 'Use original name for dest files', false);
- /**
- * To implement
- */
+ /**
+ * To implement
+ */
// $this->addOption('excludefield', 'f', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
// , 'Exclude field from XML', array());
- /**
- * To implement
- */
+ /**
+ * To implement
+ */
// $this->addOption('excludestatus', '', InputOption::VALUE_OPTIONAL
// , 'Exclude Status', false);
- $this->addOption('docperdir', 'd', InputOption::VALUE_OPTIONAL
- , 'Maximum number of files per dir', 100);
+ $this->addOption('docperdir', 'd', InputOption::VALUE_OPTIONAL
+ , 'Maximum number of files per dir', 100);
- $this->addOption('caption', 'c', InputOption::VALUE_OPTIONAL
- , 'Export Caption (XML)', false);
+ $this->addOption('caption', 'c', InputOption::VALUE_OPTIONAL
+ , 'Export Caption (XML)', false);
- $this->addOption('limit', 'l', InputOption::VALUE_OPTIONAL
- , 'Limit files quantity (for test purposes)', false);
+ $this->addOption('limit', 'l', InputOption::VALUE_OPTIONAL
+ , 'Limit files quantity (for test purposes)', false);
- $this->addOption('base_id', 'b', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
- , 'Restrict on base_ids', array());
+ $this->addOption('base_id', 'b', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
+ , 'Restrict on base_ids', array());
- $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
- , 'Restrict on sbas_ids', array());
+ $this->addOption('sbas_id', 's', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY
+ , 'Restrict on sbas_ids', array());
- $this->addArgument('directory', InputOption::VALUE_REQUIRED
- , 'The directory where to export');
+ $this->addArgument('directory', InputOption::VALUE_REQUIRED
+ , 'The directory where to export');
- $this->addOption('sanitize', '', InputOption::VALUE_REQUIRED
- , 'Sanitize filenames. Set to 0 to disable', true);
+ $this->addOption('sanitize', '', InputOption::VALUE_REQUIRED
+ , 'Sanitize filenames. Set to 0 to disable', true);
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $docPerDir = max(1, (int) $input->getOption('docperdir'));
-
- /**
- *
- * To implement
- *
- $useOriginalName = !!$input->getOption('useoriginalname');
- $excludeFields = $input->getOption('excludefield');
- $exportStatus = !$input->getOption('excludestatus');
- *
- */
-
- $Caption = $input->getOption('caption');
-
- $limit = ctype_digit($input->getOption('limit')) ? max(0, (int) $input->getOption('limit')) : false;
-
- $restrictBaseIds = $input->getOption('base_id');
-
- $restrictSbasIds = $input->getOption('sbas_id');
-
- $sanitize = $input->getOption('sanitize');
-
-
- $export_directory = $input->getArgument('directory');
-
- if (!$export_directory)
- {
- throw new Exception('Missing directory argument');
+ return $this;
}
- $export_directory = realpath(substr($export_directory, 0, 1) === '/' ? $export_directory : getcwd() . '/' . $export_directory . '/');
-
- if (!$export_directory)
+ public function execute(InputInterface $input, OutputInterface $output)
{
- throw new Exception('Export directory does not exists or is not accessible');
- }
+ $docPerDir = max(1, (int) $input->getOption('docperdir'));
- if (!is_writable($export_directory))
- {
- throw new Exception('Export directory is not writable');
- }
+ /**
+ *
+ * To implement
+ *
+ $useOriginalName = !!$input->getOption('useoriginalname');
+ $excludeFields = $input->getOption('excludefield');
+ $exportStatus = !$input->getOption('excludestatus');
+ *
+ */
+ $Caption = $input->getOption('caption');
- /**
- * Sanitize
- */
- foreach ($restrictBaseIds as $key => $base_id)
- {
- $restrictBaseIds[$key] = (int) $base_id;
- }
- foreach ($restrictSbasIds as $key => $sbas_id)
- {
- $restrictSbasIds[$key] = (int) $sbas_id;
- }
+ $limit = ctype_digit($input->getOption('limit')) ? max(0, (int) $input->getOption('limit')) : false;
+
+ $restrictBaseIds = $input->getOption('base_id');
+
+ $restrictSbasIds = $input->getOption('sbas_id');
+
+ $sanitize = $input->getOption('sanitize');
- if (count($restrictSbasIds) > 0)
- {
- $output->writeln("Export datas from selected sbas_ids");
- }
- elseif (count($restrictBaseIds) > 0)
- {
- $output->writeln("Export datas from selected base_ids");
- }
+ $export_directory = $input->getArgument('directory');
- $appbox = \appbox::get_instance(\bootstrap::getCore());
-
- $total = $errors = 0;
-
- $unicode = new \unicode();
-
- foreach ($appbox->get_databoxes() as $databox)
- {
- $output->writeln(sprintf("Processing %s ", $databox->get_viewname()));
-
- if (count($restrictSbasIds) > 0 && !in_array($databox->get_sbas_id(), $restrictSbasIds))
- {
- $output->writeln(sprintf("Databox not selected, bypassing ..."));
- continue;
- }
-
- $go = true;
- $coll_ids = array();
-
- if (count($restrictBaseIds) > 0)
- {
- $go = false;
- foreach ($databox->get_collections() as $collection)
- {
- if (in_array($collection->get_base_id(), $restrictBaseIds))
- {
-
- $go = true;
- $coll_ids[] = $collection->get_coll_id();
- }
- }
- }
-
- if (!$go)
- {
- $output->writeln(sprintf("Collections not selected, bypassing ..."));
- continue;
- }
-
- $local_export = $export_directory
- . '/' . $unicode->remove_nonazAZ09($databox->get_viewname(), true, true)
- . '/';
-
- system_file::mkdir($local_export);
-
- $sql = 'SELECT record_id FROM record WHERE parent_record_id = 0 ';
-
- if (count($coll_ids) > 0)
- {
- $sql .= ' AND coll_id IN (' . implode(', ', $coll_ids) . ') ';
- }
-
- $sql .= ' ORDER BY record_id ASC ';
-
- if ($limit)
- {
- $sql .= ' LIMIT 0, ' . $limit;
- }
-
- $stmt = $databox->get_connection()->prepare($sql);
- $stmt->execute();
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
-
- $done = 0;
- $current_total = count($rs);
- $total += $current_total;
- $l = strlen((string) $current_total) + 1;
-
- $dir_format = 'datas%' . strlen((string) ceil($current_total / $docPerDir)) . 'd';
-
- $dir_increment = 0;
- foreach ($rs as $row)
- {
- $record = $databox->get_record($row['record_id']);
- if (($done % $docPerDir) === 0)
- {
- $dir_increment++;
- $in_dir_files = array();
- $current_dir = $local_export . sprintf($dir_format, $dir_increment) . '/';
- system_file::mkdir($current_dir);
+ if ( ! $export_directory) {
+ throw new Exception('Missing directory argument');
}
- if ($sanitize)
- {
- $filename = $unicode->remove_nonazAZ09($record->get_original_name(), true, true, true);
- }
- else
- {
- $filename = $record->get_original_name();
+ $export_directory = realpath(substr($export_directory, 0, 1) === '/' ? $export_directory : getcwd() . '/' . $export_directory . '/');
+
+ if ( ! $export_directory) {
+ throw new Exception('Export directory does not exists or is not accessible');
}
- $this->generateDefinitiveFilename($in_dir_files, $filename);
-
- $output_file = $current_dir . $filename;
-
- if (!$this->processRecords($record, $output_file, $Caption))
- {
- $errors++;
+ if ( ! is_writable($export_directory)) {
+ throw new Exception('Export directory is not writable');
}
- $done++;
+ /**
+ * Sanitize
+ */
+ foreach ($restrictBaseIds as $key => $base_id) {
+ $restrictBaseIds[$key] = (int) $base_id;
+ }
+ foreach ($restrictSbasIds as $key => $sbas_id) {
+ $restrictSbasIds[$key] = (int) $sbas_id;
+ }
- $output->write(sprintf("\r#%" . $l . "d record remaining", $current_total - $done));
- }
- $output->writeln(" | " . $current_total . " records done\n");
+
+ if (count($restrictSbasIds) > 0) {
+ $output->writeln("Export datas from selected sbas_ids");
+ } elseif (count($restrictBaseIds) > 0) {
+ $output->writeln("Export datas from selected base_ids");
+ }
+
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
+
+ $total = $errors = 0;
+
+ $unicode = new \unicode();
+
+ foreach ($appbox->get_databoxes() as $databox) {
+ $output->writeln(sprintf("Processing %s ", $databox->get_viewname()));
+
+ if (count($restrictSbasIds) > 0 && ! in_array($databox->get_sbas_id(), $restrictSbasIds)) {
+ $output->writeln(sprintf("Databox not selected, bypassing ..."));
+ continue;
+ }
+
+ $go = true;
+ $coll_ids = array();
+
+ if (count($restrictBaseIds) > 0) {
+ $go = false;
+ foreach ($databox->get_collections() as $collection) {
+ if (in_array($collection->get_base_id(), $restrictBaseIds)) {
+
+ $go = true;
+ $coll_ids[] = $collection->get_coll_id();
+ }
+ }
+ }
+
+ if ( ! $go) {
+ $output->writeln(sprintf("Collections not selected, bypassing ..."));
+ continue;
+ }
+
+ $local_export = $export_directory
+ . '/' . $unicode->remove_nonazAZ09($databox->get_viewname(), true, true)
+ . '/';
+
+ system_file::mkdir($local_export);
+
+ $sql = 'SELECT record_id FROM record WHERE parent_record_id = 0 ';
+
+ if (count($coll_ids) > 0) {
+ $sql .= ' AND coll_id IN (' . implode(', ', $coll_ids) . ') ';
+ }
+
+ $sql .= ' ORDER BY record_id ASC ';
+
+ if ($limit) {
+ $sql .= ' LIMIT 0, ' . $limit;
+ }
+
+ $stmt = $databox->get_connection()->prepare($sql);
+ $stmt->execute();
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+
+ $done = 0;
+ $current_total = count($rs);
+ $total += $current_total;
+ $l = strlen((string) $current_total) + 1;
+
+ $dir_format = 'datas%' . strlen((string) ceil($current_total / $docPerDir)) . 'd';
+
+ $dir_increment = 0;
+ foreach ($rs as $row) {
+ $record = $databox->get_record($row['record_id']);
+ if (($done % $docPerDir) === 0) {
+ $dir_increment ++;
+ $in_dir_files = array();
+ $current_dir = $local_export . sprintf($dir_format, $dir_increment) . '/';
+ system_file::mkdir($current_dir);
+ }
+
+ if ($sanitize) {
+ $filename = $unicode->remove_nonazAZ09($record->get_original_name(), true, true, true);
+ } else {
+ $filename = $record->get_original_name();
+ }
+
+ $this->generateDefinitiveFilename($in_dir_files, $filename);
+
+ $output_file = $current_dir . $filename;
+
+ if ( ! $this->processRecords($record, $output_file, $Caption)) {
+ $errors ++;
+ }
+
+ $done ++;
+
+ $output->write(sprintf("\r#%" . $l . "d record remaining", $current_total - $done));
+ }
+ $output->writeln(" | " . $current_total . " records done\n");
+ }
+
+ $output->writeln("$total records done, $errors errors occured");
+
+ return 0;
}
- $output->writeln("$total records done, $errors errors occured");
-
- return 0;
- }
-
- protected function generateDefinitiveFilename(array &$existing, &$filename)
- {
- $definitive_filename = $filename;
- $suffix = 2;
- while (array_key_exists($definitive_filename, $existing))
+ protected function generateDefinitiveFilename(array &$existing, &$filename)
{
- $pathinfo = pathinfo($filename);
+ $definitive_filename = $filename;
+ $suffix = 2;
+ while (array_key_exists($definitive_filename, $existing)) {
+ $pathinfo = pathinfo($filename);
- $definitive_filename = $pathinfo['filename'] . '_' . $suffix .
- (isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '');
- $suffix++;
+ $definitive_filename = $pathinfo['filename'] . '_' . $suffix .
+ (isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '');
+ $suffix ++;
+ }
+
+ $existing[$filename] = $filename;
+ $filename = $definitive_filename;
+
+ return;
}
- $existing[$filename] = $filename;
- $filename = $definitive_filename;
-
- return;
- }
-
- protected function processRecords(\record_adapter $record, $outfile, $caption)
- {
-
- try
+ protected function processRecords(\record_adapter $record, $outfile, $caption)
{
- $file = new system_file($record->get_subdef('document')->get_pathfile());
+
+ try {
+ $file = new system_file($record->get_subdef('document')->get_pathfile());
+ } catch (\Exception_Media_SubdefNotFound $e) {
+ return false;
+ }
+
+ copy($file->getPathname(), $outfile);
+
+ $dest_file = new system_file($outfile);
+
+ touch(
+ $dest_file->getPathname()
+ , $record->get_creation_date()->format('U')
+ , $record->get_modification_date()->format('U')
+ );
+
+ switch (strtolower($caption)) {
+ case 'xml':
+ $pathinfo = pathinfo($dest_file->getPathname());
+ $xml = $record->get_caption()->serialize(caption_record::SERIALIZE_XML);
+ $xml_file = dirname($outfile) . '/' . $pathinfo['filename'] . '.xml';
+ file_put_contents($xml_file, $xml);
+ break;
+ default:
+ break;
+ }
+
+ return true;
}
- catch (\Exception_Media_SubdefNotFound $e)
- {
- return false;
- }
-
- copy($file->getPathname(), $outfile);
-
- $dest_file = new system_file($outfile);
-
- touch(
- $dest_file->getPathname()
- , $record->get_creation_date()->format('U')
- , $record->get_modification_date()->format('U')
- );
-
- switch (strtolower($caption))
- {
- case 'xml':
- $pathinfo = pathinfo($dest_file->getPathname());
- $xml = $record->get_caption()->serialize(caption_record::SERIALIZE_XML);
- $xml_file = dirname($outfile) . '/' . $pathinfo['filename'] . '.xml';
- file_put_contents($xml_file, $xml);
- break;
- default:
- break;
- }
-
- return true;
- }
-
}
diff --git a/lib/classes/module/console/systemMailCheck.class.php b/lib/classes/module/console/systemMailCheck.class.php
index 80fbc28dff..7ea3d3ab92 100644
--- a/lib/classes/module/console/systemMailCheck.class.php
+++ b/lib/classes/module/console/systemMailCheck.class.php
@@ -26,126 +26,107 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemMailCheck extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
+ public function __construct($name = null)
+ {
+ parent::__construct($name);
- $this->setDescription('Check if email addresses are unique (mandatory since 3.5)');
- $this->addOption('list'
+ $this->setDescription('Check if email addresses are unique (mandatory since 3.5)');
+ $this->addOption('list'
, 'l'
, null
, 'List all bad accounts instead of the interactive mode'
- );
+ );
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
-
- $output->writeln("Processing...");
-
- $bad_users = User_Adapter::get_wrong_email_users($appbox);
-
- foreach ($bad_users as $email => $users)
- {
- if ($input->getOption('list'))
- {
- $this->write_infos($email, $users, $output, $appbox);
- }
- elseif ($this->manage_group($email, $users, $output, $appbox) === false)
- {
- break;
- }
-
- $output->writeln("");
+ return $this;
}
- $output->write('Finished !', true);
-
- return 0;
- }
-
- protected function manage_group($email, $users, $output, $appbox)
- {
- $is_stopped = false;
-
- while (!$is_stopped)
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $this->write_infos($email, $users, $output, $appbox);
- $dialog = $this->getHelperSet()->get('dialog');
+ $appbox = appbox::get_instance(\bootstrap::getCore());
- do
- {
- $question = 'What should I do ? '
- . 'continue (C), detach from mail (d), or stop (s) ';
+ $output->writeln("Processing...");
- $continue = mb_strtolower($dialog->ask($output, $question, 'C'));
- }
- while (!in_array($continue, array('c', 'd', 's')));
+ $bad_users = User_Adapter::get_wrong_email_users($appbox);
+
+ foreach ($bad_users as $email => $users) {
+ if ($input->getOption('list')) {
+ $this->write_infos($email, $users, $output, $appbox);
+ } elseif ($this->manage_group($email, $users, $output, $appbox) === false) {
+ break;
+ }
+
+ $output->writeln("");
+ }
+
+ $output->write('Finished !', true);
+
+ return 0;
+ }
+
+ protected function manage_group($email, $users, $output, $appbox)
+ {
+ $is_stopped = false;
+
+ while ( ! $is_stopped) {
+ $this->write_infos($email, $users, $output, $appbox);
+
+ $dialog = $this->getHelperSet()->get('dialog');
+
+ do {
+ $question = 'What should I do ? '
+ . 'continue (C), detach from mail (d), or stop (s) ';
+
+ $continue = mb_strtolower($dialog->ask($output, $question, 'C'));
+ } while ( ! in_array($continue, array('c', 'd', 's')));
- if ($continue == 's')
- {
- return false;
- }
- elseif ($continue == 'c')
- {
+ if ($continue == 's') {
+ return false;
+ } elseif ($continue == 'c') {
+ return true;
+ } elseif ($continue == 'd') {
+ $dialog = $this->getHelperSet()->get('dialog');
+
+ $id = $dialog->ask($output, 'Which id ? ', '');
+
+ try {
+ $tmp_user = User_Adapter::getInstance($id, $appbox);
+
+ if ($tmp_user->get_email() != $email) {
+ throw new Exception('Invalid user');
+ }
+
+ $tmp_user->set_email(null);
+
+ unset($users[$id]);
+ } catch (Exception $e) {
+ $output->writeln('Wrong id ');
+ }
+ }
+
+ if (count($users) <= 1) {
+ $output->writeln(sprintf("\n%s fixed ! ", $email));
+ $is_stopped = true;
+ }
+ }
+
return true;
- }
- elseif ($continue == 'd')
- {
- $dialog = $this->getHelperSet()->get('dialog');
-
- $id = $dialog->ask($output, 'Which id ? ', '');
-
- try
- {
- $tmp_user = User_Adapter::getInstance($id, $appbox);
-
- if ($tmp_user->get_email() != $email)
- {
- throw new Exception('Invalid user');
- }
-
- $tmp_user->set_email(null);
-
- unset($users[$id]);
- }
- catch (Exception $e)
- {
- $output->writeln('Wrong id ');
- }
- }
-
- if (count($users) <= 1)
- {
- $output->writeln(sprintf("\n%s fixed ! ", $email));
- $is_stopped = true;
- }
}
- return true;
- }
-
- protected function write_infos($email, $users, $output, $appbox)
- {
- $output->writeln($email);
-
- foreach ($users as $user)
+ protected function write_infos($email, $users, $output, $appbox)
{
- $output->writeln(
- sprintf(
- "\t %5d %40s %s"
- , $user->get_id()
- , $user->get_display_name()
- , $user->get_last_connection()->format('Y m d')
- )
- );
- }
- }
+ $output->writeln($email);
+ foreach ($users as $user) {
+ $output->writeln(
+ sprintf(
+ "\t %5d %40s %s"
+ , $user->get_id()
+ , $user->get_display_name()
+ , $user->get_last_connection()->format('Y m d')
+ )
+ );
+ }
+ }
}
diff --git a/lib/classes/module/console/systemTemplateGenerator.class.php b/lib/classes/module/console/systemTemplateGenerator.class.php
index 66d6780608..ad5d93fb7e 100644
--- a/lib/classes/module/console/systemTemplateGenerator.class.php
+++ b/lib/classes/module/console/systemTemplateGenerator.class.php
@@ -37,22 +37,21 @@ class module_console_systemTemplateGenerator extends Command
public function execute(InputInterface $input, OutputInterface $output)
{
$tplDirs = array(
- realpath(__DIR__ . '/../../../../templates/web/'),
- realpath(__DIR__ . '/../../../../templates/mobile/')
+ realpath(__DIR__ . '/../../../../templates/web/'),
+ realpath(__DIR__ . '/../../../../templates/mobile/')
);
- $n_ok = $n_error = 0;
+ $n_ok = $n_error = 0;
- foreach ($tplDirs as $tplDir)
- {
+ foreach ($tplDirs as $tplDir) {
$tmpDir = __DIR__ . '/../../../../tmp/cache_twig/';
$loader = new Twig_Loader_Filesystem($tplDir);
$twig = new Twig_Environment($loader, array(
- 'cache' => $tmpDir,
- 'auto_reload' => true
- ));
+ 'cache' => $tmpDir,
+ 'auto_reload' => true
+ ));
$twig->addExtension(new Twig_Extensions_Extension_I18n());
@@ -93,16 +92,12 @@ class module_console_systemTemplateGenerator extends Command
$finder = new Symfony\Component\Finder\Finder();
- foreach ($finder->files()->in(array($tplDir)) as $file)
- {
- try
- {
+ foreach ($finder->files()->in(array($tplDir)) as $file) {
+ try {
$twig->loadTemplate(str_replace($tplDir, '', $file->getPathname()));
$output->writeln('' . $file . '');
$n_ok ++;
- }
- catch (Exception $e)
- {
+ } catch (Exception $e) {
$output->writeln('' . $e->getMessage() . ' ');
$n_error ++;
}
@@ -112,8 +107,7 @@ class module_console_systemTemplateGenerator extends Command
$output->writeln("");
$output->write(sprintf('%d templates generated. ', $n_ok));
- if ($n_error > 0)
- {
+ if ($n_error > 0) {
$output->write(sprintf('%d templates failed. ', $n_error));
}
@@ -121,5 +115,4 @@ class module_console_systemTemplateGenerator extends Command
return $n_error;
}
-
}
diff --git a/lib/classes/module/console/systemUpgrade.class.php b/lib/classes/module/console/systemUpgrade.class.php
index 3e8ff24c7e..31d4a0248a 100644
--- a/lib/classes/module/console/systemUpgrade.class.php
+++ b/lib/classes/module/console/systemUpgrade.class.php
@@ -26,92 +26,73 @@ use Symfony\Component\Console\Command\Command;
class module_console_systemUpgrade extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('Upgrade Phraseanet to the lastest version');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- $Core = \bootstrap::getCore();
- if (!setup::is_installed())
+ public function __construct($name = null)
{
+ parent::__construct($name);
- $output->writeln('This version of Phraseanet requires a config/config.yml, config/connexion.yml, config/service.yml');
- $output->writeln('Would you like it to be created based on your settings ?');
+ $this->setDescription('Upgrade Phraseanet to the lastest version');
- $dialog = $this->getHelperSet()->get('dialog');
- do
- {
- $continue = mb_strtolower($dialog->ask($output, '' . _('Create automatically') . ' (Y/n) ', 'y'));
- }
- while (!in_array($continue, array('y', 'n')));
-
- if ($continue == 'y')
- {
- try
- {
- $connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
- $configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
-
- $Core->getConfiguration()->upgradeFromOldConf($configInc, $connexionInc);
- }
- catch (\Exception $e)
- {
-
- }
- }
- else
- {
- throw new RuntimeException('Phraseanet is not set up');
- }
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- $output->write('Phraseanet is going to be upgraded', true);
- $dialog = $this->getHelperSet()->get('dialog');
-
- do
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $continue = mb_strtolower($dialog->ask($output, '' . _('Continuer ?') . ' (Y/n) ', 'Y'));
- }
- while (!in_array($continue, array('y', 'n')));
+ $Core = \bootstrap::getCore();
+ if ( ! setup::is_installed()) {
+ $output->writeln('This version of Phraseanet requires a config/config.yml, config/connexion.yml, config/service.yml');
+ $output->writeln('Would you like it to be created based on your settings ?');
- if ($continue == 'y')
- {
- try
- {
- $Core = \bootstrap::getCore();
- $output->write('Upgrading... ', true);
- $appbox = appbox::get_instance($Core);
+ $dialog = $this->getHelperSet()->get('dialog');
+ do {
+ $continue = mb_strtolower($dialog->ask($output, '' . _('Create automatically') . ' (Y/n) ', 'y'));
+ } while ( ! in_array($continue, array('y', 'n')));
- if (count(User_Adapter::get_wrong_email_users($appbox)) > 0)
- {
- return $output->writeln(sprintf('You have to fix your database before upgrade with the system:mailCheck command '));
+ if ($continue == 'y') {
+ try {
+ $connexionInc = new \SplFileObject(__DIR__ . '/../../../../config/connexion.inc');
+ $configInc = new \SplFileObject(__DIR__ . '/../../../../config/config.inc');
+
+ $Core->getConfiguration()->upgradeFromOldConf($configInc, $connexionInc);
+ } catch (\Exception $e) {
+
+ }
+ } else {
+ throw new RuntimeException('Phraseanet is not set up');
+ }
}
- $upgrader = new Setup_Upgrade($appbox);
- $advices = $appbox->forceUpgrade($upgrader);
- }
- catch (\Exception $e)
- {
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
- $output->writeln(sprintf('An error occured while upgrading : %s ', $e->getMessage()));
- }
+ $output->write('Phraseanet is going to be upgraded', true);
+ $dialog = $this->getHelperSet()->get('dialog');
+
+ do {
+ $continue = mb_strtolower($dialog->ask($output, '' . _('Continuer ?') . ' (Y/n) ', 'Y'));
+ } while ( ! in_array($continue, array('y', 'n')));
+
+
+ if ($continue == 'y') {
+ try {
+ $Core = \bootstrap::getCore();
+ $output->write('Upgrading... ', true);
+ $appbox = appbox::get_instance($Core);
+
+ if (count(User_Adapter::get_wrong_email_users($appbox)) > 0) {
+ return $output->writeln(sprintf('You have to fix your database before upgrade with the system:mailCheck command '));
+ }
+
+ $upgrader = new Setup_Upgrade($appbox);
+ $advices = $appbox->forceUpgrade($upgrader);
+ } catch (\Exception $e) {
+
+ $output->writeln(sprintf('An error occured while upgrading : %s ', $e->getMessage()));
+ }
+ } else {
+ $output->write('Canceled ', true);
+ }
+ $output->write('Finished !', true);
+
+ return 0;
}
- else
- {
- $output->write('Canceled ', true);
- }
- $output->write('Finished !', true);
-
- return 0;
- }
-
}
diff --git a/lib/classes/module/console/tasklist.class.php b/lib/classes/module/console/tasklist.class.php
index 4ec9646b9a..fbbf732ce5 100644
--- a/lib/classes/module/console/tasklist.class.php
+++ b/lib/classes/module/console/tasklist.class.php
@@ -26,56 +26,49 @@ use Symfony\Component\Console\Command\Command;
class module_console_tasklist extends Command
{
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->setDescription('List tasks');
-
- return $this;
- }
-
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!setup::is_installed())
+ public function __construct($name = null)
{
- $output->writeln('Phraseanet is not set up');
+ parent::__construct($name);
- return 1;
+ $this->setDescription('List tasks');
+
+ return $this;
}
- require_once __DIR__ . '/../../../../lib/bootstrap.php';
-
- try
+ public function execute(InputInterface $input, OutputInterface $output)
{
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $task_manager = new task_manager($appbox);
- $tasks = $task_manager->get_tasks();
+ if ( ! setup::is_installed()) {
+ $output->writeln('Phraseanet is not set up');
- if (count($tasks) === 0)
- {
- $output->writeln('No tasks on your install !');
- }
+ return 1;
+ }
- foreach ($tasks as $task)
- {
- $this->print_task($task, $output);
- }
+ require_once __DIR__ . '/../../../../lib/bootstrap.php';
- return 0;
+ try {
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $task_manager = new task_manager($appbox);
+ $tasks = $task_manager->get_tasks();
+
+ if (count($tasks) === 0) {
+ $output->writeln('No tasks on your install !');
+ }
+
+ foreach ($tasks as $task) {
+ $this->print_task($task, $output);
+ }
+
+ return 0;
+ } catch (\Exception $e) {
+ return 1;
+ }
}
- catch (\Exception $e)
+
+ protected function print_task(task_abstract $task, OutputInterface &$output)
{
- return 1;
+ $message = $task->get_task_id() . "\t" . ($task->get_status() ) . "\t" . $task->get_title();
+ $output->writeln($message);
+
+ return $this;
}
- }
-
- protected function print_task(task_abstract $task, OutputInterface &$output)
- {
- $message = $task->get_task_id() . "\t" . ($task->get_status() ) . "\t" . $task->get_title();
- $output->writeln($message);
-
- return $this;
- }
-
}
diff --git a/lib/classes/module/console/taskrun.class.php b/lib/classes/module/console/taskrun.class.php
index d7953cc76c..beba23d923 100644
--- a/lib/classes/module/console/taskrun.class.php
+++ b/lib/classes/module/console/taskrun.class.php
@@ -25,117 +25,105 @@ use Symfony\Component\Console\Command\Command;
class module_console_taskrun extends Command
{
+ private $task;
+ private $shedulerPID;
- private $task;
- private $shedulerPID;
-
- public function __construct($name = null)
- {
- parent::__construct($name);
-
- $this->task = NULL;
- $this->shedulerPID = NULL;
-
- $this->addArgument('task_id', InputArgument::REQUIRED, 'The task_id to run');
- $this->addOption(
- 'runner'
- , 'r'
- , InputOption::VALUE_REQUIRED
- , 'The name of the runner (manual, scheduler...)'
- , task_abstract::RUNNER_MANUAL
- );
- $this->addOption(
- 'nolog'
- , NULL
- , 1 | InputOption::VALUE_NONE
- , 'do not log to logfile'
- , NULL
- );
- $this->setDescription('Run task');
-
- return $this;
- }
-
- function sig_handler($signo)
- {
- if ($this->task)
+ public function __construct($name = null)
{
- $this->task->log(sprintf("signal %s received", $signo));
- if ($signo == SIGTERM)
- $this->task->set_running(false);
- }
- }
+ parent::__construct($name);
- public function execute(InputInterface $input, OutputInterface $output)
- {
- if (!setup::is_installed())
- {
- $output->writeln('Phraseanet is not set up');
+ $this->task = NULL;
+ $this->shedulerPID = NULL;
- return 1;
+ $this->addArgument('task_id', InputArgument::REQUIRED, 'The task_id to run');
+ $this->addOption(
+ 'runner'
+ , 'r'
+ , InputOption::VALUE_REQUIRED
+ , 'The name of the runner (manual, scheduler...)'
+ , task_abstract::RUNNER_MANUAL
+ );
+ $this->addOption(
+ 'nolog'
+ , NULL
+ , 1 | InputOption::VALUE_NONE
+ , 'do not log to logfile'
+ , NULL
+ );
+ $this->setDescription('Run task');
+
+ return $this;
}
- $task_id = (int) $input->getArgument('task_id');
-
- if ($task_id <= 0 || strlen($task_id) !== strlen($input->getArgument('task_id')))
- throw new \RuntimeException('Argument must be an Id.');
-
- $appbox = \appbox::get_instance(\bootstrap::getCore());
- $task_manager = new task_manager($appbox);
- $this->task = $task_manager->get_task($task_id);
-
- if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL)
+ function sig_handler($signo)
{
- $runner = task_abstract::RUNNER_MANUAL;
- }
- else
- {
- $runner = task_abstract::RUNNER_SCHEDULER;
- $registry = $appbox->get_registry();
- $schedFile = $registry->get('GV_RootPath') . 'tmp/locks/scheduler.lock';
- if (file_exists($schedFile))
- $this->shedulerPID = (int) (trim(file_get_contents($schedFile)));
- }
-
- register_tick_function(array($this, 'tick_handler'), true);
- declare(ticks = 1);
- pcntl_signal(SIGTERM, array($this, 'sig_handler'));
-
- $this->task->run($runner, $input, $output);
-
- $this->task->log(sprintf("%s [%d] taskrun : returned from 'run()', get_status()=%s \n", __FILE__, __LINE__, $this->task->get_status()));
-
- if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL)
- {
- $runner = task_abstract::RUNNER_MANUAL;
- }
- }
-
- public function tick_handler()
- {
- static $start = FALSE;
-
- if ($start === FALSE)
- {
- $start = time();
- }
-
- if (time() - $start > 0)
- {
- if ($this->shedulerPID)
- {
- if (!posix_kill($this->shedulerPID, 0))
- {
- if (method_exists($this->task, 'signal'))
- $this->task->signal('SIGNAL_SCHEDULER_DIED');
- else
- $this->task->set_status(task_abstract::STATUS_TOSTOP);
+ if ($this->task) {
+ $this->task->log(sprintf("signal %s received", $signo));
+ if ($signo == SIGTERM)
+ $this->task->set_running(false);
}
- }
-
- $start = time();
}
- }
+ public function execute(InputInterface $input, OutputInterface $output)
+ {
+ if ( ! setup::is_installed()) {
+ $output->writeln('Phraseanet is not set up');
+
+ return 1;
+ }
+
+ $task_id = (int) $input->getArgument('task_id');
+
+ if ($task_id <= 0 || strlen($task_id) !== strlen($input->getArgument('task_id')))
+ throw new \RuntimeException('Argument must be an Id.');
+
+ $appbox = \appbox::get_instance(\bootstrap::getCore());
+ $task_manager = new task_manager($appbox);
+ $this->task = $task_manager->get_task($task_id);
+
+ if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL) {
+ $runner = task_abstract::RUNNER_MANUAL;
+ } else {
+ $runner = task_abstract::RUNNER_SCHEDULER;
+ $registry = $appbox->get_registry();
+ $schedFile = $registry->get('GV_RootPath') . 'tmp/locks/scheduler.lock';
+ if (file_exists($schedFile))
+ $this->shedulerPID = (int) (trim(file_get_contents($schedFile)));
+ }
+
+ register_tick_function(array($this, 'tick_handler'), true);
+ declare(ticks = 1);
+ pcntl_signal(SIGTERM, array($this, 'sig_handler'));
+
+ $this->task->run($runner, $input, $output);
+
+ $this->task->log(sprintf("%s [%d] taskrun : returned from 'run()', get_status()=%s \n", __FILE__, __LINE__, $this->task->get_status()));
+
+ if ($input->getOption('runner') === task_abstract::RUNNER_MANUAL) {
+ $runner = task_abstract::RUNNER_MANUAL;
+ }
+ }
+
+ public function tick_handler()
+ {
+ static $start = FALSE;
+
+ if ($start === FALSE) {
+ $start = time();
+ }
+
+ if (time() - $start > 0) {
+ if ($this->shedulerPID) {
+ if ( ! posix_kill($this->shedulerPID, 0)) {
+ if (method_exists($this->task, 'signal'))
+ $this->task->signal('SIGNAL_SCHEDULER_DIED');
+ else
+ $this->task->set_status(task_abstract::STATUS_TOSTOP);
+ }
+ }
+
+ $start = time();
+ }
+ }
}
diff --git a/lib/classes/module/report.class.php b/lib/classes/module/report.class.php
index af8131892a..0095f0b050 100644
--- a/lib/classes/module/report.class.php
+++ b/lib/classes/module/report.class.php
@@ -17,881 +17,861 @@
*/
class module_report
{
-
- /**
- * Start date of the report
- * @var string - timestamp
- */
- protected $dmin;
-
- /**
- * End date of the report
- * @var string - timestamp
- */
- protected $dmax;
-
- /**
- * Id of the base we want to connect
- * @var int
- */
- protected $sbas_id;
-
- /**
- * Id of the current app's box user
- * @var int
- */
- protected $user_id;
-
- /**
- * The result of the report
- * @var array
- */
- public $report = array();
-
- /**
- * The title of the report
- * @var string
- */
- protected $title = '';
-
- /**
- * default displayed value in the formated tab
- * @var array
- */
- protected $display = array();
-
- /**
- * ?
- * @var
- */
- protected $default_display = array();
-
- /**
- * Contain all the field from the sql request
- * @var array
- */
- protected $champ = array();
-
- /**
- * result of the report
- * @var array
- */
- protected $result = array();
-
- /**
- * The id of all collections from a databox
- * @var string
- */
- protected $list_coll_id = '';
-
- /**
- * The number of record displayed by page if enable limit is false
- * @var int
- */
- protected $nb_record = 30;
-
- /**
- * The current number of the page where are displaying the results
- * @var int
- */
- protected $nb_page = 1;
-
- /**
- * check if there is a previous page
- * @var
- */
- protected $previous_page = false;
-
- /**
- * check if there is a next page
- * @var
- */
- protected $next_page = false;
-
- /**
- *
- * @var int total of result
- */
- protected $total = 0;
-
- /**
- * the request executed
- */
- protected $req = '';
-
- /**
- * the request executed
- */
- protected $params = array();
-
- /**
- * do we display next and previous button
- * @var bool
- */
- protected $display_nav = false;
-
- /**
- * do we display the configuration button
- * @var
- */
- protected $config = true;
-
- /**
- * gettext tags for days
- * @var
- */
- protected $jour;
-
- /**
- * gettext tags for month
- * @var
- */
- protected $month;
-
- /**
- * The name of the database
- * @var string
- */
- protected $dbname;
-
- /**
- * The periode displayed in a string of the report
- * @var string
- */
- protected $periode;
-
- /**
- * filter executed on report choose by the user
- * @var array;
- */
- protected $tab_filter = array();
-
- /**
- * column displayed in the report choose by the user
- * @var
- */
- protected $active_column = array();
-
- /**
- * array that contains the string displayed
- * foreach filters
- * @var
- */
- protected $posting_filter = array();
-
- /**
- * The ORDER BY filters of the query
- * by default is empty
- * @var array
- */
- protected $tab_order = array();
-
- /**
- * define columns that are boundable
- * @var
- */
- protected $bound = array();
-
- /**
- * do we display print button
- * @var
- */
- protected $print = true;
-
- /**
- * do we display csv button
- * @var
- */
- protected $csv = true;
-
- /**
- * do we enable limit filter for the report
- * @var bool
- */
- protected $enable_limit = true;
-
- /**
- * gettext correspondance for all available columns in report
- * @var array
- */
- protected $cor = array();
-
- /**
- * group result of a report this is the name ogf the grouped column
- * @var string
- */
- protected $groupby;
-
- /**
- * disbale or enable pretty string useful for export in csv
- * @var boolean
- */
- protected $pretty_string = true;
-
- /**
- *
- */
- protected $cor_query = array();
- protected $isInformative;
-
- /**
- * Constructor
- *
- *
- * @name report::__construct()
- * @param $arg1 the minimal date of the report
- * @param $arg2 the maximal date of the report
- * @param $sbas_id the id of the base where we want to connect
- */
- public function __construct($d1, $d2, $sbas_id, $collist)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $session = $appbox->get_session();
- $this->dmin = $d1;
- $this->dmax = $d2;
- $this->sbas_id = $sbas_id;
- $this->list_coll_id = $collist;
- $this->user_id = $session->get_usr_id();
- $this->periode = phraseadate::getPrettyString(new DateTime($d1))
- . ' - ' . phraseadate::getPrettyString(new DateTime($d2));
- $this->dbname = phrasea::sbas_names($sbas_id);
- $this->cor = $this->setCor();
- $this->jour = $this->setDay();
- $this->month = $this->setMonth();
- }
-
- public function IsInformative()
- {
- return $this->isInformative;
- }
-
- public function setIsInformative($isInformative)
- {
- $this->isInformative = $isInformative;
- }
-
- public function getUser_id()
- {
- return $this->user_id;
- }
-
- public function getParams()
- {
- return $this->params;
- }
-
- public function setUser_id($user_id)
- {
- $this->user_id = $user_id;
- }
-
- public function getSbas_id()
- {
- return $this->sbas_id;
- }
-
- public function setSbas_id($sbas_id)
- {
- $this->sbas_id = $sbas_id;
- }
-
- public function setPrettyString($bool)
- {
- $this->pretty_string = $bool;
- }
-
- public function getPrettyString()
- {
- return $this->pretty_string;
- }
-
- public function setTitle($title)
- {
- $this->title = $title;
-
- return $this;
- }
-
- public function setCsv($bool)
- {
- $this->csv = $bool;
-
- return $this;
- }
-
- public function getCsv()
- {
- return $this->csv;
- }
-
- public function setFilter(array $filter)
- {
- $this->tab_filter = $filter;
-
- return $this;
- }
-
- public function setPeriode($periode)
- {
- $this->periode = $periode;
-
- return $this;
- }
-
- public function setRequest($sql)
- {
- $this->req = $sql;
- }
-
- public function getPeriode()
- {
- return $this->periode;
- }
-
- public function setpostingFilter($filter)
- {
- $this->posting_filter = $filter;
-
- return $this;
- }
-
- public function getPostingFilter()
- {
- return $this->posting_filter;
- }
-
- public function setLimit($page, $limit)
- {
- $this->nb_page = $page;
- $this->nb_record = $limit;
-
- return $this;
- }
-
- public function getGroupBy()
- {
- return $this->groupby;
- }
-
- public function setGroupBy($groupby)
- {
- $this->groupby = $groupby;
-
- return $this;
- }
-
- public function setActiveColumn(array $active_column)
- {
- $this->active_column = $active_column;
-
- return $this;
- }
-
- public function getActiveColumn()
- {
- return $this->active_column;
- }
-
- public function setConfig($bool)
- {
- $this->config = $bool;
-
- return $this;
- }
-
- public function getConfig()
- {
- return $this->config;
- }
-
- public function setPrint($bool)
- {
- $this->print = $bool;
-
- return $this;
- }
-
- public function getPrint()
- {
- return $this->print;
- }
-
- public function setHasLimit($bool)
- {
- $this->enable_limit = $bool;
-
- return $this;
- }
-
- public function getHasLimit()
- {
- return $this->enable_limit;
- }
-
- public function setBound($column, $bool)
- {
- if ($bool)
+ /**
+ * Start date of the report
+ * @var string - timestamp
+ */
+ protected $dmin;
+
+ /**
+ * End date of the report
+ * @var string - timestamp
+ */
+ protected $dmax;
+
+ /**
+ * Id of the base we want to connect
+ * @var int
+ */
+ protected $sbas_id;
+
+ /**
+ * Id of the current app's box user
+ * @var int
+ */
+ protected $user_id;
+
+ /**
+ * The result of the report
+ * @var array
+ */
+ public $report = array();
+
+ /**
+ * The title of the report
+ * @var string
+ */
+ protected $title = '';
+
+ /**
+ * default displayed value in the formated tab
+ * @var array
+ */
+ protected $display = array();
+
+ /**
+ * ?
+ * @var
+ */
+ protected $default_display = array();
+
+ /**
+ * Contain all the field from the sql request
+ * @var array
+ */
+ protected $champ = array();
+
+ /**
+ * result of the report
+ * @var array
+ */
+ protected $result = array();
+
+ /**
+ * The id of all collections from a databox
+ * @var string
+ */
+ protected $list_coll_id = '';
+
+ /**
+ * The number of record displayed by page if enable limit is false
+ * @var int
+ */
+ protected $nb_record = 30;
+
+ /**
+ * The current number of the page where are displaying the results
+ * @var int
+ */
+ protected $nb_page = 1;
+
+ /**
+ * check if there is a previous page
+ * @var
+ */
+ protected $previous_page = false;
+
+ /**
+ * check if there is a next page
+ * @var
+ */
+ protected $next_page = false;
+
+ /**
+ *
+ * @var int total of result
+ */
+ protected $total = 0;
+
+ /**
+ * the request executed
+ */
+ protected $req = '';
+
+ /**
+ * the request executed
+ */
+ protected $params = array();
+
+ /**
+ * do we display next and previous button
+ * @var bool
+ */
+ protected $display_nav = false;
+
+ /**
+ * do we display the configuration button
+ * @var
+ */
+ protected $config = true;
+
+ /**
+ * gettext tags for days
+ * @var
+ */
+ protected $jour;
+
+ /**
+ * gettext tags for month
+ * @var
+ */
+ protected $month;
+
+ /**
+ * The name of the database
+ * @var string
+ */
+ protected $dbname;
+
+ /**
+ * The periode displayed in a string of the report
+ * @var string
+ */
+ protected $periode;
+
+ /**
+ * filter executed on report choose by the user
+ * @var array;
+ */
+ protected $tab_filter = array();
+
+ /**
+ * column displayed in the report choose by the user
+ * @var
+ */
+ protected $active_column = array();
+
+ /**
+ * array that contains the string displayed
+ * foreach filters
+ * @var
+ */
+ protected $posting_filter = array();
+
+ /**
+ * The ORDER BY filters of the query
+ * by default is empty
+ * @var array
+ */
+ protected $tab_order = array();
+
+ /**
+ * define columns that are boundable
+ * @var
+ */
+ protected $bound = array();
+
+ /**
+ * do we display print button
+ * @var
+ */
+ protected $print = true;
+
+ /**
+ * do we display csv button
+ * @var
+ */
+ protected $csv = true;
+
+ /**
+ * do we enable limit filter for the report
+ * @var bool
+ */
+ protected $enable_limit = true;
+
+ /**
+ * gettext correspondance for all available columns in report
+ * @var array
+ */
+ protected $cor = array();
+
+ /**
+ * group result of a report this is the name ogf the grouped column
+ * @var string
+ */
+ protected $groupby;
+
+ /**
+ * disbale or enable pretty string useful for export in csv
+ * @var boolean
+ */
+ protected $pretty_string = true;
+
+ /**
+ *
+ */
+ protected $cor_query = array();
+ protected $isInformative;
+
+ /**
+ * Constructor
+ *
+ *
+ * @name report::__construct()
+ * @param $arg1 the minimal date of the report
+ * @param $arg2 the maximal date of the report
+ * @param $sbas_id the id of the base where we want to connect
+ */
+ public function __construct($d1, $d2, $sbas_id, $collist)
{
- $this->bound[$column] = 1;
- }
- else
- {
- $this->bound[$column] = 0;
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $session = $appbox->get_session();
+ $this->dmin = $d1;
+ $this->dmax = $d2;
+ $this->sbas_id = $sbas_id;
+ $this->list_coll_id = $collist;
+ $this->user_id = $session->get_usr_id();
+ $this->periode = phraseadate::getPrettyString(new DateTime($d1))
+ . ' - ' . phraseadate::getPrettyString(new DateTime($d2));
+ $this->dbname = phrasea::sbas_names($sbas_id);
+ $this->cor = $this->setCor();
+ $this->jour = $this->setDay();
+ $this->month = $this->setMonth();
}
- return $this;
- }
-
- public function getBound()
- {
- return $this->bound;
- }
-
- public function setOrder($champ, $order)
- {
- $this->tab_order['champ'] = $champ;
- $this->tab_order['order'] = $order;
-
- return $this;
- }
-
- public function getTitle()
- {
- return $this->title;
- }
-
- public function getDisplay()
- {
- return $this->display;
- }
-
- public function getEnableLimit()
- {
- return $this->enable_limit;
- }
-
- public function getSbasId()
- {
- return $this->sbas_id;
- }
-
- public function getDmin()
- {
- return $this->dmin;
- }
-
- public function getDmax()
- {
- return $this->dmax;
- }
-
- public function getResult()
- {
- return $this->result;
- }
-
- public function setResult(array $rs)
- {
- $this->result = $rs;
-
- return $this;
- }
-
- public function getOrder($k = false)
- {
- if ($k === false)
+ public function IsInformative()
{
- return $this->tab_order;
+ return $this->isInformative;
}
- return $this->tab_order[$k];
- }
-
- public function getNbPage()
- {
- return $this->nb_page;
- }
-
- public function getNbRecord()
- {
- return $this->nb_record;
- }
-
- public function getTabFilter()
- {
- return $this->tab_filter;
- }
-
- public function getUserId()
- {
- return $this->user_id;
- }
-
- public function getListCollId()
- {
- return $this->list_coll_id;
- }
-
- public function getReq()
- {
- return $this->req;
- }
-
- public function getTransQueryString()
- {
- return $this->cor_query;
- }
-
- public function getTotal()
- {
- return $this->total;
- }
-
- public function setTotal($total)
- {
- $this->total = $total;
- }
-
- public function getDefault_display()
- {
- return $this->default_display;
- }
-
- public function setDefault_display($default_display)
- {
- $this->default_display = $default_display;
- }
-
- public function getChamps()
- {
- return $this->champ;
- }
-
- /**
- * Retourne un objet qui genere la requete selon le type de report
- * @param string $domain
- * @return module_report_sqlconnexion
- */
- public function sqlBuilder($domain)
- {
- switch ($domain)
+ public function setIsInformative($isInformative)
{
- case 'connexion' :
- return new module_report_sqlconnexion($this);
- break;
- case 'download' :
- return new module_report_sqldownload($this);
- break;
- case 'question' :
- return new module_report_sqlquestion($this);
- break;
- case 'action' :
- return new module_report_sqlaction($this);
- break;
- default:
- return $this->req;
- break;
+ $this->isInformative = $isInformative;
}
- }
- protected function setChamp($rs)
- {
- $row = array_shift($rs);
-
- $this->champ = is_array($row) ? array_keys($row) : array();
- $this->default_display = is_array($row) ? array_keys($row) : array();
-
- return;
- }
-
- /**
- * initialise les configuration des columns ex : boundable, linkable orderable
- * etc .. par defaut ou celle passe en parametre par $tab
- * @param array $tab
- * @param string $groupby
- * @return void
- */
- protected function setDisplay($tab, $groupby = false)
- {
- if ($tab == false && $groupby == false)
- $this->initDefaultConfigColumn($this->default_display);
- elseif ($groupby != false && $tab == false)
- $this->initDefaultConfigColumn($this->champ);
- elseif ($tab != false)
- $this->setConfigColumn($tab);
-
- return;
- }
-
- /**
- *
- */
- protected function setReport()
- {
- $registry = registry::get_instance();
- $this->report['dbid'] = $this->sbas_id;
- $this->report['periode'] = $this->periode;
- $this->report['dbname'] = $this->dbname;
- $this->report['dmin'] = $this->dmin;
- $this->report['dmax'] = $this->dmax;
- $this->report['server'] = $registry->get('GV_ServerName');
- $this->report['filter'] = $this->tab_filter;
- $this->report['posting_filter'] = $this->posting_filter;
- $this->report['active_column'] = $this->active_column;
- $this->report['default_display'] = $this->default_display;
- $this->report['config'] = $this->config;
- $this->report['total'] = $this->total;
- $this->report['display_nav'] = $this->display_nav;
- $this->report['nb_record'] = $this->nb_record;
- $this->report['page'] = $this->nb_page;
- $this->report['previous_page'] = $this->previous_page;
- $this->report['next_page'] = $this->next_page;
- $this->report['title'] = $this->title;
- $this->report['allChamps'] = $this->champ;
- $this->report['display'] = $this->display;
- $this->report['result'] = $this->result;
- $this->report['print'] = $this->print;
- $this->report['csv'] = $this->csv;
- }
-
- /**
- * etablis les correspondance entre gettext et le nom des columns du report
- * @return array
- */
- private function setCor()
- {
- return array(
- 'user' => _('report:: utilisateur'),
- 'coll_id' => _('report:: collections'),
- 'connexion' => _('report:: Connexion'),
- 'comment' => _('report:: commentaire'),
- 'search' => _('report:: question'),
- 'date' => _('report:: date'),
- 'ddate' => _('report:: date'),
- 'fonction' => _('report:: fonction'),
- 'activite' => _('report:: activite'),
- 'pays' => _('report:: pays'),
- 'societe' => _('report:: societe'),
- 'nb' => _('report:: nombre'),
- 'pourcent' => _('report:: pourcentage'),
- 'telechargement' => _('report:: telechargement'),
- 'record_id' => _('report:: record id'),
- 'final' => _('report:: type d\'action'),
-// 'xml' => _('report:: sujet'),
- 'file' => _('report:: fichier'),
- 'mime' => _('report:: type'),
- 'size' => _('report:: taille'),
- 'copyright' => _('report:: copyright'),
- 'final' => _('phraseanet:: sous definition')
- );
-
- return;
- }
-
- /**
- * etablis les correspondance entre gettext et le nom des jours du report
- * @return array
- */
- private function setDay()
- {
- return Array(
- 1 => _('phraseanet::jours:: lundi'),
- 2 => _('phraseanet::jours:: mardi'),
- 3 => _('phraseanet::jours:: mercredi'),
- 4 => _('phraseanet::jours:: jeudi'),
- 5 => _('phraseanet::jours:: vendredi'),
- 6 => _('phraseanet::jours:: samedi'),
- 7 => _('phraseanet::jours:: dimanche'));
- }
-
- /**
- * etablis les correspondance entre gettext et le nom des mois du report
- * @return array
- */
- private function setMonth()
- {
- return array(
- _('janvier'),
- _('fevrier'),
- _('mars'),
- _('avril'),
- _('mai'),
- _('juin'),
- _('juillet'),
- _('aout'),
- _('septembre'),
- _('octobre'),
- _('novembre'),
- _('decembre')
- );
- }
-
- /**
- * effectue le mechanism de pagination
- * @param resultset $rs
- */
- protected function calculatePages($rs)
- {
- if ($this->nb_record && $this->total > $this->nb_record)
+ public function getUser_id()
{
- $this->previous_page = $this->nb_page - 1;
- if ($this->previous_page == 0)
- $this->previous_page = false;
-
- $test = ($this->total / $this->nb_record);
- if ($this->nb_page == intval(ceil($test)))
- $this->next_page = false;
- else
- $this->next_page = $this->nb_page + 1;
+ return $this->user_id;
}
- }
- /**
- * on ne montre le formulaire que si il y'a plus de resultat que de nombre
- * de record que l'on veut afficher
- */
- protected function setDisplayNav()
- {
- if ($this->total > $this->nb_record)
- $this->display_nav = true;
- }
-
- /**
- * @desc Initialize the configuration foreach column displayed in the report
- * @param array $display contain the conf's variables
- * @return void
- */
- protected function initDefaultConfigColumn($display)
- {
- $array = array();
- foreach ($display as $key => $value)
- $array[$value] = array("", 0, 0, 0, 0);
- $this->setConfigColumn($array);
- }
-
- /**
- * @desc Set your own configuration for each column displayed in the html table
- * @param array $tab contain your conf's variables
- * array( 'field' =>
- * array('title of the colum', '1 = order ON / 0 = order OFF',
- * '1 = bound ON / 0 = bound OFF')
- * @example $tab = array('user' => array('user list', 1, 0),
- * 'id' => array(user id, 0, 0)); etc ..
- * @return void
- */
- protected function setConfigColumn($tab)
- {
-
- foreach ($tab as $column => $row)
+ public function getParams()
{
- foreach ($row as $ind => $value)
- {
- $def = false;
- if (array_key_exists($column, $this->cor))
- {
- $title_text = $this->cor[$column];
- $def = true;
+ return $this->params;
+ }
+
+ public function setUser_id($user_id)
+ {
+ $this->user_id = $user_id;
+ }
+
+ public function getSbas_id()
+ {
+ return $this->sbas_id;
+ }
+
+ public function setSbas_id($sbas_id)
+ {
+ $this->sbas_id = $sbas_id;
+ }
+
+ public function setPrettyString($bool)
+ {
+ $this->pretty_string = $bool;
+ }
+
+ public function getPrettyString()
+ {
+ return $this->pretty_string;
+ }
+
+ public function setTitle($title)
+ {
+ $this->title = $title;
+
+ return $this;
+ }
+
+ public function setCsv($bool)
+ {
+ $this->csv = $bool;
+
+ return $this;
+ }
+
+ public function getCsv()
+ {
+ return $this->csv;
+ }
+
+ public function setFilter(array $filter)
+ {
+ $this->tab_filter = $filter;
+
+ return $this;
+ }
+
+ public function setPeriode($periode)
+ {
+ $this->periode = $periode;
+
+ return $this;
+ }
+
+ public function setRequest($sql)
+ {
+ $this->req = $sql;
+ }
+
+ public function getPeriode()
+ {
+ return $this->periode;
+ }
+
+ public function setpostingFilter($filter)
+ {
+ $this->posting_filter = $filter;
+
+ return $this;
+ }
+
+ public function getPostingFilter()
+ {
+ return $this->posting_filter;
+ }
+
+ public function setLimit($page, $limit)
+ {
+ $this->nb_page = $page;
+ $this->nb_record = $limit;
+
+ return $this;
+ }
+
+ public function getGroupBy()
+ {
+ return $this->groupby;
+ }
+
+ public function setGroupBy($groupby)
+ {
+ $this->groupby = $groupby;
+
+ return $this;
+ }
+
+ public function setActiveColumn(array $active_column)
+ {
+ $this->active_column = $active_column;
+
+ return $this;
+ }
+
+ public function getActiveColumn()
+ {
+ return $this->active_column;
+ }
+
+ public function setConfig($bool)
+ {
+ $this->config = $bool;
+
+ return $this;
+ }
+
+ public function getConfig()
+ {
+ return $this->config;
+ }
+
+ public function setPrint($bool)
+ {
+ $this->print = $bool;
+
+ return $this;
+ }
+
+ public function getPrint()
+ {
+ return $this->print;
+ }
+
+ public function setHasLimit($bool)
+ {
+ $this->enable_limit = $bool;
+
+ return $this;
+ }
+
+ public function getHasLimit()
+ {
+ return $this->enable_limit;
+ }
+
+ public function setBound($column, $bool)
+ {
+ if ($bool) {
+ $this->bound[$column] = 1;
+ } else {
+ $this->bound[$column] = 0;
}
- empty($row[0]) ? $title = $column : $title = $row[0];
- $sort = $row[1];
- array_key_exists($column, $this->bound) ?
- $bound = $this->bound[$column] : $bound = $row[2];
- $filter = (isset($row[3]) ? $row[3] : 0);
- $groupby = $row[4];
- $config = array(
- 'title' => $title,
- 'sort' => $sort,
- 'bound' => $bound,
- 'filter' => $filter,
- 'groupby' => $groupby
- );
- $def ? $config['title'] = $title_text : "";
-
- $this->display[$column] = $config;
- }
- }
- }
-
- /**
- * @desc build the final formated array which contains all the result,
- * we construct the html code from this array
- * @param array $tab pass the configcolumn parameter to this tab
- * @return the formated array
- */
- public function buildReport($tab = false, $groupby = false, $on = false)
- {
- if (sizeof($this->report) > 0)
- {
- return $this->report;
+ return $this;
}
- $conn = connection::getPDOConnection($this->sbas_id);
-
- $this->buildReq($groupby, $on);
-
- try
+ public function getBound()
{
- try
- {
- $stmt = $conn->prepare($this->req);
- $stmt->execute($this->params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- }
- catch (PDOException $e)
- {
- echo $e->getMessage();
+ return $this->bound;
+ }
+
+ public function setOrder($champ, $order)
+ {
+ $this->tab_order['champ'] = $champ;
+ $this->tab_order['order'] = $order;
+
+ return $this;
+ }
+
+ public function getTitle()
+ {
+ return $this->title;
+ }
+
+ public function getDisplay()
+ {
+ return $this->display;
+ }
+
+ public function getEnableLimit()
+ {
+ return $this->enable_limit;
+ }
+
+ public function getSbasId()
+ {
+ return $this->sbas_id;
+ }
+
+ public function getDmin()
+ {
+ return $this->dmin;
+ }
+
+ public function getDmax()
+ {
+ return $this->dmax;
+ }
+
+ public function getResult()
+ {
+ return $this->result;
+ }
+
+ public function setResult(array $rs)
+ {
+ $this->result = $rs;
+
+ return $this;
+ }
+
+ public function getOrder($k = false)
+ {
+ if ($k === false) {
+ return $this->tab_order;
+ }
+
+ return $this->tab_order[$k];
+ }
+
+ public function getNbPage()
+ {
+ return $this->nb_page;
+ }
+
+ public function getNbRecord()
+ {
+ return $this->nb_record;
+ }
+
+ public function getTabFilter()
+ {
+ return $this->tab_filter;
+ }
+
+ public function getUserId()
+ {
+ return $this->user_id;
+ }
+
+ public function getListCollId()
+ {
+ return $this->list_coll_id;
+ }
+
+ public function getReq()
+ {
+ return $this->req;
+ }
+
+ public function getTransQueryString()
+ {
+ return $this->cor_query;
+ }
+
+ public function getTotal()
+ {
+ return $this->total;
+ }
+
+ public function setTotal($total)
+ {
+ $this->total = $total;
+ }
+
+ public function getDefault_display()
+ {
+ return $this->default_display;
+ }
+
+ public function setDefault_display($default_display)
+ {
+ $this->default_display = $default_display;
+ }
+
+ public function getChamps()
+ {
+ return $this->champ;
+ }
+
+ /**
+ * Retourne un objet qui genere la requete selon le type de report
+ * @param string $domain
+ * @return module_report_sqlconnexion
+ */
+ public function sqlBuilder($domain)
+ {
+ switch ($domain) {
+ case 'connexion' :
+ return new module_report_sqlconnexion($this);
+ break;
+ case 'download' :
+ return new module_report_sqldownload($this);
+ break;
+ case 'question' :
+ return new module_report_sqlquestion($this);
+ break;
+ case 'action' :
+ return new module_report_sqlaction($this);
+ break;
+ default:
+ return $this->req;
+ break;
+ }
+ }
+
+ protected function setChamp($rs)
+ {
+ $row = array_shift($rs);
+
+ $this->champ = is_array($row) ? array_keys($row) : array();
+ $this->default_display = is_array($row) ? array_keys($row) : array();
return;
- }
-
- //set request field
- $this->setChamp($rs);
- //set display
- $this->setDisplay($tab, $groupby);
- //construct results
- $this->buildResult($rs);
- //calculate prev and next page
- $this->calculatePages($rs);
- //do we display navigator ?
- $this->setDisplayNav();
- //assign all variables
- $this->setReport();
-
- return $this->report;
}
- catch (Exception $e)
+
+ /**
+ * initialise les configuration des columns ex : boundable, linkable orderable
+ * etc .. par defaut ou celle passe en parametre par $tab
+ * @param array $tab
+ * @param string $groupby
+ * @return void
+ */
+ protected function setDisplay($tab, $groupby = false)
{
- echo $e->getMessage();
+ if ($tab == false && $groupby == false)
+ $this->initDefaultConfigColumn($this->default_display);
+ elseif ($groupby != false && $tab == false)
+ $this->initDefaultConfigColumn($this->champ);
+ elseif ($tab != false)
+ $this->setConfigColumn($tab);
+
+ return;
}
- }
- public static function getPreff($sbasid)
- {
- $tab = array();
-
- $databox = databox::get_instance((int) $sbasid);
-
- foreach ($databox->get_meta_structure() as $databox_field)
+ /**
+ *
+ */
+ protected function setReport()
{
- /* @var $databox_field \databox_field */
-
- if ($databox_field->is_report())
- {
- $tab[] = $databox_field->get_name();
- }
+ $registry = registry::get_instance();
+ $this->report['dbid'] = $this->sbas_id;
+ $this->report['periode'] = $this->periode;
+ $this->report['dbname'] = $this->dbname;
+ $this->report['dmin'] = $this->dmin;
+ $this->report['dmax'] = $this->dmax;
+ $this->report['server'] = $registry->get('GV_ServerName');
+ $this->report['filter'] = $this->tab_filter;
+ $this->report['posting_filter'] = $this->posting_filter;
+ $this->report['active_column'] = $this->active_column;
+ $this->report['default_display'] = $this->default_display;
+ $this->report['config'] = $this->config;
+ $this->report['total'] = $this->total;
+ $this->report['display_nav'] = $this->display_nav;
+ $this->report['nb_record'] = $this->nb_record;
+ $this->report['page'] = $this->nb_page;
+ $this->report['previous_page'] = $this->previous_page;
+ $this->report['next_page'] = $this->next_page;
+ $this->report['title'] = $this->title;
+ $this->report['allChamps'] = $this->champ;
+ $this->report['display'] = $this->display;
+ $this->report['result'] = $this->result;
+ $this->report['print'] = $this->print;
+ $this->report['csv'] = $this->csv;
}
- return $tab;
- }
+ /**
+ * etablis les correspondance entre gettext et le nom des columns du report
+ * @return array
+ */
+ private function setCor()
+ {
+ return array(
+ 'user' => _('report:: utilisateur'),
+ 'coll_id' => _('report:: collections'),
+ 'connexion' => _('report:: Connexion'),
+ 'comment' => _('report:: commentaire'),
+ 'search' => _('report:: question'),
+ 'date' => _('report:: date'),
+ 'ddate' => _('report:: date'),
+ 'fonction' => _('report:: fonction'),
+ 'activite' => _('report:: activite'),
+ 'pays' => _('report:: pays'),
+ 'societe' => _('report:: societe'),
+ 'nb' => _('report:: nombre'),
+ 'pourcent' => _('report:: pourcentage'),
+ 'telechargement' => _('report:: telechargement'),
+ 'record_id' => _('report:: record id'),
+ 'final' => _('report:: type d\'action'),
+// 'xml' => _('report:: sujet'),
+ 'file' => _('report:: fichier'),
+ 'mime' => _('report:: type'),
+ 'size' => _('report:: taille'),
+ 'copyright' => _('report:: copyright'),
+ 'final' => _('phraseanet:: sous definition')
+ );
- public static function getHost($url)
- {
- $parse_url = parse_url(trim($url));
- $result = isset($parse_url['host']) ? $parse_url['host'] : array_shift(explode('/', $parse_url['path'], 2));
+ return;
+ }
- return trim($result);
- }
+ /**
+ * etablis les correspondance entre gettext et le nom des jours du report
+ * @return array
+ */
+ private function setDay()
+ {
+ return Array(
+ 1 => _('phraseanet::jours:: lundi'),
+ 2 => _('phraseanet::jours:: mardi'),
+ 3 => _('phraseanet::jours:: mercredi'),
+ 4 => _('phraseanet::jours:: jeudi'),
+ 5 => _('phraseanet::jours:: vendredi'),
+ 6 => _('phraseanet::jours:: samedi'),
+ 7 => _('phraseanet::jours:: dimanche'));
+ }
+ /**
+ * etablis les correspondance entre gettext et le nom des mois du report
+ * @return array
+ */
+ private function setMonth()
+ {
+ return array(
+ _('janvier'),
+ _('fevrier'),
+ _('mars'),
+ _('avril'),
+ _('mai'),
+ _('juin'),
+ _('juillet'),
+ _('aout'),
+ _('septembre'),
+ _('octobre'),
+ _('novembre'),
+ _('decembre')
+ );
+ }
+
+ /**
+ * effectue le mechanism de pagination
+ * @param resultset $rs
+ */
+ protected function calculatePages($rs)
+ {
+ if ($this->nb_record && $this->total > $this->nb_record) {
+ $this->previous_page = $this->nb_page - 1;
+ if ($this->previous_page == 0)
+ $this->previous_page = false;
+
+ $test = ($this->total / $this->nb_record);
+ if ($this->nb_page == intval(ceil($test)))
+ $this->next_page = false;
+ else
+ $this->next_page = $this->nb_page + 1;
+ }
+ }
+
+ /**
+ * on ne montre le formulaire que si il y'a plus de resultat que de nombre
+ * de record que l'on veut afficher
+ */
+ protected function setDisplayNav()
+ {
+ if ($this->total > $this->nb_record)
+ $this->display_nav = true;
+ }
+
+ /**
+ * @desc Initialize the configuration foreach column displayed in the report
+ * @param array $display contain the conf's variables
+ * @return void
+ */
+ protected function initDefaultConfigColumn($display)
+ {
+ $array = array();
+ foreach ($display as $key => $value)
+ $array[$value] = array("", 0, 0, 0, 0);
+ $this->setConfigColumn($array);
+ }
+
+ /**
+ * @desc Set your own configuration for each column displayed in the html table
+ * @param array $tab contain your conf's variables
+ * array( 'field' =>
+ * array('title of the colum', '1 = order ON / 0 = order OFF',
+ * '1 = bound ON / 0 = bound OFF')
+ * @example $tab = array('user' => array('user list', 1, 0),
+ * 'id' => array(user id, 0, 0)); etc ..
+ * @return void
+ */
+ protected function setConfigColumn($tab)
+ {
+
+ foreach ($tab as $column => $row) {
+ foreach ($row as $ind => $value) {
+ $def = false;
+ if (array_key_exists($column, $this->cor)) {
+ $title_text = $this->cor[$column];
+ $def = true;
+ }
+ empty($row[0]) ? $title = $column : $title = $row[0];
+
+ $sort = $row[1];
+ array_key_exists($column, $this->bound) ?
+ $bound = $this->bound[$column] : $bound = $row[2];
+ $filter = (isset($row[3]) ? $row[3] : 0);
+ $groupby = $row[4];
+ $config = array(
+ 'title' => $title,
+ 'sort' => $sort,
+ 'bound' => $bound,
+ 'filter' => $filter,
+ 'groupby' => $groupby
+ );
+ $def ? $config['title'] = $title_text : "";
+
+ $this->display[$column] = $config;
+ }
+ }
+ }
+
+ /**
+ * @desc build the final formated array which contains all the result,
+ * we construct the html code from this array
+ * @param array $tab pass the configcolumn parameter to this tab
+ * @return the formated array
+ */
+ public function buildReport($tab = false, $groupby = false, $on = false)
+ {
+ if (sizeof($this->report) > 0) {
+ return $this->report;
+ }
+
+ $conn = connection::getPDOConnection($this->sbas_id);
+
+ $this->buildReq($groupby, $on);
+
+ try {
+ try {
+ $stmt = $conn->prepare($this->req);
+ $stmt->execute($this->params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ } catch (PDOException $e) {
+ echo $e->getMessage();
+
+ return;
+ }
+
+ //set request field
+ $this->setChamp($rs);
+ //set display
+ $this->setDisplay($tab, $groupby);
+ //construct results
+ $this->buildResult($rs);
+ //calculate prev and next page
+ $this->calculatePages($rs);
+ //do we display navigator ?
+ $this->setDisplayNav();
+ //assign all variables
+ $this->setReport();
+
+ return $this->report;
+ } catch (Exception $e) {
+ echo $e->getMessage();
+ }
+ }
+
+ public static function getPreff($sbasid)
+ {
+ $tab = array();
+
+ $databox = databox::get_instance((int) $sbasid);
+
+ foreach ($databox->get_meta_structure() as $databox_field) {
+ /* @var $databox_field \databox_field */
+
+ if ($databox_field->is_report()) {
+ $tab[] = $databox_field->get_name();
+ }
+ }
+
+ return $tab;
+ }
+
+ public static function getHost($url)
+ {
+ $parse_url = parse_url(trim($url));
+ $result = isset($parse_url['host']) ? $parse_url['host'] : array_shift(explode('/', $parse_url['path'], 2));
+
+ return trim($result);
+ }
}
diff --git a/lib/classes/module/report/activity.class.php b/lib/classes/module/report/activity.class.php
index abcd89bd6b..e345c19c70 100644
--- a/lib/classes/module/report/activity.class.php
+++ b/lib/classes/module/report/activity.class.php
@@ -17,102 +17,99 @@
*/
class module_report_activity extends module_report
{
+ /**
+ * Number of questions displayed in the most asked questions
+ * @var int
+ */
+ private $nb_top = 20;
- /**
- * Number of questions displayed in the most asked questions
- * @var int
- */
- private $nb_top = 20;
+ /**
+ * Array correspondance column -> to query
+ * @var array
+ */
+ protected $cor_query = array(
+ 'user' => 'log.user',
+ 'site' => 'log.site',
+ 'societe' => 'log.societe',
+ 'pays' => 'log.pays',
+ 'activite' => 'log.activite',
+ 'fonction' => 'log.fonction',
+ 'usrid' => 'log.usrid',
+ 'coll_id' => 'record.coll_id',
+ 'ddate' => "DATE_FORMAT(log.date, '%Y-%m-%d')",
+ 'id' => 'log_docs.id',
+ 'log_id' => 'log_docs.log_id',
+ 'record_id' => 'log_docs.record_id',
+ 'final' => 'log_docs.final',
+ 'comment' => 'log_docs.comment',
+ 'size' => 'subdef.size'
+ );
- /**
- * Array correspondance column -> to query
- * @var array
- */
- protected $cor_query = array(
- 'user' => 'log.user',
- 'site' => 'log.site',
- 'societe' => 'log.societe',
- 'pays' => 'log.pays',
- 'activite' => 'log.activite',
- 'fonction' => 'log.fonction',
- 'usrid' => 'log.usrid',
- 'coll_id' => 'record.coll_id',
- 'ddate' => "DATE_FORMAT(log.date, '%Y-%m-%d')",
- 'id' => 'log_docs.id',
- 'log_id' => 'log_docs.log_id',
- 'record_id' => 'log_docs.record_id',
- 'final' => 'log_docs.final',
- 'comment' => 'log_docs.comment',
- 'size' => 'subdef.size'
- );
-
- public function __construct($arg1, $arg2, $sbas_id, $collist)
- {
- parent::__construct($arg1, $arg2, $sbas_id, $collist);
- }
-
- /**
- * set top value
- * @param int $nb_top
- * @return module_report_activity
- */
- public function setTop($nb_top)
- {
- $this->nb_top = $nb_top;
-
- return $this;
- }
-
- /**
- * get Top value
- * @return int
- */
- public function getTop()
- {
- return $this->nb_top;
- }
-
- private function setDisplayForActivity($rs)
- {
- $hours = array();
-
- for ($i = 0; $i < 24; $i++)
+ public function __construct($arg1, $arg2, $sbas_id, $collist)
{
- array_push($this->display, $i);
- $hours[$i] = 0;
+ parent::__construct($arg1, $arg2, $sbas_id, $collist);
}
- if (count($rs) > 0)
+ /**
+ * set top value
+ * @param int $nb_top
+ * @return module_report_activity
+ */
+ public function setTop($nb_top)
{
- $row = array_shift($rs);
- $this->champ = array_merge($this->champ, array_keys($row));
+ $this->nb_top = $nb_top;
+
+ return $this;
}
- return $hours;
- }
+ /**
+ * get Top value
+ * @return int
+ */
+ public function getTop()
+ {
+ return $this->nb_top;
+ }
- /**
- * @desc get the site activity per hours
- * @return array
- */
- public function getActivityPerHours()
- {
- $this->result = array();
- $this->title = _('report:: activite par heure');
+ private function setDisplayForActivity($rs)
+ {
+ $hours = array();
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
+ for ($i = 0; $i < 24; $i ++ ) {
+ array_push($this->display, $i);
+ $hours[$i] = 0;
+ }
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
+ if (count($rs) > 0) {
+ $row = array_shift($rs);
+ $this->champ = array_merge($this->champ, array_keys($row));
+ }
- $sql = "
+ return $hours;
+ }
+
+ /**
+ * @desc get the site activity per hours
+ * @return array
+ */
+ public function getActivityPerHours()
+ {
+ $this->result = array();
+ $this->title = _('report:: activite par heure');
+
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
+
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
+
+ $sql = "
SELECT DATE_FORMAT( log.date, '%k' ) AS heures, SUM(1) AS nb
FROM log
WHERE (" . $date_filter['sql'] . ")
@@ -121,62 +118,61 @@ class module_report_activity extends module_report
GROUP BY heures
ORDER BY heures ASC";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $res = $this->setDisplayForActivity($rs);
+ $res = $this->setDisplayForActivity($rs);
- $this->initDefaultConfigColumn($this->display);
+ $this->initDefaultConfigColumn($this->display);
- foreach ($rs as $row)
- {
- $row['heures'] = (string) $row['heures'];
- $res[$row['heures']] = round(($row['nb'] / 24), 2);
- if ($res[$row['heures']] < 1)
- $res[$row['heures']] = number_format($res[$row['heures']], 2);
- else
- $res[$row['heures']] = (int) $res[$row['heures']];
+ foreach ($rs as $row) {
+ $row['heures'] = (string) $row['heures'];
+ $res[$row['heures']] = round(($row['nb'] / 24), 2);
+ if ($res[$row['heures']] < 1)
+ $res[$row['heures']] = number_format($res[$row['heures']], 2);
+ else
+ $res[$row['heures']] = (int) $res[$row['heures']];
+ }
+
+ $this->result[] = $res;
+ //calculate prev and next page
+ $this->calculatePages($rs);
+ //do we display navigator ?
+ $this->setDisplayNav();
+ //set report
+ $this->setReport();
+
+
+ $this->report['legend'] = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23);
+
+ return $this->report;
}
- $this->result[] = $res;
- //calculate prev and next page
- $this->calculatePages($rs);
- //do we display navigator ?
- $this->setDisplayNav();
- //set report
- $this->setReport();
+ /**
+ * @desc get all questions by user
+ * @param string $idUser
+ */
+ public function getAllQuestionByUser($value, $what)
+ {
+ $result = array();
+
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- $this->report['legend'] = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
- 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23);
+ $params = array(':main_value' => $value);
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
- return $this->report;
- }
-
- /**
- * @desc get all questions by user
- * @param string $idUser
- */
- public function getAllQuestionByUser($value, $what)
- {
- $result = array();
-
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
-
-
- $params = array(':main_value' => $value);
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
-
- $sql = "
+ $sql = "
SELECT DATE_FORMAT(log_search.date,'%Y-%m-%d %H:%i:%S') as date ,
log_search.search ,log_search.results
FROM (log_search inner join log on log.id = log_search.log_id)
@@ -187,61 +183,60 @@ class module_report_activity extends module_report
ORDER BY date";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $s->setTotalrows($stmt->rowCount());
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $s->setTotalrows($stmt->rowCount());
+ $stmt->closeCursor();
- $sql .= $filter->getLimitFilter();
+ $sql .= $filter->getLimitFilter();
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->setChamp($rs);
- $this->initDefaultConfigColumn($this->champ);
- $i = 0;
+ $this->setChamp($rs);
+ $this->initDefaultConfigColumn($this->champ);
+ $i = 0;
- foreach ($rs as $row)
- {
- foreach ($this->champ as $key => $value)
- $result[$i][$value] = $row[$value];
- $i++;
+ foreach ($rs as $row) {
+ foreach ($this->champ as $key => $value)
+ $result[$i][$value] = $row[$value];
+ $i ++;
+ }
+
+ $this->title = _('report:: questions');
+ $this->setResult($result);
+
+ return $this->result;
}
- $this->title = _('report:: questions');
- $this->setResult($result);
+ /**
+ * get the most asked question
+ * @param array $tab config for html table
+ * @param bool $no_answer true for question with no answer
+ */
+ public function getTopQuestion($tab = false, $no_answer = false)
+ {
+ $this->report['value'] = array();
+ $this->report['value2'] = array();
- return $this->result;
- }
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- /**
- * get the most asked question
- * @param array $tab config for html table
- * @param bool $no_answer true for question with no answer
- */
- public function getTopQuestion($tab = false, $no_answer = false)
- {
- $this->report['value'] = array();
- $this->report['value2'] = array();
-
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
-
- $i = 0;
- ($no_answer) ? $this->title = _('report:: questions sans reponses') :
- $this->title = _('report:: questions les plus posees');
+ $i = 0;
+ ($no_answer) ? $this->title = _('report:: questions sans reponses') :
+ $this->title = _('report:: questions les plus posees');
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
- $sql = "
+ $sql = "
SELECT TRIM(log_search.search) as search,
SUM(1) as nb,
ROUND(avg(results)) as nb_rep
@@ -250,70 +245,69 @@ class module_report_activity extends module_report
AND log_search.search != 'all'
AND (" . $coll_filter['sql'] . ")";
- ($no_answer) ? $sql .= " AND log_search.results = 0 " : "";
+ ($no_answer) ? $sql .= " AND log_search.results = 0 " : "";
- $sql .= "
+ $sql .= "
GROUP BY log_search.search
ORDER BY nb DESC";
- (!$no_answer) ? $sql .= " LIMIT 0," . $this->nb_top : "";
+ ( ! $no_answer) ? $sql .= " LIMIT 0," . $this->nb_top : "";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->setChamp($rs);
- $this->setDisplay($tab);
+ $this->setChamp($rs);
+ $this->setDisplay($tab);
- foreach ($rs as $row)
- {
- foreach ($this->champ as $key => $value)
- $this->result[$i][$value] = $row[$value];
- $i++;
- $this->report['legend'][] = $row['search'];
- $this->report['value'][] = $row['nb'];
- $this->report['value2'][] = $row['nb_rep'];
+ foreach ($rs as $row) {
+ foreach ($this->champ as $key => $value)
+ $this->result[$i][$value] = $row[$value];
+ $i ++;
+ $this->report['legend'][] = $row['search'];
+ $this->report['value'][] = $row['nb'];
+ $this->report['value2'][] = $row['nb_rep'];
+ }
+
+ $this->total = sizeof($this->result);
+ //calculate prev and next page
+ $this->calculatePages($rs);
+ //do we display navigator ?
+ $this->setDisplayNav();
+ //set report
+ $this->setReport();
+
+ return $this->report;
}
- $this->total = sizeof($this->result);
- //calculate prev and next page
- $this->calculatePages($rs);
- //do we display navigator ?
- $this->setDisplayNav();
- //set report
- $this->setReport();
+ /**
+ * @desc get all downloads from one specific user
+ * @param $usr user id
+ * @param array $config config for the html table
+ * @return array
+ */
+ public function getAllDownloadByUserBase($usr, $config = false)
+ {
+ $result = array();
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- return $this->report;
- }
-
- /**
- * @desc get all downloads from one specific user
- * @param $usr user id
- * @param array $config config for the html table
- * @return array
- */
- public function getAllDownloadByUserBase($usr, $config = false)
- {
- $result = array();
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
-
- $databox = \databox::get_instance($this->sbas_id);
+ $databox = \databox::get_instance($this->sbas_id);
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
- $user_filter = $filter->getUserIdFilter($usr);
- $params = array_merge($params, $user_filter['params']);
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
+ $user_filter = $filter->getUserIdFilter($usr);
+ $params = array_merge($params, $user_filter['params']);
- $sql = "
+ $sql = "
SELECT log_docs.record_id,
log_docs.date, log_docs.final as objets
FROM (`log_docs` inner join log on log_docs.log_id = log.id
@@ -324,75 +318,73 @@ class module_report_activity extends module_report
AND " . $site_filter['sql'] . "
AND (" . $coll_filter['sql'] . ")";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $s->setTotalrows($stmt->rowCount());
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $s->setTotalrows($stmt->rowCount());
+ $stmt->closeCursor();
- $sql .= "
+ $sql .= "
ORDER BY date DESC";
- $sql .= $filter->getLimitFilter();
+ $sql .= $filter->getLimitFilter();
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $login = User_Adapter::getInstance($usr, appbox::get_instance(\bootstrap::getCore()))->get_display_name();
+ $login = User_Adapter::getInstance($usr, appbox::get_instance(\bootstrap::getCore()))->get_display_name();
- $this->setChamp($rs);
- ($config) ? $this->setConfigColumn($config) :
- $this->initDefaultConfigColumn($this->champ);
- $i = 0;
+ $this->setChamp($rs);
+ ($config) ? $this->setConfigColumn($config) :
+ $this->initDefaultConfigColumn($this->champ);
+ $i = 0;
- foreach ($rs as $row)
- {
- $record = $databox->get_record($row['record_id']);
+ foreach ($rs as $row) {
+ $record = $databox->get_record($row['record_id']);
- foreach ($this->champ as $key => $value)
- {
- $result[$i][$value] = $row[$value];
- }
+ foreach ($this->champ as $key => $value) {
+ $result[$i][$value] = $row[$value];
+ }
- $result[$i]['titre'] = $record->get_title();
+ $result[$i]['titre'] = $record->get_title();
- $i++;
+ $i ++;
+ }
+ $this->title = sprintf(_('report:: Telechargement effectue par l\'utilisateur %s'), $login);
+ $this->setResult($result);
+
+ return $this->result;
}
- $this->title = sprintf(_('report:: Telechargement effectue par l\'utilisateur %s'), $login);
- $this->setResult($result);
- return $this->result;
- }
+ /**
+ * @desc get all download by base by day
+ * @param array $tab config for html table
+ * @return array
+ */
+ public function getDownloadByBaseByDay($tab = false)
+ {
+ $this->title = _('report:: telechargements par jour');
- /**
- * @desc get all download by base by day
- * @param array $tab config for html table
- * @return array
- */
- public function getDownloadByBaseByDay($tab = false)
- {
- $this->title = _('report:: telechargements par jour');
+ $registry = registry::get_instance();
- $registry = registry::get_instance();
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
+ $record_filter = $filter->getUserFilter();
+ if ($record_filter)
+ $params = array_merge($params, $record_filter['params']);
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
- $record_filter = $filter->getUserFilter();
- if ($record_filter)
- $params = array_merge($params, $record_filter['params']);
-
- $sql = "
+ $sql = "
SELECT
log_docs.date
AS ddate,
@@ -408,99 +400,92 @@ class module_report_activity extends module_report
AND (log_docs.final != 'caption')
AND log_docs.action = 'download'
AND (" . $coll_filter['sql'] . ")";
- if ($record_filter['sql'])
- $sql .= "AND (" . $record_filter['sql'] . ")";
- $sql .= ' ORDER BY log_docs.date DESC';
+ if ($record_filter['sql'])
+ $sql .= "AND (" . $record_filter['sql'] . ")";
+ $sql .= ' ORDER BY log_docs.date DESC';
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->setChamp($rs);
- $this->setDisplay($tab);
- $save_date = "";
- $total = array('tot_doc' => 0, 'tot_prev' => 0, 'tot_dl' => 0);
- $i = -1;
+ $this->setChamp($rs);
+ $this->setDisplay($tab);
+ $save_date = "";
+ $total = array('tot_doc' => 0, 'tot_prev' => 0, 'tot_dl' => 0);
+ $i = -1;
- $last_date = null;
+ $last_date = null;
- foreach ($rs as $row)
- {
- $date = phraseadate::getPrettyString(new DateTime($row['ddate']));
- if ($date != $last_date)
- {
- $i++;
- $this->result[$i] = array(
- 'ddate' => $date,
- 'document' => 0,
- 'preview' => 0,
- 'total' => 0
- );
- $last_date = $date;
- }
+ foreach ($rs as $row) {
+ $date = phraseadate::getPrettyString(new DateTime($row['ddate']));
+ if ($date != $last_date) {
+ $i ++;
+ $this->result[$i] = array(
+ 'ddate' => $date,
+ 'document' => 0,
+ 'preview' => 0,
+ 'total' => 0
+ );
+ $last_date = $date;
+ }
- if ($row['final'] == 'document')
- {
- $this->result[$i]['document'] += 1;
- $total['tot_doc'] += 1;
- }
- else
- {
- $this->result[$i]['preview'] += 1;
- $total['tot_prev'] += 1;
- }
+ if ($row['final'] == 'document') {
+ $this->result[$i]['document'] += 1;
+ $total['tot_doc'] += 1;
+ } else {
+ $this->result[$i]['preview'] += 1;
+ $total['tot_prev'] += 1;
+ }
- $this->result[$i]['total'] += 1;
+ $this->result[$i]['total'] += 1;
- $total['tot_dl'] += 1;
+ $total['tot_dl'] += 1;
+ }
+
+ $nb_row = $i + 1;
+ $s->setTotalrows($nb_row);
+
+ if ($s->getTotalRows() > 0) {
+ $this->result[$nb_row]['ddate'] = 'TOTAL ';
+ $this->result[$nb_row]['document'] = '' . $total['tot_doc'] . ' ';
+ $this->result[$nb_row]['preview'] = '' . $total['tot_prev'] . ' ';
+ $this->result[$nb_row]['total'] = '' . $total['tot_dl'] . ' ';
+ }
+ $this->calculatePages($rs);
+ $this->setDisplayNav();
+ $this->setReport();
+
+ return $this->report;
}
- $nb_row = $i + 1;
- $s->setTotalrows($nb_row);
-
- if ($s->getTotalRows() > 0)
+ /**
+ * @desc get nb connexion by user , fonction ,societe etc..
+ * @param array $tab config for html table
+ * @param string $on choose the field on what you want the result
+ * @return array
+ */
+ public function getConnexionBase($tab = false, $on = "")
{
- $this->result[$nb_row]['ddate'] = 'TOTAL ';
- $this->result[$nb_row]['document'] = '' . $total['tot_doc'] . ' ';
- $this->result[$nb_row]['preview'] = '' . $total['tot_prev'] . ' ';
- $this->result[$nb_row]['total'] = '' . $total['tot_dl'] . ' ';
- }
- $this->calculatePages($rs);
- $this->setDisplayNav();
- $this->setReport();
+ //default group on user column
+ if (empty($on)) {
+ $on = "user";
+ }
- return $this->report;
- }
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- /**
- * @desc get nb connexion by user , fonction ,societe etc..
- * @param array $tab config for html table
- * @param string $on choose the field on what you want the result
- * @return array
- */
- public function getConnexionBase($tab = false, $on = "")
- {
- //default group on user column
- if (empty($on))
- {
- $on = "user";
- }
-
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
-
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
- $this->req = "
+ $this->req = "
SELECT DISTINCT(log." . $on . ") as " . $on . ",
usrid,
SUM(1) as connexion
@@ -512,93 +497,90 @@ class module_report_activity extends module_report
GROUP BY " . $on . "
ORDER BY connexion DESC ";
- $stmt = $conn->prepare($this->req);
- $stmt->execute($params);
- $s->setTotalrows($stmt->rowCount());
- $stmt->closeCursor();
+ $stmt = $conn->prepare($this->req);
+ $stmt->execute($params);
+ $s->setTotalrows($stmt->rowCount());
+ $stmt->closeCursor();
- $this->enable_limit ? $this->req .= "LIMIT 0," . $this->nb_record : "";
+ $this->enable_limit ? $this->req .= "LIMIT 0," . $this->nb_record : "";
- $stmt = $conn->prepare($this->req);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($this->req);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $i = 0;
- $total_connexion = 0;
- //set title
- $this->title = _('report:: Detail des connexions');
- //set champ
- $this->champ = array($on, 'connexion');
- //set display
- $this->default_display = array($on, 'connexion');
- //set configuration of column
- ($tab) ? $this->setConfigColumn($tab) :
- $this->initDefaultConfigColumn($this->default_display);
- //build result
- foreach ($rs as $row)
- {
- foreach ($this->champ as $key => $value)
- {
- $this->result[$i][$value] = empty($row[$value]) ?
- "" . _('report:: non-renseigne') . " " : $row[$value];
+ $i = 0;
+ $total_connexion = 0;
+ //set title
+ $this->title = _('report:: Detail des connexions');
+ //set champ
+ $this->champ = array($on, 'connexion');
+ //set display
+ $this->default_display = array($on, 'connexion');
+ //set configuration of column
+ ($tab) ? $this->setConfigColumn($tab) :
+ $this->initDefaultConfigColumn($this->default_display);
+ //build result
+ foreach ($rs as $row) {
+ foreach ($this->champ as $key => $value) {
+ $this->result[$i][$value] = empty($row[$value]) ?
+ "" . _('report:: non-renseigne') . " " : $row[$value];
- if ($value == 'connexion')
- $total_connexion += $row['connexion'];
- }
- $this->result[$i]['usrid'] = $row['usrid'];
- $i++;
- if ($i >= $this->nb_record)
- break;
+ if ($value == 'connexion')
+ $total_connexion += $row['connexion'];
+ }
+ $this->result[$i]['usrid'] = $row['usrid'];
+ $i ++;
+ if ($i >= $this->nb_record)
+ break;
+ }
+
+ $this->total = $i ++;
+
+ if ($this->total > 0) {
+ $this->result[$i]['usrid'] = 0;
+ $this->result[$i]['connexion'] = '' . $total_connexion . ' ';
+ $this->result[$i][$on] = 'TOTAL ';
+ }
+ //calculate prev and next page
+ $this->calculatePages($rs);
+ //do we display navigator ?
+ $this->setDisplayNav();
+ //set report
+ $this->setReport();
+
+ return $this->report;
}
- $this->total = $i++;
-
- if ($this->total > 0)
+ /**
+ * @desc get the deail of download by users
+ * @param bool $ext false for your appbox conn, true for external connections
+ * @param array $tab config for the html table
+ * @return array
+ */
+ public function getDetailDownload($tab = false, $on = "")
{
- $this->result[$i]['usrid'] = 0;
- $this->result[$i]['connexion'] = '' . $total_connexion . ' ';
- $this->result[$i][$on] = 'TOTAL ';
- }
- //calculate prev and next page
- $this->calculatePages($rs);
- //do we display navigator ?
- $this->setDisplayNav();
- //set report
- $this->setReport();
+ empty($on) ? $on = "user" : ""; //by default always report on user
- return $this->report;
- }
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
- /**
- * @desc get the deail of download by users
- * @param bool $ext false for your appbox conn, true for external connections
- * @param array $tab config for the html table
- * @return array
- */
- public function getDetailDownload($tab = false, $on = "")
- {
- empty($on) ? $on = "user" : ""; //by default always report on user
+ //set title
+ $this->title = _('report:: Detail des telechargements');
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
+ $record_filter = $filter->getRecordFilter();
+ $params = array_merge($params, $record_filter['params']);
- //set title
- $this->title = _('report:: Detail des telechargements');
-
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
- $record_filter = $filter->getRecordFilter();
- $params = array_merge($params, $record_filter['params']);
-
- $sql = "
+ $sql = "
SELECT
usrid,
TRIM(" . $on . ") as " . $on . ",
@@ -617,125 +599,117 @@ class module_report_activity extends module_report
GROUP BY " . $on . ", final, usrid
WITH rollup";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $save_user = "";
- $i = -1;
- $total = array(
- 'nbdoc' => 0,
- 'poiddoc' => 0,
- 'nbprev' => 0,
- 'poidprev' => 0
- );
+ $save_user = "";
+ $i = -1;
+ $total = array(
+ 'nbdoc' => 0,
+ 'poiddoc' => 0,
+ 'nbprev' => 0,
+ 'poidprev' => 0
+ );
- $this->setChamp($rs);
+ $this->setChamp($rs);
- $this->setDisplay($tab);
+ $this->setDisplay($tab);
- foreach ($rs as $row)
- {
- $user = $row[$on];
- if (($save_user != $user) && !is_null($user) && !empty($user))
- {
- if ($i >= 0)
- {
- if (($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc']) == 0 || ($this->result[$i]['poiddoc'] + $this->result[$i]['poidprev']) == 0)
- {
- unset($this->result[$i]);
- }
+ foreach ($rs as $row) {
+ $user = $row[$on];
+ if (($save_user != $user) && ! is_null($user) && ! empty($user)) {
+ if ($i >= 0) {
+ if (($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc']) == 0 || ($this->result[$i]['poiddoc'] + $this->result[$i]['poidprev']) == 0) {
+ unset($this->result[$i]);
+ }
- if (isset($this->result[$i]['poiddoc']) && isset($this->result[$i]['poidprev']))
- {
- $this->result[$i]['poiddoc'] = p4string::format_octets($this->result[$i]['poiddoc']);
- $this->result[$i]['poidprev'] = p4string::format_octets($this->result[$i]['poidprev']);
- }
+ if (isset($this->result[$i]['poiddoc']) && isset($this->result[$i]['poidprev'])) {
+ $this->result[$i]['poiddoc'] = p4string::format_octets($this->result[$i]['poiddoc']);
+ $this->result[$i]['poidprev'] = p4string::format_octets($this->result[$i]['poidprev']);
+ }
+ }
+
+
+ $i ++;
+
+ $this->result[$i]['nbprev'] = 0;
+ $this->result[$i]['poidprev'] = 0;
+ $this->result[$i]['nbdoc'] = 0;
+ $this->result[$i]['poiddoc'] = 0;
+ }
+
+ //doc info
+ if ($row['final'] == 'document' &&
+ ! is_null($user) && ! is_null($row['usrid'])) {
+ $this->result[$i]['nbdoc'] = ( ! is_null($row['nb']) ? $row['nb'] : 0);
+ $this->result[$i]['poiddoc'] = ( ! is_null($row['poid']) ? $row['poid'] : 0);
+ $this->result[$i]['user'] = empty($row[$on]) ?
+ "" . _('report:: non-renseigne') . " " : $row[$on];
+ $total['nbdoc'] += $this->result[$i]['nbdoc'];
+ $total['poiddoc'] += ( ! is_null($row['poid']) ? $row['poid'] : 0);
+ $this->result[$i]['usrid'] = $row['usrid'];
+ }
+ //preview info
+ if (($row['final'] == 'preview' || $row['final'] == 'thumbnail') &&
+ ! is_null($user) &&
+ ! is_null($row['usrid'])) {
+
+ $this->result[$i]['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
+ $this->result[$i]['poidprev'] += ( ! is_null($row['poid']) ? $row['poid'] : 0);
+
+ $this->result[$i]['user'] = empty($row[$on]) ?
+ "" . _('report:: non-renseigne') . " " : $row[$on];
+ $total['nbprev'] += ( ! is_null($row['nb']) ? $row['nb'] : 0);
+ $total['poidprev'] += ( ! is_null($row['poid']) ? $row['poid'] : 0);
+ $this->result[$i]['usrid'] = $row['usrid'];
+ }
+
+ $save_user = $user;
}
+ unset($this->result[$i]);
+ $nb_row = $i + 1;
+ $this->total = $nb_row;
- $i++;
+ if ($this->total > 0) {
+ $this->result[$nb_row]['user'] = 'TOTAL ';
+ $this->result[$nb_row]['nbdoc'] = '' . $total['nbdoc'] . ' ';
+ $this->result[$nb_row]['poiddoc'] =
+ '' . p4string::format_octets($total['poiddoc']) . ' ';
+ $this->result[$nb_row]['nbprev'] = '' . $total['nbprev'] . ' ';
+ $this->result[$nb_row]['poidprev'] =
+ '' . p4string::format_octets($total['poidprev']) . ' ';
+ }
+ $this->total = sizeof($this->result);
+ $this->calculatePages($rs);
+ $this->setDisplayNav();
+ $this->setReport();
- $this->result[$i]['nbprev'] = 0;
- $this->result[$i]['poidprev'] = 0;
- $this->result[$i]['nbdoc'] = 0;
- $this->result[$i]['poiddoc'] = 0;
- }
-
- //doc info
- if ($row['final'] == 'document' &&
- !is_null($user) && !is_null($row['usrid']))
- {
- $this->result[$i]['nbdoc'] = (!is_null($row['nb']) ? $row['nb'] : 0);
- $this->result[$i]['poiddoc'] = (!is_null($row['poid']) ? $row['poid'] : 0);
- $this->result[$i]['user'] = empty($row[$on]) ?
- "" . _('report:: non-renseigne') . " " : $row[$on];
- $total['nbdoc'] += $this->result[$i]['nbdoc'];
- $total['poiddoc'] += (!is_null($row['poid']) ? $row['poid'] : 0);
- $this->result[$i]['usrid'] = $row['usrid'];
- }
- //preview info
- if (($row['final'] == 'preview' || $row['final'] == 'thumbnail') &&
- !is_null($user) &&
- !is_null($row['usrid']))
- {
-
- $this->result[$i]['nbprev'] += (!is_null($row['nb']) ? $row['nb'] : 0);
- $this->result[$i]['poidprev'] += (!is_null($row['poid']) ? $row['poid'] : 0);
-
- $this->result[$i]['user'] = empty($row[$on]) ?
- "" . _('report:: non-renseigne') . " " : $row[$on];
- $total['nbprev'] += (!is_null($row['nb']) ? $row['nb'] : 0);
- $total['poidprev'] += (!is_null($row['poid']) ? $row['poid'] : 0);
- $this->result[$i]['usrid'] = $row['usrid'];
- }
-
- $save_user = $user;
+ return $this->report;
}
- unset($this->result[$i]);
- $nb_row = $i + 1;
- $this->total = $nb_row;
-
- if ($this->total > 0)
+ public function getPush($tab = false)
{
- $this->result[$nb_row]['user'] = 'TOTAL ';
- $this->result[$nb_row]['nbdoc'] = '' . $total['nbdoc'] . ' ';
- $this->result[$nb_row]['poiddoc'] =
- '' . p4string::format_octets($total['poiddoc']) . ' ';
- $this->result[$nb_row]['nbprev'] = '' . $total['nbprev'] . ' ';
- $this->result[$nb_row]['poidprev'] =
- '' . p4string::format_octets($total['poidprev']) . ' ';
- }
- $this->total = sizeof($this->result);
- $this->calculatePages($rs);
- $this->setDisplayNav();
- $this->setReport();
-
- return $this->report;
- }
-
- public function getPush($tab = false)
- {
- $s = new module_report_sql($this);
- $filter = $s->getFilters();
- $conn = $s->getConnBas();
- $push = array();
+ $s = new module_report_sql($this);
+ $filter = $s->getFilters();
+ $conn = $s->getConnBas();
+ $push = array();
- $params = array();
- $date_filter = $filter->getDateFilter();
- $params = array_merge($params, $date_filter['params']);
- $coll_filter = $filter->getCollectionFilter();
- $params = array_merge($params, $coll_filter['params']);
- $site_filter = $filter->getGvSitFilter();
- $params = array_merge($params, $site_filter['params']);
- $record_filter = $filter->getRecordFilter();
- $params = array_merge($params, $record_filter['params']);
+ $params = array();
+ $date_filter = $filter->getDateFilter();
+ $params = array_merge($params, $date_filter['params']);
+ $coll_filter = $filter->getCollectionFilter();
+ $params = array_merge($params, $coll_filter['params']);
+ $site_filter = $filter->getGvSitFilter();
+ $params = array_merge($params, $site_filter['params']);
+ $record_filter = $filter->getRecordFilter();
+ $params = array_merge($params, $record_filter['params']);
- $sql = "
+ $sql = "
SELECT log.usrid, log.user , d.final as getter, d.record_id, d.date, s.*
FROM (log_docs as d
INNER JOIN log ON (" . $site_filter['sql'] . "
@@ -748,78 +722,68 @@ class module_report_activity extends module_report
AND d.action='push')
";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $this->setChamp($rs);
- $this->initDefaultConfigColumn($this->champ);
+ $this->setChamp($rs);
+ $this->initDefaultConfigColumn($this->champ);
- $appbox = appbox::get_instance(\bootstrap::getCore());
+ $appbox = appbox::get_instance(\bootstrap::getCore());
- $i = 0;
- foreach ($rs as $row)
- {
- foreach ($this->champ as $key => $value)
- {
- $this->result[$i][$value] = $row[$value];
- if ($value == "getter")
- {
- try
- {
- $user = User_Adapter::getInstance($row[$value], $appbox);
- $this->result[$i][$value] = $user->get_display_name();
- }
- catch (Exception $e)
- {
+ $i = 0;
+ foreach ($rs as $row) {
+ foreach ($this->champ as $key => $value) {
+ $this->result[$i][$value] = $row[$value];
+ if ($value == "getter") {
+ try {
+ $user = User_Adapter::getInstance($row[$value], $appbox);
+ $this->result[$i][$value] = $user->get_display_name();
+ } catch (Exception $e) {
- }
+ }
+ } elseif ($value == "size") {
+ $this->result[$i][$value] = p4string::format_octets($row[$value]);
+ } elseif ($value == "date") {
+ $date_obj = new DateTime($row[$value]);
+ $this->result[$i][$value] = phraseadate::getPrettyString($date_obj);
+ }
+ }
+ $i ++;
}
- elseif ($value == "size")
- {
- $this->result[$i][$value] = p4string::format_octets($row[$value]);
- }
- elseif ($value == "date")
- {
- $date_obj = new DateTime($row[$value]);
- $this->result[$i][$value] = phraseadate::getPrettyString($date_obj);
- }
- }
- $i++;
+
+ $this->total = sizeof($this->result);
+ //calculate prev and next page
+ $this->calculatePages($rs);
+ //do we display navigator ?
+ $this->setDisplayNav();
+ //set report
+ $this->setReport();
+
+
+ return($this->report);
}
- $this->total = sizeof($this->result);
- //calculate prev and next page
- $this->calculatePages($rs);
- //do we display navigator ?
- $this->setDisplayNav();
- //set report
- $this->setReport();
+ public static function topTenUser($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
+ $result = array();
+ $result['top_ten_doc'] = array();
+ $result['top_ten_prev'] = array();
+ $result['top_ten_poiddoc'] = array();
+ $result['top_ten_poidprev'] = array();
+ $params = array(':site_id' => $registry->get('GV_sit'));
- return($this->report);
- }
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $params = array_merge($params, $datefilter['params']);
- public static function topTenUser($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
- $result = array();
- $result['top_ten_doc'] = array();
- $result['top_ten_prev'] = array();
- $result['top_ten_poiddoc'] = array();
- $result['top_ten_poidprev'] = array();
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array_merge($params, $collfilter['params']);
- $params = array(':site_id' => $registry->get('GV_sit'));
-
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $params = array_merge($params, $datefilter['params']);
-
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- $params = array_merge($params, $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT log.usrid, user, final, sum(1) AS nb, sum(size) AS poid
FROM (log_docs AS log_date
INNER JOIN log ON log.site = :site_id
@@ -832,117 +796,112 @@ class module_report_activity extends module_report
GROUP BY user, final
WITH rollup";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $save_id = "";
- foreach ($rs as $row)
- {
- $kttd = 'top_ten_doc';
- $kttp = 'top_ten_poiddoc';
+ $save_id = "";
+ foreach ($rs as $row) {
+ $kttd = 'top_ten_doc';
+ $kttp = 'top_ten_poiddoc';
- $kttpr = 'top_ten_prev';
- $kttpp = 'top_ten_poidprev';
+ $kttpr = 'top_ten_prev';
+ $kttpp = 'top_ten_poidprev';
- $id = $row['usrid'];
+ $id = $row['usrid'];
- if (!is_null($row['usrid'])
- && !is_null($row['user'])
- && !is_null($row['final']) && !is_null($row['nb'])
- && !is_null($row['poid']))
- {
- if ($row['final'] == 'document')
- {
- $result[$kttd][$id]['lib'] = $row['user'];
- $result[$kttd][$id]['id'] = $id;
- $result[$kttd][$id]['nb'] = !is_null($row['nb']) ?
- (int) $row['nb'] : 0;
- $result[$kttp][$id]['nb'] = !is_null($row['poid']) ?
- (int) $row['poid'] : 0;
- $result[$kttp][$id]['lib'] = $row['user'];
- $result[$kttp][$id]['id'] = $id;
- if (!isset($result[$kttd][$id]['nb']))
- $result[$kttd][$id]['nb'] = 0;
+ if ( ! is_null($row['usrid'])
+ && ! is_null($row['user'])
+ && ! is_null($row['final']) && ! is_null($row['nb'])
+ && ! is_null($row['poid'])) {
+ if ($row['final'] == 'document') {
+ $result[$kttd][$id]['lib'] = $row['user'];
+ $result[$kttd][$id]['id'] = $id;
+ $result[$kttd][$id]['nb'] = ! is_null($row['nb']) ?
+ (int) $row['nb'] : 0;
+ $result[$kttp][$id]['nb'] = ! is_null($row['poid']) ?
+ (int) $row['poid'] : 0;
+ $result[$kttp][$id]['lib'] = $row['user'];
+ $result[$kttp][$id]['id'] = $id;
+ if ( ! isset($result[$kttd][$id]['nb']))
+ $result[$kttd][$id]['nb'] = 0;
+ }
+ if ($row['final'] == 'preview') {
+ $result[$kttpr][$id]['lib'] = $row['user'];
+ $result[$kttpr][$id]['id'] = $id;
+ if ( ! isset($result[$kttpr][$id]['nb']))
+ $result[$kttpr][$id]['nb'] = 0;
+ $result[$kttpr][$id]['nb'] = ! is_null($row['nb']) ?
+ (int) $row['nb'] : 0;
+ $result[$kttpp][$id]['nb'] = ! is_null($row['poid']) ?
+ (int) $row['poid'] : 0;
+ $result[$kttpp][$id]['lib'] = $row['user'];
+ $result[$kttpp][$id]['id'] = $id;
+ }
+ }
+ $save_id = $id;
}
- if ($row['final'] == 'preview')
- {
- $result[$kttpr][$id]['lib'] = $row['user'];
- $result[$kttpr][$id]['id'] = $id;
- if (!isset($result[$kttpr][$id]['nb']))
- $result[$kttpr][$id]['nb'] = 0;
- $result[$kttpr][$id]['nb'] = !is_null($row['nb']) ?
- (int) $row['nb'] : 0;
- $result[$kttpp][$id]['nb'] = !is_null($row['poid']) ?
- (int) $row['poid'] : 0;
- $result[$kttpp][$id]['lib'] = $row['user'];
- $result[$kttpp][$id]['id'] = $id;
- }
- }
- $save_id = $id;
+
+ return $result;
}
- return $result;
- }
+ public static function activity($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
+ $res = array();
+ $datefilter =
+ module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter =
+ module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activity($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
- $res = array();
- $datefilter =
- module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter =
- module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array(':site_id' => $registry->get('GV_sit'));
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array(':site_id' => $registry->get('GV_sit'));
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT log_date.id, HOUR(log_date.date) as heures
FROM log as log_date
WHERE " . $datefilter['sql'] . "
AND (" . $collfilter['sql'] . ")
AND log_date.site = :site_id";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $total = $stmt->rowCount();
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $total = $stmt->rowCount();
+ $stmt->closeCursor();
- for ($i = 0; $i < 24; $i++)
- $res[$i] = 0;
+ for ($i = 0; $i < 24; $i ++ )
+ $res[$i] = 0;
- foreach ($rs as $row)
- {
- if ($total > 0)
- $res[$row["heures"]]++;
+ foreach ($rs as $row) {
+ if ($total > 0)
+ $res[$row["heures"]] ++;
+ }
+
+ foreach ($res as $heure => $value)
+ $res[$heure] = number_format(($value / 24), 2, '.', '');
+
+ return $res;
}
- foreach ($res as $heure => $value)
- $res[$heure] = number_format(($value / 24), 2, '.', '');
+ public static function activityDay($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
+ $result = array();
+ $res = array();
+ $datefilter =
+ module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter =
+ module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- return $res;
- }
+ $params = array(':site_id' => $registry->get('GV_sit'));
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- public static function activityDay($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
- $result = array();
- $res = array();
- $datefilter =
- module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter =
- module_report_sqlfilter::constructCollectionFilter($list_coll_id);
-
- $params = array(':site_id' => $registry->get('GV_sit'));
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT DISTINCT (
DATE_FORMAT( log_date.date, '%Y-%m-%d' )
) AS ddate, COUNT( DATE_FORMAT( log_date.date, '%d' ) ) AS activity
@@ -953,39 +912,37 @@ class module_report_activity extends module_report
GROUP by ddate
ORDER BY ddate ASC";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $date = new DateTime($row['ddate']);
- $result[$date->format(DATE_ATOM)] = $row['activity'];
+ foreach ($rs as $row) {
+ $date = new DateTime($row['ddate']);
+ $result[$date->format(DATE_ATOM)] = $row['activity'];
+ }
+
+ foreach ($result as $key => $act) {
+ $res[$key] = number_format($act, 2, '.', '');
+ }
+
+ return $res;
}
- foreach ($result as $key => $act)
+ public static function activityQuestion($dmin, $dmax, $sbas_id, $list_coll_id)
{
- $res[$key] = number_format($act, 2, '.', '');
- }
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
+ $result = array();
+ $datefilter =
+ module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter =
+ module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- return $res;
- }
+ $params = array(':site_id' => $registry->get('GV_sit'));
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- public static function activityQuestion($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
- $result = array();
- $datefilter =
- module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter =
- module_report_sqlfilter::constructCollectionFilter($list_coll_id);
-
- $params = array(':site_id' => $registry->get('GV_sit'));
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT log_date.usrid, log_date.user, sum(1) AS nb
FROM `log_search`
INNER JOIN log as log_date
@@ -996,35 +953,34 @@ class module_report_activity extends module_report
GROUP BY log_date.usrid
ORDER BY nb DESC";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $result[$row['usrid']]['lib'] = $row['user'];
- $result[$row['usrid']]['nb'] = (int) $row['nb'];
- $result[$row['usrid']]['id'] = $row['usrid'];
+ foreach ($rs as $row) {
+ $result[$row['usrid']]['lib'] = $row['user'];
+ $result[$row['usrid']]['nb'] = (int) $row['nb'];
+ $result[$row['usrid']]['id'] = $row['usrid'];
+ }
+
+ return $result;
}
- return $result;
- }
+ public static function activiteTopQuestion($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
+ $result = array();
+ $datefilter =
+ module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter =
+ module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activiteTopQuestion($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
- $result = array();
- $datefilter =
- module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter =
- module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array(':site_id' => $registry->get('GV_sit'));
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array(':site_id' => $registry->get('GV_sit'));
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT
TRIM(log_search.search) as question,
log_date.usrid,
@@ -1039,35 +995,34 @@ class module_report_activity extends module_report
GROUP BY log_search.search
ORDER BY nb DESC";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- $conv = array(" " => "");
- foreach ($rs as $row)
- {
- $question = $row['question'];
- $question = mb_strtolower(strtr($question, $conv));
- $result[$question]['lib'] = $row['question'];
- $result[$question]['nb'] = (int) $row['nb'];
- $result[$question]['id'] = "false";
+ $conv = array(" " => "");
+ foreach ($rs as $row) {
+ $question = $row['question'];
+ $question = mb_strtolower(strtr($question, $conv));
+ $result[$question]['lib'] = $row['question'];
+ $result[$question]['nb'] = (int) $row['nb'];
+ $result[$question]['id'] = "false";
+ }
+
+ return $result;
}
- return $result;
- }
+ public static function activiteTopTenSiteView($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $result = array();
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activiteTopTenSiteView($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $result = array();
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array();
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array();
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT referrer, COUNT(referrer) as nb_view
FROM log_view
INNER JOIN log as log_date
@@ -1077,38 +1032,37 @@ class module_report_activity extends module_report
GROUP BY referrer
ORDER BY nb_view DESC ";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- ($row['referrer'] != 'NO REFERRER') ?
- $host = parent::getHost($row['referrer']) :
- $host = 'NO REFERRER';
- if (!isset($result[$host]['nb']))
- $result[$host]['nb'] = 0;
- if (!isset($result[$host]['lib']))
- $result[$host]['lib'] = $host;
- $result[$host]['nb']+= ( (int) $row['nb_view']);
- $result[$host]['id'] = "false";
+ foreach ($rs as $row) {
+ ($row['referrer'] != 'NO REFERRER') ?
+ $host = parent::getHost($row['referrer']) :
+ $host = 'NO REFERRER';
+ if ( ! isset($result[$host]['nb']))
+ $result[$host]['nb'] = 0;
+ if ( ! isset($result[$host]['lib']))
+ $result[$host]['lib'] = $host;
+ $result[$host]['nb']+= ( (int) $row['nb_view']);
+ $result[$host]['id'] = "false";
+ }
+
+ return $result;
}
- return $result;
- }
+ public static function activiteAddedDocument($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $result = array();
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activiteAddedDocument($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $result = array();
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array();
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array();
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT DISTINCT (
DATE_FORMAT( log_date.date, '%Y-%m-%d' )
) AS ddate, COUNT( DATE_FORMAT( log_date.date, '%d' ) ) AS activity
@@ -1120,30 +1074,29 @@ class module_report_activity extends module_report
GROUP BY ddate
ORDER BY activity ASC ";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $date = new DateTime($row['ddate']);
- $result[$date->format(DATE_ATOM)] = $row['activity'];
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ foreach ($rs as $row) {
+ $date = new DateTime($row['ddate']);
+ $result[$date->format(DATE_ATOM)] = $row['activity'];
+ }
+
+ return $result;
}
- return $result;
- }
+ public static function activiteEditedDocument($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $result = array();
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activiteEditedDocument($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $result = array();
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array();
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array();
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT DISTINCT (
DATE_FORMAT( log_date.date, '%Y-%m-%d' )
) AS ddate, COUNT( DATE_FORMAT( log_date.date, '%d' ) ) AS activity
@@ -1155,31 +1108,30 @@ class module_report_activity extends module_report
GROUP BY ddate
ORDER BY activity ASC ";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $date = phraseadate::getPrettyString(new DateTime($row['ddate']));
- $result[$date] = $row['activity'];
+ foreach ($rs as $row) {
+ $date = phraseadate::getPrettyString(new DateTime($row['ddate']));
+ $result[$date] = $row['activity'];
+ }
+
+ return $result;
}
- return $result;
- }
+ public static function activiteAddedTopTenUser($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $result = array();
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
- public static function activiteAddedTopTenUser($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $result = array();
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ $params = array();
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
- $params = array();
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
-
- $sql = "
+ $sql = "
SELECT log.usrid, log.user, sum( 1 ) AS nb
FROM log_docs as log_date
INNER JOIN log ON log_date.log_id = log.id
@@ -1188,19 +1140,17 @@ class module_report_activity extends module_report
GROUP BY log.usrid
ORDER BY nb ASC ";
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
- foreach ($rs as $row)
- {
- $result[$row['usrid']]['lib'] = $row['user'];
- $result[$row['usrid']]['nb'] = $row['nb'];
- $result[$row['usrid']]['id'] = $row['usrid'];
+ foreach ($rs as $row) {
+ $result[$row['usrid']]['lib'] = $row['user'];
+ $result[$row['usrid']]['nb'] = $row['nb'];
+ $result[$row['usrid']]['id'] = $row['usrid'];
+ }
+
+ return $result;
}
-
- return $result;
- }
-
}
diff --git a/lib/classes/module/report/add.class.php b/lib/classes/module/report/add.class.php
index c62622c6bd..37050bb7ee 100644
--- a/lib/classes/module/report/add.class.php
+++ b/lib/classes/module/report/add.class.php
@@ -17,131 +17,113 @@
*/
class module_report_add extends module_report
{
+ protected $cor_query = array(
+ 'user' => 'log.user',
+ 'site' => 'log.site',
+ 'societe' => 'log.societe',
+ 'pays' => 'log.pays',
+ 'activite' => 'log.activite',
+ 'fonction' => 'log.fonction',
+ 'usrid' => 'log.usrid',
+ 'getter' => 'd.final',
+ 'date' => "DATE(d.date)",
+ 'id' => 'd.id',
+ 'log_id' => 'd.log_id',
+ 'record_id' => 'd.record_id',
+ 'final' => 'd.final',
+ 'comment' => 'd.comment',
+ 'size' => 's.size'
+ );
- protected $cor_query = array(
- 'user' => 'log.user',
- 'site' => 'log.site',
- 'societe' => 'log.societe',
- 'pays' => 'log.pays',
- 'activite' => 'log.activite',
- 'fonction' => 'log.fonction',
- 'usrid' => 'log.usrid',
- 'getter' => 'd.final',
- 'date' => "DATE(d.date)",
- 'id' => 'd.id',
- 'log_id' => 'd.log_id',
- 'record_id' => 'd.record_id',
- 'final' => 'd.final',
- 'comment' => 'd.comment',
- 'size' => 's.size'
- );
-
- /**
- * constructor
- *
- * @name download::__construct()
- * @param $arg1 start date of the report
- * @param $arg2 end date of the report
- * @param $sbas_id id of the databox
- */
- public function __construct($arg1, $arg2, $sbas_id, $collist)
- {
- parent::__construct($arg1, $arg2, $sbas_id, $collist);
- $this->title = _('report:: document ajoute');
- }
-
- /**
- * @desc build the specified requete
- * @param $obj $conn the current connection to databox
- * @return string
- */
- protected function buildReq($groupby = false, $on = false)
- {
- $s = $this->sqlBuilder('action')->setGroupBy($groupby)->setOn($on)
- ->setAction('add')->buildSql();
- $this->req = $s->getSql();
- $this->params = $s->getParams();
- $this->total = $s->getTotalRows();
- }
-
- public function colFilter($field, $on = false)
- {
- $s = $this->sqlBuilder('action')->setAction('add');
- $var = $s->sqlDistinctValByField($field);
- $sql = $var['sql'];
- $params = $var['params'];
- $stmt = $s->getConnBas()->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- $ret = array();
-
- $appbox = appbox::get_instance(\bootstrap::getCore());
-
- foreach ($rs as $row)
+ /**
+ * constructor
+ *
+ * @name download::__construct()
+ * @param $arg1 start date of the report
+ * @param $arg2 end date of the report
+ * @param $sbas_id id of the databox
+ */
+ public function __construct($arg1, $arg2, $sbas_id, $collist)
{
- $value = $row['val'];
- $caption = $value;
- if ($field == "getter")
- {
- try
- {
- $user = User_Adapter::getInstance($value, $appbox);
- $caption = $user->get_display_name();
- }
- catch (Exception $e)
- {
-
- }
- }
- elseif ($field == 'date')
- $caption = phraseadate::getPrettyString(new DateTime($value));
- elseif ($field == 'size')
- $caption = p4string::format_octets($value);
-
- $ret[] = array('val' => $caption, 'value' => $value);
+ parent::__construct($arg1, $arg2, $sbas_id, $collist);
+ $this->title = _('report:: document ajoute');
}
- return $ret;
- }
-
- protected function buildResult($rs)
- {
- $i = 0;
- foreach ($rs as $row)
+ /**
+ * @desc build the specified requete
+ * @param $obj $conn the current connection to databox
+ * @return string
+ */
+ protected function buildReq($groupby = false, $on = false)
{
- foreach ($this->champ as $key => $value)
- {
- if ($row[$value])
- {
- if ($value == 'date')
- {
- $this->result[$i][$value] = $this->pretty_string ? phraseadate::getPrettyString(new DateTime($row[$value])) : $row[$value];
- }
- elseif ($value == 'size')
- {
- $this->result[$i][$value] = p4string::format_octets($row[$value]);
- }
- else
- $this->result[$i][$value] = $row[$value];
- }
- else
- {
- if ($value == 'comment')
- {
- $this->result[$i][$value] = ' ';
- }
- else
- {
- $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
- }
- }
- }
- $i++;
- if ($i >= $this->nb_record)
- break;
+ $s = $this->sqlBuilder('action')->setGroupBy($groupby)->setOn($on)
+ ->setAction('add')->buildSql();
+ $this->req = $s->getSql();
+ $this->params = $s->getParams();
+ $this->total = $s->getTotalRows();
}
- }
+ public function colFilter($field, $on = false)
+ {
+ $s = $this->sqlBuilder('action')->setAction('add');
+ $var = $s->sqlDistinctValByField($field);
+ $sql = $var['sql'];
+ $params = $var['params'];
+ $stmt = $s->getConnBas()->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ $ret = array();
+
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+
+ foreach ($rs as $row) {
+ $value = $row['val'];
+ $caption = $value;
+ if ($field == "getter") {
+ try {
+ $user = User_Adapter::getInstance($value, $appbox);
+ $caption = $user->get_display_name();
+ } catch (Exception $e) {
+
+ }
+ } elseif ($field == 'date')
+ $caption = phraseadate::getPrettyString(new DateTime($value));
+ elseif ($field == 'size')
+ $caption = p4string::format_octets($value);
+
+ $ret[] = array('val' => $caption, 'value' => $value);
+ }
+
+ return $ret;
+ }
+
+ protected function buildResult($rs)
+ {
+ $i = 0;
+ foreach ($rs as $row) {
+ foreach ($this->champ as $key => $value) {
+ if ($row[$value]) {
+ if ($value == 'date') {
+ $this->result[$i][$value] = $this->pretty_string ? phraseadate::getPrettyString(new DateTime($row[$value])) : $row[$value];
+ } elseif ($value == 'size') {
+ $this->result[$i][$value] = p4string::format_octets($row[$value]);
+ }
+ else
+ $this->result[$i][$value] = $row[$value];
+ }
+ else {
+ if ($value == 'comment') {
+ $this->result[$i][$value] = ' ';
+ } else {
+ $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
+ }
+ }
+ }
+ $i ++;
+ if ($i >= $this->nb_record)
+ break;
+ }
+ }
}
diff --git a/lib/classes/module/report/connexion.class.php b/lib/classes/module/report/connexion.class.php
index 8b93071e81..f7b40b61ef 100644
--- a/lib/classes/module/report/connexion.class.php
+++ b/lib/classes/module/report/connexion.class.php
@@ -17,183 +17,160 @@
*/
class module_report_connexion extends module_report
{
+ protected $cor_query = array(
+ 'user' => 'log.user'
+ , 'usrid' => 'log.usrid'
+ , 'ddate' => 'log.date'
+ , 'societe' => 'log.societe'
+ , 'pays' => 'log.pays'
+ , 'activite' => 'log.activite'
+ , 'fonction' => 'log.fonction'
+ , 'site' => 'log.site'
+ , 'sit_session' => 'log.sit_session'
+ , 'coll_list' => 'log.coll_list'
+ , 'appli' => 'log.appli'
+ , 'ip' => 'log.ip'
+ );
- protected $cor_query = array(
- 'user' => 'log.user'
- , 'usrid' => 'log.usrid'
- , 'ddate' => 'log.date'
- , 'societe' => 'log.societe'
- , 'pays' => 'log.pays'
- , 'activite' => 'log.activite'
- , 'fonction' => 'log.fonction'
- , 'site' => 'log.site'
- , 'sit_session' => 'log.sit_session'
- , 'coll_list' => 'log.coll_list'
- , 'appli' => 'log.appli'
- , 'ip' => 'log.ip'
- );
-
- /**
- * constructor
- *
- * @name connexion::__construct()
- * @param $arg1 start date of the report
- * @param $arg2 end date of the report
- * @param $sbas_id id of the databox
- */
- public function __construct($arg1, $arg2, $sbas_id, $collist)
- {
- parent::__construct($arg1, $arg2, $sbas_id, $collist);
- $this->title = _('report::Connexions');
- }
-
- /**
- * @desc build the specified requete
- * @param $obj $conn the current connection to databox
- * @return string
- */
- protected function buildReq($groupby = false)
- {
- $sql = $this->sqlBuilder('connexion');
- $sql = $sql->setGroupBy($groupby);
- $sql = $sql->buildSql();
- $this->req = $sql->getSql();
- $this->params = $sql->getParams();
- $this->total = $sql->getTotalRows();
- }
-
- /**
- * @desc build the list with all distinct result
- * @param string $field the field from the request displayed in a array
- * @return string $liste
- */
- public function colFilter($field)
- {
- $ret = array();
- $s = $this->sqlBuilder('connexion');
- $var = $s->sqlDistinctValByField($field);
- $sql = $var['sql'];
- $params = $var['params'];
-
- $stmt = $s->getConnBas()->prepare($sql);
- $stmt->execute($params);
- $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- foreach ($rs as $row)
+ /**
+ * constructor
+ *
+ * @name connexion::__construct()
+ * @param $arg1 start date of the report
+ * @param $arg2 end date of the report
+ * @param $sbas_id id of the databox
+ */
+ public function __construct($arg1, $arg2, $sbas_id, $collist)
{
- $value = $row['val'];
- if ($field == "appli")
- $caption = implode(' ', phrasea::modulesName(@unserialize($value)));
- elseif ($field == 'ddate')
- $caption = phraseadate::getPrettyString(new DateTime($value));
- else
- $caption = $row['val'];
- $ret[] = array('val' => $caption, 'value' => $value);
+ parent::__construct($arg1, $arg2, $sbas_id, $collist);
+ $this->title = _('report::Connexions');
}
- return $ret;
- }
-
- /**
- * @desc build the result from the specified sql
- * @param array $champ all the field from the request displayed in a array
- * @param string $sql the request from buildreq
- * @return $this->result
- */
- protected function buildResult($rs)
- {
- $i = 0;
-
- foreach ($rs as $row)
+ /**
+ * @desc build the specified requete
+ * @param $obj $conn the current connection to databox
+ * @return string
+ */
+ protected function buildReq($groupby = false)
{
- if ($this->enable_limit && ($i > $this->nb_record))
- break;
- foreach ($this->champ as $key => $value)
- {
- if (!isset($row[$value]))
- {
- $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
- continue;
- }
+ $sql = $this->sqlBuilder('connexion');
+ $sql = $sql->setGroupBy($groupby);
+ $sql = $sql->buildSql();
+ $this->req = $sql->getSql();
+ $this->params = $sql->getParams();
+ $this->total = $sql->getTotalRows();
+ }
- if ($value == 'coll_list')
- {
- $coll = explode(",", $row[$value]);
- $this->result[$i][$value] = "";
- foreach ($coll as $id)
- {
- if ($this->result[$i][$value] != "")
- {
- $this->result[$i][$value].= " / ";
- $this->result[$i][$value] .= phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $id));
- }
- elseif ($this->result[$i][$value] == "")
- {
- $this->result[$i][$value] = phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $id));
- }
- }
- }
- elseif ($value == 'appli')
- {
- $applis = false;
- if (($applis = @unserialize($row[$value])) !== false)
- {
- if (empty($applis))
- {
- $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
- }
+ /**
+ * @desc build the list with all distinct result
+ * @param string $field the field from the request displayed in a array
+ * @return string $liste
+ */
+ public function colFilter($field)
+ {
+ $ret = array();
+ $s = $this->sqlBuilder('connexion');
+ $var = $s->sqlDistinctValByField($field);
+ $sql = $var['sql'];
+ $params = $var['params'];
+
+ $stmt = $s->getConnBas()->prepare($sql);
+ $stmt->execute($params);
+ $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+
+ foreach ($rs as $row) {
+ $value = $row['val'];
+ if ($field == "appli")
+ $caption = implode(' ', phrasea::modulesName(@unserialize($value)));
+ elseif ($field == 'ddate')
+ $caption = phraseadate::getPrettyString(new DateTime($value));
else
- {
- $this->result[$i][$value] = implode(' ', phrasea::modulesName($applis));
- }
- }
- else
- {
- $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
- }
+ $caption = $row['val'];
+ $ret[] = array('val' => $caption, 'value' => $value);
}
- elseif ($value == 'ddate')
- {
- $this->result[$i][$value] = $this->pretty_string ?
- phraseadate::getPrettyString(new DateTime($row[$value])) :
- $row[$value];
- }
- else
- {
- $this->result[$i][$value] = $row[$value];
- }
- }
- $i++;
+
+ return $ret;
}
- }
- public static function getNbConn($dmin, $dmax, $sbas_id, $list_coll_id)
- {
- $conn = connection::getPDOConnection($sbas_id);
- $registry = registry::get_instance();
+ /**
+ * @desc build the result from the specified sql
+ * @param array $champ all the field from the request displayed in a array
+ * @param string $sql the request from buildreq
+ * @return $this->result
+ */
+ protected function buildResult($rs)
+ {
+ $i = 0;
- $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
- $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+ foreach ($rs as $row) {
+ if ($this->enable_limit && ($i > $this->nb_record))
+ break;
+ foreach ($this->champ as $key => $value) {
+ if ( ! isset($row[$value])) {
+ $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
+ continue;
+ }
- $params = array(':site_id' => $registry->get('GV_sit'));
- $params = array_merge($params, $datefilter['params'], $collfilter['params']);
+ if ($value == 'coll_list') {
+ $coll = explode(",", $row[$value]);
+ $this->result[$i][$value] = "";
+ foreach ($coll as $id) {
+ if ($this->result[$i][$value] != "") {
+ $this->result[$i][$value].= " / ";
+ $this->result[$i][$value] .= phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $id));
+ } elseif ($this->result[$i][$value] == "") {
+ $this->result[$i][$value] = phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $id));
+ }
+ }
+ } elseif ($value == 'appli') {
+ $applis = false;
+ if (($applis = @unserialize($row[$value])) !== false) {
+ if (empty($applis)) {
+ $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
+ } else {
+ $this->result[$i][$value] = implode(' ', phrasea::modulesName($applis));
+ }
+ } else {
+ $this->result[$i][$value] = '' . _('report:: non-renseigne') . ' ';
+ }
+ } elseif ($value == 'ddate') {
+ $this->result[$i][$value] = $this->pretty_string ?
+ phraseadate::getPrettyString(new DateTime($row[$value])) :
+ $row[$value];
+ } else {
+ $this->result[$i][$value] = $row[$value];
+ }
+ }
+ $i ++;
+ }
+ }
- $finalfilter = $datefilter['sql'] . ' AND ';
- $finalfilter .= '(' . $collfilter['sql'] . ') AND ';
- $finalfilter .= 'log_date.site = :site_id';
+ public static function getNbConn($dmin, $dmax, $sbas_id, $list_coll_id)
+ {
+ $conn = connection::getPDOConnection($sbas_id);
+ $registry = registry::get_instance();
- $sql = "SELECT COUNT(usrid) as nb
+ $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax);
+ $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id);
+
+ $params = array(':site_id' => $registry->get('GV_sit'));
+ $params = array_merge($params, $datefilter['params'], $collfilter['params']);
+
+ $finalfilter = $datefilter['sql'] . ' AND ';
+ $finalfilter .= '(' . $collfilter['sql'] . ') AND ';
+ $finalfilter .= 'log_date.site = :site_id';
+
+ $sql = "SELECT COUNT(usrid) as nb
FROM log as log_date
WHERE " . $finalfilter;
- $stmt = $conn->prepare($sql);
- $stmt->execute($params);
- $row = $stmt->fetch(PDO::FETCH_ASSOC);
- $stmt->closeCursor();
-
- return (int) $row['nb'];
- }
+ $stmt = $conn->prepare($sql);
+ $stmt->execute($params);
+ $row = $stmt->fetch(PDO::FETCH_ASSOC);
+ $stmt->closeCursor();
+ return (int) $row['nb'];
+ }
}
diff --git a/lib/classes/module/report/dashboard.class.php b/lib/classes/module/report/dashboard.class.php
index 96a6c6fcac..6a62ca75cf 100644
--- a/lib/classes/module/report/dashboard.class.php
+++ b/lib/classes/module/report/dashboard.class.php
@@ -17,353 +17,327 @@
*/
class module_report_dashboard implements module_report_dashboard_componentInterface
{
+ /**
+ * objet user
+ * @var user
+ */
+ public $usr;
- /**
- * objet user
- * @var user
- */
- public $usr;
+ /**
+ * @la date mini du report
+ * @var
+ */
+ public $dmin;
- /**
- * @la date mini du report
- * @var
- */
- public $dmin;
+ /**
+ * @desc la date maxi du report
+ * @var
+ */
+ public $dmax;
- /**
- * @desc la date maxi du report
- * @var
- */
- public $dmax;
+ /**
+ * @desc le tableau qui contient toutes les collections ou l'utilisateur
+ * a le droit de report
+ * @var
+ */
+ public $authorizedCollection = array();
- /**
- * @desc le tableau qui contient toutes les collections ou l'utilisateur
- * a le droit de report
- * @var
- */
- public $authorizedCollection = array();
+ /**
+ * @desc le tableau qui contient le dashboard
+ * @var
+ */
+ public $dashboard = array();
- /**
- * @desc le tableau qui contient le dashboard
- * @var
- */
- public $dashboard = array();
+ /**
+ * @des le nombre par defaut de resultats afficher par categorie
+ * @var
+ */
+ public $nbtop = 10;
- /**
- * @des le nombre par defaut de resultats afficher par categorie
- * @var
- */
- public $nbtop = 10;
+ /**
+ * @desc la periode par defaut d'affichage du dashboard
+ * @var
+ */
+ public $periode = '-1 month';
- /**
- * @desc la periode par defaut d'affichage du dashboard
- * @var
- */
- public $periode = '-1 month';
+ /**
+ * @desc le sbasid de la base ou on effectue le report
+ * @var
+ */
+ public $sbasid;
- /**
- * @desc le sbasid de la base ou on effectue le report
- * @var
- */
- public $sbasid;
-
- /**
- * @desc Construit un dashboard selon les droits du usrid, si sbas vaut null
- * c'est un report sur toutes les bases, sinon sur le sbasid
- * @param $usrid
- * @param $sbasid
- */
- public function __construct($usr, $sbasid = null)
- {
- $this->usr = $usr;
- if (is_null($sbasid))
- $this->sbasid = 'all';
- else
- $this->sbasid = $sbasid;
- $this->initDate();
- $this->setAuthCollection();
- $this->getPlotLegendDay($this->dmin);
- }
-
- /**
- * @desc genere le report
- * @return dashboard_main
- */
- public function execute()
- {
- $this->setReport();
- $this->process();
-
- return $this;
- }
-
- /**
- * @desc modifier les date du report
- * @param Datetime $dmin
- * @param Datetime $dmax
- * @return
- */
- public function setDate($dmin, $dmax)
- {
- $dmin = new Datetime($dmin);
- $dmax = new Datetime($dmax);
-
- $dmax->modify('+23 hours +59 minutes +59 seconds');
-
- $this->dmax = $dmax->format('d-m-Y');
- $this->dmin = $dmin->format('d-m-Y');
-
- $this->getPlotLegendDay($this->dmin, $this->dmax);
-
- return;
- }
-
- /**
- * @desc return la liste des collection authoriséee
- * @return
- */
- public function authorizedCollection()
- {
- return $this->authorizedCollection;
- }
-
- /**
- * @desc return le titre de la date
- * @param $d vaut 'dmin' ou 'dmax'
- * @return
- */
- public function getTitleDate($d)
- {
- if ($d == 'dmax')
+ /**
+ * @desc Construit un dashboard selon les droits du usrid, si sbas vaut null
+ * c'est un report sur toutes les bases, sinon sur le sbasid
+ * @param $usrid
+ * @param $sbasid
+ */
+ public function __construct($usr, $sbasid = null)
{
- $datetime = new Datetime($this->dmax);
-
- return phraseadate::getPrettyString($datetime);
- }
- elseif ($d == 'dmin')
- {
- $datetime = new Datetime($this->dmin);
-
- return phraseadate::getPrettyString($datetime);
- }
- else
- throw new Exception('argument must be string dmin or dmax');
- }
-
- /**
- * @desc check if a dashboard is valid
- * @return
- */
- public function isValid()
- {
- if (isset($this->dashboard) && sizeof($this->dashboard) > 0)
-
- return true;
- else
-
- return false;
- }
-
- /**
- * @desc return le dashboard
- * @return
- */
- public function getDash()
- {
- return $this->dashboard;
- }
-
- /**
- * @desc construct the legend for charts
- * if dmax === false dmax = now();
- * @param $dmin
- * @param $dmax
- * @return
- */
- protected function getPlotLegendDay($dmin, $dmax = false)
- {
- if (!$dmax)
- {
- $date = new Datetime();
- $dmax = $date->format('d-m-Y');
- }
- else
- {
- $date = new Datetime($dmax);
- $dmax = $date->format('d-m-Y');
- }
- $this->legendDay[] = phraseadate::getPrettyString($date);
-
- while ($dmin != $dmax)
- {
- $date->modify('-1 day');
- $dmax = $date->format('d-m-Y');
- $this->legendDay[] = phraseadate::getPrettyString($date);
- $this->nb_days++;
- }
- $this->legendDay = array_reverse($this->legendDay);
-
- return;
- }
-
- /**
- * @desc merge tous les resultats dans dashboard
- * @return
- */
- public function process()
- {
- $tri = $this->group()->tri();
- $x = $tri->getDash();
- $a = $tri->top()->getTop($this->nbtop);
- $this->dashboard = array();
- foreach ($a as $k => $v)
- {
- if (array_key_exists($k, $x))
- {
- $x[$k] = $v;
- }
- }
- $this->dashboard = $x;
-
- return;
- }
-
- /**
- * @desc init dmin and dmax
- * @return
- */
- protected function initDate()
- {
- $datetime = new Datetime();
- $this->dmax = $datetime->format('d-m-Y');
- $datetime->modify($this->periode);
- $this->dmin = $datetime->format('d-m-Y');
-
- return;
- }
-
- /**
- * @desc construit un array avec tous les collections ou l'utilisateur
- * a le droit de reporting
- * @return
- */
- public function getAllColl()
- {
- $all_coll = array();
-
- $base_ids = $this->usr->ACL()->get_granted_base(array('canreport'));
-
- foreach ($base_ids as $base_id => $collection)
- {
- $databox = $collection->get_databox();
- $sbas_id = $databox->get_sbas_id();
- if (!isset($all_coll[$sbas_id]))
- {
- $all_coll[$sbas_id] = array();
- $all_coll[$sbas_id]['name_sbas'] = $databox->get_viewname();
- }
- $all_coll[$sbas_id]['sbas_collections'][] = array(
- 'base_id' => $base_id,
- 'sbas_id' => $sbas_id,
- 'coll_id' => $collection->get_base_id(),
- 'name' => $collection->get_name()
- );
+ $this->usr = $usr;
+ if (is_null($sbasid))
+ $this->sbasid = 'all';
+ else
+ $this->sbasid = $sbasid;
+ $this->initDate();
+ $this->setAuthCollection();
+ $this->getPlotLegendDay($this->dmin);
}
- return $all_coll;
- }
-
- /**
- * @des set authorizedCollection
- * @return
- */
- protected function setAuthCollection()
- {
- $all_coll = $this->getAllColl();
-
- foreach ($all_coll as $sbas => $info)
+ /**
+ * @desc genere le report
+ * @return dashboard_main
+ */
+ public function execute()
{
- $listeColl = array();
+ $this->setReport();
+ $this->process();
- foreach ($info['sbas_collections'] as $key => $value)
- {
- $listeColl[] = (int) $value['coll_id'];
- }
-
- $this->authorizedCollection[] = array(
- 'sbas_id' => (int) $sbas,
- 'coll' => implode(',', $listeColl),
- 'name' => phrasea::sbas_names($sbas)
- );
+ return $this;
}
- return;
- }
-
- /**
- * @desc la liste des base authorisee sous forme de string
- * @param $separotor
- * @return string
- */
- public function getListeBase($separator)
- {
- $all_coll = $this->getAllColl();
- $liste = '';
- foreach ($all_coll as $sbas => $info)
+ /**
+ * @desc modifier les date du report
+ * @param Datetime $dmin
+ * @param Datetime $dmax
+ * @return
+ */
+ public function setDate($dmin, $dmax)
{
- $liste .= phrasea::sbas_names($sbas) . ' ' . $separator . ' ';
+ $dmin = new Datetime($dmin);
+ $dmax = new Datetime($dmax);
+
+ $dmax->modify('+23 hours +59 minutes +59 seconds');
+
+ $this->dmax = $dmax->format('d-m-Y');
+ $this->dmin = $dmin->format('d-m-Y');
+
+ $this->getPlotLegendDay($this->dmin, $this->dmax);
+
+ return;
}
- return $liste;
- }
-
- /**
- * @desc Foreach authorized collection, fill the dashboard
- * with an object dashboard
- * @return
- */
- protected function setReport()
- {
- $i = 0;
- foreach ($this->authorizedCollection as $key => $value)
+ /**
+ * @desc return la liste des collection authoriséee
+ * @return
+ */
+ public function authorizedCollection()
{
- $sbasid = $value['sbas_id'];
- $coll = $value['coll'];
- try
- {
- if ($this->sbasid != "all")
- {
- if ($this->sbasid == $sbasid)
- {
- $this->dashboard[$sbasid] = module_report_dashboard_feed::getInstance(
- $sbasid, $coll, $this->dmin, $this->dmax
- );
- break;
- }
+ return $this->authorizedCollection;
+ }
+
+ /**
+ * @desc return le titre de la date
+ * @param $d vaut 'dmin' ou 'dmax'
+ * @return
+ */
+ public function getTitleDate($d)
+ {
+ if ($d == 'dmax') {
+ $datetime = new Datetime($this->dmax);
+
+ return phraseadate::getPrettyString($datetime);
+ } elseif ($d == 'dmin') {
+ $datetime = new Datetime($this->dmin);
+
+ return phraseadate::getPrettyString($datetime);
}
else
- {
- $this->dashboard[$sbasid] = module_report_dashboard_feed::getInstance(
- $sbasid, $coll, $this->dmin, $this->dmax
- );
- }
- }
- catch (Exception $e)
- {
-
- }
- $i++;
+ throw new Exception('argument must be string dmin or dmax');
}
- return;
- }
+ /**
+ * @desc check if a dashboard is valid
+ * @return
+ */
+ public function isValid()
+ {
+ if (isset($this->dashboard) && sizeof($this->dashboard) > 0)
+ return true;
+ else
+ return false;
+ }
- /**
- * @return dashboard_group
- */
- public function group()
- {
- return new module_report_dashboard_group($this);
- }
+ /**
+ * @desc return le dashboard
+ * @return
+ */
+ public function getDash()
+ {
+ return $this->dashboard;
+ }
+ /**
+ * @desc construct the legend for charts
+ * if dmax === false dmax = now();
+ * @param $dmin
+ * @param $dmax
+ * @return
+ */
+ protected function getPlotLegendDay($dmin, $dmax = false)
+ {
+ if ( ! $dmax) {
+ $date = new Datetime();
+ $dmax = $date->format('d-m-Y');
+ } else {
+ $date = new Datetime($dmax);
+ $dmax = $date->format('d-m-Y');
+ }
+ $this->legendDay[] = phraseadate::getPrettyString($date);
+
+ while ($dmin != $dmax) {
+ $date->modify('-1 day');
+ $dmax = $date->format('d-m-Y');
+ $this->legendDay[] = phraseadate::getPrettyString($date);
+ $this->nb_days ++;
+ }
+ $this->legendDay = array_reverse($this->legendDay);
+
+ return;
+ }
+
+ /**
+ * @desc merge tous les resultats dans dashboard
+ * @return
+ */
+ public function process()
+ {
+ $tri = $this->group()->tri();
+ $x = $tri->getDash();
+ $a = $tri->top()->getTop($this->nbtop);
+ $this->dashboard = array();
+ foreach ($a as $k => $v) {
+ if (array_key_exists($k, $x)) {
+ $x[$k] = $v;
+ }
+ }
+ $this->dashboard = $x;
+
+ return;
+ }
+
+ /**
+ * @desc init dmin and dmax
+ * @return
+ */
+ protected function initDate()
+ {
+ $datetime = new Datetime();
+ $this->dmax = $datetime->format('d-m-Y');
+ $datetime->modify($this->periode);
+ $this->dmin = $datetime->format('d-m-Y');
+
+ return;
+ }
+
+ /**
+ * @desc construit un array avec tous les collections ou l'utilisateur
+ * a le droit de reporting
+ * @return
+ */
+ public function getAllColl()
+ {
+ $all_coll = array();
+
+ $base_ids = $this->usr->ACL()->get_granted_base(array('canreport'));
+
+ foreach ($base_ids as $base_id => $collection) {
+ $databox = $collection->get_databox();
+ $sbas_id = $databox->get_sbas_id();
+ if ( ! isset($all_coll[$sbas_id])) {
+ $all_coll[$sbas_id] = array();
+ $all_coll[$sbas_id]['name_sbas'] = $databox->get_viewname();
+ }
+ $all_coll[$sbas_id]['sbas_collections'][] = array(
+ 'base_id' => $base_id,
+ 'sbas_id' => $sbas_id,
+ 'coll_id' => $collection->get_base_id(),
+ 'name' => $collection->get_name()
+ );
+ }
+
+ return $all_coll;
+ }
+
+ /**
+ * @des set authorizedCollection
+ * @return
+ */
+ protected function setAuthCollection()
+ {
+ $all_coll = $this->getAllColl();
+
+ foreach ($all_coll as $sbas => $info) {
+ $listeColl = array();
+
+ foreach ($info['sbas_collections'] as $key => $value) {
+ $listeColl[] = (int) $value['coll_id'];
+ }
+
+ $this->authorizedCollection[] = array(
+ 'sbas_id' => (int) $sbas,
+ 'coll' => implode(',', $listeColl),
+ 'name' => phrasea::sbas_names($sbas)
+ );
+ }
+
+ return;
+ }
+
+ /**
+ * @desc la liste des base authorisee sous forme de string
+ * @param $separotor
+ * @return string
+ */
+ public function getListeBase($separator)
+ {
+ $all_coll = $this->getAllColl();
+ $liste = '';
+ foreach ($all_coll as $sbas => $info) {
+ $liste .= phrasea::sbas_names($sbas) . ' ' . $separator . ' ';
+ }
+
+ return $liste;
+ }
+
+ /**
+ * @desc Foreach authorized collection, fill the dashboard
+ * with an object dashboard
+ * @return
+ */
+ protected function setReport()
+ {
+ $i = 0;
+ foreach ($this->authorizedCollection as $key => $value) {
+ $sbasid = $value['sbas_id'];
+ $coll = $value['coll'];
+ try {
+ if ($this->sbasid != "all") {
+ if ($this->sbasid == $sbasid) {
+ $this->dashboard[$sbasid] = module_report_dashboard_feed::getInstance(
+ $sbasid, $coll, $this->dmin, $this->dmax
+ );
+ break;
+ }
+ } else {
+ $this->dashboard[$sbasid] = module_report_dashboard_feed::getInstance(
+ $sbasid, $coll, $this->dmin, $this->dmax
+ );
+ }
+ } catch (Exception $e) {
+
+ }
+ $i ++;
+ }
+
+ return;
+ }
+
+ /**
+ * @return dashboard_group
+ */
+ public function group()
+ {
+ return new module_report_dashboard_group($this);
+ }
}
diff --git a/lib/classes/module/report/dashboard/componentInterface.class.php b/lib/classes/module/report/dashboard/componentInterface.class.php
index 843eb5a684..3e94660d4b 100644
--- a/lib/classes/module/report/dashboard/componentInterface.class.php
+++ b/lib/classes/module/report/dashboard/componentInterface.class.php
@@ -17,9 +17,10 @@
*/
interface module_report_dashboard_componentInterface
{
- public function process();
- public function getDash();
+ public function process();
- public function isValid();
+ public function getDash();
+
+ public function isValid();
}
diff --git a/lib/classes/module/report/dashboard/feed.class.php b/lib/classes/module/report/dashboard/feed.class.php
index c2d4a5cd90..ac9173c137 100644
--- a/lib/classes/module/report/dashboard/feed.class.php
+++ b/lib/classes/module/report/dashboard/feed.class.php
@@ -17,268 +17,222 @@
*/
class module_report_dashboard_feed implements module_report_dashboard_componentInterface
{
+ /**
+ * @desc la date mini des resultats
+ * @var
+ */
+ public $dmin;
- /**
- * @desc la date mini des resultats
- * @var
- */
- public $dmin;
- /**
- * @desc la date maxi des resultats
- * @var
- */
- public $dmax;
- /**
- * @desc version sql de la date mini
- * @var
- */
- public $dminsql;
- /**
- * @desc version sql de la date maxi
- * @var
- */
- public $dmaxsql;
- /**
- * @desc le sbasid de la base sur lequel on effectue les requetes
- * @var
- */
- public $sbasid;
- /**
- * @la liste des collections séparés par une virgule
- * sur laquelle on effectue les requetes
- * @var
- */
- public $collection;
- /**
- * @desc le tableau qui contien les resultats
- * @var
- */
- public $report = array();
+ /**
+ * @desc la date maxi des resultats
+ * @var
+ */
+ public $dmax;
- /**
- * @desc return l'objet stockee dans le cache si i l existe sinon instancie
- * un nouveau objet dashboard_feed
- * @param $sbasid
- * @param $sbas_coll
- * @param $dmin
- * @param $dmax
- * @return self
- */
- public static function getInstance($sbasid, $sbas_coll, $dmin, $dmax)
- {
- $appbox = appbox::get_instance(\bootstrap::getCore());
- $cache_id = 'feed_' . md5($sbasid . '_' . $sbas_coll . '_' . $dmin . '_' . $dmax);
+ /**
+ * @desc version sql de la date mini
+ * @var
+ */
+ public $dminsql;
- try
- {
- return $appbox->get_data_from_cache($cache_id);
- }
- catch (Exception $e)
+ /**
+ * @desc version sql de la date maxi
+ * @var
+ */
+ public $dmaxsql;
+
+ /**
+ * @desc le sbasid de la base sur lequel on effectue les requetes
+ * @var
+ */
+ public $sbasid;
+
+ /**
+ * @la liste des collections séparés par une virgule
+ * sur laquelle on effectue les requetes
+ * @var
+ */
+ public $collection;
+
+ /**
+ * @desc le tableau qui contien les resultats
+ * @var
+ */
+ public $report = array();
+
+ /**
+ * @desc return l'objet stockee dans le cache si i l existe sinon instancie
+ * un nouveau objet dashboard_feed
+ * @param $sbasid
+ * @param $sbas_coll
+ * @param $dmin
+ * @param $dmax
+ * @return self
+ */
+ public static function getInstance($sbasid, $sbas_coll, $dmin, $dmax)
{
+ $appbox = appbox::get_instance(\bootstrap::getCore());
+ $cache_id = 'feed_' . md5($sbasid . '_' . $sbas_coll . '_' . $dmin . '_' . $dmax);
- }
+ try {
+ return $appbox->get_data_from_cache($cache_id);
+ } catch (Exception $e) {
- $tmp = new self($sbasid, $sbas_coll, $dmin, $dmax);
+ }
- $appbox->set_data_to_cache($tmp, $cache_id);
+ $tmp = new self($sbasid, $sbas_coll, $dmin, $dmax);
- return $tmp;
- }
+ $appbox->set_data_to_cache($tmp, $cache_id);
- /**
- * @desc Remplis les resultats bruts pour valeures passees en param
- * @param $sbasid
- * @param $sbas_collection, les collection sous forme de string
- * séparés par une virgule
- * @param $dmin, Y-m-d
- * @param $dmax, Y-m-d
- */
- public function __construct($sbasid, $sbas_collection, $dmin, $dmax)
- {
- $conn = connection::getPDOConnection($sbasid);
- $this->dmin = $dmin;
- $this->dmax = $dmax;
- $this->dminsql = $this->dateToSqlDate('dmin');
- $this->dmaxsql = $this->dateToSqlDate('dmax');
- $this->sbasid = $sbasid;
- $this->collection = $sbas_collection;
- $this->process();
- }
-
- /**
- * @desc return les date dormate pour les requetes sql;
- * @param $d, vaut 'dmin' ou 'dmax'
- * @return Datetime
- */
- private function dateToSqlDate($d)
- {
- if ($d == 'dmax')
- {
- $datetime = new Datetime($this->dmax);
-
- return phraseadate::format_mysql($datetime);
- }
- elseif ($d == 'dmin')
- {
- $datetime = new Datetime($this->dmin);
-
- return phraseadate::format_mysql($datetime);
- }
- }
-
- /**
- * @desc fill the dash results for the current sbas
- * @return
- */
- public function process()
- {
- try
- {
- //Get number of DLs
- $this->report['nb_dl'] = module_report_download::getNbDl(
- $this->dminsql,
- $this->dmaxsql,
- $this->sbasid,
- $this->collection
- );
- //Get Number of connexions
- $this->report['nb_conn'] = module_report_connexion::getNbConn(
- $this->dminsql,
- $this->dmaxsql,
- $this->sbasid,
- $this->collection
- );
- $registry = registry::get_instance();
- if ($registry->get('GV_anonymousReport') == false)
- {
- /**
- * get Top ten user of
- * number of dl doc, prev
- * number of weight dl by doc, prev
- */
- $top = module_report_activity::topTenUser(
- $this->dminsql,
- $this->dmaxsql,
- $this->sbasid,
- $this->collection
- );
-
- $this->report['top_ten_user_doc'] = $top['top_ten_doc'];
- $this->report['top_ten_user_prev'] = $top['top_ten_prev'];
- $this->report['top_ten_user_poiddoc'] = $top['top_ten_poiddoc'];
- $this->report['top_ten_user_poidprev'] = $top['top_ten_poidprev'];
+ return $tmp;
}
/**
- * get avtivity by hour
+ * @desc Remplis les resultats bruts pour valeures passees en param
+ * @param $sbasid
+ * @param $sbas_collection, les collection sous forme de string
+ * séparés par une virgule
+ * @param