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 (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') . '

', - 'titre' => _('publications::votre rss personnel') - ); + 'titre' => _('publications::votre rss personnel') + ); - $Serializer = $app['Core']['Serializer']; + $Serializer = $app['Core']['Serializer']; - return new Response( - $Serializer->serialize($output, 'json') - , 200 - , array('Content-Type' => 'application/json') - ); + return new Response( + $Serializer->serialize($output, 'json') + , 200 + , array('Content-Type' => 'application/json') + ); }); - $controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) - { - $renew = ($request->get('renew') === 'true'); - $user = $app["Core"]->getAuthenticatedUser(); - $feed = \Feed_Adapter::load_with_user($appbox, $user, $id); - $registry = $appbox->get_registry(); + $controllers->get('/subscribe/{id}/', function(Application $app, Request $request, $id) use ($appbox, $twig) { + $renew = ($request->get('renew') === 'true'); + $user = $app["Core"]->getAuthenticatedUser(); + $feed = \Feed_Adapter::load_with_user($appbox, $user, $id); + $registry = $appbox->get_registry(); - $output = array( - 'texte' => '

' . _('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') . '

', - 'titre' => _('publications::votre rss personnel') - ); + 'titre' => _('publications::votre rss personnel') + ); - $Serializer = $app['Core']['Serializer']; + $Serializer = $app['Core']['Serializer']; - return new Response( - $Serializer->serialize($output, 'json') - , 200 - , array('Content-Type' => 'application/json') - ); + return new Response( + $Serializer->serialize($output, 'json') + , 200 + , array('Content-Type' => 'application/json') + ); })->assert('id', '\d+'); - return $controllers; - } - + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Language.php b/lib/Alchemy/Phrasea/Controller/Prod/Language.php index 3fe97e5ea4..5c76300678 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Language.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Language.php @@ -29,85 +29,83 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper; class Language implements ControllerProviderInterface { - public function connect(Application $app) - { - $controller = new ControllerCollection(); + public function connect(Application $app) + { + $controller = new ControllerCollection(); - $controller->get("/", function(Application $app) - { - $registry = $app["Core"]->getRegistry(); + $controller->get("/", function(Application $app) { + $registry = $app["Core"]->getRegistry(); - $out = array(); - $out['thesaurusBasesChanged'] = _('prod::recherche: Attention : la liste des bases selectionnees pour la recherche a ete changee.'); - $out['confirmDel'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?'); - $out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique'); - $out['serverName'] = $registry->get('GV_ServerName'); - $out['serverTimeout'] = _('phraseanet::erreur: La connection au serveur Phraseanet semble etre indisponible'); - $out['serverDisconnected'] = _('phraseanet::erreur: Votre session est fermee, veuillez vous re-authentifier'); - $out['hideMessage'] = _('phraseanet::Ne plus afficher ce message'); - $out['confirmGroup'] = _('Supprimer egalement les documents rattaches a ces regroupements'); - $out['confirmDelete'] = _('reponses:: Ces enregistrements vont etre definitivement supprimes et ne pourront etre recuperes. Etes vous sur ?'); - $out['cancel'] = _('boutton::annuler'); - $out['deleteTitle'] = _('boutton::supprimer'); - $out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\''); - $out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?'); - $out['loading'] = _('phraseanet::chargement'); - $out['valider'] = _('boutton::valider'); - $out['annuler'] = _('boutton::annuler'); - $out['create'] = _('boutton::creer'); - $out['rechercher'] = _('boutton::rechercher'); - $out['renewRss'] = _('boutton::renouveller'); - $out['candeletesome'] = _('Vous n\'avez pas les droits pour supprimer certains documents'); - $out['candeletedocuments'] = _('Vous n\'avez pas les droits pour supprimer ces documents'); - $out['needTitle'] = _('Vous devez donner un titre'); - $out['newPreset'] = _('Nouveau modele'); - $out['fermer'] = _('boutton::fermer'); - $out['feed_require_fields'] = _('Vous n\'avez pas rempli tous les champ requis'); - $out['feed_require_feed'] = _('Vous n\'avez pas selectionne de fil de publication'); - $out['removeTitle'] = _('panier::Supression d\'un element d\'un reportage'); - $out['confirmRemoveReg'] = _('panier::Attention, vous etes sur le point de supprimer un element du reportage. Merci de confirmer votre action.'); - $out['advsearch_title'] = _('phraseanet::recherche avancee'); - $out['bask_rename'] = _('panier:: renommer le panier'); - $out['reg_wrong_sbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); - $out['error'] = _('phraseanet:: Erreur'); - $out['warningDenyCgus'] = _('cgus :: Attention, si vous refuser les CGUs de cette base, vous n\'y aures plus acces'); - $out['cgusRelog'] = _('cgus :: Vous devez vous reauthentifier pour que vos parametres soient pris en compte.'); - $out['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes'); - $out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes'); - $out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant'); - $out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant'); - $out['cantDeletePublicOne'] = _('panier:: vous ne pouvez pas supprimer un panier public'); - $out['wrongsbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); - $out['max_record_selected'] = _('Vous ne pouvez pas selectionner plus de 800 enregistrements'); - $out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez'); - $out['error_test_publi'] = _('Erreur : soit les parametres sont incorrects, soit le serveur distant ne repond pas'); - $out['test_publi_ok'] = _('Les parametres sont corrects, le serveur distant est operationnel'); - $out['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, verifiez vos parametres'); - $out['error_not_published'] = _('Aucune publication effectuee, verifiez vos parametres'); - $out['warning_delete_publi'] = _('Attention, en supprimant ce preregalge, vous ne pourrez plus modifier ou supprimer de publications prealablement effectues avec celui-ci'); - $out['some_required_fields'] = _('edit::certains documents possedent des champs requis non remplis. Merci de les remplir pour valider votre editing'); - $out['nodocselected'] = _('Aucun document selectionne'); - $out['sureToRemoveList'] = _('Are you sure you want to delete this list ?'); - $out['newListName'] = _('New list name ?'); - $out['listNameCannotBeEmpty'] = _('List name can not be empty'); - $out['FeedBackName'] = _('Name'); - $out['FeedBackMessage'] = _('Message'); - $out['FeedBackDuration'] = _('Time for feedback (days)'); - $out['send'] = _('Send'); - $out['Recept'] = _('Accuse de reception'); - $out['nFieldsChanged'] = _('%d fields have been updated'); - $out['FeedBackNoUsersSelected'] = _('No users selected'); + $out = array(); + $out['thesaurusBasesChanged'] = _('prod::recherche: Attention : la liste des bases selectionnees pour la recherche a ete changee.'); + $out['confirmDel'] = _('paniers::Vous etes sur le point de supprimer ce panier. Cette action est irreversible. Souhaitez-vous continuer ?'); + $out['serverError'] = _('phraseanet::erreur: Une erreur est survenue, si ce probleme persiste, contactez le support technique'); + $out['serverName'] = $registry->get('GV_ServerName'); + $out['serverTimeout'] = _('phraseanet::erreur: La connection au serveur Phraseanet semble etre indisponible'); + $out['serverDisconnected'] = _('phraseanet::erreur: Votre session est fermee, veuillez vous re-authentifier'); + $out['hideMessage'] = _('phraseanet::Ne plus afficher ce message'); + $out['confirmGroup'] = _('Supprimer egalement les documents rattaches a ces regroupements'); + $out['confirmDelete'] = _('reponses:: Ces enregistrements vont etre definitivement supprimes et ne pourront etre recuperes. Etes vous sur ?'); + $out['cancel'] = _('boutton::annuler'); + $out['deleteTitle'] = _('boutton::supprimer'); + $out['edit_hetero'] = _('prod::editing valeurs heterogenes, choisir \'remplacer\', \'ajouter\' ou \'annuler\''); + $out['confirm_abandon'] = _('prod::editing::annulation: abandonner les modification ?'); + $out['loading'] = _('phraseanet::chargement'); + $out['valider'] = _('boutton::valider'); + $out['annuler'] = _('boutton::annuler'); + $out['create'] = _('boutton::creer'); + $out['rechercher'] = _('boutton::rechercher'); + $out['renewRss'] = _('boutton::renouveller'); + $out['candeletesome'] = _('Vous n\'avez pas les droits pour supprimer certains documents'); + $out['candeletedocuments'] = _('Vous n\'avez pas les droits pour supprimer ces documents'); + $out['needTitle'] = _('Vous devez donner un titre'); + $out['newPreset'] = _('Nouveau modele'); + $out['fermer'] = _('boutton::fermer'); + $out['feed_require_fields'] = _('Vous n\'avez pas rempli tous les champ requis'); + $out['feed_require_feed'] = _('Vous n\'avez pas selectionne de fil de publication'); + $out['removeTitle'] = _('panier::Supression d\'un element d\'un reportage'); + $out['confirmRemoveReg'] = _('panier::Attention, vous etes sur le point de supprimer un element du reportage. Merci de confirmer votre action.'); + $out['advsearch_title'] = _('phraseanet::recherche avancee'); + $out['bask_rename'] = _('panier:: renommer le panier'); + $out['reg_wrong_sbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); + $out['error'] = _('phraseanet:: Erreur'); + $out['warningDenyCgus'] = _('cgus :: Attention, si vous refuser les CGUs de cette base, vous n\'y aures plus acces'); + $out['cgusRelog'] = _('cgus :: Vous devez vous reauthentifier pour que vos parametres soient pris en compte.'); + $out['editDelMulti'] = _('edit:: Supprimer %s du champ dans les records selectionnes'); + $out['editAddMulti'] = _('edit:: Ajouter %s au champ courrant pour les records selectionnes'); + $out['editDelSimple'] = _('edit:: Supprimer %s du champ courrant'); + $out['editAddSimple'] = _('edit:: Ajouter %s au champ courrant'); + $out['cantDeletePublicOne'] = _('panier:: vous ne pouvez pas supprimer un panier public'); + $out['wrongsbas'] = _('panier:: Un reportage ne peux recevoir que des elements provenants de la base ou il est enregistre'); + $out['max_record_selected'] = _('Vous ne pouvez pas selectionner plus de 800 enregistrements'); + $out['confirmRedirectAuth'] = _('invite:: Redirection vers la zone d\'authentification, cliquez sur OK pour continuer ou annulez'); + $out['error_test_publi'] = _('Erreur : soit les parametres sont incorrects, soit le serveur distant ne repond pas'); + $out['test_publi_ok'] = _('Les parametres sont corrects, le serveur distant est operationnel'); + $out['some_not_published'] = _('Certaines publications n\'ont pu etre effectuees, verifiez vos parametres'); + $out['error_not_published'] = _('Aucune publication effectuee, verifiez vos parametres'); + $out['warning_delete_publi'] = _('Attention, en supprimant ce preregalge, vous ne pourrez plus modifier ou supprimer de publications prealablement effectues avec celui-ci'); + $out['some_required_fields'] = _('edit::certains documents possedent des champs requis non remplis. Merci de les remplir pour valider votre editing'); + $out['nodocselected'] = _('Aucun document selectionne'); + $out['sureToRemoveList'] = _('Are you sure you want to delete this list ?'); + $out['newListName'] = _('New list name ?'); + $out['listNameCannotBeEmpty'] = _('List name can not be empty'); + $out['FeedBackName'] = _('Name'); + $out['FeedBackMessage'] = _('Message'); + $out['FeedBackDuration'] = _('Time for feedback (days)'); + $out['send'] = _('Send'); + $out['Recept'] = _('Accuse de reception'); + $out['nFieldsChanged'] = _('%d fields have been updated'); + $out['FeedBackNoUsersSelected'] = _('No users selected'); - $Serializer = $app['Core']['Serializer']; + $Serializer = $app['Core']['Serializer']; - return new Response( - $Serializer->serialize($out, 'json') - , 200 - , array('Content-Type' => 'application/json') - ); + return new Response( + $Serializer->serialize($out, 'json') + , 200 + , array('Content-Type' => 'application/json') + ); }); - return $controller; - } - + return $controller; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/MoveCollection.php b/lib/Alchemy/Phrasea/Controller/Prod/MoveCollection.php index 0a057eac5c..8126f077b9 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/MoveCollection.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/MoveCollection.php @@ -27,39 +27,36 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper; class MoveCollection implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->post('/', function(Application $app, Request $request) - { - $request = $app['request']; - $move = new RecordHelper\MoveCollection($app['Core'], $app['request']); - $move->propose(); + $controllers->post('/', function(Application $app, Request $request) { + $request = $app['request']; + $move = new RecordHelper\MoveCollection($app['Core'], $app['request']); + $move->propose(); - $template = 'prod/actions/collection_default.twig'; - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + $template = 'prod/actions/collection_default.twig'; + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return $twig->render($template, array('action' => $move, 'message' => '')); + return $twig->render($template, array('action' => $move, 'message' => '')); } - ); + ); - $controllers->post('/apply/', function(Application $app) - { - $request = $app['request']; - $move = new RecordHelper\MoveCollection($app['Core'], $app['request']); - $move->execute($request); - $template = 'prod/actions/collection_submit.twig'; + $controllers->post('/apply/', function(Application $app) { + $request = $app['request']; + $move = new RecordHelper\MoveCollection($app['Core'], $app['request']); + $move->execute($request); + $template = 'prod/actions/collection_submit.twig'; - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return $twig->render($template, array('action' => $move, 'message' => '')); + return $twig->render($template, array('action' => $move, 'message' => '')); }); - return $controllers; - } - + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/MustacheLoader.php b/lib/Alchemy/Phrasea/Controller/Prod/MustacheLoader.php index 184cfa20da..aab8eaabd5 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/MustacheLoader.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/MustacheLoader.php @@ -25,30 +25,26 @@ use Symfony\Component\HttpFoundation\Request, class MustacheLoader implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->get('/', function(Application $app, Request $request) - { - $template_name = $request->get('template'); + $controllers->get('/', function(Application $app, Request $request) { + $template_name = $request->get('template'); - if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) - { - throw new \Exception_BadRequest('Wrong template name : ' . $template_name); - } + if ( ! preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) { + throw new \Exception_BadRequest('Wrong template name : ' . $template_name); + } - $template_path = realpath(__DIR__ . '/../../../../../templates/web/Mustache/Prod/' . $template_name . '.Mustache.html'); + $template_path = realpath(__DIR__ . '/../../../../../templates/web/Mustache/Prod/' . $template_name . '.Mustache.html'); - if (!file_exists($template_path)) - { - throw new \Exception_NotFound('Template does not exists : ' . $template_path); - } + if ( ! file_exists($template_path)) { + throw new \Exception_NotFound('Template does not exists : ' . $template_path); + } - return new \Symfony\Component\HttpFoundation\Response(file_get_contents($template_path)); + return new \Symfony\Component\HttpFoundation\Response(file_get_contents($template_path)); }); - return $controllers; - } - + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Printer.php b/lib/Alchemy/Phrasea/Controller/Prod/Printer.php index 96c4199ee5..b19ed5cb24 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Printer.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Printer.php @@ -27,47 +27,43 @@ use Symfony\Component\HttpFoundation\Response; class Printer implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->post('/', function(Application $app) - { - $printer = new RecordHelper\Printer($app['Core'], $app['request']); + $controllers->post('/', function(Application $app) { + $printer = new RecordHelper\Printer($app['Core'], $app['request']); - $template = 'prod/actions/printer_default.html.twig'; + $template = 'prod/actions/printer_default.html.twig'; - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return $twig->render($template, array('printer' => $printer, 'message' => '')); + return $twig->render($template, array('printer' => $printer, 'message' => '')); } - ); + ); - $controllers->post('/print.pdf', function(Application $app) - { - $printer = new RecordHelper\Printer($app['Core'], $app['request']); + $controllers->post('/print.pdf', function(Application $app) { + $printer = new RecordHelper\Printer($app['Core'], $app['request']); - $request = $app['request']; + $request = $app['request']; - $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core'])); + $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core'])); - $layout = $request->get('lay'); + $layout = $request->get('lay'); - foreach ($printer->get_elements() as $record) - { - $session->get_logger($record->get_databox()) + foreach ($printer->get_elements() as $record) { + $session->get_logger($record->get_databox()) ->log($record, \Session_Logger::EVENT_PRINT, $layout, ''); - } - $PDF = new PDFExport($printer->get_elements(), $layout); + } + $PDF = new PDFExport($printer->get_elements(), $layout); - return new Response($PDF->render(), 200, array('Content-Type' => 'application/pdf')); + return new Response($PDF->render(), 200, array('Content-Type' => 'application/pdf')); } - ); - - return $controllers; - } + ); + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Push.php b/lib/Alchemy/Phrasea/Controller/Prod/Push.php index fc16a2b097..23dc569ed3 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Push.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Push.php @@ -28,787 +28,700 @@ use Symfony\Component\HttpFoundation\Response, class Push implements ControllerProviderInterface { - protected function getUserFormatter() - { - return function(\User_Adapter $user) - { - return array( - 'type' => 'USER' - , 'usr_id' => $user->get_id() - , 'firstname' => $user->get_firstname() - , 'lastname' => $user->get_lastname() - , 'email' => $user->get_email() - , 'display_name' => $user->get_display_name() - ); - }; - } - - protected function getListFormatter() - { - $userFormatter = $this->getUserFormatter(); - - return function(\Entities\UsrList $List) use ($userFormatter) - { - $entries = array(); - - foreach ($List->getEntries() as $entry) - { - /* @var $entry \Entities\UsrListEntry */ - $entries[] = array( - 'Id' => $entry->getId(), - 'User' => $userFormatter($entry->getUser()) + protected function getUserFormatter() + { + return function(\User_Adapter $user) { + return array( + 'type' => 'USER' + , 'usr_id' => $user->get_id() + , 'firstname' => $user->get_firstname() + , 'lastname' => $user->get_lastname() + , 'email' => $user->get_email() + , 'display_name' => $user->get_display_name() ); - } - - return array( - 'type' => 'LIST' - , 'list_id' => $List->getId() - , 'name' => $List->getName() - , 'length' => count($entries) - , 'entries' => $entries - ); }; - } + } - protected function getUsersInSelectionExtractor() - { - return function(array $selection) - { - $Users = new \Doctrine\Common\Collections\ArrayCollection(); + protected function getListFormatter() + { + $userFormatter = $this->getUserFormatter(); - foreach ($selection as $record) - { - /* @var $record record_adapter */ - foreach ($record->get_caption()->get_fields() as $caption_field) - { - foreach ($caption_field->get_values() as $value) - { - if (!$value->getVocabularyType()) - continue; + return function(\Entities\UsrList $List) use ($userFormatter) { + $entries = array(); - if ($value->getVocabularyType()->getType() !== 'User') - continue; - - $user = $value->getRessource(); - - $Users->set($user->get_id(), $user); - } + foreach ($List->getEntries() as $entry) { + /* @var $entry \Entities\UsrListEntry */ + $entries[] = array( + 'Id' => $entry->getId(), + 'User' => $userFormatter($entry->getUser()) + ); } - } - return $Users; + return array( + 'type' => 'LIST' + , 'list_id' => $List->getId() + , 'name' => $List->getName() + , 'length' => count($entries) + , 'entries' => $entries + ); }; - } + } - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + protected function getUsersInSelectionExtractor() + { + return function(array $selection) { + $Users = new \Doctrine\Common\Collections\ArrayCollection(); - $userFormatter = $this->getUserFormatter(); + foreach ($selection as $record) { + /* @var $record record_adapter */ + foreach ($record->get_caption()->get_fields() as $caption_field) { + foreach ($caption_field->get_values() as $value) { + if ( ! $value->getVocabularyType()) + continue; - $listFormatter = $this->getListFormatter(); + if ($value->getVocabularyType()->getType() !== 'User') + continue; - $userSelection = $this->getUsersInSelectionExtractor(); + $user = $value->getRessource(); - $controllers->post('/sendform/', function(Application $app) use ($userSelection) - { - $push = new RecordHelper\Push($app['Core'], $app['request']); + $Users->set($user->get_id(), $user); + } + } + } - $em = $app['Core']->getEntityManager(); - $repository = $em->getRepository('\Entities\UsrList'); + return $Users; + }; + } - $RecommendedUsers = $userSelection($push->get_elements()); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $params = array( - 'push' => $push, - 'message' => '', - 'lists' => $repository->findUserLists($app['Core']->getAuthenticatedUser()), - 'context' => 'Push', - 'RecommendedUsers' => $RecommendedUsers - ); + $userFormatter = $this->getUserFormatter(); - $template = 'prod/actions/Push.html.twig'; + $listFormatter = $this->getListFormatter(); - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + $userSelection = $this->getUsersInSelectionExtractor(); - return new Response($twig->render($template, $params)); + $controllers->post('/sendform/', function(Application $app) use ($userSelection) { + $push = new RecordHelper\Push($app['Core'], $app['request']); + + $em = $app['Core']->getEntityManager(); + $repository = $em->getRepository('\Entities\UsrList'); + + $RecommendedUsers = $userSelection($push->get_elements()); + + $params = array( + 'push' => $push, + 'message' => '', + 'lists' => $repository->findUserLists($app['Core']->getAuthenticatedUser()), + 'context' => 'Push', + 'RecommendedUsers' => $RecommendedUsers + ); + + $template = 'prod/actions/Push.html.twig'; + + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); + + return new Response($twig->render($template, $params)); } - ); + ); - $controllers->post('/validateform/', function(Application $app) use ($userSelection) - { - $push = new RecordHelper\Push($app['Core'], $app['request']); + $controllers->post('/validateform/', function(Application $app) use ($userSelection) { + $push = new RecordHelper\Push($app['Core'], $app['request']); - $em = $app['Core']->getEntityManager(); - $repository = $em->getRepository('\Entities\UsrList'); + $em = $app['Core']->getEntityManager(); + $repository = $em->getRepository('\Entities\UsrList'); - $RecommendedUsers = $userSelection($push->get_elements()); + $RecommendedUsers = $userSelection($push->get_elements()); - $params = array( - 'push' => $push, - 'message' => '', - 'lists' => $repository->findUserLists($app['Core']->getAuthenticatedUser()), - 'context' => 'Feedback', - 'RecommendedUsers' => $RecommendedUsers - ); + $params = array( + 'push' => $push, + 'message' => '', + 'lists' => $repository->findUserLists($app['Core']->getAuthenticatedUser()), + 'context' => 'Feedback', + 'RecommendedUsers' => $RecommendedUsers + ); - $template = 'prod/actions/Push.html.twig'; + $template = 'prod/actions/Push.html.twig'; - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return new Response($twig->render($template, $params)); + return new Response($twig->render($template, $params)); } - ); + ); - $controllers->post('/send/', function(Application $app) - { - $request = $app['request']; + $controllers->post('/send/', function(Application $app) { + $request = $app['request']; - $ret = array( - 'success' => false, - 'message' => _('Unable to send the documents') - ); + $ret = array( + 'success' => false, + 'message' => _('Unable to send the documents') + ); + + try { + $em = $app['Core']->getEntityManager(); + + $registry = $app['Core']->getRegistry(); + + $pusher = new RecordHelper\Push($app['Core'], $app['request']); + + $user = $app['Core']->getAuthenticatedUser(); + + $appbox = \appbox::get_instance($app['Core']); + + $push_name = $request->get('name'); + + if (trim($push_name) === '') { + $push_name = sprintf(_('Push from %s'), $user->get_display_name()); + } + + $push_description = $request->get('push_description'); + + $receivers = $request->get('participants'); + + if ( ! is_array($receivers) || count($receivers) === 0) { + throw new ControllerException(_('No receivers specified')); + } + + if ( ! is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) { + throw new ControllerException(_('No elements to push')); + } + + + $events_manager = \eventsmanager_broker::getInstance(\appbox::get_instance($app['Core']), $app['Core']); + + foreach ($receivers as $receiver) { + try { + $user_receiver = \User_Adapter::getInstance($receiver['usr_id'], $appbox); + } catch (\Exception $e) { + throw new ControllerException(sprintf(_('Unknown user %d'), $receiver['usr_id'])); + } + + $Basket = new \Entities\Basket(); + $Basket->setName($push_name); + $Basket->setDescription($push_description); + $Basket->setOwner($user_receiver); + $Basket->setPusher($user); + $Basket->setIsRead(false); + + $em->persist($Basket); + + foreach ($pusher->get_elements() as $element) { + $BasketElement = new \Entities\BasketElement(); + $BasketElement->setRecord($element); + $BasketElement->setBasket($Basket); + + $em->persist($BasketElement); + + $Basket->addBasketElement($BasketElement); + + if ($receiver['HD']) { + $user_receiver->ACL()->grant_hd_on( + $BasketElement->getRecord() + , $user + , \ACL::GRANT_ACTION_PUSH + ); + } else { + $user_receiver->ACL()->grant_preview_on( + $BasketElement->getRecord() + , $user + , \ACL::GRANT_ACTION_PUSH + ); + } + } + + $em->flush(); + + $url = $registry->get('GV_ServerName') + . 'lightbox/index.php?LOG=' + . \random::getUrlToken(\random::TYPE_VIEW, $user_receiver->get_id(), null, $Basket->getId()); + + $params = array( + 'from' => $user->get_id() + , 'from_email' => $user->get_email() + , 'to' => $user_receiver->get_id() + , 'to_email' => $user_receiver->get_email() + , 'to_name' => $user_receiver->get_display_name() + , 'url' => $url + , 'accuse' => ! ! $request->get('recept', false) + , 'message' => $request->get('message') + , 'ssel_id' => $Basket->getId() + ); + + $events_manager->trigger('__PUSH_DATAS__', $params); + } + + $em->flush(); + + $message = sprintf( + _('%1$d records have been sent to %2$d users') + , count($pusher->get_elements()) + , count($receivers) + ); + + $ret = array( + 'success' => true, + 'message' => $message + ); + } catch (ControllerException $e) { + $ret['message'] = $e->getMessage() . $e->getFile() . $e->getLine(); + } + + $Json = $app['Core']['Serializer']->serialize($ret, 'json'); + + return new Response($Json, 200, array('Content-Type' => 'application/json')); + } + ); + + $controllers->post('/validate/', function(Application $app) { + $request = $app['request']; + + $ret = array( + 'success' => false, + 'message' => _('Unable to send the documents') + ); - try - { $em = $app['Core']->getEntityManager(); $registry = $app['Core']->getRegistry(); - $pusher = new RecordHelper\Push($app['Core'], $app['request']); + /* @var $em \Doctrine\ORM\EntityManager */ + $em->beginTransaction(); - $user = $app['Core']->getAuthenticatedUser(); + try { + $pusher = new RecordHelper\Push($app['Core'], $app['request']); + $user = $app['Core']->getAuthenticatedUser(); - $appbox = \appbox::get_instance($app['Core']); + $events_manager = \eventsmanager_broker::getInstance(\appbox::get_instance($app['Core']), $app['Core']); - $push_name = $request->get('name'); + $repository = $em->getRepository('\Entities\Basket'); - if (trim($push_name) === '') - { - $push_name = sprintf(_('Push from %s'), $user->get_display_name()); - } + $validation_name = $request->get('name'); - $push_description = $request->get('push_description'); - - $receivers = $request->get('participants'); - - if (!is_array($receivers) || count($receivers) === 0) - { - throw new ControllerException(_('No receivers specified')); - } - - if (!is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) - { - throw new ControllerException(_('No elements to push')); - } - - - $events_manager = \eventsmanager_broker::getInstance(\appbox::get_instance($app['Core']), $app['Core']); - - foreach ($receivers as $receiver) - { - try - { - $user_receiver = \User_Adapter::getInstance($receiver['usr_id'], $appbox); - } - catch (\Exception $e) - { - throw new ControllerException(sprintf(_('Unknown user %d'), $receiver['usr_id'])); - } - - $Basket = new \Entities\Basket(); - $Basket->setName($push_name); - $Basket->setDescription($push_description); - $Basket->setOwner($user_receiver); - $Basket->setPusher($user); - $Basket->setIsRead(false); - - $em->persist($Basket); - - foreach ($pusher->get_elements() as $element) - { - $BasketElement = new \Entities\BasketElement(); - $BasketElement->setRecord($element); - $BasketElement->setBasket($Basket); - - $em->persist($BasketElement); - - $Basket->addBasketElement($BasketElement); - - if ($receiver['HD']) - { - $user_receiver->ACL()->grant_hd_on( - $BasketElement->getRecord() - , $user - , \ACL::GRANT_ACTION_PUSH - ); - } - else - { - $user_receiver->ACL()->grant_preview_on( - $BasketElement->getRecord() - , $user - , \ACL::GRANT_ACTION_PUSH - ); - } - } - - $em->flush(); - - $url = $registry->get('GV_ServerName') - . 'lightbox/index.php?LOG=' - . \random::getUrlToken(\random::TYPE_VIEW, $user_receiver->get_id(), null, $Basket->getId()); - - $params = array( - 'from' => $user->get_id() - , 'from_email' => $user->get_email() - , 'to' => $user_receiver->get_id() - , 'to_email' => $user_receiver->get_email() - , 'to_name' => $user_receiver->get_display_name() - , 'url' => $url - , 'accuse' => !!$request->get('recept', false) - , 'message' => $request->get('message') - , 'ssel_id' => $Basket->getId() - ); - - $events_manager->trigger('__PUSH_DATAS__', $params); - } - - $em->flush(); - - $message = sprintf( - _('%1$d records have been sent to %2$d users') - , count($pusher->get_elements()) - , count($receivers) - ); - - $ret = array( - 'success' => true, - 'message' => $message - ); - } - catch (ControllerException $e) - { - $ret['message'] = $e->getMessage() . $e->getFile() . $e->getLine(); - } - - $Json = $app['Core']['Serializer']->serialize($ret, 'json'); - - return new Response($Json, 200, array('Content-Type' => 'application/json')); - } - ); - - $controllers->post('/validate/', function(Application $app) - { - $request = $app['request']; - - $ret = array( - 'success' => false, - 'message' => _('Unable to send the documents') - ); - - $em = $app['Core']->getEntityManager(); - - $registry = $app['Core']->getRegistry(); - - /* @var $em \Doctrine\ORM\EntityManager */ - $em->beginTransaction(); - - try - { - $pusher = new RecordHelper\Push($app['Core'], $app['request']); - $user = $app['Core']->getAuthenticatedUser(); - - $events_manager = \eventsmanager_broker::getInstance(\appbox::get_instance($app['Core']), $app['Core']); - - $repository = $em->getRepository('\Entities\Basket'); - - $validation_name = $request->get('name'); - - if (trim($validation_name) === '') - { - $validation_name = sprintf(_('Validation from %s'), $user->get_display_name()); - } - - $validation_description = $request->get('validation_description'); - - $participants = $request->get('participants'); - - if (!is_array($participants) || count($participants) === 0) - { - throw new ControllerException(_('No participants specified')); - } - - if (!is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) - { - throw new ControllerException(_('No elements to validate')); - } - - if ($pusher->is_basket()) - { - $Basket = $pusher->get_original_basket(); - } - else - { - $Basket = new \Entities\Basket(); - $Basket->setName($validation_name); - $Basket->setDescription($validation_description); - $Basket->setOwner($user); - $Basket->setIsRead(false); - - $em->persist($Basket); - - foreach ($pusher->get_elements() as $element) - { - $BasketElement = new \Entities\BasketElement(); - $BasketElement->setRecord($element); - $BasketElement->setBasket($Basket); - - $em->persist($BasketElement); - - $Basket->addBasketElement($BasketElement); - } - $em->flush(); - } - - $em->refresh($Basket); - - if (!$Basket->getValidation()) - { - $Validation = new \Entities\ValidationSession(); - $Validation->setInitiator($app['Core']->getAuthenticatedUser()); - $Validation->setBasket($Basket); - - $duration = (int) $request->get('duration'); - - if ($duration > 0) - { - $date = new \DateTime('+' . $duration . ' day' . ($duration > 1 ? 's' : '')); - $Validation->setExpires($date); - } - - $Basket->setValidation($Validation); - $em->persist($Validation); - } - else - { - $Validation = $Basket->getValidation(); - } - - - $appbox = \appbox::get_instance($app['Core']); - - $found = false; - foreach ($participants as $key => $participant) - { - if ($participant['usr_id'] == $user->get_id()) - { - $found = true; - break; - } - } - - if (!$found) - { - $participants[$user->get_id()] = array( - 'see_others' => 1, - 'usr_id' => $user->get_id(), - 'agree' => 0, - 'HD' => 0 - ); - } - - foreach ($participants as $key => $participant) - { - foreach (array('see_others', 'usr_id', 'agree', 'HD') as $mandatoryparam) - { - if (!array_key_exists($mandatoryparam, $participant)) - throw new ControllerException(sprintf(_('Missing mandatory parameter %s'), $mandatoryparam)); - } - - try - { - $participant_user = \User_Adapter::getInstance($participant['usr_id'], $appbox); - } - catch (\Exception $e) - { - throw new ControllerException(sprintf(_('Unknown user %d'), $receiver['usr_id'])); - } - - try - { - $Participant = $Validation->getParticipant($participant_user); - continue; - } - catch (\Exception_NotFound $e) - { - - } - - $Participant = new \Entities\ValidationParticipant(); - $Participant->setUser($participant_user); - $Participant->setSession($Validation); - - $Participant->setCanAgree($participant['agree']); - $Participant->setCanSeeOthers($participant['see_others']); - - $em->persist($Participant); - - foreach ($Basket->getElements() as $BasketElement) - { - $ValidationData = new \Entities\ValidationData(); - $ValidationData->setParticipant($Participant); - $ValidationData->setBasketElement($BasketElement); - $BasketElement->addValidationData($ValidationData); - - if ($participant['HD']) - { - $participant_user->ACL()->grant_hd_on( - $BasketElement->getRecord() - , $user - , \ACL::GRANT_ACTION_VALIDATE - ); - } - else - { - $participant_user->ACL()->grant_preview_on( - $BasketElement->getRecord() - , $user - , \ACL::GRANT_ACTION_VALIDATE - ); + if (trim($validation_name) === '') { + $validation_name = sprintf(_('Validation from %s'), $user->get_display_name()); } - $em->merge($BasketElement); - $em->persist($ValidationData); + $validation_description = $request->get('validation_description'); - $Participant->addValidationData($ValidationData); - } + $participants = $request->get('participants'); - $Participant = $em->merge($Participant); + if ( ! is_array($participants) || count($participants) === 0) { + throw new ControllerException(_('No participants specified')); + } - $em->flush(); + if ( ! is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) { + throw new ControllerException(_('No elements to validate')); + } - $url = $registry->get('GV_ServerName') - . 'lightbox/index.php?LOG=' - . \random::getUrlToken(\random::TYPE_VIEW, $participant_user->get_id(), null, $Basket->getId()); + if ($pusher->is_basket()) { + $Basket = $pusher->get_original_basket(); + } else { + $Basket = new \Entities\Basket(); + $Basket->setName($validation_name); + $Basket->setDescription($validation_description); + $Basket->setOwner($user); + $Basket->setIsRead(false); - $params = array( - 'from' => $user->get_id() - , 'from_email' => $user->get_email() - , 'to' => $participant_user->get_id() - , 'to_email' => $participant_user->get_email() - , 'to_name' => $participant_user->get_display_name() - , 'url' => $url - , 'accuse' => !!$request->get('recept', false) - , 'message' => $request->get('message') - , 'ssel_id' => $Basket->getId() - ); + $em->persist($Basket); - $events_manager->trigger('__PUSH_VALIDATION__', $params); - } + foreach ($pusher->get_elements() as $element) { + $BasketElement = new \Entities\BasketElement(); + $BasketElement->setRecord($element); + $BasketElement->setBasket($Basket); - $Basket = $em->merge($Basket); - $Validation = $em->merge($Validation); + $em->persist($BasketElement); - $em->flush(); + $Basket->addBasketElement($BasketElement); + } + $em->flush(); + } - $message = sprintf( + $em->refresh($Basket); + + if ( ! $Basket->getValidation()) { + $Validation = new \Entities\ValidationSession(); + $Validation->setInitiator($app['Core']->getAuthenticatedUser()); + $Validation->setBasket($Basket); + + $duration = (int) $request->get('duration'); + + if ($duration > 0) { + $date = new \DateTime('+' . $duration . ' day' . ($duration > 1 ? 's' : '')); + $Validation->setExpires($date); + } + + $Basket->setValidation($Validation); + $em->persist($Validation); + } else { + $Validation = $Basket->getValidation(); + } + + + $appbox = \appbox::get_instance($app['Core']); + + $found = false; + foreach ($participants as $key => $participant) { + if ($participant['usr_id'] == $user->get_id()) { + $found = true; + break; + } + } + + if ( ! $found) { + $participants[$user->get_id()] = array( + 'see_others' => 1, + 'usr_id' => $user->get_id(), + 'agree' => 0, + 'HD' => 0 + ); + } + + foreach ($participants as $key => $participant) { + foreach (array('see_others', 'usr_id', 'agree', 'HD') as $mandatoryparam) { + if ( ! array_key_exists($mandatoryparam, $participant)) + throw new ControllerException(sprintf(_('Missing mandatory parameter %s'), $mandatoryparam)); + } + + try { + $participant_user = \User_Adapter::getInstance($participant['usr_id'], $appbox); + } catch (\Exception $e) { + throw new ControllerException(sprintf(_('Unknown user %d'), $receiver['usr_id'])); + } + + try { + $Participant = $Validation->getParticipant($participant_user); + continue; + } catch (\Exception_NotFound $e) { + + } + + $Participant = new \Entities\ValidationParticipant(); + $Participant->setUser($participant_user); + $Participant->setSession($Validation); + + $Participant->setCanAgree($participant['agree']); + $Participant->setCanSeeOthers($participant['see_others']); + + $em->persist($Participant); + + foreach ($Basket->getElements() as $BasketElement) { + $ValidationData = new \Entities\ValidationData(); + $ValidationData->setParticipant($Participant); + $ValidationData->setBasketElement($BasketElement); + $BasketElement->addValidationData($ValidationData); + + if ($participant['HD']) { + $participant_user->ACL()->grant_hd_on( + $BasketElement->getRecord() + , $user + , \ACL::GRANT_ACTION_VALIDATE + ); + } else { + $participant_user->ACL()->grant_preview_on( + $BasketElement->getRecord() + , $user + , \ACL::GRANT_ACTION_VALIDATE + ); + } + + $em->merge($BasketElement); + $em->persist($ValidationData); + + $Participant->addValidationData($ValidationData); + } + + $Participant = $em->merge($Participant); + + $em->flush(); + + $url = $registry->get('GV_ServerName') + . 'lightbox/index.php?LOG=' + . \random::getUrlToken(\random::TYPE_VIEW, $participant_user->get_id(), null, $Basket->getId()); + + $params = array( + 'from' => $user->get_id() + , 'from_email' => $user->get_email() + , 'to' => $participant_user->get_id() + , 'to_email' => $participant_user->get_email() + , 'to_name' => $participant_user->get_display_name() + , 'url' => $url + , 'accuse' => ! ! $request->get('recept', false) + , 'message' => $request->get('message') + , 'ssel_id' => $Basket->getId() + ); + + $events_manager->trigger('__PUSH_VALIDATION__', $params); + } + + $Basket = $em->merge($Basket); + $Validation = $em->merge($Validation); + + $em->flush(); + + $message = sprintf( _('%1$d records have been sent for validation to %2$d users') , count($pusher->get_elements()) , count($request->get('participants')) - ); + ); - $ret = array( - 'success' => true, - 'message' => $message - ); + $ret = array( + 'success' => true, + 'message' => $message + ); - $em->commit(); - } - catch (ControllerException $e) - { - $ret['message'] = $e->getMessage(); - $em->rollback(); - } - - $Json = $app['Core']['Serializer']->serialize($ret, 'json'); - - return new Response($Json, 200, array('Content-Type' => 'application/json')); - } - ); - - $controllers->get('/user/{usr_id}/', function(Application $app, $usr_id) use ($userFormatter) - { - - $datas = null; - - $request = $app['request']; - $em = $app['Core']->getEntityManager(); - $user = $app['Core']->getAuthenticatedUser(); - - $query = new \User_Query(\appbox::get_instance($app['Core'])); - - $query->on_bases_where_i_am($user->ACL(), array('canpush')); - - $query->in(array($usr_id)); - - $result = $query->include_phantoms() - ->limit(0, 1) - ->execute()->get_results(); - - if ($result) - { - foreach ($result as $user) - { - $datas = $userFormatter($user); + $em->commit(); + } catch (ControllerException $e) { + $ret['message'] = $e->getMessage(); + $em->rollback(); } - } - $Json = $app['Core']['Serializer']->serialize($datas, 'json'); + $Json = $app['Core']['Serializer']->serialize($ret, 'json'); - return new Response($Json, 200, array('Content-Type' => 'application/json')); + return new Response($Json, 200, array('Content-Type' => 'application/json')); + } + ); + + $controllers->get('/user/{usr_id}/', function(Application $app, $usr_id) use ($userFormatter) { + + $datas = null; + + $request = $app['request']; + $em = $app['Core']->getEntityManager(); + $user = $app['Core']->getAuthenticatedUser(); + + $query = new \User_Query(\appbox::get_instance($app['Core'])); + + $query->on_bases_where_i_am($user->ACL(), array('canpush')); + + $query->in(array($usr_id)); + + $result = $query->include_phantoms() + ->limit(0, 1) + ->execute()->get_results(); + + if ($result) { + foreach ($result as $user) { + $datas = $userFormatter($user); + } + } + + $Json = $app['Core']['Serializer']->serialize($datas, 'json'); + + return new Response($Json, 200, array('Content-Type' => 'application/json')); })->assert('usr_id', '\d+'); - $controllers->get('/list/{list_id}/', function(Application $app, $list_id) use ($listFormatter) - { - $datas = null; + $controllers->get('/list/{list_id}/', function(Application $app, $list_id) use ($listFormatter) { + $datas = null; - $em = $app['Core']->getEntityManager(); - $user = $app['Core']->getAuthenticatedUser(); + $em = $app['Core']->getEntityManager(); + $user = $app['Core']->getAuthenticatedUser(); - $repository = $em->getRepository('\Entities\UsrList'); + $repository = $em->getRepository('\Entities\UsrList'); - $list = $repository->findUserListByUserAndId($user, $list_id); + $list = $repository->findUserListByUserAndId($user, $list_id); - if ($list) - { - $datas = $listFormatter($list); - } + if ($list) { + $datas = $listFormatter($list); + } - $Json = $app['Core']['Serializer']->serialize($datas, 'json'); + $Json = $app['Core']['Serializer']->serialize($datas, 'json'); - return new Response($Json, 200, array('Content-Type' => 'application/json')); + return new Response($Json, 200, array('Content-Type' => 'application/json')); })->assert('list_id', '\d+'); - $controllers->post('/add-user/', function(Application $app, Request $request) use ($userFormatter) - { - $result = array('success' => false, 'message' => '', 'user' => null); + $controllers->post('/add-user/', function(Application $app, Request $request) use ($userFormatter) { + $result = array('success' => false, 'message' => '', 'user' => null); - $Serializer = $app['Core']['Serializer']; + $Serializer = $app['Core']['Serializer']; - $AdminUser = $app['Core']->getAuthenticatedUser(); + $AdminUser = $app['Core']->getAuthenticatedUser(); - try - { - /* @var $AdminUser \User_Adapter */ - if (!$AdminUser->ACL()->has_right('manageusers')) - throw new ControllerException(_('You are not allowed to add users')); + try { + /* @var $AdminUser \User_Adapter */ + if ( ! $AdminUser->ACL()->has_right('manageusers')) + throw new ControllerException(_('You are not allowed to add users')); - if (!$request->get('firstname')) - throw new ControllerException(_('First name is required')); + if ( ! $request->get('firstname')) + throw new ControllerException(_('First name is required')); - if (!$request->get('lastname')) - throw new ControllerException(_('Last name is required')); + if ( ! $request->get('lastname')) + throw new ControllerException(_('Last name is required')); - if (!$request->get('email')) - throw new ControllerException(_('Email is required')); + if ( ! $request->get('email')) + throw new ControllerException(_('Email is required')); + + if ( ! \mail::validateEmail($request->get('email'))) + throw new ControllerException(_('Email is invalid')); + } catch (ControllerException $e) { + $result['message'] = $e->getMessage(); + + return new Response($Serializer->serialize($result, 'json'), 200, array('Content-Type' => 'application/json')); + } + + $appbox = \appbox::get_instance($app['Core']); + + $user = null; + $email = $request->get('email'); + + try { + $usr_id = \User_Adapter::get_usr_id_from_email($email); + $user = \User_Adapter::getInstance($usr_id, $appbox); + + $result['message'] = _('User already exists'); + $result['success'] = true; + $result['user'] = $userFormatter($user); + } catch (\Exception $e) { + + } + + if ( ! $user instanceof \User_Adapter) { + try { + $password = \random::generatePassword(); + + $user = \User_Adapter::create($appbox, $email, $password, $email, false); + + $user->set_firstname($request->get('firstname')) + ->set_lastname($request->get('lastname')); + + if ($request->get('company')) + $user->set_company($request->get('company')); + if ($request->get('job')) + $user->set_company($request->get('job')); + if ($request->get('form_geonameid')) + $user->set_geonameid($request->get('form_geonameid')); + + $result['message'] = _('User successfully created'); + $result['success'] = true; + $result['user'] = $userFormatter($user); + } catch (\Exception $e) { + $result['message'] = _('Error while creating user'); + } + } - if (!\mail::validateEmail($request->get('email'))) - throw new ControllerException(_('Email is invalid')); - } - catch (ControllerException $e) - { - $result['message'] = $e->getMessage(); return new Response($Serializer->serialize($result, 'json'), 200, array('Content-Type' => 'application/json')); - } - - $appbox = \appbox::get_instance($app['Core']); - - $user = null; - $email = $request->get('email'); - - try - { - $usr_id = \User_Adapter::get_usr_id_from_email($email); - $user = \User_Adapter::getInstance($usr_id, $appbox); - - $result['message'] = _('User already exists'); - $result['success'] = true; - $result['user'] = $userFormatter($user); - } - catch (\Exception $e) - { - - } - - if (!$user instanceof \User_Adapter) - { - try - { - $password = \random::generatePassword(); - - $user = \User_Adapter::create($appbox, $email, $password, $email, false); - - $user->set_firstname($request->get('firstname')) - ->set_lastname($request->get('lastname')); - - if ($request->get('company')) - $user->set_company($request->get('company')); - if ($request->get('job')) - $user->set_company($request->get('job')); - if ($request->get('form_geonameid')) - $user->set_geonameid($request->get('form_geonameid')); - - $result['message'] = _('User successfully created'); - $result['success'] = true; - $result['user'] = $userFormatter($user); - } - catch (\Exception $e) - { - $result['message'] = _('Error while creating user'); - } - } - - - return new Response($Serializer->serialize($result, 'json'), 200, array('Content-Type' => 'application/json')); }); - $controllers->get('/add-user/', function(Application $app, Request $request) - { - $params = array('callback' => $request->get('callback')); + $controllers->get('/add-user/', function(Application $app, Request $request) { + $params = array('callback' => $request->get('callback')); - return new Response($app['Core']['Twig']->render('prod/User/Add.html.twig', $params)); + return new Response($app['Core']['Twig']->render('prod/User/Add.html.twig', $params)); }); - $controllers->get('/search-user/', function(Application $app) use ($userFormatter, $listFormatter) - { - $request = $app['request']; - $em = $app['Core']->getEntityManager(); - $user = $app['Core']->getAuthenticatedUser(); + $controllers->get('/search-user/', function(Application $app) use ($userFormatter, $listFormatter) { + $request = $app['request']; + $em = $app['Core']->getEntityManager(); + $user = $app['Core']->getAuthenticatedUser(); - $query = new \User_Query(\appbox::get_instance($app['Core'])); + $query = new \User_Query(\appbox::get_instance($app['Core'])); - $query->on_bases_where_i_am($user->ACL(), array('canpush')); + $query->on_bases_where_i_am($user->ACL(), array('canpush')); - $query->like(\User_Query::LIKE_FIRSTNAME, $request->get('query')) - ->like(\User_Query::LIKE_LASTNAME, $request->get('query')) - ->like(\User_Query::LIKE_LOGIN, $request->get('query')) - ->like_match(\User_Query::LIKE_MATCH_OR); + $query->like(\User_Query::LIKE_FIRSTNAME, $request->get('query')) + ->like(\User_Query::LIKE_LASTNAME, $request->get('query')) + ->like(\User_Query::LIKE_LOGIN, $request->get('query')) + ->like_match(\User_Query::LIKE_MATCH_OR); - $result = $query->include_phantoms() - ->limit(0, 50) - ->execute()->get_results(); + $result = $query->include_phantoms() + ->limit(0, 50) + ->execute()->get_results(); - $repository = $em->getRepository('\Entities\UsrList'); + $repository = $em->getRepository('\Entities\UsrList'); - $lists = $repository->findUserListLike($user, $request->get('query')); + $lists = $repository->findUserListLike($user, $request->get('query')); - $datas = array(); + $datas = array(); - if ($lists) - { - foreach ($lists as $list) - { - $datas[] = $listFormatter($list); + if ($lists) { + foreach ($lists as $list) { + $datas[] = $listFormatter($list); + } } - } - if ($result) - { - foreach ($result as $user) - { - $datas[] = $userFormatter($user); + if ($result) { + foreach ($result as $user) { + $datas[] = $userFormatter($user); + } } - } - $Json = $app['Core']['Serializer']->serialize($datas, 'json'); + $Json = $app['Core']['Serializer']->serialize($datas, 'json'); - return new Response($Json, 200, array('Content-Type' => 'application/json')); + return new Response($Json, 200, array('Content-Type' => 'application/json')); } - ); + ); - $controllers->match('/edit-list/{list_id}/', function(Application $app, Request $request, $list_id) - { + $controllers->match('/edit-list/{list_id}/', function(Application $app, Request $request, $list_id) { - $user = $app['Core']->getAuthenticatedUser(); - $em = $app['Core']->getEntityManager(); + $user = $app['Core']->getAuthenticatedUser(); + $em = $app['Core']->getEntityManager(); - $repository = $em->getRepository('\Entities\UsrList'); + $repository = $em->getRepository('\Entities\UsrList'); - $list = $repository->findUserListByUserAndId($user, $list_id); + $list = $repository->findUserListByUserAndId($user, $list_id); - $query = new \User_Query(\appbox::get_instance($app['Core'])); + $query = new \User_Query(\appbox::get_instance($app['Core'])); - $query->on_bases_where_i_am($user->ACL(), array('canpush')); + $query->on_bases_where_i_am($user->ACL(), array('canpush')); - if ($request->get('query')) - { - $query->like($request->get('like_field'), $request->get('query')) + if ($request->get('query')) { + $query->like($request->get('like_field'), $request->get('query')) ->like_match(\User_Query::LIKE_MATCH_OR); - } - if (is_array($request->get('Activity'))) - { - $query->haveActivities($request->get('Activity')); - } - if (is_array($request->get('Template'))) - { - $query->haveTemplate($request->get('Template')); - } - if (is_array($request->get('Company'))) - { - $query->inCompanies($request->get('Company')); - } - if (is_array($request->get('Country'))) - { - $query->inCountries($request->get('Country')); - } - if (is_array($request->get('Position'))) - { - $query->havePositions($request->get('Position')); - } + } + if (is_array($request->get('Activity'))) { + $query->haveActivities($request->get('Activity')); + } + if (is_array($request->get('Template'))) { + $query->haveTemplate($request->get('Template')); + } + if (is_array($request->get('Company'))) { + $query->inCompanies($request->get('Company')); + } + if (is_array($request->get('Country'))) { + $query->inCountries($request->get('Country')); + } + if (is_array($request->get('Position'))) { + $query->havePositions($request->get('Position')); + } - $sort = $request->get('srt', 'usr_creationdate'); - $ord = $request->get('ord', 'desc'); + $sort = $request->get('srt', 'usr_creationdate'); + $ord = $request->get('ord', 'desc'); - $perPage = 10; - $offset_start = Max(((int) $request->get('page') - 1) * $perPage, 0); + $perPage = 10; + $offset_start = Max(((int) $request->get('page') - 1) * $perPage, 0); - $query->sort_by($sort, $ord); + $query->sort_by($sort, $ord); - $results = $query->include_phantoms() - ->limit($offset_start, $perPage) - ->execute()->get_results(); + $results = $query->include_phantoms() + ->limit($offset_start, $perPage) + ->execute()->get_results(); - $params = array( - 'query' => $query - , 'results' => $results - , 'list' => $list - , 'sort' => $sort - , 'ord' => $ord - ); - - if ($request->get('type') === 'fragment') - { - return new Response( - $app['Core']->getTwig()->render('prod/actions/Feedback/ResultTable.html.twig', $params) + $params = array( + 'query' => $query + , 'results' => $results + , 'list' => $list + , 'sort' => $sort + , 'ord' => $ord ); - } - else - { - return new Response( - $app['Core']->getTwig()->render('prod/actions/Feedback/list.html.twig', $params) - ); - } + + if ($request->get('type') === 'fragment') { + return new Response( + $app['Core']->getTwig()->render('prod/actions/Feedback/ResultTable.html.twig', $params) + ); + } else { + return new Response( + $app['Core']->getTwig()->render('prod/actions/Feedback/list.html.twig', $params) + ); + } } - )->assert('list_id', '\d+'); - - return $controllers; - } + )->assert('list_id', '\d+'); + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Query.php b/lib/Alchemy/Phrasea/Controller/Prod/Query.php index 6693b9efcd..9b62944c46 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Query.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Query.php @@ -27,228 +27,199 @@ use Symfony\Component\HttpFoundation\Response, class Query implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->match('/', function(Application $app, Request $request) - { + $controllers->match('/', function(Application $app, Request $request) { - $appbox = \appbox::get_instance($app['Core']); - $registry = $appbox->get_registry(); + $appbox = \appbox::get_instance($app['Core']); + $registry = $appbox->get_registry(); - $user = $app['Core']->getAuthenticatedUser(); + $user = $app['Core']->getAuthenticatedUser(); - $query = (string) $request->get('qry'); + $query = (string) $request->get('qry'); - $mod = $user->getPrefs('view'); + $mod = $user->getPrefs('view'); - $json = array(); + $json = array(); - $options = new \searchEngine_options(); + $options = new \searchEngine_options(); - $bas = is_array($request->get('bas')) ? $request->get('bas') : array_keys($user->ACL()->get_granted_base()); + $bas = is_array($request->get('bas')) ? $request->get('bas') : array_keys($user->ACL()->get_granted_base()); - /* @var $user \User_Adapter */ - if ($user->ACL()->has_right('modifyrecord')) - { - $options->set_business_fields(array()); + /* @var $user \User_Adapter */ + if ($user->ACL()->has_right('modifyrecord')) { + $options->set_business_fields(array()); - $BF = array(); + $BF = array(); - foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) - { - if (count($bas) === 0 || in_array($collection->get_base_id(), $bas)) - { - $BF[] = $collection->get_base_id(); - } - } - $options->set_business_fields($BF); - } - else - { - $options->set_business_fields(array()); - } + foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) { + if (count($bas) === 0 || in_array($collection->get_base_id(), $bas)) { + $BF[] = $collection->get_base_id(); + } + } + $options->set_business_fields($BF); + } else { + $options->set_business_fields(array()); + } - $status = is_array($request->get('status')) ? $request->get('status') : array(); - $fields = is_array($request->get('fields')) ? $request->get('fields') : array(); + $status = is_array($request->get('status')) ? $request->get('status') : array(); + $fields = is_array($request->get('fields')) ? $request->get('fields') : array(); - $options->set_fields($fields); - $options->set_status($status); - $options->set_bases($bas, $user->ACL()); + $options->set_fields($fields); + $options->set_status($status); + $options->set_bases($bas, $user->ACL()); - $options->set_search_type($request->get('search_type')); - $options->set_record_type($request->get('recordtype')); - $options->set_min_date($request->get('datemin')); - $options->set_max_date($request->get('datemax')); - $options->set_date_fields(explode('|', $request->get('datefield'))); - $options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC)); - $options->set_use_stemming($request->get('stemme')); + $options->set_search_type($request->get('search_type')); + $options->set_record_type($request->get('recordtype')); + $options->set_min_date($request->get('datemin')); + $options->set_max_date($request->get('datemax')); + $options->set_date_fields(explode('|', $request->get('datefield'))); + $options->set_sort($request->get('sort'), $request->get('ord', PHRASEA_ORDER_DESC)); + $options->set_use_stemming($request->get('stemme')); - $form = serialize($options); + $form = serialize($options); - $perPage = (int) $user->getPrefs('images_per_page'); + $perPage = (int) $user->getPrefs('images_per_page'); - $search_engine = new \searchEngine_adapter($registry); - $search_engine->set_options($options); + $search_engine = new \searchEngine_adapter($registry); + $search_engine->set_options($options); - $page = (int) $request->get('pag'); + $page = (int) $request->get('pag'); - if ($page < 1) - { - $search_engine->set_is_first_page(true); - $search_engine->reset_cache(); - $page = 1; - } + if ($page < 1) { + $search_engine->set_is_first_page(true); + $search_engine->reset_cache(); + $page = 1; + } - $result = $search_engine->query_per_page($query, $page, $perPage); + $result = $search_engine->query_per_page($query, $page, $perPage); - $proposals = $search_engine->is_first_page() ? $result->get_propositions() : false; + $proposals = $search_engine->is_first_page() ? $result->get_propositions() : false; - $npages = $result->get_total_pages(); + $npages = $result->get_total_pages(); - $page = $result->get_current_page(); + $page = $result->get_current_page(); - $string = ''; + $string = ''; - if ($npages > 1) - { + if ($npages > 1) { - $d2top = ($npages - $page); - $d2bottom = $page; + $d2top = ($npages - $page); + $d2bottom = $page; - if (min($d2top, $d2bottom) < 4) - { - if ($d2bottom < 4) - { - for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ ) - { - if ($i == $page) - $string .= ''; - else - $string .= "" . $i . ""; - } - if ($npages > 4) - $string .= ">>"; - } - else - { - $start = $npages - 4; - if (($start) > 0) - $string .= "<<"; - else - $start = 1; - for ($i = ($start); $i <= $npages; $i ++ ) - { - if ($i == $page) - $string .= ''; - else - $string .= "" . $i . ""; - } - } - } - else - { - $string .= "<<"; + if (min($d2top, $d2bottom) < 4) { + if ($d2bottom < 4) { + for ($i = 1; ($i <= 4 && (($i <= $npages) === true)); $i ++ ) { + if ($i == $page) + $string .= ''; + else + $string .= "" . $i . ""; + } + if ($npages > 4) + $string .= ">>"; + } + else { + $start = $npages - 4; + if (($start) > 0) + $string .= "<<"; + else + $start = 1; + for ($i = ($start); $i <= $npages; $i ++ ) { + if ($i == $page) + $string .= ''; + else + $string .= "" . $i . ""; + } + } + } + else { + $string .= "<<"; - for ($i = ($page - 2); $i <= ($page + 2); $i ++ ) - { - if ($i == $page) - $string .= ''; - else - $string .= "" . $i . ""; - } + for ($i = ($page - 2); $i <= ($page + 2); $i ++ ) { + if ($i == $page) + $string .= ''; + else + $string .= "" . $i . ""; + } - $string .= ">>"; - } - } - $string .= '
'; + $string .= ">>"; + } + } + $string .= '
'; - $explain = "
"; + $explain = "
"; - $explain .= ""; + $explain .= ""; - if ($result->get_count_total_results() != $result->get_count_available_results()) - { - $explain .= sprintf(_('reponses:: %d Resultats rappatries sur un total de %d trouves'), $result->get_count_available_results(), $result->get_count_total_results()); - } - else - { - $explain .= sprintf(_('reponses:: %d Resultats'), $result->get_count_total_results()); - } + if ($result->get_count_total_results() != $result->get_count_available_results()) { + $explain .= sprintf(_('reponses:: %d Resultats rappatries sur un total de %d trouves'), $result->get_count_available_results(), $result->get_count_total_results()); + } else { + $explain .= sprintf(_('reponses:: %d Resultats'), $result->get_count_total_results()); + } - $explain .= " "; - $explain .= '
' . $result->get_query_time() . ' s
dans index ' . $result->get_search_indexes(); - $explain .= "
"; + $explain .= " "; + $explain .= '
' . $result->get_query_time() . ' s
dans index ' . $result->get_search_indexes(); + $explain .= "
"; - $infoResult = '' . sprintf(_('reponses:: %d reponses'), $result->get_count_total_results()) . ' | ' . sprintf(_('reponses:: %s documents selectionnes'), ''); + $infoResult = '' . sprintf(_('reponses:: %d reponses'), $result->get_count_total_results()) . ' | ' . sprintf(_('reponses:: %s documents selectionnes'), ''); - $json['infos'] = $infoResult; - $json['navigation'] = $string; + $json['infos'] = $infoResult; + $json['navigation'] = $string; - $prop = null; + $prop = null; - if ($search_engine->is_first_page()) - { - $propals = $result->get_suggestions(); - if (count($propals) > 0) - { - foreach ($propals as $prop_array) - { - if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results()) - { - $prop = $prop_array['value']; - break; - } - } - } - } + if ($search_engine->is_first_page()) { + $propals = $result->get_suggestions(); + if (count($propals) > 0) { + foreach ($propals as $prop_array) { + if ($prop_array['value'] !== $query && $prop_array['hits'] > $result->get_count_total_results()) { + $prop = $prop_array['value']; + break; + } + } + } + } - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); + $core = \bootstrap::getCore(); + $twig = $core->getTwig(); - if ($result->get_count_total_results() === 0) - { - $template = 'prod/results/help.twig'; - } - else - { - if ($mod == 'thumbs') - { - $template = 'prod/results/answergrid.html'; - } - else - { - $template = 'prod/results/answerlist.html'; - } - } + if ($result->get_count_total_results() === 0) { + $template = 'prod/results/help.twig'; + } else { + if ($mod == 'thumbs') { + $template = 'prod/results/answergrid.html'; + } else { + $template = 'prod/results/answerlist.html'; + } + } - $json['results'] = $twig->render($template, array( - 'results' => $result, - 'GV_social_tools' => $registry->get('GV_social_tools'), - 'highlight' => $search_engine->get_query(), - 'searchEngine' => $search_engine, - 'suggestions' => $prop - ) - ); + $json['results'] = $twig->render($template, array( + 'results' => $result, + 'GV_social_tools' => $registry->get('GV_social_tools'), + 'highlight' => $search_engine->get_query(), + 'searchEngine' => $search_engine, + 'suggestions' => $prop + ) + ); - $json['query'] = $query; - $json['phrasea_props'] = $proposals; - $json['total_answers'] = (int) $result->get_count_available_results(); - $json['next_page'] = ($page < $npages && $result->get_count_available_results() > 0) ? ($page + 1) : false; - $json['prev_page'] = ($page > 1 && $result->get_count_available_results() > 0) ? ($page - 1) : false; - $json['form'] = $form; + $json['query'] = $query; + $json['phrasea_props'] = $proposals; + $json['total_answers'] = (int) $result->get_count_available_results(); + $json['next_page'] = ($page < $npages && $result->get_count_available_results() > 0) ? ($page + 1) : false; + $json['prev_page'] = ($page > 1 && $result->get_count_available_results() > 0) ? ($page - 1) : false; + $json['form'] = $form; - $datas = $app['Core']['Serializer']->serialize($json, 'json'); + $datas = $app['Core']['Serializer']->serialize($json, 'json'); - return new Response($datas, 200, array('Content-Type' => 'application/json')); - }); - - return $controllers; - } + return new Response($datas, 200, array('Content-Type' => 'application/json')); + }); + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Root.php b/lib/Alchemy/Phrasea/Controller/Prod/Root.php index 8d7bd9b7a7..c31226d40d 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Root.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Root.php @@ -31,118 +31,108 @@ use Alchemy\Phrasea\Helper; class Root implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->get('/', function(Application $app) - { + $controllers->get('/', function(Application $app) { - \User_Adapter::updateClientInfos(1); + \User_Adapter::updateClientInfos(1); - $appbox = \appbox::get_instance($app['Core']); - $registry = $app['Core']->getRegistry(); - $user = $app['Core']->getAuthenticatedUser(); - $cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/'; + $appbox = \appbox::get_instance($app['Core']); + $registry = $app['Core']->getRegistry(); + $user = $app['Core']->getAuthenticatedUser(); + $cssPath = $registry->get('GV_RootPath') . 'www/skins/prod/'; - $css = array(); - $cssfile = false; + $css = array(); + $cssfile = false; - $finder = new Finder(); + $finder = new Finder(); - $iterator = $finder - ->directories() - ->depth(0) - ->filter(function(\SplFileInfo $fileinfo) - { - return ctype_xdigit($fileinfo->getBasename()); - }) - ->in($cssPath); + $iterator = $finder + ->directories() + ->depth(0) + ->filter(function(\SplFileInfo $fileinfo) { + return ctype_xdigit($fileinfo->getBasename()); + }) + ->in($cssPath); - foreach ($iterator as $dir) - { - $baseName = $dir->getBaseName(); - $css[$baseName] = $baseName; - } - - $cssfile = $user->getPrefs('css'); - - if (!$cssfile && isset($css['000000'])) - { - $cssfile = '000000'; - } - - - $user_feeds = \Feed_Collection::load_all($appbox, $user); - $feeds = array_merge(array($user_feeds->get_aggregate()), $user_feeds->get_feeds()); - - $thjslist = ""; - - $queries_topics = ''; - - if ($registry->get('GV_client_render_topics') == 'popups') - { - $queries_topics = \queries::dropdown_topics(); - } - elseif ($registry->get('GV_client_render_topics') == 'tree') - { - $queries_topics = \queries::tree_topics(); - } - - $sbas = $bas2sbas = array(); - - foreach ($appbox->get_databoxes() as $databox) - { - $sbas_id = $databox->get_sbas_id(); - - $sbas['s' + $sbas_id] = array( - 'sbid' => $sbas_id, - 'seeker' => null); - - foreach ($databox->get_collections() as $coll) - { - $bas2sbas['b' . $coll->get_base_id()] = array( - 'sbid' => $sbas_id, - 'ckobj' => array('checked' => false), - 'waschecked' => false - ); + foreach ($iterator as $dir) { + $baseName = $dir->getBaseName(); + $css[$baseName] = $baseName; } - } - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + $cssfile = $user->getPrefs('css'); - $Serializer = $app['Core']['Serializer']; + if ( ! $cssfile && isset($css['000000'])) { + $cssfile = '000000'; + } - $out = $twig->render('prod/index.html.twig', array( - 'module_name' => 'Production', - 'WorkZone' => new Helper\WorkZone($app['Core'], $app['request']), - 'module_prod' => new Helper\Prod($app['Core'], $app['request']), - 'cssfile' => $cssfile, - 'module' => 'prod', - 'events' => \eventsmanager_broker::getInstance($appbox, $app['Core']), - 'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'), - 'GV_multiAndReport' => $registry->get('GV_multiAndReport'), - 'GV_thesaurus' => $registry->get('GV_thesaurus'), - 'cgus_agreement' => \databox_cgu::askAgreement(), - 'css' => $css, - 'feeds' => $feeds, - 'GV_google_api' => $registry->get('GV_google_api'), - 'queries_topics' => $queries_topics, - 'search_status' => \databox_status::getSearchStatus(), - 'queries_history' => \queries::history(), - 'thesau_js_list' => $thjslist, - 'thesau_json_sbas' => $Serializer->serialize($sbas, 'json'), - 'thesau_json_bas2sbas' => $Serializer->serialize($bas2sbas, 'json'), - 'thesau_languages' => \User_Adapter::avLanguages(), - 'GV_bitly_user' => $registry->get('GV_bitly_user'), - 'GV_bitly_key' => $registry->get('GV_bitly_key') - )); - return new Response($out); + $user_feeds = \Feed_Collection::load_all($appbox, $user); + $feeds = array_merge(array($user_feeds->get_aggregate()), $user_feeds->get_feeds()); + + $thjslist = ""; + + $queries_topics = ''; + + if ($registry->get('GV_client_render_topics') == 'popups') { + $queries_topics = \queries::dropdown_topics(); + } elseif ($registry->get('GV_client_render_topics') == 'tree') { + $queries_topics = \queries::tree_topics(); + } + + $sbas = $bas2sbas = array(); + + foreach ($appbox->get_databoxes() as $databox) { + $sbas_id = $databox->get_sbas_id(); + + $sbas['s' + $sbas_id] = array( + 'sbid' => $sbas_id, + 'seeker' => null); + + foreach ($databox->get_collections() as $coll) { + $bas2sbas['b' . $coll->get_base_id()] = array( + 'sbid' => $sbas_id, + 'ckobj' => array('checked' => false), + 'waschecked' => false + ); + } + } + + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); + + $Serializer = $app['Core']['Serializer']; + + $out = $twig->render('prod/index.html.twig', array( + 'module_name' => 'Production', + 'WorkZone' => new Helper\WorkZone($app['Core'], $app['request']), + 'module_prod' => new Helper\Prod($app['Core'], $app['request']), + 'cssfile' => $cssfile, + 'module' => 'prod', + 'events' => \eventsmanager_broker::getInstance($appbox, $app['Core']), + 'GV_defaultQuery_type' => $registry->get('GV_defaultQuery_type'), + 'GV_multiAndReport' => $registry->get('GV_multiAndReport'), + 'GV_thesaurus' => $registry->get('GV_thesaurus'), + 'cgus_agreement' => \databox_cgu::askAgreement(), + 'css' => $css, + 'feeds' => $feeds, + 'GV_google_api' => $registry->get('GV_google_api'), + 'queries_topics' => $queries_topics, + 'search_status' => \databox_status::getSearchStatus(), + 'queries_history' => \queries::history(), + 'thesau_js_list' => $thjslist, + 'thesau_json_sbas' => $Serializer->serialize($sbas, 'json'), + 'thesau_json_bas2sbas' => $Serializer->serialize($bas2sbas, 'json'), + 'thesau_languages' => \User_Adapter::avLanguages(), + 'GV_bitly_user' => $registry->get('GV_bitly_user'), + 'GV_bitly_key' => $registry->get('GV_bitly_key') + )); + + return new Response($out); }); - return $controllers; - } - + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Story.php b/lib/Alchemy/Phrasea/Controller/Prod/Story.php index ae5d2c3ea3..cf90f7e8de 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Story.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Story.php @@ -32,320 +32,284 @@ use Alchemy\Phrasea\RouteProcessor\Basket as BasketRoute, class Story implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->get('/create/', function(Application $app) - { - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + $controllers->get('/create/', function(Application $app) { + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return new Response($twig->render('prod/Story/Create.html.twig', array())); + return new Response($twig->render('prod/Story/Create.html.twig', array())); }); - $controllers->post('/', function(Application $app, Request $request) - { - /* @var $request \Symfony\Component\HttpFoundation\Request */ - $em = $app['Core']->getEntityManager(); + $controllers->post('/', function(Application $app, Request $request) { + /* @var $request \Symfony\Component\HttpFoundation\Request */ + $em = $app['Core']->getEntityManager(); - $user = $app['Core']->getAuthenticatedUser(); + $user = $app['Core']->getAuthenticatedUser(); - $collection = \collection::get_from_base_id($request->get('base_id')); + $collection = \collection::get_from_base_id($request->get('base_id')); - if (!$user->ACL()->has_right_on_base($collection->get_base_id(), 'canaddrecord')) - { - throw new \Exception_Forbidden('You can not create a story on this collection'); - } - - - $system_file = new \system_file( - $app['Core']->getRegistry() - ->get('GV_RootPath') . 'www/skins/icons/substitution/regroup_doc.png' - ); - - $Story = \record_adapter::create($collection, $system_file, false, true); - - foreach (explode(';', $request->get('lst')) as $sbas_rec) - { - $sbas_rec = explode('_', $sbas_rec); - - if (count($sbas_rec) !== 2) - { - continue; + if ( ! $user->ACL()->has_right_on_base($collection->get_base_id(), 'canaddrecord')) { + throw new \Exception_Forbidden('You can not create a story on this collection'); } - $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]); - if (!$user->ACL()->has_access_to_base($record->get_base_id()) - && !$user->ACL()->has_hd_grant($record) - && !$user->ACL()->has_preview_grant($record)) - { - continue; - } - - if ($Story->hasChild($record)) - continue; - - $Story->appendChild($record); - } - - $metadatas = array(); - - foreach ($collection->get_databox()->get_meta_structure() as $meta) - { - if ($meta->get_thumbtitle()) - { - $value = $request->get('name'); - } - else - { - continue; - } - - $metadatas[] = array( - 'meta_struct_id' => $meta->get_id() - , 'meta_id' => null - , 'value' => $value + $system_file = new \system_file( + $app['Core']->getRegistry() + ->get('GV_RootPath') . 'www/skins/icons/substitution/regroup_doc.png' ); - break; - } + $Story = \record_adapter::create($collection, $system_file, false, true); - $Story->set_metadatas($metadatas)->rebuild_subdefs(); + foreach (explode(';', $request->get('lst')) as $sbas_rec) { + $sbas_rec = explode('_', $sbas_rec); - $StoryWZ = new \Entities\StoryWZ(); - $StoryWZ->setUser($user); - $StoryWZ->setRecord($Story); + if (count($sbas_rec) !== 2) { + continue; + } - $em->persist($StoryWZ); + $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]); - $em->flush(); + if ( ! $user->ACL()->has_access_to_base($record->get_base_id()) + && ! $user->ACL()->has_hd_grant($record) + && ! $user->ACL()->has_preview_grant($record)) { + continue; + } + + if ($Story->hasChild($record)) + continue; + + $Story->appendChild($record); + } + + $metadatas = array(); + + foreach ($collection->get_databox()->get_meta_structure() as $meta) { + if ($meta->get_thumbtitle()) { + $value = $request->get('name'); + } else { + continue; + } + + $metadatas[] = array( + 'meta_struct_id' => $meta->get_id() + , 'meta_id' => null + , 'value' => $value + ); + + break; + } + + $Story->set_metadatas($metadatas)->rebuild_subdefs(); + + $StoryWZ = new \Entities\StoryWZ(); + $StoryWZ->setUser($user); + $StoryWZ->setRecord($Story); + + $em->persist($StoryWZ); + + $em->flush(); + + if ($request->getRequestFormat() == 'json') { + $data = array( + 'success' => true + , 'message' => _('Story created') + , 'WorkZone' => $StoryWZ->getId() + , 'story' => array( + 'sbas_id' => $Story->get_sbas_id(), + 'record_id' => $Story->get_record_id(), + ) + ); + + $datas = $app['Core']['Serializer']->serialize($data, 'json'); + + return new Response($datas, 200, array('Content-type' => 'application/json')); + } else { + return new RedirectResponse(sprintf('/%d/', $StoryWZ->getId())); + } + }); + + + + $controllers->get('/{sbas_id}/{record_id}/', function(Application $app, $sbas_id, $record_id) { + $Story = new \record_adapter($sbas_id, $record_id); + + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); + + $html = $twig->render('prod/WorkZone/Story.html.twig', array('Story' => $Story)); + + return new Response($html); + })->assert('sbas_id', '\d+')->assert('record_id', '\d+'); + + + $controllers->post( + '/{sbas_id}/{record_id}/addElements/' + , function(Application $app, Request $request, $sbas_id, $record_id) { + $Story = new \record_adapter($sbas_id, $record_id); + + $user = $app['Core']->getAuthenticatedUser(); + + if ( ! $user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) + throw new \Exception_Forbidden('You can not add document to this Story'); + + /* @var $user \User_Adapter */ + + $n = 0; + + foreach (explode(';', $request->get('lst')) as $sbas_rec) { + $sbas_rec = explode('_', $sbas_rec); + + if (count($sbas_rec) !== 2) + continue; + + $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]); + + if ( ! $user->ACL()->has_access_to_base($record->get_base_id()) + && ! $user->ACL()->has_hd_grant($record) + && ! $user->ACL()->has_preview_grant($record)) { + continue; + } + + if ($Story->hasChild($record)) + continue; + + $Story->appendChild($record); + + $n ++; + } - if ($request->getRequestFormat() == 'json') - { $data = array( 'success' => true - , 'message' => _('Story created') - , 'WorkZone' => $StoryWZ->getId() - , 'story' => array( - 'sbas_id' => $Story->get_sbas_id(), - 'record_id' => $Story->get_record_id(), - ) + , 'message' => sprintf(_('%d records added'), $n) ); - $datas = $app['Core']['Serializer']->serialize($data, 'json'); + if ($request->getRequestFormat() == 'json') { - return new Response($datas, 200, array('Content-type' => 'application/json')); - } - else - { - return new RedirectResponse(sprintf('/%d/', $StoryWZ->getId())); - } - }); + $datas = $app['Core']['Serializer']->serialize($data, 'json'); - - - $controllers->get('/{sbas_id}/{record_id}/', function(Application $app, $sbas_id, $record_id) - { - $Story = new \record_adapter($sbas_id, $record_id); - - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); - - $html = $twig->render('prod/WorkZone/Story.html.twig', array('Story' => $Story)); - - return new Response($html); - })->assert('sbas_id', '\d+')->assert('record_id', '\d+'); - - - $controllers->post( - '/{sbas_id}/{record_id}/addElements/' - , function(Application $app, Request $request, $sbas_id, $record_id) - { - $Story = new \record_adapter($sbas_id, $record_id); - - $user = $app['Core']->getAuthenticatedUser(); - - if (!$user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) - throw new \Exception_Forbidden('You can not add document to this Story'); - - /* @var $user \User_Adapter */ - - $n = 0; - - foreach (explode(';', $request->get('lst')) as $sbas_rec) - { - $sbas_rec = explode('_', $sbas_rec); - - if (count($sbas_rec) !== 2) - continue; - - $record = new \record_adapter($sbas_rec[0], $sbas_rec[1]); - - if (!$user->ACL()->has_access_to_base($record->get_base_id()) - && !$user->ACL()->has_hd_grant($record) - && !$user->ACL()->has_preview_grant($record)) - { - continue; + return new Response($datas, 200, array('Content-type' => 'application/json')); + } else { + return new RedirectResponse('/'); } - - if ($Story->hasChild($record)) - continue; - - $Story->appendChild($record); - - $n++; - } - - $data = array( - 'success' => true - , 'message' => sprintf(_('%d records added'), $n) - ); - - if ($request->getRequestFormat() == 'json') - { - - $datas = $app['Core']['Serializer']->serialize($data, 'json'); - - return new Response($datas, 200, array('Content-type' => 'application/json')); - } - else - { - return new RedirectResponse('/'); - } })->assert('sbas_id', '\d+')->assert('record_id', '\d+'); - $controllers->post( - '/{sbas_id}/{record_id}/delete/{child_sbas_id}/{child_record_id}/' - , function(Application $app, Request $request, $sbas_id, $record_id, $child_sbas_id, $child_record_id) - { - $Story = new \record_adapter($sbas_id, $record_id); + $controllers->post( + '/{sbas_id}/{record_id}/delete/{child_sbas_id}/{child_record_id}/' + , function(Application $app, Request $request, $sbas_id, $record_id, $child_sbas_id, $child_record_id) { + $Story = new \record_adapter($sbas_id, $record_id); - $record = new \record_adapter($child_sbas_id, $child_record_id); + $record = new \record_adapter($child_sbas_id, $child_record_id); - $user = $app['Core']->getAuthenticatedUser(); + $user = $app['Core']->getAuthenticatedUser(); - if (!$user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) + if ( ! $user->ACL()->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) throw new \Exception_Forbidden('You can not add document to this Story'); - /* @var $user \User_Adapter */ + /* @var $user \User_Adapter */ - $Story->removeChild($record); + $Story->removeChild($record); - $data = array( - 'success' => true - , 'message' => _('Record removed from story') - ); + $data = array( + 'success' => true + , 'message' => _('Record removed from story') + ); - if ($request->getRequestFormat() == 'json') - { + if ($request->getRequestFormat() == 'json') { $datas = $app['Core']['Serializer']->serialize($data, 'json'); return new Response($datas, 200, array('Content-type' => 'application/json')); - } - else - { + } else { return new RedirectResponse('/'); - } - }) + } + }) ->assert('sbas_id', '\d+') ->assert('record_id', '\d+') ->assert('child_sbas_id', '\d+') ->assert('child_record_id', '\d+'); - /** - * Get the Basket reorder form - */ - $controllers->get( - '/{sbas_id}/{record_id}/reorder/' - , function(Application $app, $sbas_id, $record_id) - { - /* @var $em \Doctrine\ORM\EntityManager */ - $em = $app['Core']->getEntityManager(); + /** + * Get the Basket reorder form + */ + $controllers->get( + '/{sbas_id}/{record_id}/reorder/' + , function(Application $app, $sbas_id, $record_id) { + /* @var $em \Doctrine\ORM\EntityManager */ + $em = $app['Core']->getEntityManager(); - $story = new \record_adapter($sbas_id, $record_id); + $story = new \record_adapter($sbas_id, $record_id); - if (!$story->is_grouping()) - { + if ( ! $story->is_grouping()) { throw new \Exception('This is not a story'); - } + } - /* @var $twig \Twig_Environment */ - $twig = $app['Core']->getTwig(); + /* @var $twig \Twig_Environment */ + $twig = $app['Core']->getTwig(); - return new Response( - $twig->render( - 'prod/Story/Reorder.html.twig' - , array('story' => $story) - ) - ); - }) + return new Response( + $twig->render( + 'prod/Story/Reorder.html.twig' + , array('story' => $story) + ) + ); + }) ->assert('sbas_id', '\d+') ->assert('record_id', '\d+'); - $controllers->post( - '/{sbas_id}/{record_id}/reorder/' - , function(Application $app, $sbas_id, $record_id) - { - $ret = array('success' => false, 'message' => _('An error occured')); - try - { + $controllers->post( + '/{sbas_id}/{record_id}/reorder/' + , function(Application $app, $sbas_id, $record_id) { + $ret = array('success' => false, 'message' => _('An error occured')); + try { $user = $app['Core']->getAuthenticatedUser(); /* @var $user \User_Adapter */ $story = new \record_adapter($sbas_id, $record_id); - if (!$story->is_grouping()) - { - throw new \Exception('This is not a story'); + if ( ! $story->is_grouping()) { + throw new \Exception('This is not a story'); } - if (!$user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord')) - { - throw new ControllerException(_('You can not edit this story')); + if ( ! $user->ACL()->has_right_on_base($story->get_base_id(), 'canmodifrecord')) { + throw new ControllerException(_('You can not edit this story')); } $sql = 'UPDATE regroup SET ord = :ord WHERE rid_parent = :parent_id AND rid_child = :children_id'; $stmt = $story->get_databox()->get_connection()->prepare($sql); - foreach ($app['request']->get('element') as $record_id => $ord) - { - $params = array( - ':ord' => $ord, - ':parent_id' => $story->get_record_id(), - ':children_id' => $record_id - ); - $stmt->execute($params); + foreach ($app['request']->get('element') as $record_id => $ord) { + $params = array( + ':ord' => $ord, + ':parent_id' => $story->get_record_id(), + ':children_id' => $record_id + ); + $stmt->execute($params); } $stmt->closeCursor(); $ret = array('success' => true, 'message' => _('Story updated')); - } - catch (ControllerException $e) - { + } catch (ControllerException $e) { $ret = array('success' => false, 'message' => $e->getMessage()); - } - catch (\Exception $e) - { + } catch (\Exception $e) { - } + } - $Serializer = $app['Core']['Serializer']; + $Serializer = $app['Core']['Serializer']; - return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json')); - }) + return new Response($Serializer->serialize($ret, 'json'), 200, array('Content-type' => 'application/json')); + }) ->assert('sbas_id', '\d+') ->assert('record_id', '\d+'); - return $controllers; - } - + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/TOU.php b/lib/Alchemy/Phrasea/Controller/Prod/TOU.php index 57a0fa1fb1..9e3cc4f160 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/TOU.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/TOU.php @@ -29,42 +29,37 @@ use Alchemy\Phrasea\Helper\Record as RecordHelper; class TOU implements ControllerProviderInterface { - public function connect(Application $app) - { - $controllers = new ControllerCollection(); + public function connect(Application $app) + { + $controllers = new ControllerCollection(); - $controllers->post('/deny/{sbas_id}/', function(Application $app, Request $request, $sbas_id) - { - $ret = array('success' => false, 'message' => ''); + $controllers->post('/deny/{sbas_id}/', function(Application $app, Request $request, $sbas_id) { + $ret = array('success' => false, 'message' => ''); - try - { - $user = $app['Core']->getAuthenticatedUser(); - $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core'])); + try { + $user = $app['Core']->getAuthenticatedUser(); + $session = \Session_Handler::getInstance(\appbox::get_instance($app['Core'])); - $databox = \databox::get_instance((int) $sbas_id); + $databox = \databox::get_instance((int) $sbas_id); - $user->ACL()->revoke_access_from_bases( - $user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) - ); - $user->ACL()->revoke_unused_sbas_rights(); + $user->ACL()->revoke_access_from_bases( + $user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) + ); + $user->ACL()->revoke_unused_sbas_rights(); - $session->logout(); + $session->logout(); - $ret = array('success' => true, 'message' => ''); - } - catch (\Exception $e) - { + $ret = array('success' => true, 'message' => ''); + } catch (\Exception $e) { - } + } - $Serializer = $app['Core']['Serializer']; - $datas = $Serializer->serialize($ret, 'json'); + $Serializer = $app['Core']['Serializer']; + $datas = $Serializer->serialize($ret, 'json'); - return new Response($datas, 200, array('Content-Type' => 'application/json')); - }); - - return $controllers; - } + return new Response($datas, 200, array('Content-Type' => 'application/json')); + }); + return $controllers; + } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Tools.php b/lib/Alchemy/Phrasea/Controller/Prod/Tools.php index 89ef11799d..d12e54de48 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Tools.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Tools.php @@ -36,287 +36,243 @@ class Tools implements ControllerProviderInterface { $controllers = new ControllerCollection(); - $controllers->get('/', function(Application $app, Request $request) - { - $helper = new Helper\Record\Tools($app['Core'], $request); + $controllers->get('/', function(Application $app, Request $request) { + $helper = new Helper\Record\Tools($app['Core'], $request); - $selection = $helper->get_elements(); + $selection = $helper->get_elements(); - $binary = $app['Core']->getRegistry()->get('GV_exiftool'); + $binary = $app['Core']->getRegistry()->get('GV_exiftool'); - $metadatas = false; - $record = null; - $metadatasFirst = $metadatasSecond = array(); + $metadatas = false; + $record = null; + $metadatasFirst = $metadatasSecond = array(); - if (count($selection) == 1 && ! empty($binary)) - { - try - { - $record = reset($selection); - $file = $record->get_subdef('document')->get_pathfile(); - $cmd = $binary . ' -h ' . escapeshellarg($file); + if (count($selection) == 1 && ! empty($binary)) { + try { + $record = reset($selection); + $file = $record->get_subdef('document')->get_pathfile(); + $cmd = $binary . ' -h ' . escapeshellarg($file); - $out = ""; - exec($cmd, $out); - foreach ($out as $liout) - { - if (strpos($liout, 'Directory') === false) - $metadatasFirst[] = $liout; - } - $out = ""; - $cmd = $binary . ' -X -n -fast ' . escapeshellarg($file) . ''; - exec($cmd, $out); - foreach ($out as $liout) - { - $metadatasSecond[] = htmlentities($liout); - } - $metadatas = true; - } - catch (\Exception $e) - { + $out = ""; + exec($cmd, $out); + foreach ($out as $liout) { + if (strpos($liout, '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" - . "10" - . "0utf8"; - } - 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" + . "10" + . "0utf8"; + } 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 $out; -} - -function giveInscript($lng, $demandes=null) -{ - $appbox = appbox::get_instance(\bootstrap::getCore()); - - $out = '' . - '' . - '' . - '' . - '' . - ''; - - $inscriptions = giveMeBases(); - - foreach ($inscriptions as $sbasId => $baseInsc) - { - - if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript'])// il y a des coll ou s'inscrire ! - { - //je pr�sente la base - $out .= ''; - - 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 .= ''; - //$out .= ''; - } - foreach ($baseInsc['Colls'] as $collId => $collName) - { - - $baseId = phrasea::baseFromColl($sbasId, $collId); - $ch = "checked"; - if ((!is_null($demandes) && !isset($demandes[$baseId]))) - $ch = ""; - $out .= '' . - '' . - '' . - '' . - ''; - } - } - if ($baseInsc['CollsCGU']) - { - foreach ($baseInsc['CollsCGU'] as $collId => $collDesc) - { - - $baseId = phrasea::baseFromColl($sbasId, $collId); - - $ch = "checked"; - if (!is_null($demandes) && !isset($demandes[$baseId])) - $ch = ""; - $out .= '' . - '' . - // '' . - // '' . - // '' . - '' . - '' . - '' . - '' . - ''; - } - } + if ($noDemand) { + $out .= '
' . _('login::register: Vous avez acces a toutes les collections de toutes les bases') . '
'; + } else { + $out .= '
'; } - } - $out .= '
   

' . phrasea::sbas_names($sbasId) . '

' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . '
' . _('login::register::CGU: ouvrir dans une nouvelle fenetre') . '
'.(string)$baseInsc['CGU'].'
' . $collName . '' . - '' . - '' . _('login::register: Faire une demande d\'acces') . '' . - '

' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . - '
' . _('login::register::CGU: ouvrir dans une nouvelle fenetre') . '
' . - // ''.(string)$collDesc['CGU'].'' . - // '
' . $collDesc['name'] . '' . - '' . - '' . _('login::register: Faire une demande d\'acces') . '' . - '
'; - return $out; + $out .= '' . + '' . + ''; + + return $out; } +function giveInscript($lng, $demandes = null) +{ + $appbox = appbox::get_instance(\bootstrap::getCore()); + + $out = '' . + '' . + '' . + '' . + '' . + ''; + + $inscriptions = giveMeBases(); + + foreach ($inscriptions as $sbasId => $baseInsc) { + + if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript']) {// il y a des coll ou s'inscrire ! + //je pr�sente la base + $out .= ''; + + 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 .= ''; + //$out .= ''; + } + foreach ($baseInsc['Colls'] as $collId => $collName) { + + $baseId = phrasea::baseFromColl($sbasId, $collId); + $ch = "checked"; + if (( ! is_null($demandes) && ! isset($demandes[$baseId]))) + $ch = ""; + $out .= '' . + '' . + '' . + '' . + ''; + } + } + if ($baseInsc['CollsCGU']) { + foreach ($baseInsc['CollsCGU'] as $collId => $collDesc) { + + $baseId = phrasea::baseFromColl($sbasId, $collId); + + $ch = "checked"; + if ( ! is_null($demandes) && ! isset($demandes[$baseId])) + $ch = ""; + $out .= '' . + '' . + // '' . + // '' . + // '' . + '' . + '' . + '' . + '' . + ''; + } + } + } + } + $out .= '
   

' . phrasea::sbas_names($sbasId) . '

' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . '
' . _('login::register::CGU: ouvrir dans une nouvelle fenetre') . '
'.(string)$baseInsc['CGU'].'
' . $collName . '' . + '' . + '' . _('login::register: Faire une demande d\'acces') . '' . + '

' . _('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . + '
' . _('login::register::CGU: ouvrir dans une nouvelle fenetre') . '
' . + // ''.(string)$collDesc['CGU'].'' . + // '
' . $collDesc['name'] . '' . + '' . + '' . _('login::register: Faire une demande d\'acces') . '' . + '
'; + + 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 .= "
" . '' . $url . '' . "
\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
    " . $accept . "
\n"; - } - if ($deny != '') - { - $body .= "
\n
" . _('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . "
\n
    " . $deny . "
\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
    " . $auto . "
\n"; - } - - if ($others != '') - { - $body .= "
\n
" . _('login::register: vos demandes concernat les collections suivantes sont sujettes a approbation d\'un administrateur') . "
\n
    " . $others . "
\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
    " . $others . "
\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 .= "
    " . '' . $url . '' . "
    \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
      " . $accept . "
    \n"; + } + if ($deny != '') { + $body .= "
    \n
    " . _('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . "
    \n
      " . $deny . "
    \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
      " . $auto . "
    \n"; + } + + if ($others != '') { + $body .= "
    \n
    " . _('login::register: vos demandes concernat les collections suivantes sont sujettes a approbation d\'un administrateur') . "
    \n
      " . $others . "
    \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
      " . $others . "
    \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 $dmin, Y-m-d + * @param $dmax, Y-m-d */ - $this->report['activity'] = module_report_activity::activity( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - - // get activty by day - $this->report['activity_day'] = module_report_activity::activityDay( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - // get Most document and preview DL - $topdl = module_report_download::getTopDl( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - - $this->report['top_dl_preview'] = $topdl['preview']; - $this->report['top_dl_document'] = $topdl['document']; - - if ($registry->get('GV_anonymousReport') == false) + public function __construct($sbasid, $sbas_collection, $dmin, $dmax) { - // get users that ask the most questions - $this->report['ask'] = module_report_activity::activityQuestion( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); + $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(); } - //get the refferer - $this->report['top_ten_site'] = module_report_activity::activiteTopTenSiteView( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - //Get the most asked questions - $this->report['top_ten_question'] = module_report_activity::activiteTopQuestion( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - //get the number of added docuùments - $this->report['activity_added'] = module_report_activity::activiteAddedDocument( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - - //get number of edited document - $this->report['activity_edited'] = module_report_activity::activiteEditedDocument( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); - if ($registry->get('GV_anonymousReport') == false) + /** + * @desc return les date dormate pour les requetes sql; + * @param $d, vaut 'dmin' ou 'dmax' + * @return Datetime + */ + private function dateToSqlDate($d) { - //get users that add the most documents - $this->report['top_ten_added'] = module_report_activity::activiteAddedTopTenUser( - $this->dminsql, - $this->dmaxsql, - $this->sbasid, - $this->collection - ); + 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); + } } - } - catch(PDOException $e) + + /** + * @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']; + } + + /** + * get avtivity by hour + */ + $this->report['activity'] = module_report_activity::activity( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + + // get activty by day + $this->report['activity_day'] = module_report_activity::activityDay( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + // get Most document and preview DL + $topdl = module_report_download::getTopDl( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + + $this->report['top_dl_preview'] = $topdl['preview']; + $this->report['top_dl_document'] = $topdl['document']; + + if ($registry->get('GV_anonymousReport') == false) { + // get users that ask the most questions + $this->report['ask'] = module_report_activity::activityQuestion( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + } + //get the refferer + $this->report['top_ten_site'] = module_report_activity::activiteTopTenSiteView( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + //Get the most asked questions + $this->report['top_ten_question'] = module_report_activity::activiteTopQuestion( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + + //get the number of added docuùments + $this->report['activity_added'] = module_report_activity::activiteAddedDocument( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + + //get number of edited document + $this->report['activity_edited'] = module_report_activity::activiteEditedDocument( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + if ($registry->get('GV_anonymousReport') == false) { + //get users that add the most documents + $this->report['top_ten_added'] = module_report_activity::activiteAddedTopTenUser( + $this->dminsql, $this->dmaxsql, $this->sbasid, $this->collection + ); + } + } catch (PDOException $e) { + + } + + return; } - return; - } - - /** - * @desc return variable that contains the results - * @return - */ - public function getDash() - { - return $this->report; - } - - /** - * @desc check if the results are valid - * @return - */ - public function isValid() - { - if (isset($this->report) && sizeof($this->report) > 0) - - return true; - else - - return false; - } + /** + * @desc return variable that contains the results + * @return + */ + public function getDash() + { + return $this->report; + } + /** + * @desc check if the results are valid + * @return + */ + public function isValid() + { + if (isset($this->report) && sizeof($this->report) > 0) + return true; + else + return false; + } } ?> diff --git a/lib/classes/module/report/dashboard/group.class.php b/lib/classes/module/report/dashboard/group.class.php index 671a8b3628..ac8a32cc5b 100644 --- a/lib/classes/module/report/dashboard/group.class.php +++ b/lib/classes/module/report/dashboard/group.class.php @@ -17,93 +17,81 @@ */ class module_report_dashboard_group implements module_report_dashboard_componentInterface { + public $group_dash; + public $dashboard = array(); + private $valid = false; - public $group_dash; - public $dashboard = array(); - private $valid = false; - - /** - * @desc group the dashboard - */ - public function __construct(module_report_dashboard $report) - { - if ($report->isValid()) + /** + * @desc group the dashboard + */ + public function __construct(module_report_dashboard $report) { - $this->valid = true; - $this->dashboard = $report->getDash(); + if ($report->isValid()) { + $this->valid = true; + $this->dashboard = $report->getDash(); + } + $this->process(); } - $this->process(); - } - /** - * @desc GROUP the dashboard - * @return - */ - public function process() - { - if ($this->valid) + /** + * @desc GROUP the dashboard + * @return + */ + public function process() { - if (is_null($this->group_dash)) - $this->group_dash = array(); - foreach ($this->dashboard as $key => $dash) - { - if (is_object($dash) && - $dash instanceof module_report_dashboard_feed && - $dash->isValid()) - { - $onedash = $dash->getDash(); - foreach ($onedash as $typeofreport => $value) - { - if (is_array($value) && sizeof($value) == 0) - continue; - else - { - $this->group_dash[$typeofreport][] = $value; + if ($this->valid) { + if (is_null($this->group_dash)) + $this->group_dash = array(); + foreach ($this->dashboard as $key => $dash) { + if (is_object($dash) && + $dash instanceof module_report_dashboard_feed && + $dash->isValid()) { + $onedash = $dash->getDash(); + foreach ($onedash as $typeofreport => $value) { + if (is_array($value) && sizeof($value) == 0) + continue; + else { + $this->group_dash[$typeofreport][] = $value; + } + } + } else { + throw new Exception("cannot group on a none dashboard object"); + } } - } } - else - { - throw new Exception("cannot group on a none dashboard object"); - } - } + + return; } - return; - } + /** + * @desc check if the grouped dash is valid + * @return + */ + public function isValid() + { + if (isset($this->group_dash) && sizeof($this->group_dash) > 0) + return true; + else + return false; + } - /** - * @desc check if the grouped dash is valid - * @return - */ - public function isValid() - { - if (isset($this->group_dash) && sizeof($this->group_dash) > 0) - - return true; - else - - return false; - } - - /** - * @desc return the results - * @return - */ - public function getDash() - { - return $this->group_dash; - } - - /** - * @desc Tri de grouped dash - * @return dashboard_merge - */ - public function tri() - { - return new module_report_dashboard_merge($this); - } + /** + * @desc return the results + * @return + */ + public function getDash() + { + return $this->group_dash; + } + /** + * @desc Tri de grouped dash + * @return dashboard_merge + */ + public function tri() + { + return new module_report_dashboard_merge($this); + } } ?> diff --git a/lib/classes/module/report/dashboard/merge.class.php b/lib/classes/module/report/dashboard/merge.class.php index af94ebf40b..a9ecbe8aa3 100644 --- a/lib/classes/module/report/dashboard/merge.class.php +++ b/lib/classes/module/report/dashboard/merge.class.php @@ -17,205 +17,192 @@ */ class module_report_dashboard_merge implements module_report_dashboard_componentInterface { + public $sort = array(); + public $sorted = array(); + private $currentkey; + private $valid = false; - public $sort = array(); - public $sorted = array(); - private $currentkey; - private $valid = false; - - /** - * @desc tri le dashboard - * @param dashboard_group $dash_organize - */ - public function __construct(module_report_dashboard_group $dash_organize) - { - if ($dash_organize->isValid()) + /** + * @desc tri le dashboard + * @param dashboard_group $dash_organize + */ + public function __construct(module_report_dashboard_group $dash_organize) { - $this->valid = true; - $this->sort = $dash_organize->getDash(); - } - $this->process(); - } - - /** - * @des main function execute the process of triage - * @return - */ - public function process() - { - if ($this->valid) - { - foreach ($this->sort as $key => $value) - { - $this->currentkey = $key; - switch ($this->currentkey) - { - case "nb_conn": - $this->sum(); - break; - case "nb_dl": - $this->sum(); - break; - case "activity": - $this->triActivity(); - $this->toString(); - break; - case "activity_day": - $this->triActivity(); - $this->toString(); - break; - case "activity_edited": - $this->triActivity(); - $this->toString(); - break; - case "activity_added": - $this->triActivity(); - $this->toString(); - break; - case "top_ten_user_doc": - $this->triTopTen(); - break; - case "top_ten_user_prev": - $this->triTopTen(); - break; - case "top_ten_user_poiddoc": - $this->triTopTen(); - break; - case "top_ten_user_poidprev": - $this->triTopTen(); - break; - case "top_dl_preview": - $this->triTopTen(); - break; - case "top_dl_document": - $this->triTopTen(); - break; - case "top_ten_question": - $this->triTopTen(); - break; - case "ask": - $this->triTopTen(); - break; - case "top_ten_site": - $this->triTopTen(); - break; - case "top_ten_added": - $this->triTopTen(); - break; - default: - break; + if ($dash_organize->isValid()) { + $this->valid = true; + $this->sort = $dash_organize->getDash(); } - } + $this->process(); } - return; - } - - /** - * @return le dashboard trie - * @return - */ - public function getDash() - { - return $this->sorted; - } - - /** - * @desc check si les resultats sont valides - * @return - */ - public function isValid() - { - if (isset($this->sorted) && sizeof($this->sorted) > 0) - - return true; - else - - return false; - } - - /** - * @return - */ - private function sum() - { - $this->sorted[$this->currentkey] = 0; - foreach ($this->sort[$this->currentkey] as $k => $v) - $this->sorted[$this->currentkey] += $v; - - return; - } - - /** - * @desc Tri all result of activity type - * @return - */ - private function triActivity() - { - foreach ($this->sort[$this->currentkey] as $sbas => $val) + /** + * @des main function execute the process of triage + * @return + */ + public function process() { - foreach ($val as $key => $value) - { + if ($this->valid) { + foreach ($this->sort as $key => $value) { + $this->currentkey = $key; + switch ($this->currentkey) { + case "nb_conn": + $this->sum(); + break; + case "nb_dl": + $this->sum(); + break; + case "activity": + $this->triActivity(); + $this->toString(); + break; + case "activity_day": + $this->triActivity(); + $this->toString(); + break; + case "activity_edited": + $this->triActivity(); + $this->toString(); + break; + case "activity_added": + $this->triActivity(); + $this->toString(); + break; + case "top_ten_user_doc": + $this->triTopTen(); + break; + case "top_ten_user_prev": + $this->triTopTen(); + break; + case "top_ten_user_poiddoc": + $this->triTopTen(); + break; + case "top_ten_user_poidprev": + $this->triTopTen(); + break; + case "top_dl_preview": + $this->triTopTen(); + break; + case "top_dl_document": + $this->triTopTen(); + break; + case "top_ten_question": + $this->triTopTen(); + break; + case "ask": + $this->triTopTen(); + break; + case "top_ten_site": + $this->triTopTen(); + break; + case "top_ten_added": + $this->triTopTen(); + break; + default: + break; + } + } + } - isset($this->sorted[$this->currentkey][$key]) ? + return; + } + + /** + * @return le dashboard trie + * @return + */ + public function getDash() + { + return $this->sorted; + } + + /** + * @desc check si les resultats sont valides + * @return + */ + public function isValid() + { + if (isset($this->sorted) && sizeof($this->sorted) > 0) + return true; + else + return false; + } + + /** + * @return + */ + private function sum() + { + $this->sorted[$this->currentkey] = 0; + foreach ($this->sort[$this->currentkey] as $k => $v) + $this->sorted[$this->currentkey] += $v; + + return; + } + + /** + * @desc Tri all result of activity type + * @return + */ + private function triActivity() + { + foreach ($this->sort[$this->currentkey] as $sbas => $val) { + foreach ($val as $key => $value) { + + isset($this->sorted[$this->currentkey][$key]) ? $this->sorted[$this->currentkey][$key] += $value : $this->sorted[$this->currentkey][$key] = $value; - } - } - } - - /** - * @desc force value to string values - * this is the format to respect for displaying float results in - * SVG google charts - * - * @return void; - */ - private function toString() - { - foreach ($this->sorted[$this->currentkey] as $k => $v) - $this->sorted[$this->currentkey][$k] = - (string) number_format($v, 2, '.', ''); - - return; - } - - /** - * @desc tri all result of top ten type - * @return void - */ - private function triTopTen() - { - foreach ($this->sort[$this->currentkey] as $sbas => $val) - { - foreach ($val as $id => $info) - { - foreach ($info as $k => $v) - { - if (is_int($v) || is_float($v)) - isset($this->sorted[$this->currentkey][$id][$k]) ? - $this->sorted[$this->currentkey][$id][$k] += $v : - $this->sorted[$this->currentkey][$id][$k] = $v; - elseif (is_string($v)) - $this->sorted[$this->currentkey][$id][$k] = $v; - else - $this->sorted[$this->currentkey][$id][$k] = null; + } } - } } - return; - } + /** + * @desc force value to string values + * this is the format to respect for displaying float results in + * SVG google charts + * + * @return void; + */ + private function toString() + { + foreach ($this->sorted[$this->currentkey] as $k => $v) + $this->sorted[$this->currentkey][$k] = + (string) number_format($v, 2, '.', ''); - /** - * @desc get only the number of result we wants - * @return dashboard_order - */ - public function top() - { - return new module_report_dashboard_sort($this); - } + return; + } + /** + * @desc tri all result of top ten type + * @return void + */ + private function triTopTen() + { + foreach ($this->sort[$this->currentkey] as $sbas => $val) { + foreach ($val as $id => $info) { + foreach ($info as $k => $v) { + if (is_int($v) || is_float($v)) + isset($this->sorted[$this->currentkey][$id][$k]) ? + $this->sorted[$this->currentkey][$id][$k] += $v : + $this->sorted[$this->currentkey][$id][$k] = $v; + elseif (is_string($v)) + $this->sorted[$this->currentkey][$id][$k] = $v; + else + $this->sorted[$this->currentkey][$id][$k] = null; + } + } + } + + return; + } + + /** + * @desc get only the number of result we wants + * @return dashboard_order + */ + public function top() + { + return new module_report_dashboard_sort($this); + } } ?> diff --git a/lib/classes/module/report/dashboard/sort.class.php b/lib/classes/module/report/dashboard/sort.class.php index 94c2f2418a..ea6bf5598f 100644 --- a/lib/classes/module/report/dashboard/sort.class.php +++ b/lib/classes/module/report/dashboard/sort.class.php @@ -17,178 +17,145 @@ */ class module_report_dashboard_sort implements module_report_dashboard_componentInterface { + public $arrayToSort = array(); + public $arraySorted = array(); - public $arrayToSort = array(); - public $arraySorted = array(); - - public function __construct(module_report_dashboard_merge $tridash) - { - if ($tridash->isValid()) + public function __construct(module_report_dashboard_merge $tridash) { - $this->arrayToSort = $tridash->getDash(); - } - $this->process(); - } - - public function process() - { - foreach ($this->arrayToSort as $key => $value) - { - switch ($key) - { - case "top_ten_user_doc": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_user_prev": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_user_poiddoc": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_user_poidprev": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_dl_preview": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_dl_document": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_question": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "ask": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_site": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - case "top_ten_added": - $this->arraySorted[$key] = $this->array_orderby( - $this->arrayToSort[$key], - 'nb', - SORT_DESC - ); - break; - default; - break; - } - } - } - - /** - * @desc tri les tableaux en fonction des parametres qu'on lui passe c'est la - * fonction array_multisort qui est appelée - * p1 : le tableau a trier, p2: la clef du tableau sur lequel on effectue le - * tri, p3 SORT_DESC ou SORT_ASC, - * - * @return array - */ - private function array_orderby() - { - //arguments - $args = func_get_args(); - //data = first argument - $data = array_shift($args); - - foreach ($args as $n => $field) - { - if (is_string($field)) // = clef - { - $tmp = array(); - foreach ($data as $key => $row) - $tmp[$key] = $row[$field]; - $args[$n] = &$tmp; - } - else - $args[$n] = &$field; - } - $args[] = &$data; - - call_user_func_array("array_multisort", $args); - - return array_pop($args); - } - - public function isValid() - { - if (isset($this->arraySorted) && sizeof($this->arraySorted) > 0) - - return true; - else - - return false; - } - - public function getDash() - { - return $this->arraySorted; - } - - public function getTop($nbtop) - { - if (!is_int($nbtop)) - - return array(); - - $tmp = array(); - - if ($this->isValid()) - { - foreach ($this->arraySorted as $k => $v) - { - $i = 0; - $tmp[$k] = array(); - foreach ($v as $a) - { - if ($i < $nbtop) - array_push($tmp[$k], $a); - else - break; - $i++; + if ($tridash->isValid()) { + $this->arrayToSort = $tridash->getDash(); } - } + $this->process(); } - return $tmp; - } + public function process() + { + foreach ($this->arrayToSort as $key => $value) { + switch ($key) { + case "top_ten_user_doc": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_user_prev": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_user_poiddoc": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_user_poidprev": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_dl_preview": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_dl_document": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_question": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "ask": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_site": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + case "top_ten_added": + $this->arraySorted[$key] = $this->array_orderby( + $this->arrayToSort[$key], 'nb', SORT_DESC + ); + break; + default; + break; + } + } + } + /** + * @desc tri les tableaux en fonction des parametres qu'on lui passe c'est la + * fonction array_multisort qui est appelée + * p1 : le tableau a trier, p2: la clef du tableau sur lequel on effectue le + * tri, p3 SORT_DESC ou SORT_ASC, + * + * @return array + */ + private function array_orderby() + { + //arguments + $args = func_get_args(); + //data = first argument + $data = array_shift($args); + + foreach ($args as $n => $field) { + if (is_string($field)) { // = clef + $tmp = array(); + foreach ($data as $key => $row) + $tmp[$key] = $row[$field]; + $args[$n] = &$tmp; + } + else + $args[$n] = &$field; + } + $args[] = &$data; + + call_user_func_array("array_multisort", $args); + + return array_pop($args); + } + + public function isValid() + { + if (isset($this->arraySorted) && sizeof($this->arraySorted) > 0) + return true; + else + return false; + } + + public function getDash() + { + return $this->arraySorted; + } + + public function getTop($nbtop) + { + if ( ! is_int($nbtop)) + return array(); + + $tmp = array(); + + if ($this->isValid()) { + foreach ($this->arraySorted as $k => $v) { + $i = 0; + $tmp[$k] = array(); + foreach ($v as $a) { + if ($i < $nbtop) + array_push($tmp[$k], $a); + else + break; + $i ++; + } + } + } + + return $tmp; + } } ?> diff --git a/lib/classes/module/report/download.class.php b/lib/classes/module/report/download.class.php index 5607e5b94e..9d793b3347 100644 --- a/lib/classes/module/report/download.class.php +++ b/lib/classes/module/report/download.class.php @@ -17,189 +17,176 @@ */ class module_report_download 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', + 'coll_id' => 'record.coll_id', + 'ddate' => "log_docs.date", + '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', + 'mime' => 'subdef.mime', + 'file' => 'subdef.file' + ); - 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' => "log_docs.date", - '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', - 'mime' => 'subdef.mime', - 'file' => 'subdef.file' - ); - - /** - * 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:: telechargements'); - } - - /** - * @desc build the specified requete - * @param $obj $conn the current connection to databox - * @return string - */ - protected function buildReq($groupby = false, $on = false) - { - $sql = $this->sqlBuilder('download') - ->setOn($on)->setGroupBy($groupby)->buildSql(); - - $this->req = $sql->getSql(); - $this->params = $sql->getParams(); - $this->total = $sql->getTotalRows(); - } - - public function colFilter($field, $on = false) - { - $ret = array(); - $s = $this->sqlBuilder('download'); - $var = $s->sqlDistinctValByField($field); - $sql = $var['sql']; - $params = $var['params']; - - $registry = registry::get_instance(); - - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - 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']; - if ($field == 'coll_id') - { - $caption = phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $value)); - } - elseif ($field == 'ddate') - $caption = phraseadate::getPrettyString(new DateTime($value)); - elseif ($field == 'size') - $caption = p4string::format_octets($value); - else - $caption = $value; - $ret[] = array('val' => $caption, 'value' => $value); + parent::__construct($arg1, $arg2, $sbas_id, $collist); + $this->title = _('report:: telechargements'); } - 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; - $pref = parent::getPreff($this->sbas_id); - - 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) { - if ($this->enable_limit && ($i > $this->nb_record)) - break; + $sql = $this->sqlBuilder('download') + ->setOn($on)->setGroupBy($groupby)->buildSql(); - foreach ($this->champ as $column) - { - $this->formatResult($column, $row[$column], $i); - } + $this->req = $sql->getSql(); + $this->params = $sql->getParams(); + $this->total = $sql->getTotalRows(); + } - if (array_key_exists('record_id', $row)) - { - $record = new \record_adapter($this->sbas_id, $row['record_id']); + public function colFilter($field, $on = false) + { + $ret = array(); + $s = $this->sqlBuilder('download'); + $var = $s->sqlDistinctValByField($field); + $sql = $var['sql']; + $params = $var['params']; - foreach ($pref as $field) - { - try - { - $this->result[$i][$field] = $record->get_caption() - ->get_field($field) - ->get_serialized_values(); - } - catch (\Exception $e) - { - $this->result[$i][$field] = ''; - } + $registry = registry::get_instance(); + + $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 == 'coll_id') { + $caption = phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $value)); + } elseif ($field == 'ddate') + $caption = phraseadate::getPrettyString(new DateTime($value)); + elseif ($field == 'size') + $caption = p4string::format_octets($value); + else + $caption = $value; + $ret[] = array('val' => $caption, 'value' => $value); } - } - $i++; - } - } - private function formatResult($column, $value, $i) - { - if ($value) + 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) { - if ($column == 'coll_id') - $this->result[$i][$column] = $this->formatCollId($value); - elseif ($column == 'ddate') - $this->result[$i][$column] = $this->formatDateValue($value); - elseif ($column == 'size') - $this->result[$i][$column] = p4string::format_octets($value); - else - $this->result[$i][$column] = $value; + $i = 0; + $pref = parent::getPreff($this->sbas_id); + + foreach ($rs as $row) { + if ($this->enable_limit && ($i > $this->nb_record)) + break; + + foreach ($this->champ as $column) { + $this->formatResult($column, $row[$column], $i); + } + + if (array_key_exists('record_id', $row)) { + $record = new \record_adapter($this->sbas_id, $row['record_id']); + + foreach ($pref as $field) { + try { + $this->result[$i][$field] = $record->get_caption() + ->get_field($field) + ->get_serialized_values(); + } catch (\Exception $e) { + $this->result[$i][$field] = ''; + } + } + } + $i ++; + } } - else + + private function formatResult($column, $value, $i) { - if ($column == 'comment') - $this->result[$i][$column] = ''; - else - $this->result[$i][$column] = $this->formatEmptyValue(); + if ($value) { + if ($column == 'coll_id') + $this->result[$i][$column] = $this->formatCollId($value); + elseif ($column == 'ddate') + $this->result[$i][$column] = $this->formatDateValue($value); + elseif ($column == 'size') + $this->result[$i][$column] = p4string::format_octets($value); + else + $this->result[$i][$column] = $value; + } + else { + if ($column == 'comment') + $this->result[$i][$column] = ''; + else + $this->result[$i][$column] = $this->formatEmptyValue(); + } } - } - private function formatEmptyValue() - { - return '' . _('report:: non-renseigne') . ''; - } + private function formatEmptyValue() + { + return '' . _('report:: non-renseigne') . ''; + } - private function formatDateValue($value) - { - $datetime = new DateTime($value); - $dateString = $datetime->format(DATE_ATOM); + private function formatDateValue($value) + { + $datetime = new DateTime($value); + $dateString = $datetime->format(DATE_ATOM); - return $this->pretty_string ? - phraseadate::getPrettyString($datetime) : $dateString; - } + return $this->pretty_string ? + phraseadate::getPrettyString($datetime) : $dateString; + } - private function formatCollId($value) - { - return phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $value)); - } + private function formatCollId($value) + { + return phrasea::bas_names(phrasea::baseFromColl($this->sbas_id, $value)); + } - public static function getNbDl($dmin, $dmax, $sbas_id, $list_coll_id) - { - $conn = connection::getPDOConnection($sbas_id); - $registry = registry::get_instance(); + public static function getNbDl($dmin, $dmax, $sbas_id, $list_coll_id) + { + $conn = connection::getPDOConnection($sbas_id); + $registry = registry::get_instance(); - $params = array(':site_id' => $registry->get('GV_sit')); - $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); - $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id); - $params = array_merge($params, $datefilter['params'], $collfilter['params']); + $params = array(':site_id' => $registry->get('GV_sit')); + $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); + $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id); + $params = array_merge($params, $datefilter['params'], $collfilter['params']); - $finalfilter = $datefilter['sql'] . ' AND '; - $finalfilter .= $collfilter['sql'] . ' AND '; - $finalfilter .= 'log.site = :site_id'; + $finalfilter = $datefilter['sql'] . ' AND '; + $finalfilter .= $collfilter['sql'] . ' AND '; + $finalfilter .= 'log.site = :site_id'; - $sql = ' + $sql = ' SELECT SUM(1) AS nb FROM ( log INNER JOIN log_docs as log_date ON log.id = log_date.log_id @@ -214,38 +201,38 @@ class module_report_download extends module_report ) ORDER BY log_date.date DESC '; - $stmt = $conn->prepare($sql); - $stmt->execute($params); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $row ? $row['nb'] : 0; - } + return $row ? $row['nb'] : 0; + } - public static function getTopDl($dmin, $dmax, $sbas_id, $list_coll_id) - { - $databox = \databox::get_instance((int) $sbas_id); - $conn = $databox->get_connection(); + public static function getTopDl($dmin, $dmax, $sbas_id, $list_coll_id) + { + $databox = \databox::get_instance((int) $sbas_id); + $conn = $databox->get_connection(); - $registry = $databox->get_registry(); + $registry = $databox->get_registry(); - $params = array(':site_id' => $registry->get('GV_sit')); - $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); - $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id); - $params = array_merge($params, $datefilter['params'], $collfilter['params']); + $params = array(':site_id' => $registry->get('GV_sit')); + $datefilter = module_report_sqlfilter::constructDateFilter($dmin, $dmax); + $collfilter = module_report_sqlfilter::constructCollectionFilter($list_coll_id); + $params = array_merge($params, $datefilter['params'], $collfilter['params']); - $finalfilter = ""; - $array = array( - 'preview' => array(), - 'document' => array() - ); + $finalfilter = ""; + $array = array( + 'preview' => array(), + 'document' => array() + ); - $finalfilter .= $datefilter['sql'] . ' AND '; - $finalfilter .= $collfilter['sql'] . ' AND '; - $finalfilter .= 'log.site = :site_id'; + $finalfilter .= $datefilter['sql'] . ' AND '; + $finalfilter .= $collfilter['sql'] . ' AND '; + $finalfilter .= 'log.site = :site_id'; - $sql = ' + $sql = ' SELECT record.record_id as id, SUM(1) AS nb, subdef.name FROM ( log INNER JOIN log_docs as log_date ON log.id = log_date.log_id @@ -263,36 +250,31 @@ class module_report_download extends module_report 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) - { - $record = $databox->get_record($row['id']); + foreach ($rs as $row) { + $record = $databox->get_record($row['id']); - $k = $row['id'] . '_' . $sbas_id; - $orig_name = $record->get_original_name(); + $k = $row['id'] . '_' . $sbas_id; + $orig_name = $record->get_original_name(); - if ($row['name'] == 'document') - { - $array[$row['name']][$k]['nb'] = (int) $row['nb']; - $array[$row['name']][$k]['lib'] = $orig_name; - $array[$row['name']][$k]['sbasid'] = $sbas_id; - $array[$row['name']][$k]['id'] = $row['id']; - } - elseif ($row['name'] == "preview") - { - $array[$row['name']][$k]['nb'] = (int) $row['nb']; - $array[$row['name']][$k]['lib'] = $orig_name; - $array[$row['name']][$k]['sbasid'] = $sbas_id; - $array[$row['name']][$k]['id'] = $row['id']; - } + if ($row['name'] == 'document') { + $array[$row['name']][$k]['nb'] = (int) $row['nb']; + $array[$row['name']][$k]['lib'] = $orig_name; + $array[$row['name']][$k]['sbasid'] = $sbas_id; + $array[$row['name']][$k]['id'] = $row['id']; + } elseif ($row['name'] == "preview") { + $array[$row['name']][$k]['nb'] = (int) $row['nb']; + $array[$row['name']][$k]['lib'] = $orig_name; + $array[$row['name']][$k]['sbasid'] = $sbas_id; + $array[$row['name']][$k]['id'] = $row['id']; + } + } + + return $array; } - - return $array; - } - } diff --git a/lib/classes/module/report/edit.class.php b/lib/classes/module/report/edit.class.php index de9e0c5bac..0622780bed 100644 --- a/lib/classes/module/report/edit.class.php +++ b/lib/classes/module/report/edit.class.php @@ -17,137 +17,116 @@ */ class module_report_edit 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:: edited documents'); - } - - /** - * @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('edit')->buildSql(); - $this->req = $s->getSql(); - $this->params = $s->getParams(); - $this->total = $s->getTotalRows(); - } - - public function colFilter($field, $on = false) - { - $s = $this->sqlBuilder('action')->setAction('edit'); - $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(); - - $appbox = appbox::get_instance(\bootstrap::getCore()); - - $ret = array(); - 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:: edited documents'); } - 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) { - if ($i >= $this->nb_record) - break; - 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++; + $s = $this->sqlBuilder('action')->setGroupBy($groupby)->setOn($on) + ->setAction('edit')->buildSql(); + $this->req = $s->getSql(); + $this->params = $s->getParams(); + $this->total = $s->getTotalRows(); } - } + public function colFilter($field, $on = false) + { + $s = $this->sqlBuilder('action')->setAction('edit'); + $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(); + + $appbox = appbox::get_instance(\bootstrap::getCore()); + + $ret = array(); + 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) { + if ($i >= $this->nb_record) + break; + 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 ++; + } + } } diff --git a/lib/classes/module/report/filter.class.php b/lib/classes/module/report/filter.class.php index 8422d759bf..3960dd90fe 100644 --- a/lib/classes/module/report/filter.class.php +++ b/lib/classes/module/report/filter.class.php @@ -17,118 +17,104 @@ */ class module_report_filter { + private $posting_filter = array(); + private $cor_query = array(); + private $active_column = array(); + private $trans = array( + 'user' => 'phraseanet::utilisateurs', + 'ddate' => 'report:: date', + 'ip' => 'report:: IP', + 'appli' => 'report:: modules', + 'fonction' => 'report::fonction', + 'activite' => 'report::activite', + 'pays' => 'report::pays', + 'societe' => 'report::societe', + 'record_id' => 'report:: record id', + 'final' => 'phraseanet:: sous definition', + 'coll_id' => 'report:: collections', + 'comment' => 'report:: commentaire', + 'search' => 'report:: question', + ); - private $posting_filter = array(); - private $cor_query = array(); - private $active_column = array(); - private $trans = array( - 'user' => 'phraseanet::utilisateurs', - 'ddate' => 'report:: date', - 'ip' => 'report:: IP', - 'appli' => 'report:: modules', - 'fonction' => 'report::fonction', - 'activite' => 'report::activite', - 'pays' => 'report::pays', - 'societe' => 'report::societe', - 'record_id' => 'report:: record id', - 'final' => 'phraseanet:: sous definition', - 'coll_id' => 'report:: collections', - 'comment' => 'report:: commentaire', - 'search' => 'report:: question', - ); - - public function __construct($current_filter, $correspondance) - { - $this->tab_filter = $current_filter; - $this->cor_query = $correspondance; - } - - private function checkSameFilter($field, $operator, $value) - { - $test = true; - if (sizeof($this->tab_filter) > 0) + public function __construct($current_filter, $correspondance) { - foreach ($this->tab_filter as $filters => $a_filter) - { - if (in_array($field, $a_filter) && - in_array($operator, $a_filter) && in_array($value, $a_filter)) - { - $test = false; - break; - } - elseif (in_array($field, $a_filter) && - in_array($operator, $a_filter) && !in_array($value, $a_filter)) - { - $a_filter['v'] = $value; - $test = false; - break; - } - } + $this->tab_filter = $current_filter; + $this->cor_query = $correspondance; } - return $test; - } - - public function addFilter($field, $operator, $value) - { - if ($this->checkSameFilter($field, $operator, $value)) - $this->tab_filter[] = array('f' => $field, 'o' => $operator, 'v' => $value); - } - - public function getPostingFilter() - { - if (sizeof($this->tab_filter) > 0) + private function checkSameFilter($field, $operator, $value) { - foreach ($this->tab_filter as $key => $filter) - { - if (empty($filter['v'])) - $value = _('report:: non-renseigne'); - else - $value = $filter['v']; - - if (array_key_exists($filter['f'], $this->trans)) - $field = _($this->trans[$filter['f']]); - else - $field = $filter['f']; - - if ($filter['f'] == 'appli') - { - $value = implode(' ', phrasea::modulesName(@unserialize($value))); - } - elseif ($filter['f'] == "ddate") - { - $value = phraseadate::getPrettyString(new DateTime($value)); + $test = true; + if (sizeof($this->tab_filter) > 0) { + foreach ($this->tab_filter as $filters => $a_filter) { + if (in_array($field, $a_filter) && + in_array($operator, $a_filter) && in_array($value, $a_filter)) { + $test = false; + break; + } elseif (in_array($field, $a_filter) && + in_array($operator, $a_filter) && ! in_array($value, $a_filter)) { + $a_filter['v'] = $value; + $test = false; + break; + } + } } - $this->posting_filter[] = array('f' => $field, 'v' => $value); - } + return $test; } - return $this->posting_filter; - } - - public function removeFilter($field) - { - foreach ($this->tab_filter as $key => $value) + public function addFilter($field, $operator, $value) { - if ($value['f'] == $field) - unset($this->tab_filter[$key]); + if ($this->checkSameFilter($field, $operator, $value)) + $this->tab_filter[] = array('f' => $field, 'o' => $operator, 'v' => $value); } - } - public function getActiveColumn() - { - foreach ($this->tab_filter as $key => $value) + public function getPostingFilter() { - $this->active_column[] = $value['f']; + if (sizeof($this->tab_filter) > 0) { + foreach ($this->tab_filter as $key => $filter) { + if (empty($filter['v'])) + $value = _('report:: non-renseigne'); + else + $value = $filter['v']; + + if (array_key_exists($filter['f'], $this->trans)) + $field = _($this->trans[$filter['f']]); + else + $field = $filter['f']; + + if ($filter['f'] == 'appli') { + $value = implode(' ', phrasea::modulesName(@unserialize($value))); + } elseif ($filter['f'] == "ddate") { + $value = phraseadate::getPrettyString(new DateTime($value)); + } + + $this->posting_filter[] = array('f' => $field, 'v' => $value); + } + } + + return $this->posting_filter; } - return $this->active_column; - } + public function removeFilter($field) + { + foreach ($this->tab_filter as $key => $value) { + if ($value['f'] == $field) + unset($this->tab_filter[$key]); + } + } - public function getTabFilter() - { - return $this->tab_filter; - } + public function getActiveColumn() + { + foreach ($this->tab_filter as $key => $value) { + $this->active_column[] = $value['f']; + } + return $this->active_column; + } + + public function getTabFilter() + { + return $this->tab_filter; + } } diff --git a/lib/classes/module/report/nav.class.php b/lib/classes/module/report/nav.class.php index 40f35f482b..b7fa07e115 100644 --- a/lib/classes/module/report/nav.class.php +++ b/lib/classes/module/report/nav.class.php @@ -17,60 +17,59 @@ */ class module_report_nav extends module_report { + /** + * @desc total of record on current report + * @var string + */ + public $total_pourcent = null; + public $config = false; + public $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' => "log.date", + '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' + ); - /** - * @desc total of record on current report - * @var string - */ - public $total_pourcent = null; - public $config = false; - public $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' => "log.date", - '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' - ); + /** + * constructor + * + * @name nav::__construct() + * @param $arg1 start date of the report + * @param $arg2 end date of the report + * @param $sbas_id databox id + */ + public function __construct($arg1, $arg2, $sbas_id, $collist) + { + parent::__construct($arg1, $arg2, $sbas_id, $collist); + $this->total_pourcent = $this->setTotalPourcent(); + } - /** - * constructor - * - * @name nav::__construct() - * @param $arg1 start date of the report - * @param $arg2 end date of the report - * @param $sbas_id databox id - */ - public function __construct($arg1, $arg2, $sbas_id, $collist) - { - parent::__construct($arg1, $arg2, $sbas_id, $collist); - $this->total_pourcent = $this->setTotalPourcent(); - } + private function setTotalPourcent() + { + $registry = registry::get_instance(); + $x = $this->getTransQueryString(); - private function setTotalPourcent() - { - $registry = registry::get_instance(); - $x = $this->getTransQueryString(); + $s = new module_report_sql($this); + $filter = $s->getFilters(); - $s = new module_report_sql($this); - $filter = $s->getFilters(); + $params = array(); + $report_filter = $filter->getReportFilter(); + $coll_filter = $filter->getCollectionFilter(); + $site_filter = $filter->getGvSitFilter(); + $params = array_merge($report_filter['params'], $coll_filter['params'], $site_filter['params']); - $params = array(); - $report_filter = $filter->getReportFilter(); - $coll_filter = $filter->getCollectionFilter(); - $site_filter = $filter->getGvSitFilter(); - $params = array_merge($report_filter['params'], $coll_filter['params'], $site_filter['params']); - - $sql = ' + $sql = ' SELECT SUM(1) AS total FROM log @@ -80,63 +79,62 @@ class module_report_nav extends module_report AND ' . $site_filter['sql'] . ' AND (' . $coll_filter['sql'] . ')'; - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $s->getConnBas()->prepare($sql); + $stmt->execute($params); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $row['total']; - } - - /** - * @desc empty $champ, $result, $display, $display_value - * @return void - */ - private function initialize() - { - $this->report['legend'] = array(); - $this->report['value'] = array(); - $this->result = array(); - $this->champ = array(); - $this->default_display = array(); - $this->display = array(); - } - - /** - * @desc return the filter to generate the good request - * @param object $conn the current connexion to appbox - * @return string - */ - private function getFilter() - { - return; - } - - /** - * @desc report the browser used by users - * @param array $tab config for the html table - * @return tab - */ - public function buildTabNav($tab = false) - { - $i = 0; - - $registry = registry::get_instance(); - - $s = new module_report_sql($this); - $filter = $s->getFilters(); - $this->title = _('report:: navigateur'); - - if (is_null($this->total_pourcent)) - { - return $this->report; + return $row['total']; } - $params = array(); - $report_filter = $filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); + /** + * @desc empty $champ, $result, $display, $display_value + * @return void + */ + private function initialize() + { + $this->report['legend'] = array(); + $this->report['value'] = array(); + $this->result = array(); + $this->champ = array(); + $this->default_display = array(); + $this->display = array(); + } - $sql = ' + /** + * @desc return the filter to generate the good request + * @param object $conn the current connexion to appbox + * @return string + */ + private function getFilter() + { + return; + } + + /** + * @desc report the browser used by users + * @param array $tab config for the html table + * @return tab + */ + public function buildTabNav($tab = false) + { + $i = 0; + + $registry = registry::get_instance(); + + $s = new module_report_sql($this); + $filter = $s->getFilters(); + $this->title = _('report:: navigateur'); + + if (is_null($this->total_pourcent)) { + return $this->report; + } + + $params = array(); + $report_filter = $filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); + + $sql = ' SELECT nav, COUNT(nav) AS nb, @@ -151,59 +149,56 @@ class module_report_nav extends module_report GROUP BY nav ORDER BY pourcent DESC'; - $this->initialize(); + $this->initialize(); - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $s->getConnBas()->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] = ($value == 'pourcent') ? $row[$value] . '%' : $row[$value]; - } - $this->report['value'][] = $row['nb']; - $this->report['legend'][] = $row['nav']; - $i++; + foreach ($rs as $row) { + foreach ($this->champ as $key => $value) { + $this->result[$i][$value] = ($value == 'pourcent') ? $row[$value] . '%' : $row[$value]; + } + $this->report['value'][] = $row['nb']; + $this->report['legend'][] = $row['nav']; + $i ++; + } + + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); + + return $this->report; } - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); - - return $this->report; - } - - /** - * @desc report the OS from user - * @param array $tab config for the html table - * @return array - */ - public function buildTabOs($tab = false) - { - - $registry = registry::get_instance(); - $s = new module_report_sql($this); - $filter = $s->getFilters(); - $i = 0; - $this->title = _('report:: Plateforme'); - - if (is_null($this->total_pourcent)) + /** + * @desc report the OS from user + * @param array $tab config for the html table + * @return array + */ + public function buildTabOs($tab = false) { - return $this->report; - } - $params = array(); - $report_filter = $filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); + $registry = registry::get_instance(); + $s = new module_report_sql($this); + $filter = $s->getFilters(); + $i = 0; + $this->title = _('report:: Plateforme'); - $sql = ' + if (is_null($this->total_pourcent)) { + return $this->report; + } + + $params = array(); + $report_filter = $filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); + + $sql = ' SELECT os, COUNT(os) AS nb, @@ -215,57 +210,54 @@ class module_report_nav extends module_report GROUP BY os ORDER BY pourcent DESC'; - $this->initialize(); + $this->initialize(); - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $s->getConnBas()->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] = ($value == 'pourcent') ? $row[$value] . '%' : $row[$value]; - } - $i++; - $this->report['value'][] = $row['nb']; - $this->report['legend'][] = $row['os']; - } - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); + foreach ($rs as $row) { + foreach ($this->champ as $key => $value) { + $this->result[$i][$value] = ($value == 'pourcent') ? $row[$value] . '%' : $row[$value]; + } + $i ++; + $this->report['value'][] = $row['nb']; + $this->report['legend'][] = $row['os']; + } + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); - return $this->report; - } - - /** - * @desc report the resolution that are using the users - * @param array $tab config for the html table - * @return array - */ - public function buildTabRes($tab = false) - { - - $registry = registry::get_instance(); - $s = new module_report_sql($this); - $filter = $s->getFilters(); - $this->title = _('report:: resolution'); - $i = 0; - if (is_null($this->total_pourcent)) - { - return($this->report); + return $this->report; } - $params = array(); - $report_filter = $filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); + /** + * @desc report the resolution that are using the users + * @param array $tab config for the html table + * @return array + */ + public function buildTabRes($tab = false) + { - $sql = ' + $registry = registry::get_instance(); + $s = new module_report_sql($this); + $filter = $s->getFilters(); + $this->title = _('report:: resolution'); + $i = 0; + if (is_null($this->total_pourcent)) { + return($this->report); + } + + $params = array(); + $report_filter = $filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); + + $sql = ' SELECT res, COUNT(res) AS nb, @@ -278,57 +270,54 @@ class module_report_nav extends module_report ORDER BY pourcent DESC LIMIT 0, 10'; - $this->initialize(); + $this->initialize(); - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $s->getConnBas()->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] = ($value == 'pourcent') ? - $row[$value] . '%' : $row[$value]; - } - $i++; - $this->report['value'][] = $row['nb']; - $this->report['legend'][] = $row['res']; + foreach ($rs as $row) { + foreach ($this->champ as $key => $value) { + $this->result[$i][$value] = ($value == 'pourcent') ? + $row[$value] . '%' : $row[$value]; + } + $i ++; + $this->report['value'][] = $row['nb']; + $this->report['legend'][] = $row['res']; + } + + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); + + return $this->report; } - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); - - return $this->report; - } - - /** - * @desc report the combination (OS - Navigateur) that are using the users - * @param array $tab config for the html table - */ - public function buildTabCombo($tab = false) - { - $s = new module_report_sql($this); - $filter = $s->getFilters(); - $this->title = _('report:: navigateurs et plateforme'); - $i = 0; - if (is_null($this->total_pourcent)) + /** + * @desc report the combination (OS - Navigateur) that are using the users + * @param array $tab config for the html table + */ + public function buildTabCombo($tab = false) { - return($this->report); - } + $s = new module_report_sql($this); + $filter = $s->getFilters(); + $this->title = _('report:: navigateurs et plateforme'); + $i = 0; + if (is_null($this->total_pourcent)) { + return($this->report); + } - $params = array(); - $report_filter = $filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); + $params = array(); + $report_filter = $filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); - $sql = " + $sql = " SELECT CONCAT( nav, '-', os ) AS combo, COUNT( CONCAT( nav, '-', os ) ) AS nb, @@ -344,60 +333,57 @@ class module_report_nav extends module_report ORDER BY nb DESC LIMIT 0 , 10"; - $this->initialize(); + $this->initialize(); - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $s->getConnBas()->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] = ($value == 'pourcent') ? - $row[$value] . '%' : $row[$value]; - } - $i++; - $this->report['value'][] = $row['nb']; - $this->report['legend'][] = $row['combo']; - } - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); + foreach ($rs as $row) { + foreach ($this->champ as $key => $value) { + $this->result[$i][$value] = ($value == 'pourcent') ? + $row[$value] . '%' : $row[$value]; + } + $i ++; + $this->report['value'][] = $row['nb']; + $this->report['legend'][] = $row['combo']; + } + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); - return $this->report; - } - - /** - * @desc report the most consulted module by the users - * @param array $tab - * @return array - */ - public function buildTabModule($tab = false) - { - $this->initialize(); - $registry = registry::get_instance(); - $s = new module_report_sql($this); - $filter = $s->getFilters(); - $this->title = _('report:: modules'); - $x = array(); - $tab_appli = array(); - - if (is_null($this->total_pourcent)) - { - return($this->report); + return $this->report; } - $params = array(); - $report_filter = $filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); + /** + * @desc report the most consulted module by the users + * @param array $tab + * @return array + */ + public function buildTabModule($tab = false) + { + $this->initialize(); + $registry = registry::get_instance(); + $s = new module_report_sql($this); + $filter = $s->getFilters(); + $this->title = _('report:: modules'); + $x = array(); + $tab_appli = array(); - $sql = ' + if (is_null($this->total_pourcent)) { + return($this->report); + } + + $params = array(); + $report_filter = $filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); + + $sql = ' SELECT appli FROM log @@ -408,107 +394,97 @@ class module_report_nav extends module_report ORDER BY appli DESC '; - $this->initialize(); + $this->initialize(); - $stmt = $s->getConnBas()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) - { - $applis = false; - if (($applis = @unserialize($row['appli'])) !== false) - array_push($x, phrasea::modulesName($applis)); - else - array_push($x, 'NULL'); - } - foreach ($x as $key => $tab_value) - { - if (is_array($tab_value)) - { - foreach ($tab_value as $key2 => $value) - { - if (!isset($tab_appli[$value])) - $tab_appli[$value] = 0; - $tab_appli[$value]++; - } - } - } - $total = array_sum($tab_appli); - - $this->setChamp($rs); - $this->setDisplay($tab); - - foreach ($tab_appli as $appli => $nb) - { - $pourcent = round(($nb / $total) * 100, 1); - foreach ($this->champ as $key => $value) - { - $this->result[] = array( - 'appli' => $appli, - 'nb' => $nb, - 'pourcent' => $pourcent . '%' - ); - } - $this->report['value'][] = $nb; - $this->report['legend'][] = $appli; - } - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); - - return $this->report; - } - - /** - * @desc report basic user informations - * @param int $val user id - * @param array $tab config for the html table - * @param string $on the field - * @return array - */ - public function buildTabGrpInfo($req, array $params, $val, $tab = false, $on = false) - { - - $this->initialize(); - $registry = registry::get_instance(); - empty($on) ? $on = false : ""; - $filter_id_apbox = $filter_id_datbox = array(); - $conn = connection::getPDOConnection(); - $conn2 = connection::getPDOConnection($this->sbas_id); - - - $datefilter = array(); - - if ($this->dmin && $this->dmax) - { - $params = array(':dmin' => $this->dmin, ':dmax' => $this->dmax); - $datefilter = "date > :dmin AND date < :dmax"; - } - - $this->title = sprintf(_('report:: Information sur les utilisateurs correspondant a %s'), $val); - - if ($on) - { - if (!empty($req)) - { - $stmt = $conn2->prepare($req); + $stmt = $s->getConnBas()->prepare($sql); $stmt->execute($params); - $rsu = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rsu as $row_user) - { - $filter_id_apbox[] = "usr_id = " . (int) $row_user['usrid']; - $filter_id_datbox[] = "log.usrid = " . (int) $row_user['usrid']; + foreach ($rs as $row) { + $applis = false; + if (($applis = @unserialize($row['appli'])) !== false) + array_push($x, phrasea::modulesName($applis)); + else + array_push($x, 'NULL'); } - $filter_id_apbox = implode(' OR ', $filter_id_apbox); - $filter_id_datbox = implode(' OR ', $filter_id_datbox); - } + foreach ($x as $key => $tab_value) { + if (is_array($tab_value)) { + foreach ($tab_value as $key2 => $value) { + if ( ! isset($tab_appli[$value])) + $tab_appli[$value] = 0; + $tab_appli[$value] ++; + } + } + } + $total = array_sum($tab_appli); - $sql = " + $this->setChamp($rs); + $this->setDisplay($tab); + + foreach ($tab_appli as $appli => $nb) { + $pourcent = round(($nb / $total) * 100, 1); + foreach ($this->champ as $key => $value) { + $this->result[] = array( + 'appli' => $appli, + 'nb' => $nb, + 'pourcent' => $pourcent . '%' + ); + } + $this->report['value'][] = $nb; + $this->report['legend'][] = $appli; + } + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); + + return $this->report; + } + + /** + * @desc report basic user informations + * @param int $val user id + * @param array $tab config for the html table + * @param string $on the field + * @return array + */ + public function buildTabGrpInfo($req, array $params, $val, $tab = false, $on = false) + { + + $this->initialize(); + $registry = registry::get_instance(); + empty($on) ? $on = false : ""; + $filter_id_apbox = $filter_id_datbox = array(); + $conn = connection::getPDOConnection(); + $conn2 = connection::getPDOConnection($this->sbas_id); + + + $datefilter = array(); + + if ($this->dmin && $this->dmax) { + $params = array(':dmin' => $this->dmin, ':dmax' => $this->dmax); + $datefilter = "date > :dmin AND date < :dmax"; + } + + $this->title = sprintf(_('report:: Information sur les utilisateurs correspondant a %s'), $val); + + if ($on) { + if ( ! empty($req)) { + $stmt = $conn2->prepare($req); + $stmt->execute($params); + $rsu = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rsu as $row_user) { + $filter_id_apbox[] = "usr_id = " . (int) $row_user['usrid']; + $filter_id_datbox[] = "log.usrid = " . (int) $row_user['usrid']; + } + $filter_id_apbox = implode(' OR ', $filter_id_apbox); + $filter_id_datbox = implode(' OR ', $filter_id_datbox); + } + + $sql = " SELECT usr_login as identifiant, usr_nom as nom, @@ -516,10 +492,8 @@ class module_report_nav extends module_report adresse, tel FROM usr WHERE $on = :value AND (" . $filter_id_apbox . ")"; - } - else - { - $sql = ' + } else { + $sql = ' SELECT usr_login AS identifiant, usr_nom AS nom, @@ -528,117 +502,114 @@ class module_report_nav extends module_report tel FROM usr WHERE (usr_id = :value)'; + } + + $params2 = array(':value' => $val); + $stmt = $conn->prepare($sql); + $stmt->execute($params2); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $this->setChamp($rs); + $this->setDisplay($tab); + + foreach ($rs as $row) { + foreach ($row as $fieldname => $value) + $row[$fieldname] = $value ? $value : _('report:: non-renseigne'); + $this->result[] = $row; + } + if ($on == false) { + $login = empty($this->result[0]['identifiant']) ? + _('phraseanet::utilisateur inconnu') : + $this->result[0]['identifiant']; + + $this->title = sprintf( + _('report:: Information sur l\'utilisateur %s'), $login + ); + } + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); + + return $this->report; } - $params2 = array(':value' => $val); - $stmt = $conn->prepare($sql); - $stmt->execute($params2); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $this->setChamp($rs); - $this->setDisplay($tab); - - foreach ($rs as $row) + /** + * @desc return basic information about a record + * @param $ses session id + * @param $bid base id + * @param $rid record id + * @param $tab config for the html table + * @return array + */ + public function buildTabUserWhat($bid, $rid, $tab = false) { - foreach ($row as $fieldname => $value) - $row[$fieldname] = $value ? $value : _('report:: non-renseigne'); - $this->result[] = $row; - } - if ($on == false) - { - $login = empty($this->result[0]['identifiant']) ? - _('phraseanet::utilisateur inconnu') : - $this->result[0]['identifiant']; + $this->initialize(); + $sbas_id = phrasea::sbasFromBas($bid); + $record = new record_adapter($sbas_id, $rid); - $this->title = sprintf( - _('report:: Information sur l\'utilisateur %s'), $login - ); - } - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); + $this->setDisplay($tab); + $this->champ = array( + 'photo', + 'record_id', + 'date', + 'type', + 'titre', + 'taille' + ); - return $this->report; - } - - /** - * @desc return basic information about a record - * @param $ses session id - * @param $bid base id - * @param $rid record id - * @param $tab config for the html table - * @return array - */ - public function buildTabUserWhat($bid, $rid, $tab = false) - { - $this->initialize(); - $sbas_id = phrasea::sbasFromBas($bid); - $record = new record_adapter($sbas_id, $rid); - - $this->setDisplay($tab); - $this->champ = array( - 'photo', - 'record_id', - 'date', - 'type', - 'titre', - 'taille' - ); - - $document = $record->get_subdef('document'); - $this->title = sprintf( + $document = $record->get_subdef('document'); + $this->title = sprintf( _('report:: Information sur l\'enregistrement numero %d'), (int) $rid); - $x = $record->get_thumbnail(); - $this->result[] = array( - 'photo' => - "get_thumbnail(); + $this->result[] = array( + 'photo' => + "" - , 'record_id' => $record->get_record_id() - , 'date' => phraseadate::getPrettyString($document->get_creation_date()) - , 'type' => $document->get_mime() - , 'titre' => $record->get_title() - , 'taille' => $document->get_size() - ); + , 'record_id' => $record->get_record_id() + , 'date' => phraseadate::getPrettyString($document->get_creation_date()) + , 'type' => $document->get_mime() + , 'titre' => $record->get_title() + , 'taille' => $document->get_size() + ); - $this->setDisplayNav(); - $this->setReport(); + $this->setDisplayNav(); + $this->setReport(); - return $this->report; - } + return $this->report; + } - public function buildTabInfoNav($tab = false, $navigator) - { - $conn = connection::getPDOConnection($this->sbas_id); - $this->title = sprintf( + public function buildTabInfoNav($tab = false, $navigator) + { + $conn = connection::getPDOConnection($this->sbas_id); + $this->title = sprintf( _('report:: Information sur le navigateur %s'), $navigator); - $params = array(':browser' => $navigator); + $params = array(':browser' => $navigator); - $sql = "SELECT DISTINCT(version) as version, COUNT(version) as nb + $sql = "SELECT DISTINCT(version) as version, COUNT(version) as nb FROM log WHERE nav = :browser GROUP BY version 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(); - $this->setChamp($rs); - $this->setDisplay($tab); + $this->setChamp($rs); + $this->setDisplay($tab); - $this->result = $rs; - $this->total = sizeof($this->result); - $this->calculatePages($rs); - $this->setDisplayNav(); - $this->setReport(); - - return $this->report; - } + $this->result = $rs; + $this->total = sizeof($this->result); + $this->calculatePages($rs); + $this->setDisplayNav(); + $this->setReport(); + return $this->report; + } } diff --git a/lib/classes/module/report/push.class.php b/lib/classes/module/report/push.class.php index 114db7d36c..9785071bff 100644 --- a/lib/classes/module/report/push.class.php +++ b/lib/classes/module/report/push.class.php @@ -17,138 +17,117 @@ */ class module_report_push 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:: pushed documents'); - } - - /** - * @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('push')->buildSql(); - $this->req = $s->getSql(); - $this->params = $s->getParams(); - $this->total = $s->getTotalRows(); - } - - public function colFilter($field, $on = false) - { - $s = $this->sqlBuilder('action')->setAction('push'); - $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(); - - 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:: pushed documents'); } - 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) { - if ($i >= $this->nb_record) - break; - 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++; + $s = $this->sqlBuilder('action')->setGroupBy($groupby)->setOn($on) + ->setAction('push')->buildSql(); + $this->req = $s->getSql(); + $this->params = $s->getParams(); + $this->total = $s->getTotalRows(); } - } + public function colFilter($field, $on = false) + { + $s = $this->sqlBuilder('action')->setAction('push'); + $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(); + + 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) { + if ($i >= $this->nb_record) + break; + 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 ++; + } + } } diff --git a/lib/classes/module/report/question.class.php b/lib/classes/module/report/question.class.php index d09d101532..8e4958887c 100644 --- a/lib/classes/module/report/question.class.php +++ b/lib/classes/module/report/question.class.php @@ -17,101 +17,95 @@ */ class module_report_question extends module_report { + protected $cor_query = array( + 'user' => 'log.user' + , 'usrid' => 'log.usrid' + , 'ddate' => 'log_search.date' + , 'date' => 'log_search.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_search.date' - , 'date' => 'log_search.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 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:: question'); - } - - /** - * @desc build the specified requete - * @param $obj $conn the current connection to databox - * @return string - */ - protected function buildReq($groupby = false) - { - $sql = $this->sqlBuilder('question')->setGroupBy($groupby)->buildSql(); - $this->req = $sql->getSql(); - $this->params = $sql->getParams(); - $this->total = $sql->getTotalRows(); - } - - public function colFilter($field) - { - $ret = array(); - $s = $this->sqlBuilder('question'); - $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 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']; - if ($field == 'appli') - $caption = implode(' ', phrasea::modulesName(@unserialize($row['val']))); - 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:: question'); } - return $ret; - } - - protected function buildResult($rs) - { - $tab = array(); - $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 ($row[$value]) - { - if ($value == 'ddate') - $this->result[$i][$value] = - $this->pretty_string ? phraseadate::getPrettyString(new DateTime($row[$value])) : $row[$value]; - else - $this->result[$i][$value] = $row[$value]; + $sql = $this->sqlBuilder('question')->setGroupBy($groupby)->buildSql(); + $this->req = $sql->getSql(); + $this->params = $sql->getParams(); + $this->total = $sql->getTotalRows(); + } + + public function colFilter($field) + { + $ret = array(); + $s = $this->sqlBuilder('question'); + $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($row['val']))); + elseif ($field == "ddate") + $caption = phraseadate::getPrettyString(new DateTime($value)); + else + $caption = $row['val']; + $ret[] = array('val' => $caption, 'value' => $value); } - else - $this->result[$i][$value] = "" . _('report:: non-renseigne') . ""; - } - $i++; - } - } + return $ret; + } + + protected function buildResult($rs) + { + $tab = array(); + $i = 0; + foreach ($rs as $row) { + if ($this->enable_limit && ($i > $this->nb_record)) + break; + foreach ($this->champ as $key => $value) { + if ($row[$value]) { + if ($value == 'ddate') + $this->result[$i][$value] = + $this->pretty_string ? phraseadate::getPrettyString(new DateTime($row[$value])) : $row[$value]; + else + $this->result[$i][$value] = $row[$value]; + } + else + $this->result[$i][$value] = "" . _('report:: non-renseigne') . ""; + } + $i ++; + } + } } diff --git a/lib/classes/module/report/sql.class.php b/lib/classes/module/report/sql.class.php index 53db66e54f..618d30bba0 100644 --- a/lib/classes/module/report/sql.class.php +++ b/lib/classes/module/report/sql.class.php @@ -17,115 +17,114 @@ */ class module_report_sql { + /** + * + * @var connection_PDO + */ + public $conn; - /** - * - * @var connection_PDO - */ - public $conn; - /** - * - * @var connection_PDO - */ - public $connbas; - /** - * - * @var module_report_sqlfilter - */ - public $filter; - public $sql; - public $params; - public $total_row; - public $enable_limit; - public $groupby = false; - public $on = false; + /** + * + * @var connection_PDO + */ + public $connbas; - public function __construct(module_report $report) - { - $this->conn = connection::getPDOConnection(); - $this->connbas = connection::getPDOConnection($report->getSbasId()); - $this->filter = new module_report_sqlfilter($report); - $this->sql = ''; - $this->params = array(); - $this->total_row = 0; - $this->enable_limit = $report->getEnableLimit(); - } + /** + * + * @var module_report_sqlfilter + */ + public $filter; + public $sql; + public $params; + public $total_row; + public $enable_limit; + public $groupby = false; + public $on = false; - public function setGroupBy($groupby) - { - $this->groupby = $groupby; + public function __construct(module_report $report) + { + $this->conn = connection::getPDOConnection(); + $this->connbas = connection::getPDOConnection($report->getSbasId()); + $this->filter = new module_report_sqlfilter($report); + $this->sql = ''; + $this->params = array(); + $this->total_row = 0; + $this->enable_limit = $report->getEnableLimit(); + } - return $this; - } + public function setGroupBy($groupby) + { + $this->groupby = $groupby; - public function getGroupby() - { - return $this->groupby; - } + return $this; + } - public function setOn($on) - { - $this->on = $on; + public function getGroupby() + { + return $this->groupby; + } - return $this; - } + public function setOn($on) + { + $this->on = $on; - public function getOn() - { - return $this->on; - } + return $this; + } - public function setFilter(module_report_sqlfilter $filter) - { - $this->filter = $filter; - } - /** - * - * @return module_report_sqlfilter - */ - public function getFilters() - { - return $this->filter; - } + public function getOn() + { + return $this->on; + } - public function getSql() - { - return $this->sql; - } + public function setFilter(module_report_sqlfilter $filter) + { + $this->filter = $filter; + } - public function getParams() - { - return $this->params; - } + /** + * + * @return module_report_sqlfilter + */ + public function getFilters() + { + return $this->filter; + } - public function getTotalRows() - { - return $this->total_row; - } + public function getSql() + { + return $this->sql; + } - public function setTotalrows($total) - { - $this->total_row = $total; - } + public function getParams() + { + return $this->params; + } - public function getTransQuery($champ) - { - $tanslation = $this->filter->getCorFilter(); - if (array_key_exists($champ, $tanslation)) + public function getTotalRows() + { + return $this->total_row; + } - return $tanslation[$champ]; - else + public function setTotalrows($total) + { + $this->total_row = $total; + } - return $champ; - } - - /** - * - * @return connection_PDO - */ - public function getConnBas() - { - return $this->connbas; - } + public function getTransQuery($champ) + { + $tanslation = $this->filter->getCorFilter(); + if (array_key_exists($champ, $tanslation)) + return $tanslation[$champ]; + else + return $champ; + } + /** + * + * @return connection_PDO + */ + public function getConnBas() + { + return $this->connbas; + } } diff --git a/lib/classes/module/report/sqlReportInterface.class.php b/lib/classes/module/report/sqlReportInterface.class.php index c2c1037da4..87cc2684f4 100644 --- a/lib/classes/module/report/sqlReportInterface.class.php +++ b/lib/classes/module/report/sqlReportInterface.class.php @@ -17,7 +17,8 @@ */ interface module_report_sqlReportinterface { - public function buildSql(); - public function sqlDistinctValByField($field); + public function buildSql(); + + public function sqlDistinctValByField($field); } diff --git a/lib/classes/module/report/sqlaction.class.php b/lib/classes/module/report/sqlaction.class.php index d9b6f5d264..eb9ad1035c 100644 --- a/lib/classes/module/report/sqlaction.class.php +++ b/lib/classes/module/report/sqlaction.class.php @@ -17,41 +17,39 @@ */ class module_report_sqlaction extends module_report_sql implements module_report_sqlReportInterface { + private $action = 'add'; - private $action = 'add'; - - public function __construct(module_report $report) - { - parent::__construct($report); - } - - public function setAction($action) - { - //possible action - $a = array('edit', 'add', 'push', 'validate'); - if (in_array($action, $a)) - $this->action = $action; - - return $this; - } - - public function getAction() - { - return $this->action; - } - - public function buildSql() - { - if ($this->groupby == false) + public function __construct(module_report $report) { - $params = array(':action' => $this->action); - $site_filter = $this->filter->getGvSitFilter()?: array('params' => array(), 'sql' => false); - $report_filter = $this->filter->getReportFilter() ?: array('params' => array(), 'sql' => false); - $record_filter = $this->filter->getRecordFilter() ?: array('params' => array(), 'sql' => false); - $params = array_merge($params, $site_filter['params'], $report_filter['params'], $record_filter['params']); + parent::__construct($report); + } - $this->sql = - " + public function setAction($action) + { + //possible action + $a = array('edit', 'add', 'push', 'validate'); + if (in_array($action, $a)) + $this->action = $action; + + return $this; + } + + public function getAction() + { + return $this->action; + } + + public function buildSql() + { + if ($this->groupby == false) { + $params = array(':action' => $this->action); + $site_filter = $this->filter->getGvSitFilter()? : array('params' => array(), 'sql' => false); + $report_filter = $this->filter->getReportFilter() ? : array('params' => array(), 'sql' => false); + $record_filter = $this->filter->getRecordFilter() ? : array('params' => array(), 'sql' => false); + $params = array_merge($params, $site_filter['params'], $report_filter['params'], $record_filter['params']); + + $this->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'] . " @@ -60,31 +58,29 @@ class module_report_sqlaction extends module_report_sql implements module_report LEFT JOIN subdef as s ON s.record_id=d.record_id and s.name='document') WHERE"; - $this->sql .= $report_filter['sql'] . " AND (d.action = :action)"; + $this->sql .= $report_filter['sql'] . " AND (d.action = :action)"; - $this->sql .= $record_filter['sql'] ? " AND (" . $record_filter['sql'] . ")" : ""; + $this->sql .= $record_filter['sql'] ? " AND (" . $record_filter['sql'] . ")" : ""; - $this->sql .= $this->filter->getOrderFilter(); + $this->sql .= $this->filter->getOrderFilter(); - $stmt = $this->getConnBas()->prepare($this->sql); + $stmt = $this->getConnBas()->prepare($this->sql); - $this->total = $stmt->rowCount(); - $stmt->closeCursor(); + $this->total = $stmt->rowCount(); + $stmt->closeCursor(); - $this->sql .= $this->filter->getLimitFilter() ?: ''; + $this->sql .= $this->filter->getLimitFilter() ? : ''; - $this->params = $params; - } - else - { + $this->params = $params; + } else { - $params = array(':action' => $this->action); - $site_filter = $this->filter->getGvSitFilter()?: array('params' => array(), 'sql' => false); - $report_filter = $this->filter->getReportFilter() ?: array('params' => array(), 'sql' => false); - $record_filter = $this->filter->getRecordFilter() ?: array('params' => array(), 'sql' => false); - $params = array_merge($params, $site_filter['params'], $report_filter['params'], $record_filter['params']); + $params = array(':action' => $this->action); + $site_filter = $this->filter->getGvSitFilter()? : array('params' => array(), 'sql' => false); + $report_filter = $this->filter->getReportFilter() ? : array('params' => array(), 'sql' => false); + $record_filter = $this->filter->getRecordFilter() ? : array('params' => array(), 'sql' => false); + $params = array_merge($params, $site_filter['params'], $report_filter['params'], $record_filter['params']); - $this->sql = " + $this->sql = " SELECT TRIM(" . $this->getTransQuery($this->groupby) . ") as " . $this->groupby . ", SUM(1) as nombre @@ -95,34 +91,34 @@ class module_report_sqlaction extends module_report_sql implements module_report LEFT JOIN subdef as s ON s.record_id=d.record_id and s.name='document') WHERE "; - $this->sql .= $report_filter['sql'] . " AND (d.action = :action)"; + $this->sql .= $report_filter['sql'] . " AND (d.action = :action)"; - $this->sql .= $record_filter['sql'] ? "AND (" . $record_filter['sql'] . ")" : ""; + $this->sql .= $record_filter['sql'] ? "AND (" . $record_filter['sql'] . ")" : ""; - $this->sql .= " GROUP BY " . $this->groupby; - $this->sql .= $this->filter->getOrderFilter(); + $this->sql .= " GROUP BY " . $this->groupby; + $this->sql .= $this->filter->getOrderFilter(); - $this->params = $params; + $this->params = $params; - $stmt = $this->getConnBas()->prepare($this->sql); - $stmt->execute($params); - $this->total = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->getConnBas()->prepare($this->sql); + $stmt->execute($params); + $this->total = $stmt->rowCount(); + $stmt->closeCursor(); + } + + return $this; } - return $this; - } + public function sqlDistinctValByField($field) + { - public function sqlDistinctValByField($field) - { + $params = array(); + $site_filter = $this->filter->getGvSitFilter(); + $date_filter = $this->filter->getDateFilter(); - $params = array(); - $site_filter = $this->filter->getGvSitFilter(); - $date_filter = $this->filter->getDateFilter(); + $params = array_merge($params, $site_filter['params'], $date_filter['params']); //, $record_filter ? $record_filter['params'] : array() - $params = array_merge($params, $site_filter['params'], $date_filter['params']);//, $record_filter ? $record_filter['params'] : array() - - $sql = " + $sql = " SELECT DISTINCT(" . $this->getTransQuery($field) . ") as val FROM (log_docs as d INNER JOIN log ON (" . $site_filter['sql'] . " @@ -132,16 +128,14 @@ class module_report_sqlaction extends module_report_sql implements module_report LEFT JOIN subdef as s ON (s.record_id=d.record_id AND s.name='document')) WHERE "; - if ($this->filter->getReportFilter()) - { - $report_filter = $this->filter->getReportFilter(); - $sql .= $report_filter['sql'] . " AND (d.action = :action)"; - $params = array_merge($params, $report_filter['params'], array(':action' => $this->action)); + if ($this->filter->getReportFilter()) { + $report_filter = $this->filter->getReportFilter(); + $sql .= $report_filter['sql'] . " AND (d.action = :action)"; + $params = array_merge($params, $report_filter['params'], array(':action' => $this->action)); + } + $this->sql .= $this->filter->getOrderFilter(); + $this->params = $params; + + return array('sql' => $sql, 'params' => $params); } - $this->sql .= $this->filter->getOrderFilter(); - $this->params = $params; - - return array('sql' => $sql, 'params' => $params); - } - } diff --git a/lib/classes/module/report/sqlconnexion.class.php b/lib/classes/module/report/sqlconnexion.class.php index 039e3a223e..7a39cb652c 100644 --- a/lib/classes/module/report/sqlconnexion.class.php +++ b/lib/classes/module/report/sqlconnexion.class.php @@ -15,24 +15,22 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ -class module_report_sqlconnexion extends module_report_sql -implements module_report_sqlReportInterface +class module_report_sqlconnexion extends module_report_sql implements module_report_sqlReportInterface { - public function __construct(module_report $report) - { - parent::__construct($report); - } - - public function buildSql() - { - $report_filter = $this->filter->getReportFilter(); - $params = $report_filter['params']; - - $this->params = $params; - if ($this->groupby == false) + public function __construct(module_report $report) { - $this->sql = " + parent::__construct($report); + } + + public function buildSql() + { + $report_filter = $this->filter->getReportFilter(); + $params = $report_filter['params']; + + $this->params = $params; + if ($this->groupby == false) { + $this->sql = " SELECT user, usrid, @@ -48,56 +46,53 @@ implements module_report_sqlReportInterface ip FROM log"; - $this->sql .= " WHERE " . $report_filter['sql']; - $this->sql .= $this->filter->getOrderFilter() ?: ''; + $this->sql .= " WHERE " . $report_filter['sql']; + $this->sql .= $this->filter->getOrderFilter() ? : ''; - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($params); - $this->total_row = $stmt->rowCount(); - $stmt->closeCursor(); - if($this->enable_limit) - $this->sql .= $this->filter->getLimitFilter() ?: ''; - - } - else - { - $this->sql = " + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($params); + $this->total_row = $stmt->rowCount(); + $stmt->closeCursor(); + if ($this->enable_limit) + $this->sql .= $this->filter->getLimitFilter() ? : ''; + } + else { + $this->sql = " SELECT TRIM(" . $this->getTransQuery($this->groupby) . ") as " . $this->groupby . ", SUM(1) as nb FROM log "; - if ($report_filter['sql']) - $this->sql .= " WHERE " . $report_filter['sql']; + if ($report_filter['sql']) + $this->sql .= " WHERE " . $report_filter['sql']; - $this->sql .= " GROUP BY " . $this->groupby; - $this->sql .= $this->filter->getOrderFilter() ?: ''; + $this->sql .= " GROUP BY " . $this->groupby; + $this->sql .= $this->filter->getOrderFilter() ? : ''; - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($params); - $this->total_row = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($params); + $this->total_row = $stmt->rowCount(); + $stmt->closeCursor(); + } + + return $this; } - return $this; - } + public function sqlDistinctValByField($field) + { + $report_filter = $this->filter->getReportFilter(); + $params = $report_filter['params']; - public function sqlDistinctValByField($field) - { - $report_filter = $this->filter->getReportFilter(); - $params = $report_filter['params']; - - $sql = 'SELECT DISTINCT(' . $this->getTransQuery($field) . ') as val + $sql = 'SELECT DISTINCT(' . $this->getTransQuery($field) . ') as val FROM log '; - if ($report_filter['sql']) - $sql .= ' WHERE ' . $report_filter['sql']; + if ($report_filter['sql']) + $sql .= ' WHERE ' . $report_filter['sql']; - $sql .= ' ORDER BY val ASC'; - - return array('sql' => $sql, 'params' => $params); - } + $sql .= ' ORDER BY val ASC'; + return array('sql' => $sql, 'params' => $params); + } } diff --git a/lib/classes/module/report/sqldownload.class.php b/lib/classes/module/report/sqldownload.class.php index 04052e0fab..4f16ba1d35 100644 --- a/lib/classes/module/report/sqldownload.class.php +++ b/lib/classes/module/report/sqldownload.class.php @@ -17,28 +17,25 @@ */ class module_report_sqldownload extends module_report_sql implements module_report_sqlReportInterface { + protected $restrict = false; - protected $restrict = false; - - public function __construct(module_report $report) - { - parent::__construct($report); - if($report->isInformative()) + public function __construct(module_report $report) { - $this->restrict = true; + parent::__construct($report); + if ($report->isInformative()) { + $this->restrict = true; + } } - } - public function buildSql() - { - $registry = registry::get_instance(); - $report_filters = $this->filter->getReportFilter(); - $record_filters = $this->filter->getRecordFilter() ? : array('sql' => '', 'params' => array()); - $this->params = array_merge($report_filters['params'], $record_filters['params']); - - if ($this->groupby == false) + public function buildSql() { - $this->sql = " + $registry = registry::get_instance(); + $report_filters = $this->filter->getReportFilter(); + $record_filters = $this->filter->getRecordFilter() ? : array('sql' => '', 'params' => array()); + $this->params = array_merge($report_filters['params'], $record_filters['params']); + + if ($this->groupby == false) { + $this->sql = " SELECT log.user, log.site, @@ -60,30 +57,28 @@ class module_report_sqldownload extends module_report_sql implements module_repo ) WHERE "; - $this->sql .= $report_filters['sql'] ? : ''; + $this->sql .= $report_filters['sql'] ? : ''; - $this->sql .= ' AND ( log_docs.action = \'download\' OR log_docs.action = \'mail\')'; - if($this->restrict) - $this->sql .= ' AND ( log_docs.final = "document" OR log_docs.final = "preview")'; - $this->sql .= empty($record_filters['sql']) ? '' : ' AND ( ' . $record_filters['sql'] . ' )'; + $this->sql .= ' AND ( log_docs.action = \'download\' OR log_docs.action = \'mail\')'; + if ($this->restrict) + $this->sql .= ' AND ( log_docs.final = "document" OR log_docs.final = "preview")'; + $this->sql .= empty($record_filters['sql']) ? '' : ' AND ( ' . $record_filters['sql'] . ' )'; - $this->sql .= $this->filter->getOrderFilter() ? : ''; + $this->sql .= $this->filter->getOrderFilter() ? : ''; - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($this->params); - $this->total_row = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($this->params); + $this->total_row = $stmt->rowCount(); + $stmt->closeCursor(); - $this->sql .= $this->filter->getLimitFilter() ? : ''; - } - else - { - $name = $this->groupby; - $field = $this->getTransQuery($this->groupby); + $this->sql .= $this->filter->getLimitFilter() ? : ''; + } + else { + $name = $this->groupby; + $field = $this->getTransQuery($this->groupby); - if ($name == 'record_id' && $this->on == 'DOC') - { - $this->sql = ' + if ($name == 'record_id' && $this->on == 'DOC') { + $this->sql = ' SELECT TRIM( ' . $field . ' ) AS ' . $name . ', SUM(1) AS telechargement, @@ -102,10 +97,8 @@ class module_report_sqldownload extends module_report_sql implements module_repo ) WHERE '; - } - elseif ($this->on == 'DOC') - { - $this->sql = ' + } elseif ($this->on == 'DOC') { + $this->sql = ' SELECT TRIM(' . $field . ') AS ' . $name . ', SUM(1) AS telechargement @@ -118,11 +111,9 @@ class module_report_sqldownload extends module_report_sql implements module_repo ) WHERE '; - } - else - { + } else { - $this->sql = ' + $this->sql = ' SELECT TRIM( ' . $this->getTransQuery($this->groupby) . ') AS ' . $name . ', SUM(1) AS nombre @@ -132,41 +123,41 @@ class module_report_sqldownload extends module_report_sql implements module_repo INNER JOIN subdef ON (record.record_id = subdef.record_id AND subdef.name = "document") ) WHERE '; - } + } - $this->sql .= $report_filters['sql']; + $this->sql .= $report_filters['sql']; - $this->sql .= ' AND ( log_docs.action = \'download\' OR log_docs.action = \'mail\')'; + $this->sql .= ' AND ( log_docs.action = \'download\' OR log_docs.action = \'mail\')'; - $this->sql .= empty($record_filters['sql']) ? '' : ' AND ( ' . $record_filters['sql'] . ' )'; + $this->sql .= empty($record_filters['sql']) ? '' : ' AND ( ' . $record_filters['sql'] . ' )'; - $this->sql .= $this->on == 'DOC' ? 'AND subdef.name = \'document\' ' : ''; + $this->sql .= $this->on == 'DOC' ? 'AND subdef.name = \'document\' ' : ''; - $this->sql .= ' GROUP BY ' . $this->groupby; + $this->sql .= ' GROUP BY ' . $this->groupby; - $this->sql .= ( $name == 'record_id' && $this->on == 'DOC') ? ' , final' : ''; + $this->sql .= ( $name == 'record_id' && $this->on == 'DOC') ? ' , final' : ''; - if ($this->filter->getOrderFilter()) - $this->sql .= $this->filter->getOrderFilter(); + if ($this->filter->getOrderFilter()) + $this->sql .= $this->filter->getOrderFilter(); - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($this->params); - $this->total = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($this->params); + $this->total = $stmt->rowCount(); + $stmt->closeCursor(); - $this->sql .= $this->filter->getLimitFilter() ? : ''; + $this->sql .= $this->filter->getLimitFilter() ? : ''; + } + + return $this; } - return $this; - } + public function sqlDistinctValByField($field) + { + $report_filters = $this->filter->getReportFilter(); + $params = array_merge($report_filters['params']); + $this->params = $params; - public function sqlDistinctValByField($field) - { - $report_filters = $this->filter->getReportFilter(); - $params = array_merge($report_filters['params']); - $this->params = $params; - - $sql = ' + $sql = ' SELECT DISTINCT( ' . $this->getTransQuery($field) . ' ) AS val FROM (log INNER JOIN log_docs ON log.id = log_docs.log_id @@ -174,15 +165,14 @@ class module_report_sqldownload extends module_report_sql implements module_repo INNER JOIN subdef ON log_docs.record_id = subdef.record_id) WHERE '; - $sql .= $report_filters['sql']; - $sql .= ' AND (log_docs.action = ' . + $sql .= $report_filters['sql']; + $sql .= ' AND (log_docs.action = ' . '\'download\'OR log_docs.action = \'mail\')'; - $sql .= $this->on == 'DOC' ? 'AND subdef.name = \'document\'' : ''; - $sql .= $this->filter->getOrderFilter() ? : ''; - $sql .= $this->filter->getLimitFilter() ? : ''; - - return array('sql' => $sql, 'params' => $params); - } + $sql .= $this->on == 'DOC' ? 'AND subdef.name = \'document\'' : ''; + $sql .= $this->filter->getOrderFilter() ? : ''; + $sql .= $this->filter->getLimitFilter() ? : ''; + return array('sql' => $sql, 'params' => $params); + } } diff --git a/lib/classes/module/report/sqlfilter.class.php b/lib/classes/module/report/sqlfilter.class.php index a38e3531b0..1ff1d2513a 100644 --- a/lib/classes/module/report/sqlfilter.class.php +++ b/lib/classes/module/report/sqlfilter.class.php @@ -17,265 +17,243 @@ */ class module_report_sqlfilter { + public $conn; + private $filter; + private $cor_query = array(); - public $conn; - private $filter; - private $cor_query = array(); - - public function __construct(module_report $report) - { - $this->conn = connection::getPDOConnection($report->getSbasid()); - - if (is_array($report->getTransQueryString())) - $this->cor_query = $report->getTransQueryString(); - - $this->buildFilter($report); - } - - public static function constructDateFilter($dmin, $dmax) - { - return array( - 'sql' => ($dmin && $dmax ? ' log_date.date > :date_min AND log_date.date < :date_max ' : false) - , 'params' => ($dmin && $dmax ? array(':date_min' => $dmin, ':date_max' => $dmax) : array()) - ); - } - - public static function constructCollectionFilter($list_coll_id) - { - $ret = array('sql' => '', 'params' => array()); - $coll_filter = array(); - foreach (explode(',', $list_coll_id) as $val) + public function __construct(module_report $report) { - $coll_filter [] = " position('," . phrasea::collFromBas($val) . ",' in concat(',' ,coll_list, ',')) > 0 "; - } - $ret['sql'] = implode(' OR ', $coll_filter); + $this->conn = connection::getPDOConnection($report->getSbasid()); - return $ret; - } + if (is_array($report->getTransQueryString())) + $this->cor_query = $report->getTransQueryString(); - public function getCorFilter() - { - return $this->cor_query; - } - - public function getReportFilter() - { - $finalfilter = ''; - $registry = registry::get_instance(); - - $params = array(':log_site' => $registry->get('GV_sit')); - - if ($this->filter['date']) - { - $finalfilter .= $this->filter['date']['sql'] . ' AND '; - $params = array_merge($params, $this->filter['date']['params']); - } - if ($this->filter['user']) - { - $finalfilter .= $this->filter['user']['sql'] . ' AND '; - $params = array_merge($params, $this->filter['user']['params']); - } - if ($this->filter['collection']) - { - $finalfilter .= '(' . $this->filter['collection']['sql'] . ') AND '; - $params = array_merge($params, $this->filter['collection']['params']); - } - $finalfilter .= ' log.site = :log_site'; - - return array('sql' => $finalfilter, 'params' => $params); - } - - public function getGvSitFilter() - { - $registry = registry::get_instance(); - $params = array(); - $sql = ''; - - if ($registry->is_set('GV_sit')) - { - $sql = 'log.site = :log_site_gv_filter'; - $params[':log_site_gv_filter'] = $registry->get('GV_sit'); + $this->buildFilter($report); } - return array('sql' => $sql, 'params' => $params); - } - - public function getUserIdFilter($id) - { - return array('sql' => "log.usrid = :usr_id_filter", 'params' => array(':usr_id_filter' => $id)); - } - - public function getDateFilter() - { - return $this->filter['date']; - } - - public function getUserFilter() - { - return $this->filter['user']; - } - - public function getCollectionFilter() - { - return $this->filter['collection']; - } - - public function getRecordFilter() - { - return $this->filter['record']; - } - - public function getLimitFilter() - { - return $this->filter['limit']; - } - - public function getOrderFilter() - { - return $this->filter['order']; - } - - private function dateFilter(module_report $report) - { - $this->filter['date'] = false; - if ($report->getDmin() && $report->getDmax()) + public static function constructDateFilter($dmin, $dmax) { - $this->filter['date'] = array( - 'sql' => ' (log.date > :date_min_f AND log.date < :date_max_f) ' - , 'params' => array( - ':date_min_f' => $report->getDmin() - , ':date_max_f' => $report->getDmax() - ) - ); + return array( + 'sql' => ($dmin && $dmax ? ' log_date.date > :date_min AND log_date.date < :date_max ' : false) + , 'params' => ($dmin && $dmax ? array(':date_min' => $dmin, ':date_max' => $dmax) : array()) + ); } - return; - } - - private function userFilter(module_report $report) - { - $this->filter['user'] = false; - $f = $report->getTabFilter(); - - if (sizeof($f) > 0) + public static function constructCollectionFilter($list_coll_id) { - $filter = array(); - $params = array(); - $n = 0; - foreach ($f as $field => $value) - { - if (array_key_exists($value['f'], $this->cor_query)) - $value['f'] = $this->cor_query[$value['f']]; - - if ($value['o'] == 'LIKE') - { - $filter[] = $value['f'] . ' ' . $value['o'] . ' \'%' . str_replace(array("'", '%'), array("\'", '\%'), ' :user_filter' . $n) . '%\''; - $params[':user_filter' . $n] = $value['v']; + $ret = array('sql' => '', 'params' => array()); + $coll_filter = array(); + foreach (explode(',', $list_coll_id) as $val) { + $coll_filter [] = " position('," . phrasea::collFromBas($val) . ",' in concat(',' ,coll_list, ',')) > 0 "; } - elseif ($value['o'] == 'OR') - { - $filter[] = $value['f'] . ' ' . $value['o'] . ' :user_filter' . $n; - $params[':user_filter' . $n] = $value['v']; + $ret['sql'] = implode(' OR ', $coll_filter); + + return $ret; + } + + public function getCorFilter() + { + return $this->cor_query; + } + + public function getReportFilter() + { + $finalfilter = ''; + $registry = registry::get_instance(); + + $params = array(':log_site' => $registry->get('GV_sit')); + + if ($this->filter['date']) { + $finalfilter .= $this->filter['date']['sql'] . ' AND '; + $params = array_merge($params, $this->filter['date']['params']); } - else - { - $filter[] = $value['f'] . ' ' . $value['o'] . ' :user_filter' . $n; - $params[':user_filter' . $n] = $value['v']; + if ($this->filter['user']) { + $finalfilter .= $this->filter['user']['sql'] . ' AND '; + $params = array_merge($params, $this->filter['user']['params']); + } + if ($this->filter['collection']) { + $finalfilter .= '(' . $this->filter['collection']['sql'] . ') AND '; + $params = array_merge($params, $this->filter['collection']['params']); + } + $finalfilter .= ' log.site = :log_site'; + + return array('sql' => $finalfilter, 'params' => $params); + } + + public function getGvSitFilter() + { + $registry = registry::get_instance(); + $params = array(); + $sql = ''; + + if ($registry->is_set('GV_sit')) { + $sql = 'log.site = :log_site_gv_filter'; + $params[':log_site_gv_filter'] = $registry->get('GV_sit'); } - $n++; - } - $filter_user = array('sql' => implode(' AND ', $filter), 'params' => $params); - - $this->filter['user'] = $filter_user; + return array('sql' => $sql, 'params' => $params); } - return; - } - - private function collectionFilter(module_report $report) - { - $this->filter['collection'] = false; - $coll_filter = array(); - - if ($report->getUserId() == '') - - return; - - $tab = explode(",", $report->getListCollId()); - if(count($tab) > 0) + public function getUserIdFilter($id) { - foreach ($tab as $val) - { - $coll_filter[] = " position('," . phrasea::collFromBas($val) . ",' in concat(',' ,coll_list, ',')) > 0 "; - } - $this->filter['collection'] = array('sql' => implode(' OR ', $coll_filter), 'params' => array()); + return array('sql' => "log.usrid = :usr_id_filter", 'params' => array(':usr_id_filter' => $id)); } - return; - } - - private function recordFilter(module_report $report) - { - $this->filter['record'] = false; - $dl_coll_filter = $params = array(); - $n = 0; - if (($report->getUserId() != '')) + public function getDateFilter() { - $tab = explode(",", $report->getListCollId()); - foreach ($tab as $val) - { - $dl_coll_filter[] = "record.coll_id = :record_fil" . $n; - $params[":record_fil" . $n] = phrasea::collFromBas($val); - $n++; - } - $this->filter['record'] = array('sql' => implode(' OR ', $dl_coll_filter), 'params' => $params); + return $this->filter['date']; } - return; - } - - private function orderFilter(module_report $report) - { - $this->filter['order'] = false; - if (sizeof($report->getOrder()) > 0) + public function getUserFilter() { - $this->filter['order'] = " ORDER BY " - . $this->cor_query[$report->getOrder('champ')] - . ' ' . $report->getOrder('order'); + return $this->filter['user']; } - return; - } - - private function limitFilter(module_report $report) - { - $p = $report->getNbPage(); - $r = $report->getNbRecord(); - - $this->filter['limit'] = false; - if ($p && $r) + public function getCollectionFilter() { - $limit_inf = (int)($p - 1) * $r; - $limit_sup = (int) $r; - $this->filter['limit'] = " LIMIT " . $limit_inf . ', ' . $limit_sup; + return $this->filter['collection']; } - return; - } + public function getRecordFilter() + { + return $this->filter['record']; + } - private function buildFilter(module_report $report) - { - $this->dateFilter($report); - $this->limitFilter($report); - $this->orderFilter($report); - $this->recordFilter($report); - $this->userFilter($report); - $this->collectionFilter($report); + public function getLimitFilter() + { + return $this->filter['limit']; + } - return; - } + public function getOrderFilter() + { + return $this->filter['order']; + } + private function dateFilter(module_report $report) + { + $this->filter['date'] = false; + if ($report->getDmin() && $report->getDmax()) { + $this->filter['date'] = array( + 'sql' => ' (log.date > :date_min_f AND log.date < :date_max_f) ' + , 'params' => array( + ':date_min_f' => $report->getDmin() + , ':date_max_f' => $report->getDmax() + ) + ); + } + + return; + } + + private function userFilter(module_report $report) + { + $this->filter['user'] = false; + $f = $report->getTabFilter(); + + if (sizeof($f) > 0) { + $filter = array(); + $params = array(); + $n = 0; + foreach ($f as $field => $value) { + if (array_key_exists($value['f'], $this->cor_query)) + $value['f'] = $this->cor_query[$value['f']]; + + if ($value['o'] == 'LIKE') { + $filter[] = $value['f'] . ' ' . $value['o'] . ' \'%' . str_replace(array("'", '%'), array("\'", '\%'), ' :user_filter' . $n) . '%\''; + $params[':user_filter' . $n] = $value['v']; + } elseif ($value['o'] == 'OR') { + $filter[] = $value['f'] . ' ' . $value['o'] . ' :user_filter' . $n; + $params[':user_filter' . $n] = $value['v']; + } else { + $filter[] = $value['f'] . ' ' . $value['o'] . ' :user_filter' . $n; + $params[':user_filter' . $n] = $value['v']; + } + + $n ++; + } + $filter_user = array('sql' => implode(' AND ', $filter), 'params' => $params); + + $this->filter['user'] = $filter_user; + } + + return; + } + + private function collectionFilter(module_report $report) + { + $this->filter['collection'] = false; + $coll_filter = array(); + + if ($report->getUserId() == '') + return; + + $tab = explode(",", $report->getListCollId()); + if (count($tab) > 0) { + foreach ($tab as $val) { + $coll_filter[] = " position('," . phrasea::collFromBas($val) . ",' in concat(',' ,coll_list, ',')) > 0 "; + } + $this->filter['collection'] = array('sql' => implode(' OR ', $coll_filter), 'params' => array()); + } + + return; + } + + private function recordFilter(module_report $report) + { + $this->filter['record'] = false; + $dl_coll_filter = $params = array(); + $n = 0; + if (($report->getUserId() != '')) { + $tab = explode(",", $report->getListCollId()); + foreach ($tab as $val) { + $dl_coll_filter[] = "record.coll_id = :record_fil" . $n; + $params[":record_fil" . $n] = phrasea::collFromBas($val); + $n ++; + } + $this->filter['record'] = array('sql' => implode(' OR ', $dl_coll_filter), 'params' => $params); + } + + return; + } + + private function orderFilter(module_report $report) + { + $this->filter['order'] = false; + if (sizeof($report->getOrder()) > 0) { + $this->filter['order'] = " ORDER BY " + . $this->cor_query[$report->getOrder('champ')] + . ' ' . $report->getOrder('order'); + } + + return; + } + + private function limitFilter(module_report $report) + { + $p = $report->getNbPage(); + $r = $report->getNbRecord(); + + $this->filter['limit'] = false; + if ($p && $r) { + $limit_inf = (int) ($p - 1) * $r; + $limit_sup = (int) $r; + $this->filter['limit'] = " LIMIT " . $limit_inf . ', ' . $limit_sup; + } + + return; + } + + private function buildFilter(module_report $report) + { + $this->dateFilter($report); + $this->limitFilter($report); + $this->orderFilter($report); + $this->recordFilter($report); + $this->userFilter($report); + $this->collectionFilter($report); + + return; + } } ?> diff --git a/lib/classes/module/report/sqlquestion.class.php b/lib/classes/module/report/sqlquestion.class.php index e46c90f64c..41bd35ab2a 100644 --- a/lib/classes/module/report/sqlquestion.class.php +++ b/lib/classes/module/report/sqlquestion.class.php @@ -18,22 +18,21 @@ class module_report_sqlquestion extends module_report_sql implements module_report_sqlReportInterface { - public function __construct(module_report $report) - { - parent::__construct($report); - } - - public function buildSql() - { - $params = array(); - $report_filter = $this->filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); - $this->params = $params; - - if ($this->groupby == false) + public function __construct(module_report $report) { - $this->sql = - " + parent::__construct($report); + } + + public function buildSql() + { + $params = array(); + $report_filter = $this->filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); + $this->params = $params; + + if ($this->groupby == false) { + $this->sql = + " SELECT log_search.date ddate, search, @@ -49,20 +48,18 @@ class module_report_sqlquestion extends module_report_sql implements module_repo "; - $this->sql .= " WHERE " . $report_filter['sql']; + $this->sql .= " WHERE " . $report_filter['sql']; - $this->sql .= $this->filter->getOrderFilter() ?: ''; + $this->sql .= $this->filter->getOrderFilter() ? : ''; - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($params); - $this->total_row = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($params); + $this->total_row = $stmt->rowCount(); + $stmt->closeCursor(); - $this->sql .= $this->filter->getLimitFilter() ?: ''; - } - else - { - $this->sql = " + $this->sql .= $this->filter->getLimitFilter() ? : ''; + } else { + $this->sql = " SELECT TRIM(" . $this->getTransQuery($this->groupby) . ") as " . $this->groupby . ", SUM(1) as nb @@ -71,40 +68,39 @@ class module_report_sqlquestion extends module_report_sql implements module_repo ON log.id = log_search.log_id "; - $this->sql .= " WHERE " . $report_filter['sql']; - $this->sql .= " GROUP BY " . $this->groupby; - $this->sql .= " ORDER BY nb DESC"; + $this->sql .= " WHERE " . $report_filter['sql']; + $this->sql .= " GROUP BY " . $this->groupby; + $this->sql .= " ORDER BY nb DESC"; - $stmt = $this->connbas->prepare($this->sql); - $stmt->execute($params); - $this->total_row = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $this->connbas->prepare($this->sql); + $stmt->execute($params); + $this->total_row = $stmt->rowCount(); + $stmt->closeCursor(); + } + + return $this; } - return $this; - } + public function sqlDistinctValByField($field) + { + $params = array(); + $report_filter = $this->filter->getReportFilter(); + $params = array_merge($params, $report_filter['params']); - public function sqlDistinctValByField($field) - { - $params = array(); - $report_filter = $this->filter->getReportFilter(); - $params = array_merge($params, $report_filter['params']); - - $sql = " + $sql = " SELECT DISTINCT(" . $this->getTransQuery($field) . ") as val FROM `log_search` INNER JOIN log ON log.id = log_search.log_id "; - if ($report_filter['sql']) - $sql .= ' WHERE ' . $report_filter['sql']; + if ($report_filter['sql']) + $sql .= ' WHERE ' . $report_filter['sql']; - $sql .= " ORDER BY " . $this->getTransQuery($field) . " ASC"; - - return array('sql' => $sql, 'params' => $params); - } + $sql .= " ORDER BY " . $this->getTransQuery($field) . " ASC"; + return array('sql' => $sql, 'params' => $params); + } } ?> diff --git a/lib/classes/module/report/validate.class.php b/lib/classes/module/report/validate.class.php index a795718573..41638680f5 100644 --- a/lib/classes/module/report/validate.class.php +++ b/lib/classes/module/report/validate.class.php @@ -17,138 +17,117 @@ */ class module_report_validate 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:: validated documents'); - } - - /** - * @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('validate')->buildSql(); - $this->req = $s->getSql(); - $this->params = $s->getParams(); - $this->total = $s->getTotalRows(); - } - - public function colFilter($field, $on = false) - { - $s = $this->sqlBuilder('action')->setAction('validate'); - $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(); - - 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:: validated documents'); } - 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) { - if ($i >= $this->nb_record) - break; - 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++; + $s = $this->sqlBuilder('action')->setGroupBy($groupby)->setOn($on) + ->setAction('validate')->buildSql(); + $this->req = $s->getSql(); + $this->params = $s->getParams(); + $this->total = $s->getTotalRows(); } - } + public function colFilter($field, $on = false) + { + $s = $this->sqlBuilder('action')->setAction('validate'); + $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(); + + 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) { + if ($i >= $this->nb_record) + break; + 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 ++; + } + } } diff --git a/lib/classes/p4field.class.php b/lib/classes/p4field.class.php index a734f9cda2..db6f33418e 100644 --- a/lib/classes/p4field.class.php +++ b/lib/classes/p4field.class.php @@ -16,5 +16,4 @@ class p4field return($v == '0' || $v == 'n' || $v == 'no' || $v == 'non' || $v = 'off' || $v == 'false'); } - } diff --git a/lib/classes/p4file.class.php b/lib/classes/p4file.class.php index 0f6ba525b7..cd34df600b 100644 --- a/lib/classes/p4file.class.php +++ b/lib/classes/p4file.class.php @@ -12,206 +12,182 @@ class p4file { - public static function apache_tokenize($file) - { - $ret = false; - $registry = registry::get_instance(); - - if ($registry->get('GV_h264_streaming') && is_file($file)) + public static function apache_tokenize($file) { - if (($pos = mb_strpos($file, $registry->get('GV_mod_auth_token_directory_path'))) === false) - { - return false; - } + $ret = false; + $registry = registry::get_instance(); - $server = new system_server(); + if ($registry->get('GV_h264_streaming') && is_file($file)) { + if (($pos = mb_strpos($file, $registry->get('GV_mod_auth_token_directory_path'))) === false) { + return false; + } - if ($server->is_nginx()) - { - $fileToProtect = mb_substr($file, mb_strlen($registry->get('GV_mod_auth_token_directory_path'))); + $server = new system_server(); - $secret = $registry->get('GV_mod_auth_token_passphrase'); - $protectedPath = p4string::addFirstSlash(p4string::delEndSlash($registry->get('GV_mod_auth_token_directory'))); + if ($server->is_nginx()) { + $fileToProtect = mb_substr($file, mb_strlen($registry->get('GV_mod_auth_token_directory_path'))); - $hexTime = strtoupper(dechex(time() + 3600)); + $secret = $registry->get('GV_mod_auth_token_passphrase'); + $protectedPath = p4string::addFirstSlash(p4string::delEndSlash($registry->get('GV_mod_auth_token_directory'))); - $token = md5($protectedPath . $fileToProtect . '/' . $secret . '/' . $hexTime); + $hexTime = strtoupper(dechex(time() + 3600)); - $url = $protectedPath . $fileToProtect . '/' . $token . '/' . $hexTime; + $token = md5($protectedPath . $fileToProtect . '/' . $secret . '/' . $hexTime); - $ret = $url; - } - elseif ($server->is_apache()) - { - $fileToProtect = mb_substr($file, mb_strlen($registry->get('GV_mod_auth_token_directory_path'))); + $url = $protectedPath . $fileToProtect . '/' . $token . '/' . $hexTime; + + $ret = $url; + } elseif ($server->is_apache()) { + $fileToProtect = mb_substr($file, mb_strlen($registry->get('GV_mod_auth_token_directory_path'))); - $secret = $registry->get('GV_mod_auth_token_passphrase'); // Same as AuthTokenSecret - $protectedPath = p4string::addEndSlash(p4string::delFirstSlash($registry->get('GV_mod_auth_token_directory'))); // Same as AuthTokenPrefix - $hexTime = dechex(time()); // Time in Hexadecimal + $secret = $registry->get('GV_mod_auth_token_passphrase'); // Same as AuthTokenSecret + $protectedPath = p4string::addEndSlash(p4string::delFirstSlash($registry->get('GV_mod_auth_token_directory'))); // Same as AuthTokenPrefix + $hexTime = dechex(time()); // Time in Hexadecimal - $token = md5($secret . $fileToProtect . $hexTime); + $token = md5($secret . $fileToProtect . $hexTime); - // We build the url - $url = '/' . $protectedPath . $token . "/" . $hexTime . $fileToProtect; + // We build the url + $url = '/' . $protectedPath . $token . "/" . $hexTime . $fileToProtect; - $ret = $url; - } + $ret = $url; + } + } + + return $ret; } - return $ret; - } + public static function archiveFile(system_file &$system_file, $base_id, $delete = true, $name = false) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); - public static function archiveFile(system_file &$system_file, $base_id, $delete=true, $name=false) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $name ? $name : $system_file->getFilename()); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, null); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, null); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $name ? $name : $system_file->getFilename()); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, null); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, null); - - $go = User_Adapter::getInstance($session->get_usr_id(), $appbox) + $go = User_Adapter::getInstance($session->get_usr_id(), $appbox) ->ACL() ->has_right_on_base($base_id, 'canaddrecord'); - if (!$go) - { - echo "\ndroits insuffisants"; + if ( ! $go) { + echo "\ndroits insuffisants"; - return false; - } - - $sbas_id = phrasea::sbasFromBas($base_id); - $databox = databox::get_instance($sbas_id); - $collection = collection::get_from_base_id($base_id); - - $collprefs = simplexml_load_string($collection->get_prefs()); - - $server_coll_id = phrasea::collFromBas($base_id); - - if ($collprefs === false) - { - if (GV_debug) - echo 'Error loading collprefs'; - - return false; - } - - $metadatas = $system_file->extract_metadatas($databox->get_meta_structure()); - - $status = "0"; - - if ($collprefs->status) - $status = (string) ($collprefs->status); - - $record_id = $record = false; - - try - { - $record = record_adapter::create($collection, $system_file, $name); - $record_id = $record->get_record_id(); - $record->set_metadatas($metadatas['metadatas'], true); - } - catch (Exception $e) - { - echo $e->getMessage(); - if ($record instanceof record_adapter) - $record->delete(); - - return false; - } - - $record->set_binary_status(databox_status::dec2bin($status)); - $record->rebuild_subdefs(); - $record->reindex(); - - if ($delete) - { - @unlink($system_file->getPathname()); - unset($system_file); - } - - return $record_id; - } - - public static function check_file_error($filename, $sbas_id, $originalname) - { - $registry = registry::get_instance(); - - $system_file = new system_file($filename); - - $doctype = $system_file->get_phrasea_type(); - - $databox = databox::get_instance($sbas_id); - if ($baseprefs = $databox->get_sxml_structure()) - { - $file_checks = $baseprefs->filechecks; - } - else - throw new Exception(_('prod::erreur : impossible de lire les preferences de base')); - - - $errors = array(); - - $datas = exiftool::get_fields($filename, array('Color Space Data', 'Color Space', 'Color Mode', 'Image Width', 'Image Height')); - - if ($checks = $file_checks->$doctype) - { - foreach ($checks[0] as $name => $value) - { - switch ($name) - { - case 'name': - $records = record_adapter::get_records_by_originalname($databox, $original_name, 0, 1); - if (count($records) > 0) - $errors[] = sprintf(_('Le fichier \'%s\' existe deja'), $originalname); - break; - case 'size': - $min = min($datas['Image Height'], $datas['Image Width']); - if ($min < (int) $value) - { - $errors[] = sprintf(_('Taille trop petite : %dpx'), $min); - } - break; - case 'color_space': - $required = in_array($value, array('sRGB', 'RGB')) ? 'RGB' : $value; - $go = false; - - $results = array($datas['Color Space'], $datas['Color Space Data'], $datas['Color Mode']); - - $results_str = implode(' ', $results); - - if (trim($results_str) === '') - { - $go = true; - } - else - { - if ($required == 'RGB' && count(array_intersect($results, array('sRGB', 'RGB'))) > 0) - { - $go = true; - } - elseif (in_array($required, $results)) - { - $go = true; - } - } - - - if (!$go) - { - $errors[] = sprintf(_('Mauvais mode colorimetrique : %s'), $results_str); - } - - break; + return false; } - } + + $sbas_id = phrasea::sbasFromBas($base_id); + $databox = databox::get_instance($sbas_id); + $collection = collection::get_from_base_id($base_id); + + $collprefs = simplexml_load_string($collection->get_prefs()); + + $server_coll_id = phrasea::collFromBas($base_id); + + if ($collprefs === false) { + if (GV_debug) + echo 'Error loading collprefs'; + + return false; + } + + $metadatas = $system_file->extract_metadatas($databox->get_meta_structure()); + + $status = "0"; + + if ($collprefs->status) + $status = (string) ($collprefs->status); + + $record_id = $record = false; + + try { + $record = record_adapter::create($collection, $system_file, $name); + $record_id = $record->get_record_id(); + $record->set_metadatas($metadatas['metadatas'], true); + } catch (Exception $e) { + echo $e->getMessage(); + if ($record instanceof record_adapter) + $record->delete(); + + return false; + } + + $record->set_binary_status(databox_status::dec2bin($status)); + $record->rebuild_subdefs(); + $record->reindex(); + + if ($delete) { + @unlink($system_file->getPathname()); + unset($system_file); + } + + return $record_id; } - return $errors; - } + public static function check_file_error($filename, $sbas_id, $originalname) + { + $registry = registry::get_instance(); + $system_file = new system_file($filename); + + $doctype = $system_file->get_phrasea_type(); + + $databox = databox::get_instance($sbas_id); + if ($baseprefs = $databox->get_sxml_structure()) { + $file_checks = $baseprefs->filechecks; + } + else + throw new Exception(_('prod::erreur : impossible de lire les preferences de base')); + + + $errors = array(); + + $datas = exiftool::get_fields($filename, array('Color Space Data', 'Color Space', 'Color Mode', 'Image Width', 'Image Height')); + + if ($checks = $file_checks->$doctype) { + foreach ($checks[0] as $name => $value) { + switch ($name) { + case 'name': + $records = record_adapter::get_records_by_originalname($databox, $original_name, 0, 1); + if (count($records) > 0) + $errors[] = sprintf(_('Le fichier \'%s\' existe deja'), $originalname); + break; + case 'size': + $min = min($datas['Image Height'], $datas['Image Width']); + if ($min < (int) $value) { + $errors[] = sprintf(_('Taille trop petite : %dpx'), $min); + } + break; + case 'color_space': + $required = in_array($value, array('sRGB', 'RGB')) ? 'RGB' : $value; + $go = false; + + $results = array($datas['Color Space'], $datas['Color Space Data'], $datas['Color Mode']); + + $results_str = implode(' ', $results); + + if (trim($results_str) === '') { + $go = true; + } else { + if ($required == 'RGB' && count(array_intersect($results, array('sRGB', 'RGB'))) > 0) { + $go = true; + } elseif (in_array($required, $results)) { + $go = true; + } + } + + + if ( ! $go) { + $errors[] = sprintf(_('Mauvais mode colorimetrique : %s'), $results_str); + } + + break; + } + } + } + + return $errors; + } } diff --git a/lib/classes/p4string.class.php b/lib/classes/p4string.class.php index c8d04c87f4..f955765a70 100644 --- a/lib/classes/p4string.class.php +++ b/lib/classes/p4string.class.php @@ -5,15 +5,13 @@ class p4string public static function addFirstSlash($path) { - if ($path == "") - { + if ($path == "") { return("./"); } $c = substr($path, 0, 1); - if ($c != "/" && $c != "\\") - { + if ($c != "/" && $c != "\\") { return "/" . $path; } @@ -22,27 +20,23 @@ class p4string public static function delFirstSlash($path) { - if ($path == "/" || $path == "\\") - { + if ($path == "/" || $path == "\\") { return(""); } $c = substr($path, 0, 1); - if ($c == "/" || $c == "\\") - { + if ($c == "/" || $c == "\\") { return substr($path, 1, strlen($path)); } $c = substr($path, 0, 2); - if ($c == "\\") - { + if ($c == "\\") { return substr($path, 2, strlen($path) - 1); } - if ($path == "") - { + if ($path == "") { return "./"; } @@ -51,15 +45,13 @@ class p4string public static function addEndSlash($path) { - if ($path == "") - { + if ($path == "") { $path = getcwd(); } $lastCharacter = substr($path, -1, 1); - if ( ! in_array($lastCharacter, array('\\', '/'))) - { + if ( ! in_array($lastCharacter, array('\\', '/'))) { $path .= DIRECTORY_SEPARATOR; } @@ -68,20 +60,17 @@ class p4string public static function delEndSlash($path) { - if ($path == "/" || $path == "\\") - { + if ($path == "/" || $path == "\\") { return(""); } $c = substr($path, -1, 1); - if ($c == "/" || $c == "\\") - { + if ($c == "/" || $c == "\\") { $path = substr($path, 0, strlen($path) - 1); } - if ($path == "") - { + if ($path == "") { $path = "."; } @@ -114,8 +103,7 @@ class p4string */ public static function MakeString($s, $context = 'html', $quoted = '') { - switch (mb_strtolower($context . '_' . $quoted)) - { + switch (mb_strtolower($context . '_' . $quoted)) { case 'js_': // old method $s = str_replace(array("\\", "\"", "'", "\r", "\n"), array("\\\\", "\\\"", "\\'", "\\r", "\\n"), $s); break; @@ -168,8 +156,7 @@ class p4string $ret = true; preg_match('/^[a-zA-Z0-9-_]*$/', $string, $matches); - if (count($matches) == '1' && $matches[0] == $string) - { + if (count($matches) == '1' && $matches[0] == $string) { $ret = false; } @@ -178,12 +165,9 @@ class p4string public static function jsonencode($datas) { - if (version_compare(PHP_VERSION, '5.3.0') >= 0) - { + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { return json_encode($datas, JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS); - } - else - { + } else { return json_encode($datas); } } @@ -191,23 +175,19 @@ class p4string public static function format_octets($octets, $precision = 2) { $octets = (float) $octets; - if ($octets < 900) - { + if ($octets < 900) { return $octets . ' o'; } $koctet = round($octets / 1024, $precision); - if ($koctet < 900) - { + if ($koctet < 900) { return $koctet . ' ko'; } $Moctet = round($octets / (1024 * 1024), $precision); - if ($Moctet < 900) - { + if ($Moctet < 900) { return $Moctet . ' Mo'; } $Goctet = round($octets / (1024 * 1024 * 1024), $precision); - if ($Goctet < 900) - { + if ($Goctet < 900) { return $Goctet . ' Go'; } $Toctet = round($octets / (1024 * 1024 * 1024 * 1024), $precision); @@ -224,23 +204,19 @@ class p4string $durationm = ($durationm <= 9 ? '0' . $durationm : $durationm) . ':'; $durationh = floor($seconds / 3600); $durationh = $durationh == 0 ? '' : ( - ($durationh <= 9 ? '0' . $durationh : $durationh) . ':'); - $d = $durationh . $durationm . $durations; + ($durationh <= 9 ? '0' . $durationh : $durationh) . ':'); + $d = $durationh . $durationm . $durations; - if ($d == '00:00') - { + if ($d == '00:00') { $d = ''; } - if ($seconds < 0) - { + if ($seconds < 0) { $d = ''; } - if ($seconds === 0) - { + if ($seconds === 0) { $d = '00:00'; } return $d; } - } diff --git a/lib/classes/patch/303.class.php b/lib/classes/patch/303.class.php index 22a0696d8e..dc251306c6 100644 --- a/lib/classes/patch/303.class.php +++ b/lib/classes/patch/303.class.php @@ -17,12 +17,12 @@ */ class patch_303 implements patchInterface { - /** * * @var string */ private $release = '3.0.3'; + /** * * @var Array @@ -76,24 +76,20 @@ class patch_303 implements patchInterface $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $tab_usr[$row['usr_id']] = array( - 'fonction' => $row['fonction'], - 'societe' => $row['societe'], - 'activite' => $row['activite'], - 'pays' => $row['pays'] + 'fonction' => $row['fonction'], + 'societe' => $row['societe'], + 'activite' => $row['activite'], + 'pays' => $row['pays'] ); } - foreach ($appbox->get_databoxes() as $databox) - { - foreach ($tab_usr as $id => $columns) - { + foreach ($appbox->get_databoxes() as $databox) { + foreach ($tab_usr as $id => $columns) { $f_req = array(); - $params = array(':usr_id' => $id, ':site' => $appbox->get_registry()->get('GV_sit')); - foreach ($columns as $column => $value) - { + $params = array(':usr_id' => $id, ':site' => $appbox->get_registry()->get('GV_sit')); + foreach ($columns as $column => $value) { $column = trim($column); $f_req[] = $column . " = :" . $column; $params[':' . $column] = $value; @@ -116,8 +112,7 @@ class patch_303 implements patchInterface */ function update_users_search_datas(appbox &$appbox) { - foreach ($appbox->get_databoxes() as $databox) - { + foreach ($appbox->get_databoxes() as $databox) { $date_debut = '0000-00-00 00:00:00'; $sql = 'SELECT MAX(date) as debut FROM `log_search`'; @@ -127,8 +122,7 @@ class patch_303 implements patchInterface $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - if ($row) - { + if ($row) { $date_debut = $row['debut']; } @@ -144,5 +138,4 @@ class patch_303 implements patchInterface return $this; } - } diff --git a/lib/classes/patch/304.class.php b/lib/classes/patch/304.class.php index ddbff95d0b..a498840c3d 100644 --- a/lib/classes/patch/304.class.php +++ b/lib/classes/patch/304.class.php @@ -17,7 +17,6 @@ */ class patch_304 implements patchInterface { - /** * * @var string @@ -61,8 +60,7 @@ class patch_304 implements patchInterface $rowcount = $stmt->rowCount(); $stmt->closeCursor(); - if ($rowcount == 0) - { + if ($rowcount == 0) { $sql = 'INSERT INTO pref (id, prop, value, locale, updated_on, created_on) VALUES @@ -74,5 +72,4 @@ class patch_304 implements patchInterface return true; } - } diff --git a/lib/classes/patch/305.class.php b/lib/classes/patch/305.class.php index 814cd21884..45ed5699c1 100644 --- a/lib/classes/patch/305.class.php +++ b/lib/classes/patch/305.class.php @@ -17,12 +17,12 @@ */ class patch_305 implements patchInterface { - /** * * @var string */ private $release = '3.0.5'; + /** * * @var Array @@ -65,5 +65,4 @@ class patch_305 implements patchInterface return true; } - } diff --git a/lib/classes/patch/306.class.php b/lib/classes/patch/306.class.php index dfff7728d2..641b4a3e42 100644 --- a/lib/classes/patch/306.class.php +++ b/lib/classes/patch/306.class.php @@ -17,12 +17,12 @@ */ class patch_306 implements patchInterface { - /** * * @var string */ private $release = '3.0.6'; + /** * * @var Array @@ -58,19 +58,16 @@ class patch_306 implements patchInterface $xpath = $databox->get_xpath_structure(); $res = $xpath->query('/record/subdefs/preview/type'); - foreach ($res as $type) - { - if ($type->nodeValue == 'video') - { + foreach ($res as $type) { + if ($type->nodeValue == 'video') { $preview = $type->parentNode; $to_add = array( - 'acodec' => 'faac', - 'vcodec' => 'libx264', - 'bitrate' => '700' + 'acodec' => 'faac', + 'vcodec' => 'libx264', + 'bitrate' => '700' ); - foreach ($to_add as $k => $v) - { + foreach ($to_add as $k => $v) { $el = $dom->createElement($k); $el->appendChild($dom->createTextNode($v)); $preview->appendChild($el); @@ -82,5 +79,4 @@ class patch_306 implements patchInterface return true; } - } diff --git a/lib/classes/patch/310.class.php b/lib/classes/patch/310.class.php index 462471fed6..170ace5e47 100644 --- a/lib/classes/patch/310.class.php +++ b/lib/classes/patch/310.class.php @@ -17,12 +17,12 @@ */ class patch_310 implements patchInterface { - /** * * @var string */ private $release = '3.1.0'; + /** * * @var Array @@ -60,7 +60,6 @@ class patch_310 implements patchInterface $subdefgroups = $sx_structure->xpath('//subdefgroup'); if (count($subdefgroups) > 0) - return; $subdefs = $sx_structure->xpath('/record/subdefs'); @@ -72,21 +71,18 @@ class patch_310 implements patchInterface $subdefs_groups = array(); - foreach ($subdefs[0] as $k => $v) - { + foreach ($subdefs[0] as $k => $v) { $type = isset($v->type) ? (string) $v->type : 'image'; if ($type == 'image') $media = 'image'; - elseif ($type == 'audio') - { + elseif ($type == 'audio') { if ($v->method == 'MP3') $media = "audio"; else $media = "image"; } - elseif ($type == 'video') - { + elseif ($type == 'video') { if ($v->method == 'AnimGIF') $media = "gif"; elseif ($v->method == 'JPG') @@ -95,8 +91,7 @@ class patch_310 implements patchInterface $media = 'video'; } - if (!isset($subdefs_groups[$type])) - { + if ( ! isset($subdefs_groups[$type])) { $subdefs_groups[$type] = $dom_structure->createElement('subdefgroup'); $subdefs_groups[$type]->setAttribute('name', $type); } @@ -107,8 +102,7 @@ class patch_310 implements patchInterface $dom_subdef->setAttribute('name', $k); $dom_subdef->setAttribute('downloadable', 'true'); - foreach ($v as $tag => $value) - { + foreach ($v as $tag => $value) { if (in_array($tag, array('type', 'name'))) continue; @@ -118,35 +112,29 @@ class patch_310 implements patchInterface $dom_element = $dom_structure->createElement('mediatype', $media); $dom_subdef->appendChild($dom_element); - if ($media == 'video') - { + if ($media == 'video') { $dom_element = $dom_structure->createElement('threads', '1'); $dom_subdef->appendChild($dom_element); } //preview, thumbnail et thumbnailGIF - if ($k == 'preview') - { + if ($k == 'preview') { $dom_element = - $dom_structure->createElement('label', 'Prévisualisation'); + $dom_structure->createElement('label', 'Prévisualisation'); $dom_element->setAttribute('xml:lang', 'fr'); $dom_subdef->appendChild($dom_element); $dom_element = $dom_structure->createElement('label', 'Preview'); $dom_element->setAttribute('lang', 'en'); $dom_subdef->appendChild($dom_element); - } - elseif ($k == 'thumbnailGIF') - { + } elseif ($k == 'thumbnailGIF') { $dom_element = $dom_structure->createElement('label', 'Animation GIF'); $dom_element->setAttribute('lang', 'fr'); $dom_subdef->appendChild($dom_element); $dom_element = $dom_structure->createElement('label', 'GIF animation'); $dom_element->setAttribute('lang', 'en'); $dom_subdef->appendChild($dom_element); - } - else - { + } else { $dom_element = $dom_structure->createElement('label', 'Imagette'); $dom_element->setAttribute('lang', 'fr'); $dom_subdef->appendChild($dom_element); @@ -164,14 +152,12 @@ class patch_310 implements patchInterface $record = $dom_structure->documentElement; $record->replaceChild( - $new_subefs_node, - $record->getElementsByTagName('subdefs')->item(0) + $new_subefs_node, $record->getElementsByTagName('subdefs')->item(0) ); $databox->saveStructure($dom_structure); return true; } - } diff --git a/lib/classes/patch/3102.class.php b/lib/classes/patch/3102.class.php index 9f6360fb30..b71ad4ee7b 100644 --- a/lib/classes/patch/3102.class.php +++ b/lib/classes/patch/3102.class.php @@ -17,7 +17,6 @@ */ class patch_3102 implements patchInterface { - /** * * @var string @@ -64,8 +63,7 @@ class patch_3102 implements patchInterface $rowcount = $stmt->rowCount(); $stmt->closeCursor(); - if ($rowcount == 0) - { + if ($rowcount == 0) { $sql = 'INSERT INTO `task2` (`task_id`, `usr_id_owner`, `pid`, `status`, `crashed`, `active`, `name`, `last_exec_time`, `class`, `settings`, `completed`) @@ -73,7 +71,7 @@ class patch_3102 implements patchInterface (null, 0, 0, "stopped", 0, 1, "upgrade to v3.1", "0000-00-00 00:00:00", "task_period_upgradetov31", "' . - '", -1)'; + '", -1)'; $stmt = $conn->prepare($sql); $stmt->execute(); @@ -81,8 +79,7 @@ class patch_3102 implements patchInterface } - if ($base->get_base_type() == base::DATA_BOX) - { + if ($base->get_base_type() == base::DATA_BOX) { $sql = 'UPDATE record SET sha256 = "" WHERE sha256 IS NULL AND parent_record_id = 0'; $stmt = $base->get_connection()->prepare($sql); @@ -92,5 +89,4 @@ class patch_3102 implements patchInterface return true; } - } diff --git a/lib/classes/patch/3103.class.php b/lib/classes/patch/3103.class.php index f103d6b7ba..f511da7081 100644 --- a/lib/classes/patch/3103.class.php +++ b/lib/classes/patch/3103.class.php @@ -17,12 +17,12 @@ */ class patch_3103 implements patchInterface { - /** * * @var string */ private $release = '3.1.0'; + /** * * @var Array @@ -64,28 +64,25 @@ class patch_3103 implements patchInterface $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $validate_process[$row['ssel_id']][$row['usr_id']] = $row['id']; } $sql = 'SELECT u.*, s.ssel_id, c.base_id, c.record_id , s.usr_id as pushFrom FROM sselcontusr u, sselcont c, ssel s' . - ' WHERE s.ssel_id = c.ssel_id AND u.sselcont_id = c.sselcont_id' . - ' AND s.deleted="0" ' . - ' ORDER BY s.ssel_id ASC, c.sselcont_id ASC'; + ' WHERE s.ssel_id = c.ssel_id AND u.sselcont_id = c.sselcont_id' . + ' AND s.deleted="0" ' . + ' ORDER BY s.ssel_id ASC, c.sselcont_id ASC'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { - if (!isset($validate_process[$row['ssel_id']]) || - !array_key_exists($row['usr_id'], $validate_process[$row['ssel_id']]) - ) - { + foreach ($rs as $row) { + if ( ! isset($validate_process[$row['ssel_id']]) || + ! array_key_exists($row['usr_id'], $validate_process[$row['ssel_id']]) + ) { $sql = 'INSERT INTO validate (id, ssel_id, created_on, updated_on, expires_on, last_reminder, @@ -98,17 +95,17 @@ class patch_3103 implements patchInterface $expire = new DateTime($row['dateFin']); $expire = $expire->format('u') == 0 ? - null : phraseadate::format_mysql($expire); + null : phraseadate::format_mysql($expire); $params = array( - ':ssel_id' => $row['ssel_id'] - , ':created_on' => $row['date_maj'] - , ':updated_on' => $row['date_maj'] - , ':expires_on' => $expire - , ':usr_id' => $row['usr_id'] - , ':can_agree' => $row['canAgree'] - , ':can_see' => $row['canSeeOther'] + ':ssel_id' => $row['ssel_id'] + , ':created_on' => $row['date_maj'] + , ':updated_on' => $row['date_maj'] + , ':expires_on' => $expire + , ':usr_id' => $row['usr_id'] + , ':can_agree' => $row['canAgree'] + , ':can_see' => $row['canSeeOther'] ); $stmt->execute($params); @@ -135,10 +132,10 @@ class patch_3103 implements patchInterface $stmt = $conn->prepare($sql); $params = array( - ':validate_id' => $validate_process[$row['ssel_id']][$row['usr_id']] - , ':sselcont_id' => $row['sselcont_id'] - , ':updated_on' => $row['date_maj'] - , ':agreement' => $row['agree'] + ':validate_id' => $validate_process[$row['ssel_id']][$row['usr_id']] + , ':sselcont_id' => $row['sselcont_id'] + , ':updated_on' => $row['date_maj'] + , ':agreement' => $row['agree'] ); $stmt->execute($params); $stmt->closeCursor(); @@ -146,5 +143,4 @@ class patch_3103 implements patchInterface return true; } - } diff --git a/lib/classes/patch/311.class.php b/lib/classes/patch/311.class.php index a0198a02e3..01cdc28e90 100644 --- a/lib/classes/patch/311.class.php +++ b/lib/classes/patch/311.class.php @@ -17,12 +17,12 @@ */ class patch_311 implements patchInterface { - /** * * @var string */ private $release = '3.1.1'; + /** * * @var Array @@ -55,7 +55,7 @@ class patch_311 implements patchInterface function apply(base &$databox) { $sql = 'UPDATE record SET jeton = ' - . (JETON_WRITE_META_DOC | JETON_WRITE_META_SUBDEF); + . (JETON_WRITE_META_DOC | JETON_WRITE_META_SUBDEF); $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); @@ -63,6 +63,5 @@ class patch_311 implements patchInterface return true; } - } diff --git a/lib/classes/patch/320.class.php b/lib/classes/patch/320.class.php index 9de66a9bbe..0420ab680a 100644 --- a/lib/classes/patch/320.class.php +++ b/lib/classes/patch/320.class.php @@ -17,12 +17,12 @@ */ class patch_320 implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a1'; + /** * * @var Array @@ -62,6 +62,5 @@ class patch_320 implements patchInterface return true; } - } diff --git a/lib/classes/patch/320a.class.php b/lib/classes/patch/320a.class.php index 7b6ed19e94..1b23eb2cfe 100644 --- a/lib/classes/patch/320a.class.php +++ b/lib/classes/patch/320a.class.php @@ -17,12 +17,12 @@ */ class patch_320a implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a2'; + /** * * @var Array @@ -63,10 +63,9 @@ class patch_320a implements patchInterface $sql = 'UPDATE usr SET nonce = :nonce WHERE usr_id = :usr_id'; $stmt = $appbox->get_connection()->prepare($sql); - foreach ($rs as $row) - { + foreach ($rs as $row) { $nonce = random::generatePassword(16); - $params = array(':usr_id' => $row['usr_id'], ':nonce' => $nonce); + $params = array(':usr_id' => $row['usr_id'], ':nonce' => $nonce); $stmt->execute($params); } $stmt->closeCursor(); @@ -83,14 +82,13 @@ class patch_320a implements patchInterface $sql = 'UPDATE task2 SET `class` = :class WHERE task_id = :task_id'; $stmt = $appbox->get_connection()->prepare($sql); - foreach ($rs as $row) - { + foreach ($rs as $row) { if (strpos($row['class'], 'task_period_') !== false) continue; $params = array( - ':task_id' => $row['task_id'] - , ':class' => str_replace('task_', 'task_period_', $row['class']) + ':task_id' => $row['task_id'] + , ':class' => str_replace('task_', 'task_period_', $row['class']) ); $stmt->execute($params); @@ -100,5 +98,4 @@ class patch_320a implements patchInterface return true; } - } diff --git a/lib/classes/patch/320aa.class.php b/lib/classes/patch/320aa.class.php index 5781e20401..c165c107a6 100644 --- a/lib/classes/patch/320aa.class.php +++ b/lib/classes/patch/320aa.class.php @@ -17,12 +17,12 @@ */ class patch_320aa implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a1'; + /** * * @var Array @@ -54,7 +54,7 @@ class patch_320aa implements patchInterface function apply(base &$appbox) { - if(is_file(__DIR__ . '/../../../config/_GV.php')) + if (is_file(__DIR__ . '/../../../config/_GV.php')) require __DIR__ . '/../../../config/_GV.php'; require __DIR__ . '/../../../lib/conf.d/_GV_template.inc'; @@ -67,15 +67,12 @@ class patch_320aa implements patchInterface $registry = $appbox->get_registry(); - foreach ($GV as $section => $datas_section) - { - foreach ($datas_section['vars'] as $datas) - { + foreach ($GV as $section => $datas_section) { + foreach ($datas_section['vars'] as $datas) { $registry->un_set($datas['name']); eval('$test = defined("' . $datas["name"] . '");'); - if (!$test) - { + if ( ! $test) { continue; } eval('$val = ' . $datas["name"] . ';'); @@ -83,13 +80,11 @@ class patch_320aa implements patchInterface $val = $val === true ? '1' : $val; $val = $val === false ? '0' : $val; - if($datas['name'] == 'GV_exiftool' && strpos($val, 'lib/exiftool/exiftool') !== false) - { + if ($datas['name'] == 'GV_exiftool' && strpos($val, 'lib/exiftool/exiftool') !== false) { $val = str_replace('lib/exiftool/exiftool', 'lib/vendor/exiftool/exiftool', $val); } - switch ($datas['type']) - { + switch ($datas['type']) { case registry::TYPE_ENUM_MULTI: case registry::TYPE_INTEGER: case registry::TYPE_BOOLEAN: @@ -108,5 +103,4 @@ class patch_320aa implements patchInterface return true; } - } diff --git a/lib/classes/patch/320ab.class.php b/lib/classes/patch/320ab.class.php index 8a8eb34d5c..2670fe4f9b 100644 --- a/lib/classes/patch/320ab.class.php +++ b/lib/classes/patch/320ab.class.php @@ -17,12 +17,12 @@ */ class patch_320ab implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a1'; + /** * * @var Array @@ -67,5 +67,4 @@ class patch_320ab implements patchInterface return true; } - } diff --git a/lib/classes/patch/320b.class.php b/lib/classes/patch/320b.class.php index 6d62b481e2..deb03b658e 100644 --- a/lib/classes/patch/320b.class.php +++ b/lib/classes/patch/320b.class.php @@ -15,15 +15,14 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - class patch_320b implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a3'; + /** * * @var Array @@ -63,5 +62,4 @@ class patch_320b implements patchInterface return true; } - } diff --git a/lib/classes/patch/320c.class.php b/lib/classes/patch/320c.class.php index 42e1eece9e..030de32c81 100644 --- a/lib/classes/patch/320c.class.php +++ b/lib/classes/patch/320c.class.php @@ -17,7 +17,6 @@ */ class patch_320c implements patchInterface { - /** * * @var string @@ -72,42 +71,39 @@ class patch_320c implements patchInterface $phrasea_maps = array( - 'pdftext' => '/rdf:RDF/rdf:Description/PHRASEANET:pdftext' - , 'tf-archivedate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-archivedate' - , 'tf-atime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-atime' - , 'tf-chgdocdate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-chgdocdate' - , 'tf-ctime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-ctime' - , 'tf-editdate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-editdate' - , 'tf-mtime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-mtime' - , 'tf-parentdir' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-parentdir' - , 'tf-bits' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-bits' - , 'tf-channels' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-channels' - , 'tf-extension' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-extension' - , 'tf-filename' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-filename' - , 'tf-filepath' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-filepath' - , 'tf-height' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-height' - , 'tf-mimetype' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-mimetype' - , 'tf-recordid' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-recordid' - , 'tf-size' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-size' - , 'tf-width' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-width' + 'pdftext' => '/rdf:RDF/rdf:Description/PHRASEANET:pdftext' + , 'tf-archivedate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-archivedate' + , 'tf-atime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-atime' + , 'tf-chgdocdate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-chgdocdate' + , 'tf-ctime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-ctime' + , 'tf-editdate' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-editdate' + , 'tf-mtime' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-mtime' + , 'tf-parentdir' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-parentdir' + , 'tf-bits' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-bits' + , 'tf-channels' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-channels' + , 'tf-extension' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-extension' + , 'tf-filename' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-filename' + , 'tf-filepath' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-filepath' + , 'tf-height' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-height' + , 'tf-mimetype' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-mimetype' + , 'tf-recordid' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-recordid' + , 'tf-size' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-size' + , 'tf-width' => '/rdf:RDF/rdf:Description/PHRASEANET:tf-width' ); $sxe = $databox->get_sxml_structure(); $dom_struct = $databox->get_dom_structure(); $xp_struct = $databox->get_xpath_structure(); - foreach ($sxe->description->children() as $fname => $field) - { + foreach ($sxe->description->children() as $fname => $field) { $src = trim(isset($field['src']) ? $field['src'] : ''); - if (array_key_exists($src, $phrasea_maps)) - { + if (array_key_exists($src, $phrasea_maps)) { $src = $phrasea_maps[$src]; } $nodes = $xp_struct->query('/record/description/' . $fname); - if ($nodes->length > 0) - { + if ($nodes->length > 0) { $node = $nodes->item(0); $node->setAttribute('src', $src); $node->removeAttribute('meta_id'); @@ -131,7 +127,7 @@ class patch_320c implements patchInterface (null, 0, 0, "stopped", 0, 1, "upgrade to v3.2 for sbas ' . $databox->get_sbas_id() . '", "0000-00-00 00:00:00", "task_period_upgradetov32", "' . - '' . $databox->get_sbas_id() . '", -1)'; + '' . $databox->get_sbas_id() . '", -1)'; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->closeCursor(); @@ -145,18 +141,16 @@ class patch_320c implements patchInterface return true; } - } - class extended_databox extends databox { + public function __construct($sbas_id) { parent::__construct($sbas_id); } - public function migrate_fields() { $this->feed_meta_fields(); diff --git a/lib/classes/patch/320d.class.php b/lib/classes/patch/320d.class.php index 0714c98d69..b1318ecad2 100644 --- a/lib/classes/patch/320d.class.php +++ b/lib/classes/patch/320d.class.php @@ -17,12 +17,12 @@ */ class patch_320d implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a5'; + /** * * @var Array @@ -65,11 +65,10 @@ class patch_320d implements patchInterface WHERE base_id = :base_id AND usr_id = :usr_id'; $stmt = $appbox->get_connection()->prepare($sql); - foreach ($rs as $row) - { + foreach ($rs as $row) { $params = array( - ':base_id' => $row['base_id'], - ':usr_id' => $row['usr_id'] + ':base_id' => $row['base_id'], + ':usr_id' => $row['usr_id'] ); $stmt->execute($params); } @@ -78,5 +77,4 @@ class patch_320d implements patchInterface return true; } - } diff --git a/lib/classes/patch/320e.class.php b/lib/classes/patch/320e.class.php index 03946fb1d8..757b1d3b58 100644 --- a/lib/classes/patch/320e.class.php +++ b/lib/classes/patch/320e.class.php @@ -17,7 +17,6 @@ */ class patch_320e implements patchInterface { - /** * * @var string @@ -80,8 +79,7 @@ class patch_320e implements patchInterface $nodes = $xpath->query('//record/subdefs/subdefgroup/subdef'); - foreach ($nodes as $node) - { + foreach ($nodes as $node) { $name = mb_strtolower(trim($node->getAttribute('name'))); if ($name === '') continue; @@ -92,5 +90,4 @@ class patch_320e implements patchInterface return true; } - } diff --git a/lib/classes/patch/320f.class.php b/lib/classes/patch/320f.class.php index c9f1287237..a9f4476e24 100644 --- a/lib/classes/patch/320f.class.php +++ b/lib/classes/patch/320f.class.php @@ -17,12 +17,12 @@ */ class patch_320f implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a4'; + /** * * @var Array @@ -56,15 +56,12 @@ class patch_320f implements patchInterface { $feeds = array(); - try - { + try { $sql = 'ALTER TABLE `ssel` ADD `migrated` INT NOT NULL DEFAULT "0"'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - } - catch(Exception $e) - { + } catch (Exception $e) { } @@ -79,26 +76,22 @@ class patch_320f implements patchInterface $date_ref = new DateTime(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $user = User_Adapter::getInstance($row['usr_id'], $appbox); $feed = $this->get_feed($appbox, $user, $row['pub_restrict'], $row['homelink']); - if(!$feed instanceof Feed_Adapter) - { + if ( ! $feed instanceof Feed_Adapter) { continue; } $entry = Feed_Entry_Adapter::create($appbox, $feed, array_shift($feed->get_publishers()), $row['name'], $row['descript'], $user->get_display_name(), $user->get_email()); $date_create = new DateTime($row['pub_date']); - if ($date_create < $date_ref) - { + if ($date_create < $date_ref) { $date_ref = $date_create; } $entry->set_created_on($date_create); - if ($row['updater'] != '0000-00-00 00:00:00') - { + if ($row['updater'] != '0000-00-00 00:00:00') { $date_update = new DateTime($row['updater']); $entry->set_updated_on($date_update); } @@ -110,15 +103,11 @@ class patch_320f implements patchInterface $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { - try - { + foreach ($rs as $row) { + try { $record = new record_adapter(phrasea::sbasFromBas($row['base_id']), $row['record_id']); $item = Feed_Entry_Item::create($appbox, $entry, $record); - } - catch (Exception_NotFound $e) - { + } catch (Exception_NotFound $e) { } } @@ -136,17 +125,14 @@ class patch_320f implements patchInterface protected function set_feed_dates(DateTime $date_ref) { - foreach (self::$feeds as $array_feeds) - { - foreach ($array_feeds as $feed) - { + foreach (self::$feeds as $array_feeds) { + foreach ($array_feeds as $feed) { $feed->set_created_on($date_ref); } } return; } - protected static $feeds = array(); protected function get_feed(appbox &$appbox, User_Adapter &$user, $pub_restrict, $homelink) @@ -159,8 +145,7 @@ class patch_320f implements patchInterface else $feed_key = 'feed_public'; - if (!array_key_exists($user_key, self::$feeds) || !isset(self::$feeds[$user_key][$feed_key])) - { + if ( ! array_key_exists($user_key, self::$feeds) || ! isset(self::$feeds[$user_key][$feed_key])) { if ($homelink == '1') $title = $user->get_display_name() . ' - ' . 'homelink Feed'; elseif ($pub_restrict == '1') @@ -170,19 +155,13 @@ class patch_320f implements patchInterface $feed = Feed_Adapter::create($appbox, $user, $title, ''); - if ($homelink) - { + if ($homelink) { $feed->set_public(true); - } - elseif ($pub_restrict == 1) - { + } elseif ($pub_restrict == 1) { $collection = array_shift($user->ACL()->get_granted_base()); - if (!($collection instanceof collection)) - { - foreach ($appbox->get_databoxes() as $databox) - { - foreach ($databox->get_collections() as $coll) - { + if ( ! ($collection instanceof collection)) { + foreach ($appbox->get_databoxes() as $databox) { + foreach ($databox->get_collections() as $coll) { $collection = $coll; break; } @@ -191,8 +170,7 @@ class patch_320f implements patchInterface } } - if (!($collection instanceof collection)) - { + if ( ! ($collection instanceof collection)) { echo "unable to find a collection to protect feeds"; return false; @@ -200,13 +178,10 @@ class patch_320f implements patchInterface $feed->set_collection($collection); } self::$feeds[$user_key][$feed_key] = $feed; - } - else - { + } else { $feed = self::$feeds[$user_key][$feed_key]; } return $feed; } - } diff --git a/lib/classes/patch/320h.class.php b/lib/classes/patch/320h.class.php index 90db0bb095..48e80afc82 100644 --- a/lib/classes/patch/320h.class.php +++ b/lib/classes/patch/320h.class.php @@ -17,12 +17,12 @@ */ class patch_320h implements patchInterface { - /** * * @var string */ private $release = '3.2.0.0.a8'; + /** * * @var Array @@ -62,5 +62,4 @@ class patch_320h implements patchInterface return true; } - } diff --git a/lib/classes/patch/360.class.php b/lib/classes/patch/360.class.php index 72f8c0cdbe..66052d1eec 100644 --- a/lib/classes/patch/360.class.php +++ b/lib/classes/patch/360.class.php @@ -17,7 +17,6 @@ */ class patch_360 implements patchInterface { - /** * * @var string @@ -57,9 +56,8 @@ class patch_360 implements patchInterface { $tables = array('StoryWZ', 'ValidationDatas', 'ValidationParticipants', 'ValidationSessions', 'BasketElements', 'Baskets'); - foreach ($tables as $table) - { - $sql = 'DELETE FROM ' . $table; + foreach ($tables as $table) { + $sql = 'DELETE FROM ' . $table; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); @@ -79,25 +77,22 @@ class patch_360 implements patchInterface $current = array(); - foreach ($rs_s as $row_story) - { + foreach ($rs_s as $row_story) { $serial = $row_story['sbas_id'] . '_' . $row_story['usr_id'] . '_' . $row_story['record_id']; - if (isset($current[$serial])) - { + if (isset($current[$serial])) { $stories[] = $row_story; } $current[$serial] = $serial; } - $sql = 'DELETE FROM ssel + $sql = 'DELETE FROM ssel WHERE temporaryType="1" AND record_id = :record_id AND usr_id = :usr_id AND sbas_id = :sbas_id'; $stmt = $appbox->get_connection()->prepare($sql); - foreach ($stories as $row) - { + foreach ($stories as $row) { $params = array( ':usr_id' => $row['usr_id'], ':sbas_id' => $row['sbas_id'], @@ -133,16 +128,15 @@ class patch_360 implements patchInterface $stmt->closeCursor(); - $sql = 'SELECT ssel_id FROM ssel WHERE temporaryType = "0"'; + $sql = 'SELECT ssel_id FROM ssel WHERE temporaryType = "0"'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $sselcont_ids = array(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $sql = 'SELECT c.sselcont_id, c.record_id, b.sbas_id FROM sselcont c, bas b, ssel s WHERE s.temporaryType = "0" AND b.base_id = c.base_id @@ -150,17 +144,15 @@ class patch_360 implements patchInterface $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(array(':ssel_id' => $row['ssel_id'])); - $rs_be = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs_be = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $current = array(); - foreach ($rs_be as $row_sselcont) - { + foreach ($rs_be as $row_sselcont) { $serial = $row_sselcont['sbas_id'] . '_' . $row_sselcont['record_id']; - if (isset($current[$serial])) - { + if (isset($current[$serial])) { $sselcont_ids[] = $row_sselcont['sselcont_id']; } @@ -168,11 +160,10 @@ class patch_360 implements patchInterface } } - $sql = 'DELETE FROM sselcont WHERE sselcont_id = :sselcont_id'; - $stmt = $appbox->get_connection()->prepare($sql); + $sql = 'DELETE FROM sselcont WHERE sselcont_id = :sselcont_id'; + $stmt = $appbox->get_connection()->prepare($sql); - foreach ($sselcont_ids as $sselcont_id) - { + foreach ($sselcont_ids as $sselcont_id) { $stmt->execute(array(':sselcont_id' => $sselcont_id)); } @@ -232,11 +223,11 @@ class patch_360 implements patchInterface $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - $sql = 'INSERT INTO ValidationDatas ( + $sql = 'INSERT INTO ValidationDatas ( SELECT d.id , :participant_id as participant_id, d.sselcont_id, d.agreement, d.note, d.updated_on as updated FROM validate v, validate_datas d, sselcont c @@ -244,8 +235,7 @@ class patch_360 implements patchInterface AND v.usr_id = :usr_id AND v.ssel_id = :basket_id )'; $stmt = $appbox->get_connection()->prepare($sql); - foreach ($rs as $row) - { + foreach ($rs as $row) { $params = array( ':participant_id' => $row['participant_id'], ':basket_id' => $row['basket_id'], @@ -272,5 +262,4 @@ class patch_360 implements patchInterface return true; } - } diff --git a/lib/classes/patch/3602.class.php b/lib/classes/patch/3602.class.php index 16dc25db3e..e7f605941e 100644 --- a/lib/classes/patch/3602.class.php +++ b/lib/classes/patch/3602.class.php @@ -17,12 +17,12 @@ */ class patch_3602 implements patchInterface { - /** * * @var string */ private $release = '3.6.0a1'; + /** * * @var Array @@ -54,20 +54,16 @@ class patch_3602 implements patchInterface function apply(base &$databox) { - try - { + try { $sql = 'ALTER TABLE `metadatas` DROP INDEX `unique`'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - } - catch(\PDOException $e) - { + } catch (\PDOException $e) { } return true; } - } diff --git a/lib/classes/patch/3603.class.php b/lib/classes/patch/3603.class.php index f51b4dcc6b..5c0ee36786 100644 --- a/lib/classes/patch/3603.class.php +++ b/lib/classes/patch/3603.class.php @@ -17,12 +17,12 @@ */ class patch_3603 implements patchInterface { - /** * * @var string */ private $release = '3.6.0a2'; + /** * * @var Array @@ -64,5 +64,4 @@ class patch_3603 implements patchInterface return true; } - } diff --git a/lib/classes/patch/3604.class.php b/lib/classes/patch/3604.class.php index 20667935f2..648b89cd40 100644 --- a/lib/classes/patch/3604.class.php +++ b/lib/classes/patch/3604.class.php @@ -17,7 +17,6 @@ */ class patch_3604 implements patchInterface { - /** * * @var string @@ -58,9 +57,8 @@ class patch_3604 implements patchInterface /** * Fail if upgrade has previously failed, no problem */ - try - { - $sql = "ALTER TABLE `metadatas` + try { + $sql = "ALTER TABLE `metadatas` ADD `updated` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1', ADD INDEX ( `updated` )"; @@ -68,29 +66,24 @@ class patch_3604 implements patchInterface $stmt->execute(); $stmt->closeCursor(); - $sql = 'UPDATE metadatas SET updated = "0" + $sql = 'UPDATE metadatas SET updated = "0" WHERE meta_struct_id IN (SELECT id FROM metadatas_structure WHERE multi = "1")'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - } - catch (\Exception $e) - { + } catch (\Exception $e) { } - try - { + try { $sql = 'ALTER TABLE `metadatas` DROP INDEX `unique`'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - } - catch(\PDOException $e) - { + } catch (\PDOException $e) { } @@ -99,16 +92,15 @@ class patch_3604 implements patchInterface WHERE m.meta_struct_id = s.id AND s.multi = "1" AND updated="0"'; - $stmt = $databox->get_connection()->prepare($sql); + $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rowCount = $stmt->rowCount(); $stmt->closeCursor(); - $n = 0; + $n = 0; $perPage = 1000; - while ($n < $rowCount) - { + while ($n < $rowCount) { $sql = 'SELECT m . * FROM metadatas_structure s, metadatas m WHERE m.meta_struct_id = s.id @@ -116,30 +108,27 @@ class patch_3604 implements patchInterface $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $databox->get_connection()->beginTransaction(); - $sql = 'INSERT INTO metadatas(id, record_id, meta_struct_id, value) + $sql = 'INSERT INTO metadatas(id, record_id, meta_struct_id, value) VALUES (null, :record_id, :meta_struct_id, :value)'; $stmt = $databox->get_connection()->prepare($sql); $databox_fields = array(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $meta_struct_id = $row['meta_struct_id']; - if ( ! isset($databox_fields[$meta_struct_id])) - { + if ( ! isset($databox_fields[$meta_struct_id])) { $databox_fields[$meta_struct_id] = \databox_field::get_instance($databox, $meta_struct_id); } $values = \caption_field::get_multi_values($row['value'], $databox_fields[$meta_struct_id]->get_separator()); - foreach ($values as $value) - { + foreach ($values as $value) { $params = array( ':record_id' => $row['record_id'], ':meta_struct_id' => $row['meta_struct_id'], @@ -152,11 +141,10 @@ class patch_3604 implements patchInterface $stmt->closeCursor(); - $sql = 'DELETE FROM metadatas WHERE id = :id'; + $sql = 'DELETE FROM metadatas WHERE id = :id'; $stmt = $databox->get_connection()->prepare($sql); - foreach ($rs as $row) - { + foreach ($rs as $row) { $params = array(':id' => $row['id']); $stmt->execute($params); } @@ -171,19 +159,15 @@ class patch_3604 implements patchInterface /** * Remove the extra column */ - try - { - $sql = "ALTER TABLE `metadatas` DROP `updated`"; + try { + $sql = "ALTER TABLE `metadatas` DROP `updated`"; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); - } - catch (\Exception $e) - { + } catch (\Exception $e) { } return true; } - } diff --git a/lib/classes/patch/361.class.php b/lib/classes/patch/361.class.php index 9994700167..3ad29025e2 100644 --- a/lib/classes/patch/361.class.php +++ b/lib/classes/patch/361.class.php @@ -19,7 +19,6 @@ use Doctrine\ORM\Tools\Pagination\Paginator; */ class patch_361 implements patchInterface { - /** * * @var string @@ -63,35 +62,30 @@ class patch_361 implements patchInterface $conn = $appbox->get_connection(); - $sql = 'SELECT sbas_id, record_id, id FROM BasketElements'; - $stmt = $conn->prepare($sql); + $sql = 'SELECT sbas_id, record_id, id FROM BasketElements'; + $stmt = $conn->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($result as $row) - { + foreach ($result as $row) { $sbas_id = (int) $row['sbas_id']; - try - { + try { $connbas = connection::getPDOConnection($sbas_id); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']); $conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']); continue; } - $sql = 'SELECT record_id FROM record WHERE record_id = :record_id'; + $sql = 'SELECT record_id FROM record WHERE record_id = :record_id'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $row['record_id'])); - $rowCount = $stmt->rowCount(); + $rowCount = $stmt->rowCount(); $stmt->closeCursor(); - if ($rowCount == 0) - { + if ($rowCount == 0) { $conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']); $conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']); } @@ -100,7 +94,7 @@ class patch_361 implements patchInterface $dql = "SELECT b FROM Entities\Basket b WHERE b.description != ''"; - $n = 0; + $n = 0; $perPage = 100; $query = $em->createQuery($dql) @@ -111,22 +105,19 @@ class patch_361 implements patchInterface $count = count($paginator); - while ($n < $count) - { + while ($n < $count) { $query = $em->createQuery($dql) ->setFirstResult($n) ->setMaxResults($perPage); $paginator = new Paginator($query, true); - foreach ($paginator as $basket) - { + foreach ($paginator as $basket) { $htmlDesc = $basket->getDescription(); $description = trim(strip_tags(str_replace("
      ", "\n", $htmlDesc))); - if ($htmlDesc == $description) - { + if ($htmlDesc == $description) { continue; } @@ -142,6 +133,5 @@ class patch_361 implements patchInterface return true; } - } diff --git a/lib/classes/patch/370.class.php b/lib/classes/patch/370.class.php index 13a332dd57..8bdc1bbdbe 100644 --- a/lib/classes/patch/370.class.php +++ b/lib/classes/patch/370.class.php @@ -19,7 +19,6 @@ use Doctrine\ORM\Tools\Pagination\Paginator; */ class patch_370 implements patchInterface { - /** * * @var string @@ -59,14 +58,13 @@ class patch_370 implements patchInterface { $conn = $databox->get_connection(); - $sql = 'SELECT value FROM pref WHERE prop = "structure"'; - $stmt = $conn->prepare($sql); + $sql = 'SELECT value FROM pref WHERE prop = "structure"'; + $stmt = $conn->prepare($sql); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - if ( ! $result) - { + if ( ! $result) { throw new \RuntimeException('Unable to find structure'); } @@ -75,18 +73,16 @@ class patch_370 implements patchInterface $XPath = new DOMXPath($DOMDocument); - foreach ($XPath->query('/record/subdefs/subdefgroup/subdef/delay') as $delay) - { + foreach ($XPath->query('/record/subdefs/subdefgroup/subdef/delay') as $delay) { $delay->nodeValue = min(500, max(50, (int) $delay->nodeValue * 400)); } - $sql = 'UPDATE pref SET value = :structure WHERE prop = "structure"'; + $sql = 'UPDATE pref SET value = :structure WHERE prop = "structure"'; $stmt = $conn->prepare($sql); $stmt->execute(array(':structure' => $DOMDocument->saveXML())); $stmt->closeCursor(); return true; } - } diff --git a/lib/classes/patchInterface.class.php b/lib/classes/patchInterface.class.php index 3e0930e32d..e9ea24bf9a 100644 --- a/lib/classes/patchInterface.class.php +++ b/lib/classes/patchInterface.class.php @@ -2,11 +2,12 @@ interface patchInterface { - function get_release(); - function concern(); + function get_release(); - function require_all_upgrades(); + function concern(); - function apply(base &$base); + function require_all_upgrades(); + + function apply(base &$base); } diff --git a/lib/classes/phrasea.class.php b/lib/classes/phrasea.class.php index cfc2856d13..2986e1f519 100644 --- a/lib/classes/phrasea.class.php +++ b/lib/classes/phrasea.class.php @@ -11,549 +11,496 @@ class phrasea { + private static $_bas2sbas = false; + private static $_sbas_names = false; + private static $_coll2bas = false; + private static $_bas2coll = false; + private static $_bas_names = false; + private static $_sbas_params = false; - private static $_bas2sbas = false; - private static $_sbas_names = false; - private static $_coll2bas = false; - private static $_bas2coll = false; - private static $_bas_names = false; - private static $_sbas_params = false; + const CACHE_BAS_2_SBAS = 'bas_2_sbas'; + const CACHE_COLL_2_BAS = 'coll_2_bas'; + const CACHE_BAS_2_COLL = 'bas_2_coll'; + const CACHE_BAS_NAMES = 'bas_names'; + const CACHE_SBAS_NAMES = 'sbas_names'; + const CACHE_SBAS_FROM_BAS = 'sbas_from_bas'; + const CACHE_SBAS_PARAMS = 'sbas_params'; - const CACHE_BAS_2_SBAS = 'bas_2_sbas'; - const CACHE_COLL_2_BAS = 'coll_2_bas'; - const CACHE_BAS_2_COLL = 'bas_2_coll'; - const CACHE_BAS_NAMES = 'bas_names'; - const CACHE_SBAS_NAMES = 'sbas_names'; - const CACHE_SBAS_FROM_BAS = 'sbas_from_bas'; - const CACHE_SBAS_PARAMS = 'sbas_params'; - - public static function copy_custom_files() - { - $registry = registry::get_instance(); - - $origine = $registry->get('GV_RootPath') . 'config/custom_files/'; - $dest = $registry->get('GV_RootPath') . 'www/custom/'; - - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) + public static function copy_custom_files() { - if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) - continue; + $registry = registry::get_instance(); - $dest_file = str_replace($origine, $dest, $file->getRealPath()); - $dest_dir = dirname($dest_file); - if (!is_dir($dest_dir)) - system_file::mkdir($dest_dir); - copy($file->getRealPath(), $dest_file); - $system_file = new system_file($dest_file); - $system_file->chmod(); - unset($system_file); - } - $origine = $registry->get('GV_RootPath') . 'config/minilogos/'; - $dest = $registry->get('GV_RootPath') . 'www/custom/minilogos/'; + $origine = $registry->get('GV_RootPath') . 'config/custom_files/'; + $dest = $registry->get('GV_RootPath') . 'www/custom/'; - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) - { - if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) - continue; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) + continue; - $dest_file = str_replace($origine, $dest, $file->getRealPath()); - $dest_dir = dirname($dest_file); - if (!is_dir($dest_dir)) - system_file::mkdir($dest_dir); - copy($file->getRealPath(), $dest_file); - $system_file = new system_file($dest_file); - $system_file->chmod(); - unset($system_file); - } - $origine = $registry->get('GV_RootPath') . 'config/status/'; - $dest = $registry->get('GV_RootPath') . 'www/custom/status/'; + $dest_file = str_replace($origine, $dest, $file->getRealPath()); + $dest_dir = dirname($dest_file); + if ( ! is_dir($dest_dir)) + system_file::mkdir($dest_dir); + copy($file->getRealPath(), $dest_file); + $system_file = new system_file($dest_file); + $system_file->chmod(); + unset($system_file); + } + $origine = $registry->get('GV_RootPath') . 'config/minilogos/'; + $dest = $registry->get('GV_RootPath') . 'www/custom/minilogos/'; - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) - { - if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) - continue; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) + continue; - $dest_file = str_replace($origine, $dest, $file->getRealPath()); - $dest_dir = dirname($dest_file); - if (!is_dir($dest_dir)) - system_file::mkdir($dest_dir); - copy($file->getRealPath(), $dest_file); - $system_file = new system_file($dest_file); - $system_file->chmod(); - unset($system_file); - } - } + $dest_file = str_replace($origine, $dest, $file->getRealPath()); + $dest_dir = dirname($dest_file); + if ( ! is_dir($dest_dir)) + system_file::mkdir($dest_dir); + copy($file->getRealPath(), $dest_file); + $system_file = new system_file($dest_file); + $system_file->chmod(); + unset($system_file); + } + $origine = $registry->get('GV_RootPath') . 'config/status/'; + $dest = $registry->get('GV_RootPath') . 'www/custom/status/'; - public static function is_scheduler_started() - { - $retval = false; - $conn = connection::getPDOConnection(); - $sql = 'SELECT schedstatus FROM sitepreff'; + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if (substr($file->getFilename(), 0, 1) == '.' || strpos($file->getRealPath(), '.svn') !== false) + continue; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if ($row && $row['schedstatus'] != 'stopped') - { - $retval = true; + $dest_file = str_replace($origine, $dest, $file->getRealPath()); + $dest_dir = dirname($dest_file); + if ( ! is_dir($dest_dir)) + system_file::mkdir($dest_dir); + copy($file->getRealPath(), $dest_file); + $system_file = new system_file($dest_file); + $system_file->chmod(); + unset($system_file); + } } - return $retval; - } - - public static function start(\Alchemy\Phrasea\Core $Core) - { - $configuration = $Core->getConfiguration(); - - $choosenConnexion = $configuration->getPhraseanet()->get('database'); - - $connexion = $configuration->getConnexion($choosenConnexion); - - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - $dbname = $connexion->get('dbname'); - - if (!extension_loaded('phrasea2')) - printf("Missing Extension php-phrasea"); - - if (function_exists('phrasea_conn')) - if (phrasea_conn($hostname, $port, $user, $password, $dbname) !== true) - self::headers(500); - } - - function getHome($type='PUBLI', $context='prod') - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - if ($type == 'HELP') + public static function is_scheduler_started() { - if (file_exists($registry->get('GV_RootPath') . "config/help_" . $session->get_I18n() . ".php")) - { - require($registry->get('GV_RootPath') . "config/help_" . $session->get_I18n() . ".php"); - } - elseif (file_exists($registry->get('GV_RootPath') . 'config/help.php'))// on verifie si il y a une home personnalisee sans langage - { - require($registry->get('GV_RootPath') . 'config/help.php'); - } - else - { - require($registry->get('GV_RootPath') . 'www/client/help.php'); - } + $retval = false; + $conn = connection::getPDOConnection(); + $sql = 'SELECT schedstatus FROM sitepreff'; + + $stmt = $conn->prepare($sql); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row && $row['schedstatus'] != 'stopped') { + $retval = true; + } + + return $retval; } - if ($type == 'PUBLI') + public static function start(\Alchemy\Phrasea\Core $Core) { - if ($context == 'prod') - require($registry->get('GV_RootPath') . "www/prod/homeinterpubbask.php"); - else - require($registry->get('GV_RootPath') . "www/client/homeinterpubbask.php"); + $configuration = $Core->getConfiguration(); + + $choosenConnexion = $configuration->getPhraseanet()->get('database'); + + $connexion = $configuration->getConnexion($choosenConnexion); + + $hostname = $connexion->get('host'); + $port = $connexion->get('port'); + $user = $connexion->get('user'); + $password = $connexion->get('password'); + $dbname = $connexion->get('dbname'); + + if ( ! extension_loaded('phrasea2')) + printf("Missing Extension php-phrasea"); + + if (function_exists('phrasea_conn')) + if (phrasea_conn($hostname, $port, $user, $password, $dbname) !== true) + self::headers(500); } - if (in_array($type, array('QUERY', 'LAST_QUERY'))) + function getHome($type = 'PUBLI', $context = 'prod') { - $context = in_array($context, array('client', 'prod')) ? $context : 'prod'; - $parm = array(); - - $bas = array(); - - $searchSet = json_decode($user->getPrefs('search')); - - if ($searchSet && isset($searchSet->bases)) - { - foreach ($searchSet->bases as $bases) - $bas = array_merge($bas, $bases); - } - else - { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $bas = array_keys($user->ACL()->get_granted_base()); - } + if ($type == 'HELP') { + if (file_exists($registry->get('GV_RootPath') . "config/help_" . $session->get_I18n() . ".php")) { + require($registry->get('GV_RootPath') . "config/help_" . $session->get_I18n() . ".php"); + } elseif (file_exists($registry->get('GV_RootPath') . 'config/help.php')) {// on verifie si il y a une home personnalisee sans langage + require($registry->get('GV_RootPath') . 'config/help.php'); + } else { + require($registry->get('GV_RootPath') . 'www/client/help.php'); + } + } - $start_page_query = $user->getPrefs('start_page_query'); + if ($type == 'PUBLI') { + if ($context == 'prod') + require($registry->get('GV_RootPath') . "www/prod/homeinterpubbask.php"); + else + require($registry->get('GV_RootPath') . "www/client/homeinterpubbask.php"); + } - if ($context == "prod") - { - $parm["bas"] = $bas; - $parm["qry"] = $start_page_query; - $parm["pag"] = 0; - $parm["sel"] = ''; - $parm["ord"] = null; - $parm["search_type"] = 0; - $parm["recordtype"] = ''; - $parm["status"] = array(); - $parm["fields"] = array(); - $parm["datemin"] = ''; - $parm["datemax"] = ''; - $parm["datefield"] = ''; - } - if ($context == "client") - { - $parm["mod"] = $user->getPrefs('client_view'); - $parm["bas"] = $bas; - $parm["qry"] = $start_page_query; - $parm["pag"] = ''; - $parm["search_type"] = 0; - $parm["qryAdv"] = ''; - $parm["opAdv"] = array(); - $parm["status"] = ''; - $parm["nba"] = ''; - $parm["datemin"] = ''; - $parm["datemax"] = ''; - $parm["recordtype"] = ''; - $parm["datefield"] = ''; - $parm["sort"] = ''; - $parm["stemme"] = ''; - $parm["dateminfield"] = array(); - $parm["datemaxfield"] = array(); - $parm["infield"] = ''; - $parm["regroup"] = null; - $parm["ord"] = 0; - } + if (in_array($type, array('QUERY', 'LAST_QUERY'))) { + $context = in_array($context, array('client', 'prod')) ? $context : 'prod'; + $parm = array(); - require($registry->get('GV_RootPath') . 'www/' . $context . "/answer.php"); + $bas = array(); + + $searchSet = json_decode($user->getPrefs('search')); + + if ($searchSet && isset($searchSet->bases)) { + foreach ($searchSet->bases as $bases) + $bas = array_merge($bas, $bases); + } else { + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $bas = array_keys($user->ACL()->get_granted_base()); + } + + $start_page_query = $user->getPrefs('start_page_query'); + + if ($context == "prod") { + $parm["bas"] = $bas; + $parm["qry"] = $start_page_query; + $parm["pag"] = 0; + $parm["sel"] = ''; + $parm["ord"] = null; + $parm["search_type"] = 0; + $parm["recordtype"] = ''; + $parm["status"] = array(); + $parm["fields"] = array(); + $parm["datemin"] = ''; + $parm["datemax"] = ''; + $parm["datefield"] = ''; + } + if ($context == "client") { + $parm["mod"] = $user->getPrefs('client_view'); + $parm["bas"] = $bas; + $parm["qry"] = $start_page_query; + $parm["pag"] = ''; + $parm["search_type"] = 0; + $parm["qryAdv"] = ''; + $parm["opAdv"] = array(); + $parm["status"] = ''; + $parm["nba"] = ''; + $parm["datemin"] = ''; + $parm["datemax"] = ''; + $parm["recordtype"] = ''; + $parm["datefield"] = ''; + $parm["sort"] = ''; + $parm["stemme"] = ''; + $parm["dateminfield"] = array(); + $parm["datemaxfield"] = array(); + $parm["infield"] = ''; + $parm["regroup"] = null; + $parm["ord"] = 0; + } + + require($registry->get('GV_RootPath') . 'www/' . $context . "/answer.php"); + } + + return; } - return; - } - - public static function clear_sbas_params() - { - self::$_sbas_params = null; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $appbox->delete_data_from_cache(self::CACHE_SBAS_PARAMS); - - return true; - } - - public static function sbas_params() - { - if (self::$_sbas_params) - - return self::$_sbas_params; - - $appbox = appbox::get_instance(\bootstrap::getCore()); - try - { - self::$_sbas_params = $appbox->get_data_from_cache(self::CACHE_SBAS_PARAMS); - - return self::$_sbas_params; - } - catch (Exception $e) + public static function clear_sbas_params() { + self::$_sbas_params = null; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $appbox->delete_data_from_cache(self::CACHE_SBAS_PARAMS); + return true; } - self::$_sbas_params = array(); - - $sql = 'SELECT sbas_id, host, port, user, pwd, dbname FROM sbas'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) + public static function sbas_params() { - self::$_sbas_params[$row['sbas_id']] = $row; - } + if (self::$_sbas_params) + return self::$_sbas_params; - $appbox->set_data_to_cache(self::$_sbas_params, self::CACHE_SBAS_PARAMS); + $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + self::$_sbas_params = $appbox->get_data_from_cache(self::CACHE_SBAS_PARAMS); - return self::$_sbas_params; - } + return self::$_sbas_params; + } catch (Exception $e) { - public static function guest_allowed() - { - $usr_id = User_Adapter::get_usr_id_from_login('invite'); - if (!$usr_id) + } - return false; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $user = User_Adapter::getInstance($usr_id, $appbox); + self::$_sbas_params = array(); - return count($user->ACL()->get_granted_base()) > 0; - } - - public static function use_i18n($locale, $textdomain = 'phraseanet') - { - $codeset = "UTF-8"; - - putenv('LANG=' . $locale . '.' . $codeset); - putenv('LANGUAGE=' . $locale . '.' . $codeset); - bind_textdomain_codeset($textdomain, 'UTF-8'); - - bindtextdomain($textdomain, __DIR__ . '/../../locale/'); - setlocale(LC_ALL - , $locale . '.UTF-8' - , $locale . '.UTF8' - , $locale . '.utf-8' - , $locale . '.utf8'); - textdomain($textdomain); - } - - public static function modulesName($array_modules) - { - $array = array(); - - $modules = array( - 1 => _('admin::monitor: module production'), - 2 => _('admin::monitor: module client'), - 3 => _('admin::monitor: module admin'), - 4 => _('admin::monitor: module report'), - 5 => _('admin::monitor: module thesaurus'), - 6 => _('admin::monitor: module comparateur'), - 7 => _('admin::monitor: module validation'), - 8 => _('admin::monitor: module upload') - ); - - foreach ($array_modules as $a) - { - if (isset($modules[$a])) - $array[] = $modules[$a]; - } - - - return $array; - } - - public static function sbasFromBas($base_id) - { - if (!self::$_bas2sbas) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - try - { - self::$_bas2sbas = $appbox->get_data_from_cache(self::CACHE_SBAS_FROM_BAS); - } - catch (Exception $e) - { - $sql = 'SELECT base_id, sbas_id FROM bas'; + $sql = 'SELECT sbas_id, host, port, user, pwd, dbname FROM sbas'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { - self::$_bas2sbas[$row['base_id']] = (int) $row['sbas_id']; + foreach ($rs as $row) { + self::$_sbas_params[$row['sbas_id']] = $row; } - $appbox->set_data_to_cache(self::$_bas2sbas, self::CACHE_SBAS_FROM_BAS); - } + $appbox->set_data_to_cache(self::$_sbas_params, self::CACHE_SBAS_PARAMS); + + return self::$_sbas_params; } - return isset(self::$_bas2sbas[$base_id]) ? self::$_bas2sbas[$base_id] : false; - } - - public static function baseFromColl($sbas_id, $coll_id) - { - if (!self::$_coll2bas) + public static function guest_allowed() { - $conn = connection::getPDOConnection(); - $sql = 'SELECT base_id, server_coll_id, sbas_id FROM bas'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $usr_id = User_Adapter::get_usr_id_from_login('invite'); + if ( ! $usr_id) + return false; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $user = User_Adapter::getInstance($usr_id, $appbox); - foreach ($rs as $row) - { - if (!isset(self::$_coll2bas[$row['sbas_id']])) - self::$_coll2bas[$row['sbas_id']] = array(); - self::$_coll2bas[$row['sbas_id']][$row['server_coll_id']] = (int) $row['base_id']; - } + return count($user->ACL()->get_granted_base()) > 0; } - return isset(self::$_coll2bas[$sbas_id][$coll_id]) ? self::$_coll2bas[$sbas_id][$coll_id] : false; - } + public static function use_i18n($locale, $textdomain = 'phraseanet') + { + $codeset = "UTF-8"; - public static function reset_baseDatas() - { - self::$_coll2bas = self::$_bas2coll = self::$_bas_names = self::$_bas2sbas = null; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $appbox->delete_data_from_cache( + putenv('LANG=' . $locale . '.' . $codeset); + putenv('LANGUAGE=' . $locale . '.' . $codeset); + bind_textdomain_codeset($textdomain, 'UTF-8'); + + bindtextdomain($textdomain, __DIR__ . '/../../locale/'); + setlocale(LC_ALL + , $locale . '.UTF-8' + , $locale . '.UTF8' + , $locale . '.utf-8' + , $locale . '.utf8'); + textdomain($textdomain); + } + + public static function modulesName($array_modules) + { + $array = array(); + + $modules = array( + 1 => _('admin::monitor: module production'), + 2 => _('admin::monitor: module client'), + 3 => _('admin::monitor: module admin'), + 4 => _('admin::monitor: module report'), + 5 => _('admin::monitor: module thesaurus'), + 6 => _('admin::monitor: module comparateur'), + 7 => _('admin::monitor: module validation'), + 8 => _('admin::monitor: module upload') + ); + + foreach ($array_modules as $a) { + if (isset($modules[$a])) + $array[] = $modules[$a]; + } + + + return $array; + } + + public static function sbasFromBas($base_id) + { + if ( ! self::$_bas2sbas) { + $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + self::$_bas2sbas = $appbox->get_data_from_cache(self::CACHE_SBAS_FROM_BAS); + } catch (Exception $e) { + $sql = 'SELECT base_id, sbas_id FROM bas'; + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row) { + self::$_bas2sbas[$row['base_id']] = (int) $row['sbas_id']; + } + + $appbox->set_data_to_cache(self::$_bas2sbas, self::CACHE_SBAS_FROM_BAS); + } + } + + return isset(self::$_bas2sbas[$base_id]) ? self::$_bas2sbas[$base_id] : false; + } + + public static function baseFromColl($sbas_id, $coll_id) + { + if ( ! self::$_coll2bas) { + $conn = connection::getPDOConnection(); + $sql = 'SELECT base_id, server_coll_id, sbas_id FROM bas'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row) { + if ( ! isset(self::$_coll2bas[$row['sbas_id']])) + self::$_coll2bas[$row['sbas_id']] = array(); + self::$_coll2bas[$row['sbas_id']][$row['server_coll_id']] = (int) $row['base_id']; + } + } + + return isset(self::$_coll2bas[$sbas_id][$coll_id]) ? self::$_coll2bas[$sbas_id][$coll_id] : false; + } + + public static function reset_baseDatas() + { + self::$_coll2bas = self::$_bas2coll = self::$_bas_names = self::$_bas2sbas = null; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $appbox->delete_data_from_cache( array( self::CACHE_BAS_2_COLL , self::CACHE_BAS_2_COLL , self::CACHE_BAS_NAMES , self::CACHE_SBAS_FROM_BAS ) - ); + ); - return; - } + return; + } - public static function reset_sbasDatas() - { - self::$_sbas_names = self::$_sbas_params = self::$_bas2sbas = null; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $appbox->delete_data_from_cache( + public static function reset_sbasDatas() + { + self::$_sbas_names = self::$_sbas_params = self::$_bas2sbas = null; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $appbox->delete_data_from_cache( array( self::CACHE_SBAS_NAMES , self::CACHE_SBAS_FROM_BAS , self::CACHE_SBAS_PARAMS ) - ); + ); - return; - } - - public static function collFromBas($base_id) - { - if (!self::$_bas2coll) - { - $conn = connection::getPDOConnection(); - $sql = 'SELECT base_id, server_coll_id FROM bas'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) - { - self::$_bas2coll[$row['base_id']] = (int) $row['server_coll_id']; - } + return; } - return isset(self::$_bas2coll[$base_id]) ? self::$_bas2coll[$base_id] : false; - } - - public static function sbas_names($sbas_id) - { - if (!self::$_sbas_names) + public static function collFromBas($base_id) { - $appbox = appbox::get_instance(\bootstrap::getCore()); - try - { - self::$_sbas_names = $appbox->get_data_from_cache(self::CACHE_SBAS_NAMES); - } - catch (Exception $e) - { - $sql = 'SELECT sbas_id, viewname, dbname FROM sbas'; - $stmt = $appbox->get_connection()->prepare($sql); + if ( ! self::$_bas2coll) { + $conn = connection::getPDOConnection(); + $sql = 'SELECT base_id, server_coll_id FROM bas'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row) { + self::$_bas2coll[$row['base_id']] = (int) $row['server_coll_id']; + } + } + + return isset(self::$_bas2coll[$base_id]) ? self::$_bas2coll[$base_id] : false; + } + + public static function sbas_names($sbas_id) + { + if ( ! self::$_sbas_names) { + $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + self::$_sbas_names = $appbox->get_data_from_cache(self::CACHE_SBAS_NAMES); + } catch (Exception $e) { + $sql = 'SELECT sbas_id, viewname, dbname FROM sbas'; + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row) { + $row['viewname'] = trim($row['viewname']); + self::$_sbas_names[$row['sbas_id']] = $row['viewname'] ? $row['viewname'] : $row['dbname']; + } + $appbox->set_data_to_cache(self::$_sbas_names, self::CACHE_SBAS_NAMES); + } + } + + return isset(self::$_sbas_names[$sbas_id]) ? self::$_sbas_names[$sbas_id] : 'Unknown base'; + } + + public static function bas_names($base_id) + { + if ( ! self::$_bas_names) { + $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + self::$_bas_names = $appbox->get_data_from_cache(self::CACHE_BAS_NAMES); + } catch (Exception $e) { + foreach ($appbox->get_databoxes() as $databox) { + foreach ($databox->get_collections() as $collection) { + self::$_bas_names[$collection->get_base_id()] = $collection->get_name(); + } + } + + $appbox->set_data_to_cache(self::$_bas_names, self::CACHE_BAS_NAMES); + } + } + + return isset(self::$_bas_names[$base_id]) ? self::$_bas_names[$base_id] : 'Unknown collection'; + } + + public static function redirect($url) + { + header("Location: $url"); + exit; + } + + public static function headers($code = 200, $nocache = false, $content = 'text/html', $charset = 'UTF-8', $doctype = true) + { + switch ((int) $code) { + case 204: + case 403: + case 404: + case 400: + case 500: + $request = http_request::getInstance(); + if ($request->is_ajax()) { + $Response = new \Symfony\Component\HttpFoundation\Response(sprintf('error %d : Content unavailable', (int) $code), $code); + $Response->send(); + exit(); + } else { + $request->set_code($code); + include(__DIR__ . '/../../www/include/error.php'); + } + die(); + break; + + case 200: + header("Content-Type: " . $content . "; charset=" . $charset); + if ($nocache) { + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified + header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); // HTTP/1.0 + } + if ($doctype) + echo ''; + break; + } + + return; + } + + public static function scheduler_key($renew = false) + { + $conn = connection::getPDOConnection(); + + $schedulerkey = false; + + $sql = 'SELECT schedulerkey FROM sitepreff'; + + $stmt = $conn->prepare($sql); $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { - $row['viewname'] = trim($row['viewname']); - self::$_sbas_names[$row['sbas_id']] = $row['viewname'] ? $row['viewname'] : $row['dbname']; - } - $appbox->set_data_to_cache(self::$_sbas_names, self::CACHE_SBAS_NAMES); - } - } - - return isset(self::$_sbas_names[$sbas_id]) ? self::$_sbas_names[$sbas_id] : 'Unknown base'; - } - - public static function bas_names($base_id) - { - if (!self::$_bas_names) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - try - { - self::$_bas_names = $appbox->get_data_from_cache(self::CACHE_BAS_NAMES); - } - catch (Exception $e) - { - foreach ($appbox->get_databoxes() as $databox) - { - foreach ($databox->get_collections() as $collection) - { - self::$_bas_names[$collection->get_base_id()] = $collection->get_name(); - } + if ($row) { + $schedulerkey = trim($row['schedulerkey']); } - $appbox->set_data_to_cache(self::$_bas_names, self::CACHE_BAS_NAMES); - } - } - - return isset(self::$_bas_names[$base_id]) ? self::$_bas_names[$base_id] : 'Unknown collection'; - } - - public static function redirect($url) - { - header("Location: $url"); - exit; - } - - public static function headers($code = 200, $nocache=false, $content='text/html', $charset='UTF-8', $doctype=true) - { - switch ((int) $code) - { - case 204: - case 403: - case 404: - case 400: - case 500: - $request = http_request::getInstance(); - if ($request->is_ajax()) - { - $Response = new \Symfony\Component\HttpFoundation\Response(sprintf('error %d : Content unavailable', (int) $code), $code); - $Response->send(); - exit(); + if ($renew === true || $schedulerkey == '') { + $schedulerkey = random::generatePassword(20); + $sql = 'UPDATE sitepreff SET schedulerkey = :scheduler_key'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':scheduler_key' => $schedulerkey)); + $stmt->closeCursor(); } - else - { - $request->set_code($code); - include(__DIR__ . '/../../www/include/error.php'); - } - die(); - break; - case 200: - header("Content-Type: " . $content . "; charset=" . $charset); - if ($nocache) - { - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified - header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); // HTTP/1.0 - } - if ($doctype) - echo ''; - break; + return $schedulerkey; } - - return; - } - - public static function scheduler_key($renew = false) - { - $conn = connection::getPDOConnection(); - - $schedulerkey = false; - - $sql = 'SELECT schedulerkey FROM sitepreff'; - - $stmt = $conn->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if ($row) - { - $schedulerkey = trim($row['schedulerkey']); - } - - if ($renew === true || $schedulerkey == '') - { - $schedulerkey = random::generatePassword(20); - $sql = 'UPDATE sitepreff SET schedulerkey = :scheduler_key'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':scheduler_key' => $schedulerkey)); - $stmt->closeCursor(); - } - - return $schedulerkey; - } - } diff --git a/lib/classes/phraseadate.class.php b/lib/classes/phraseadate.class.php index 0fcb6b05ad..a68210afad 100644 --- a/lib/classes/phraseadate.class.php +++ b/lib/classes/phraseadate.class.php @@ -16,413 +16,362 @@ class phraseadate { - /** - * - * @param DateTime $date - * @return string - */ - public static function getTime(DateTime $date) - { - $locale = Session_Handler::get_locale(); - - switch ($locale) + /** + * + * @param DateTime $date + * @return string + */ + public static function getTime(DateTime $date) { - default: - case 'fr_FR': - case 'de_DE': - $time = $date->format('H:i'); - break; - case 'en_GB': - $time = $date->format('h:iA'); - break; - } + $locale = Session_Handler::get_locale(); - return $time; - } - - /** - * - * @param DateTime $date - * @return string - */ - public static function getDate(DateTime $date) - { - $compareTo = new DateTime('now'); - $diff = $compareTo->format('U') - $date->format('U'); - $dayDiff = floor($diff / 86400); - - if (is_nan($dayDiff)) - { - return ''; - } - - if ($dayDiff < 365) - { - return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH'); - } - else - { - return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH_YEAR'); - } - } - - /** - * - * @param DateTime $date - * @return string - */ - public static function getPrettyString(DateTime $date = null) - { - if(is_null($date)) - - return null; - - $compareTo = new DateTime('now'); - $diff = $compareTo->format('U') - $date->format('U'); - $dayDiff = floor($diff / 86400); - - if (is_nan($dayDiff) || $dayDiff > 365000) - { - return ''; - } - - $date_string = self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH'); - - if ($dayDiff == 0) - { - if ($diff < 60) - { - return _('phraseanet::temps:: a l\'instant'); - } - elseif ($diff < 120) - { - return _('phraseanet::temps:: il y a une minute'); - } - elseif ($diff < 3600) - { - return sprintf(_('phraseanet::temps:: il y a %d minutes') - , floor($diff / 60)); - } - elseif ($diff < 7200) - { - return _('phraseanet::temps:: il y a une heure'); - } - elseif ($diff < 86400) - { - return sprintf(_('phraseanet::temps:: il y a %d heures') - , floor($diff / 3600)); - } - } - elseif ($dayDiff == 1) - { - return _('phraseanet::temps:: hier'); - } - elseif ($dayDiff < 365 && $dayDiff > 0) - { - return $date_string; - } - else - { - return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH_YEAR'); - } - } - - /** - * - * @param DateTime $date - * @return string - */ - public static function format_mysql(DateTime $date) - { - return $date->format(DATE_ISO8601); - } - - /** - * - * @param DateTime $date - * @param string $locale - * @param string $format - * @return string - */ - private function formatDate(DateTime $date, $locale, $format) - { - - switch ($locale) - { - default: - case 'fr_FR': - switch ($format) - { - default: - case 'DAY_MONTH': - $date_formated = strftime("%e %B", $date->format('U')); - break; - case 'DAY_MONTH_YEAR': - $date_formated = strftime("%e %B %Y", $date->format('U')); - break; + switch ($locale) { + default: + case 'fr_FR': + case 'de_DE': + $time = $date->format('H:i'); + break; + case 'en_GB': + $time = $date->format('h:iA'); + break; } - break; - case 'en_GB': - switch ($format) - { - default: - case 'DAY_MONTH': - $date_formated = strftime("%B %e", $date->format('U')); - break; - case 'DAY_MONTH_YEAR': - $date_formated = strftime("%B %e %Y", $date->format('U')); - break; - } - break; - case 'de_DE': - switch ($format) - { - default: - case 'DAY_MONTH': - $date_formated = strftime("%e. %B", $date->format('U')); - break; - case 'DAY_MONTH_YEAR': - $date_formated = strftime("%e. %B %Y", $date->format('U')); - break; - } - break; + + return $time; } - return $date_formated; - } - - /** - * - * @param string $isodelimdate - * @param string $format - * @return string - */ - public static function isodateToDate($isodelimdate, $format) - { - $tc = array(); - $bal = array(); - $isodelimdate = trim($isodelimdate); - - while ($isodelimdate != "") + /** + * + * @param DateTime $date + * @return string + */ + public static function getDate(DateTime $date) { - if (($c = $isodelimdate[0]) == "<") - { - if (($p = strpos($isodelimdate, ">")) !== false) - { - if ($isodelimdate[1] == "/") - { - array_pop($bal); - } - else - { - if ($isodelimdate[$p - 1] != "/") - array_push($bal, substr($isodelimdate, 1, $p - 1)); - } - $isodelimdate = substr($isodelimdate, $p + 1); + $compareTo = new DateTime('now'); + $diff = $compareTo->format('U') - $date->format('U'); + $dayDiff = floor($diff / 86400); + + if (is_nan($dayDiff)) { + return ''; } - else - { - $isodelimdate = ""; + + if ($dayDiff < 365) { + return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH'); + } else { + return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH_YEAR'); } - } - else - { - $tc[] = array("char" => $c, "bals" => $bal); - $isodelimdate = substr($isodelimdate, 1); - } } - $strdate = ""; - $paterns = array("YYYY" => 0, "YY" => 2, "MM" => 5, - "DD" => 8, "HH" => 11, "NN" => 14, "SS" => 17); - - while ($format != "") + /** + * + * @param DateTime $date + * @return string + */ + public static function getPrettyString(DateTime $date = null) { - $patfound = false; - foreach ($paterns as $pat => $idx) - { - if (substr($format, 0, ($l = strlen($pat))) == $pat) - { - for ($i = 0; $i < $l; $i++) - { - $bal_out = ""; - if (isset($tc[$idx + $i])) - { - foreach ($tc[$idx + $i]["bals"] as $b) - { - $strdate .= "<$b>"; - $bal_out = "" . $bal_out; - } - $strdate .= $tc[$idx + $i]["char"] . $bal_out; + if (is_null($date)) + return null; + + $compareTo = new DateTime('now'); + $diff = $compareTo->format('U') - $date->format('U'); + $dayDiff = floor($diff / 86400); + + if (is_nan($dayDiff) || $dayDiff > 365000) { + return ''; + } + + $date_string = self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH'); + + if ($dayDiff == 0) { + if ($diff < 60) { + return _('phraseanet::temps:: a l\'instant'); + } elseif ($diff < 120) { + return _('phraseanet::temps:: il y a une minute'); + } elseif ($diff < 3600) { + return sprintf(_('phraseanet::temps:: il y a %d minutes') + , floor($diff / 60)); + } elseif ($diff < 7200) { + return _('phraseanet::temps:: il y a une heure'); + } elseif ($diff < 86400) { + return sprintf(_('phraseanet::temps:: il y a %d heures') + , floor($diff / 3600)); } - } - $format = substr($format, $l); - $patfound = true; - break; + } elseif ($dayDiff == 1) { + return _('phraseanet::temps:: hier'); + } elseif ($dayDiff < 365 && $dayDiff > 0) { + return $date_string; + } else { + return self::formatDate($date, Session_Handler::get_locale(), 'DAY_MONTH_YEAR'); } - } - if (!$patfound) - { - $strdate .= $format[0]; - $format = substr($format, 1); - } } - return($strdate); - } + /** + * + * @param DateTime $date + * @return string + */ + public static function format_mysql(DateTime $date) + { + return $date->format(DATE_ISO8601); + } - /** - * - * @param string $strdate - * @param string $format - * @return string - */ - public static function dateToIsodate($strdate, $format) - { - $v_y = $v_m = $v_d = $v_h = $v_n = $v_s = 0; - $v = str_replace( + /** + * + * @param DateTime $date + * @param string $locale + * @param string $format + * @return string + */ + private function formatDate(DateTime $date, $locale, $format) + { + + switch ($locale) { + default: + case 'fr_FR': + switch ($format) { + default: + case 'DAY_MONTH': + $date_formated = strftime("%e %B", $date->format('U')); + break; + case 'DAY_MONTH_YEAR': + $date_formated = strftime("%e %B %Y", $date->format('U')); + break; + } + break; + case 'en_GB': + switch ($format) { + default: + case 'DAY_MONTH': + $date_formated = strftime("%B %e", $date->format('U')); + break; + case 'DAY_MONTH_YEAR': + $date_formated = strftime("%B %e %Y", $date->format('U')); + break; + } + break; + case 'de_DE': + switch ($format) { + default: + case 'DAY_MONTH': + $date_formated = strftime("%e. %B", $date->format('U')); + break; + case 'DAY_MONTH_YEAR': + $date_formated = strftime("%e. %B %Y", $date->format('U')); + break; + } + break; + } + + return $date_formated; + } + + /** + * + * @param string $isodelimdate + * @param string $format + * @return string + */ + public static function isodateToDate($isodelimdate, $format) + { + $tc = array(); + $bal = array(); + $isodelimdate = trim($isodelimdate); + + while ($isodelimdate != "") { + if (($c = $isodelimdate[0]) == "<") { + if (($p = strpos($isodelimdate, ">")) !== false) { + if ($isodelimdate[1] == "/") { + array_pop($bal); + } else { + if ($isodelimdate[$p - 1] != "/") + array_push($bal, substr($isodelimdate, 1, $p - 1)); + } + $isodelimdate = substr($isodelimdate, $p + 1); + } + else { + $isodelimdate = ""; + } + } else { + $tc[] = array("char" => $c, "bals" => $bal); + $isodelimdate = substr($isodelimdate, 1); + } + } + + $strdate = ""; + $paterns = array("YYYY" => 0, "YY" => 2, "MM" => 5, + "DD" => 8, "HH" => 11, "NN" => 14, "SS" => 17); + + while ($format != "") { + $patfound = false; + foreach ($paterns as $pat => $idx) { + if (substr($format, 0, ($l = strlen($pat))) == $pat) { + for ($i = 0; $i < $l; $i ++ ) { + $bal_out = ""; + if (isset($tc[$idx + $i])) { + foreach ($tc[$idx + $i]["bals"] as $b) { + $strdate .= "<$b>"; + $bal_out = "" . $bal_out; + } + $strdate .= $tc[$idx + $i]["char"] . $bal_out; + } + } + $format = substr($format, $l); + $patfound = true; + break; + } + } + if ( ! $patfound) { + $strdate .= $format[0]; + $format = substr($format, 1); + } + } + + return($strdate); + } + + /** + * + * @param string $strdate + * @param string $format + * @return string + */ + public static function dateToIsodate($strdate, $format) + { + $v_y = $v_m = $v_d = $v_h = $v_n = $v_s = 0; + $v = str_replace( array("-", ":", "/", "."), array(" ", " ", " ", " "), trim($strdate) - ); - $n = 0; - - $format = str_replace( - array("-", ":", "/", "."), array(" ", " ", " ", " "), $format - ); - $isodelimdate = null; - switch ($format) - { - case "MM YYYY": - case "MM YYYY HH NN SS": - $n = sscanf($v, "%d %d %d %d %d", $v_m, $v_y, $v_h, $v_n, $v_s); - break; - case "MMYYYY": - case "MMYYYYHHNNSS": - $n = sscanf($v, "%d%d%d%d%d", $v_m, $v_y, $v_h, $v_n, $v_s); - break; - case "DD MM YYYY": - case "DD MM YYYY HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); - break; - case "DDMMYYYY": - case "DDMMYYYYHHNNSS": - $n = sscanf($v, "%02d%02d%04d%02d%02d%02d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); - break; - case "DD MM YY": - case "DD MM YY HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - if ($v_y < 100) - $v += 1900; - break; - case "DDMMYY": - case "DDMMYYHHNNSS": - $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - $v += 1900; - break; - case "MM DD YYYY": - case "MM DD YYYY HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); - break; - case "MMDDYYYY": - case "MMDDYYYYHHNNSS": - $n = sscanf($v, "%02d%02d%04d%02d%02d%02d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); - break; - case "MM DD YY": - case "MM DD YY HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - if ($v_y < 100) - $v += 1900; - break; - case "MMDDYY": - case "MMDDYYHHNNSS": - $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - $v += 1900; - break; - case "YYYY MM DD": - case "YYYY MM DD HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); - break; - case "YYYYMMDD": - case "YYYYMMDDHHNNSS": - $n = sscanf($v, "%04d%02d%02d%02d%02d%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); - break; - case "YY MM DD": - case "YY MM DD HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - if ($v_y < 100) - $v += 1900; - break; - case "YYMMDD": - case "YYMMDDHHNNSS": - $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - $v += 1900; - break; - case "YYYY DD MM": - case "YYYY DD MM HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); - break; - case "YYYYDDMM": - case "YYYYDDMMHHNNSS": - $n = sscanf($v, "%04d%02d%02d%02d%02d%02d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); - break; - case "YY DD MM": - case "YY DD MM HH NN SS": - $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - if ($v_y < 100) - $v += 1900; - break; - case "YYDDMM": - case "YYDDMMHHNNSS": - $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); - if ($v_y < 20) - $v_y += 2000; - else - $v += 1900; - break; - default: + ); $n = 0; - // printf("format de date inconnu : %s\n", $format); - break; + + $format = str_replace( + array("-", ":", "/", "."), array(" ", " ", " ", " "), $format + ); + $isodelimdate = null; + switch ($format) { + case "MM YYYY": + case "MM YYYY HH NN SS": + $n = sscanf($v, "%d %d %d %d %d", $v_m, $v_y, $v_h, $v_n, $v_s); + break; + case "MMYYYY": + case "MMYYYYHHNNSS": + $n = sscanf($v, "%d%d%d%d%d", $v_m, $v_y, $v_h, $v_n, $v_s); + break; + case "DD MM YYYY": + case "DD MM YYYY HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); + break; + case "DDMMYYYY": + case "DDMMYYYYHHNNSS": + $n = sscanf($v, "%02d%02d%04d%02d%02d%02d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); + break; + case "DD MM YY": + case "DD MM YY HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + if ($v_y < 100) + $v += 1900; + break; + case "DDMMYY": + case "DDMMYYHHNNSS": + $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_d, $v_m, $v_y, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + $v += 1900; + break; + case "MM DD YYYY": + case "MM DD YYYY HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); + break; + case "MMDDYYYY": + case "MMDDYYYYHHNNSS": + $n = sscanf($v, "%02d%02d%04d%02d%02d%02d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); + break; + case "MM DD YY": + case "MM DD YY HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + if ($v_y < 100) + $v += 1900; + break; + case "MMDDYY": + case "MMDDYYHHNNSS": + $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_m, $v_d, $v_y, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + $v += 1900; + break; + case "YYYY MM DD": + case "YYYY MM DD HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); + break; + case "YYYYMMDD": + case "YYYYMMDDHHNNSS": + $n = sscanf($v, "%04d%02d%02d%02d%02d%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); + break; + case "YY MM DD": + case "YY MM DD HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + if ($v_y < 100) + $v += 1900; + break; + case "YYMMDD": + case "YYMMDDHHNNSS": + $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + $v += 1900; + break; + case "YYYY DD MM": + case "YYYY DD MM HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); + break; + case "YYYYDDMM": + case "YYYYDDMMHHNNSS": + $n = sscanf($v, "%04d%02d%02d%02d%02d%02d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); + break; + case "YY DD MM": + case "YY DD MM HH NN SS": + $n = sscanf($v, "%d %d %d %d %d %d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + if ($v_y < 100) + $v += 1900; + break; + case "YYDDMM": + case "YYDDMMHHNNSS": + $n = sscanf($v, "%02d%02d%02d%02d%02d%02d", $v_y, $v_d, $v_m, $v_h, $v_n, $v_s); + if ($v_y < 20) + $v_y += 2000; + else + $v += 1900; + break; + default: + $n = 0; + // printf("format de date inconnu : %s\n", $format); + break; + } + if ($n > 0) { + if ($v_y >= 0 && $v_y <= 9999 && $v_m >= 0 && $v_m <= 99 + && $v_d >= 0 && $v_d <= 99 && $v_h >= 0 && $v_h <= 99 + && $v_n >= 0 && $v_n <= 99 && $v_s >= 0 && $v_s <= 99) { + $isodelimdate = sprintf("%04d/%02d/%02d %02d:%02d:%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); + } else { + + } + } else { + + } + + return($isodelimdate); } - if ($n > 0) - { - if ($v_y >= 0 && $v_y <= 9999 && $v_m >= 0 && $v_m <= 99 - && $v_d >= 0 && $v_d <= 99 && $v_h >= 0 && $v_h <= 99 - && $v_n >= 0 && $v_n <= 99 && $v_s >= 0 && $v_s <= 99) - { - $isodelimdate = sprintf("%04d/%02d/%02d %02d:%02d:%02d", $v_y, $v_m, $v_d, $v_h, $v_n, $v_s); - } - else - { - - } - } - else - { - - } - - return($isodelimdate); - } - } diff --git a/lib/classes/queries.class.php b/lib/classes/queries.class.php index 9dd906eb5b..d63f09aebe 100644 --- a/lib/classes/queries.class.php +++ b/lib/classes/queries.class.php @@ -18,113 +18,103 @@ class queries { - public static function tree_topics() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - - $out = ''; - - $xmlTopics = null; - $sxTopics = null; - - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml')) - $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml'; - - if (!$xmlTopics) + public static function tree_topics() { - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics.xml')) - { - $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics.xml'; - } - } + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); - $cssTopics = ''; - if ($xmlTopics && ($sxTopics = simplexml_load_file($xmlTopics))) - { - $cssTopics = (string) ($sxTopics->display->css); - } + $out = ''; - $out .= ''; - $out .='
      + $out .='
      '; - if ($sxTopics) - { - $defaultview = mb_strtolower($sxTopics->display->defaultview); - if (!$defaultview) - $defaultview = 'static'; - $out .= ( "
        \n"); - $out .= self::drawTopics($sxTopics->topics, 0, '', $defaultview); - $out .= ( "\n
      \n"); - } + if ($sxTopics) { + $defaultview = mb_strtolower($sxTopics->display->defaultview); + if ( ! $defaultview) + $defaultview = 'static'; + $out .= ( "
        \n"); + $out .= self::drawTopics($sxTopics->topics, 0, '', $defaultview); + $out .= ( "\n
      \n"); + } - $out .= '
      + $out .= '
      '; - return $out; - } - - public static function topics_exists() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml')) - - return true; - - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics.xml')) - - return true; - - return false; - } - - public static function dropdown_topics() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - - $out = ''; - - $xmlTopics = ''; - $sxTopics = null; - - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml')) - $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml'; - - if ($xmlTopics == '') - { - if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics.xml')) - { - $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics.xml'; - } + return $out; } - - if ($xmlTopics == '') + public static function topics_exists() { - return ''; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); + + if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml')) + return true; + + if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics.xml')) + return true; + + return false; } - - $jsTopics = 'null'; - $maxdepth = 0; - if (($sxTopics = simplexml_load_file($xmlTopics))) + public static function dropdown_topics() { - $jsTopics = self::topicsAsJS($sxTopics->topics, 0, $maxdepth); - } + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); + + $out = ''; + + $xmlTopics = ''; + $sxTopics = null; + + if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml')) + $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics_' . $session->get_I18n() . '.xml'; + + if ($xmlTopics == '') { + if (file_exists($registry->get('GV_RootPath') . 'config/topics/topics.xml')) { + $xmlTopics = $registry->get('GV_RootPath') . 'config/topics/topics.xml'; + } + } + + + if ($xmlTopics == '') { + return ''; + } + + + $jsTopics = 'null'; + $maxdepth = 0; + if (($sxTopics = simplexml_load_file($xmlTopics))) { + $jsTopics = self::topicsAsJS($sxTopics->topics, 0, $maxdepth); + } - $out .= ' '; - $out .= '
      + $out .= '
      @@ -200,14 +190,13 @@ class queries
      ' . _('client::recherche: dans les categories') . '
      '; - for ($i = 0; $i <= $maxdepth; $i++) - { - $out .= '

      + for ($i = 0; $i <= $maxdepth; $i ++ ) { + $out .= '

      '; - } - $out .= '
      + } + $out .= '
      @@ -216,136 +205,118 @@ class queries '; - return $out; - } + return $out; + } - public static function history() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $conn = $appbox->get_connection(); + public static function history() + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $conn = $appbox->get_connection(); - $usr_id = $session->get_usr_id(); + $usr_id = $session->get_usr_id(); - $sql = "SELECT query from dsel where usr_id = :usr_id + $sql = "SELECT query from dsel where usr_id = :usr_id ORDER BY id DESC LIMIT 0,25"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':usr_id' => $usr_id)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':usr_id' => $usr_id)); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $history = '
        '; + $history = '
          '; - foreach ($rs as $row) - { - $longueur = strlen($row["query"]); + foreach ($rs as $row) { + $longueur = strlen($row["query"]); - $history .= '
        • ' . $row["query"] . '
        • '; - } - - $history .= '
            '; - - return $history; - } - - private static function hastopics(&$topics) - { - foreach ($topics->topics as $subtopic) - - return true; - return false; - } - - private static function topicsAsJS($topics, $depth, &$maxdepth) - { - if ($depth > $maxdepth) - $maxdepth = $depth; - $t = ''; - $tab = str_repeat("\t", $depth); - foreach ($topics->topic as $subtopic) - { - $t .= $t ? "$tab, " : "$tab "; - $t .= '{ '; - $t .= 'label:"' . p4string::MakeString(utf8_decode($subtopic->label), 'js') . '"'; - if ($q = $subtopic->query) - { - $q = str_replace(array("\\", "'", "\r", "\n"), array("\\\\", "\\'", "\\r", "\\n"), $subtopic->query); - $t .= ", query:'" . $q . "'"; - } - else - { - $t .= ', query:null'; - } - if (self::hastopics($subtopic)) - { - $t .= ', topics:' . "\n" . self::topicsAsJS($subtopic->topics, $depth + 1, $maxdepth); //, $fullquery) ; - } - else - { - $t .= ', topics:null'; - } - $t .= " }\n"; - } - - return("$tab" . "[\n" . $t . "\n$tab]"); - } - - private static function drawTopics($topics, $depth=0, $triid='', $defaultview) - { - $n = 0; - $out = ''; - foreach ($topics->topic as $subtopic) - { - $tid = $triid . '_' . $n; - $s = $subtopic->label; - $l = p4string::MakeString($s, 'html'); - $l = '' . $l . ''; - if ($subtopic->query) - { - $q = str_replace(array("\\", "\"", "'", "\r", "\n"), array("\\\\", """, "\\'", "\\r", "\\n"), $subtopic->query); - $q = '' . $l . ''; - } - else - { - $q = $l; - } - if (self::hastopics($subtopic)) - { - $view = mb_strtolower($subtopic['view']); - if (!$view) - $view = $defaultview; - switch ($view) - { - case 'opened': - $out .= ( '
          •  ' . $q . '
          • ' . "\n"); - $out .= ( "
              \n"); - $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); - $out .= ( "
            \n
            \n"); - break; - case 'closed': - $out .= ( '
          •  ' . $q . '
          • ' . "\n"); - $out .= ( "
              \n"); - $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); - $out .= ( "
            \n
            \n"); - break; - case 'static': - default: - $out .= ( '
          •   ' . $q . '
          • ' . "\n"); - $out .= ( "
              \n"); - $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); - $out .= ( "
            \n
            \n"); - break; + $history .= '
          • ' . $row["query"] . '
          • '; } - } - else - { - $out .= ( '
          •   ' . $q . '
          • ' . "\n"); - } - $n++; + + $history .= '
              '; + + return $history; } - return $out; - } + private static function hastopics(&$topics) + { + foreach ($topics->topics as $subtopic) + return true; + return false; + } + private static function topicsAsJS($topics, $depth, &$maxdepth) + { + if ($depth > $maxdepth) + $maxdepth = $depth; + $t = ''; + $tab = str_repeat("\t", $depth); + foreach ($topics->topic as $subtopic) { + $t .= $t ? "$tab, " : "$tab "; + $t .= '{ '; + $t .= 'label:"' . p4string::MakeString(utf8_decode($subtopic->label), 'js') . '"'; + if ($q = $subtopic->query) { + $q = str_replace(array("\\", "'", "\r", "\n"), array("\\\\", "\\'", "\\r", "\\n"), $subtopic->query); + $t .= ", query:'" . $q . "'"; + } else { + $t .= ', query:null'; + } + if (self::hastopics($subtopic)) { + $t .= ', topics:' . "\n" . self::topicsAsJS($subtopic->topics, $depth + 1, $maxdepth); //, $fullquery) ; + } else { + $t .= ', topics:null'; + } + $t .= " }\n"; + } + + return("$tab" . "[\n" . $t . "\n$tab]"); + } + + private static function drawTopics($topics, $depth = 0, $triid = '', $defaultview) + { + $n = 0; + $out = ''; + foreach ($topics->topic as $subtopic) { + $tid = $triid . '_' . $n; + $s = $subtopic->label; + $l = p4string::MakeString($s, 'html'); + $l = '' . $l . ''; + if ($subtopic->query) { + $q = str_replace(array("\\", "\"", "'", "\r", "\n"), array("\\\\", """, "\\'", "\\r", "\\n"), $subtopic->query); + $q = '' . $l . ''; + } else { + $q = $l; + } + if (self::hastopics($subtopic)) { + $view = mb_strtolower($subtopic['view']); + if ( ! $view) + $view = $defaultview; + switch ($view) { + case 'opened': + $out .= ( '
            •  ' . $q . '
            • ' . "\n"); + $out .= ( "
                \n"); + $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); + $out .= ( "
              \n
              \n"); + break; + case 'closed': + $out .= ( '
            •  ' . $q . '
            • ' . "\n"); + $out .= ( "
                \n"); + $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); + $out .= ( "
              \n
              \n"); + break; + case 'static': + default: + $out .= ( '
            •   ' . $q . '
            • ' . "\n"); + $out .= ( "
                \n"); + $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); + $out .= ( "
              \n
              \n"); + break; + } + } else { + $out .= ( '
            •   ' . $q . '
            • ' . "\n"); + } + $n ++; + } + + return $out; + } } diff --git a/lib/classes/random.class.php b/lib/classes/random.class.php index 5a73b0fb31..c0c32e8ac6 100644 --- a/lib/classes/random.class.php +++ b/lib/classes/random.class.php @@ -11,233 +11,214 @@ class random { + /** + * + */ + const NUMBERS = "0123456789"; + /** + * + */ + const LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + /** + * + */ + const LETTERS_AND_NUMBERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + const TYPE_FEED_ENTRY = 'FEED_ENTRY'; + const TYPE_PASSWORD = 'password'; + const TYPE_DOWNLOAD = 'download'; + const TYPE_MAIL_DOWNLOAD = 'mail-download'; + const TYPE_EMAIL = 'email'; + const TYPE_VIEW = 'view'; + const TYPE_VALIDATE = 'validate'; + const TYPE_RSS = 'rss'; - /** - * - */ - - const NUMBERS = "0123456789"; - /** - * - */ - const LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - /** - * - */ - const LETTERS_AND_NUMBERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - const TYPE_FEED_ENTRY = 'FEED_ENTRY'; - const TYPE_PASSWORD = 'password'; - const TYPE_DOWNLOAD = 'download'; - const TYPE_MAIL_DOWNLOAD = 'mail-download'; - const TYPE_EMAIL = 'email'; - const TYPE_VIEW = 'view'; - const TYPE_VALIDATE = 'validate'; - const TYPE_RSS = 'rss'; - - /** - * - * @return Void - */ - public static function cleanTokens() - { - try + /** + * + * @return Void + */ + public static function cleanTokens() { - $conn = connection::getPDOConnection(); + try { + $conn = connection::getPDOConnection(); - $date = new DateTime(); - $date = phraseadate::format_mysql($date); - $registry = registry::get_instance(); + $date = new DateTime(); + $date = phraseadate::format_mysql($date); + $registry = registry::get_instance(); - $sql = 'SELECT * FROM tokens WHERE expire_on < :date + $sql = 'SELECT * FROM tokens WHERE expire_on < :date AND datas IS NOT NULL AND (type="download" OR type="email")'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':date' => $date)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - foreach ($rs as $row) - { - switch ($row['type']) - { - case 'download': - case 'email': - $file = $registry->get('GV_RootPath') . 'tmp/download/' . $row['value'] . '.zip'; - if (is_file($file)) - unlink($file); - break; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':date' => $date)); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + foreach ($rs as $row) { + switch ($row['type']) { + case 'download': + case 'email': + $file = $registry->get('GV_RootPath') . 'tmp/download/' . $row['value'] . '.zip'; + if (is_file($file)) + unlink($file); + break; + } + } + + $sql = 'DELETE FROM tokens WHERE expire_on < :date and (type="download" OR type="email")'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':date' => $date)); + $stmt->closeCursor(); + + return true; + } catch (Exception $e) { + } - } - - $sql = 'DELETE FROM tokens WHERE expire_on < :date and (type="download" OR type="email")'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':date' => $date)); - $stmt->closeCursor(); - - return true; - } - catch (Exception $e) - { + return false; } - return false; - } - - /** - * - * @param int $length - * @param constant $possible - * @return string - */ - public static function generatePassword($length = 8, $possible = SELF::LETTERS_AND_NUMBERS) - { - if (!is_int($length)) - throw new Exception_InvalidArgument (); - - $password = ""; - if (!in_array($possible, array(self::LETTERS_AND_NUMBERS, self::LETTERS, self::NUMBERS))) - $possible = self::LETTERS_AND_NUMBERS; - $i = 0; - $possible_length = strlen($possible); - while ($i < $length) + /** + * + * @param int $length + * @param constant $possible + * @return string + */ + public static function generatePassword($length = 8, $possible = SELF::LETTERS_AND_NUMBERS) { - $char = substr($possible, mt_rand(0, $possible_length - 1), 1); - $password .= $char; - $i++; + if ( ! is_int($length)) + throw new Exception_InvalidArgument (); + + $password = ""; + if ( ! in_array($possible, array(self::LETTERS_AND_NUMBERS, self::LETTERS, self::NUMBERS))) + $possible = self::LETTERS_AND_NUMBERS; + $i = 0; + $possible_length = strlen($possible); + while ($i < $length) { + $char = substr($possible, mt_rand(0, $possible_length - 1), 1); + $password .= $char; + $i ++; + } + + return $password; } - return $password; - } - - /** - * - * @param string $type - * @param int $usr - * @param string $end_date - * @param mixed content $datas - * @return boolean - */ - public static function getUrlToken($type, $usr, DateTime $end_date = null, $datas = '') - { - self::cleanTokens(); - $conn = connection::getPDOConnection(); - $token = $test = false; - - switch ($type) + /** + * + * @param string $type + * @param int $usr + * @param string $end_date + * @param mixed content $datas + * @return boolean + */ + public static function getUrlToken($type, $usr, DateTime $end_date = null, $datas = '') { - case self::TYPE_DOWNLOAD: - case self::TYPE_PASSWORD: - case self::TYPE_MAIL_DOWNLOAD: - case self::TYPE_EMAIL: - case self::TYPE_VALIDATE: - case self::TYPE_VIEW: - case self::TYPE_RSS: - case self::TYPE_FEED_ENTRY: + self::cleanTokens(); + $conn = connection::getPDOConnection(); + $token = $test = false; - break; - default: - throw new Exception_InvalidArgument(); - break; - } + switch ($type) { + case self::TYPE_DOWNLOAD: + case self::TYPE_PASSWORD: + case self::TYPE_MAIL_DOWNLOAD: + case self::TYPE_EMAIL: + case self::TYPE_VALIDATE: + case self::TYPE_VIEW: + case self::TYPE_RSS: + case self::TYPE_FEED_ENTRY: - $n = 1; + break; + default: + throw new Exception_InvalidArgument(); + break; + } - $sql = 'SELECT id FROM tokens WHERE value = :test '; - $stmt = $conn->prepare($sql); - while ($n < 100) - { - $test = self::generatePassword(16); - $stmt->execute(array(':test' => $test)); - if ($stmt->rowCount() === 0) - { - $token = $test; - break; - } - $n++; - } - $stmt->closeCursor(); + $n = 1; - if ($token) - { - $sql = 'INSERT INTO tokens (id, value, type, usr_id, created_on, expire_on, datas) + $sql = 'SELECT id FROM tokens WHERE value = :test '; + $stmt = $conn->prepare($sql); + while ($n < 100) { + $test = self::generatePassword(16); + $stmt->execute(array(':test' => $test)); + if ($stmt->rowCount() === 0) { + $token = $test; + break; + } + $n ++; + } + $stmt->closeCursor(); + + if ($token) { + $sql = 'INSERT INTO tokens (id, value, type, usr_id, created_on, expire_on, datas) VALUES (null, :token, :type, :usr, NOW(), :end_date, :datas)'; - $stmt = $conn->prepare($sql); + $stmt = $conn->prepare($sql); - $params = array( - ':token' => $token - , ':type' => $type - , ':usr' => ($usr ? $usr : '-1') - , ':end_date' => ($end_date instanceof DateTime ? phraseadate::format_mysql($end_date) : null) - , ':datas' => ((trim($datas) != '') ? $datas : null) - ); - $stmt->execute($params); - $stmt->closeCursor(); + $params = array( + ':token' => $token + , ':type' => $type + , ':usr' => ($usr ? $usr : '-1') + , ':end_date' => ($end_date instanceof DateTime ? phraseadate::format_mysql($end_date) : null) + , ':datas' => ((trim($datas) != '') ? $datas : null) + ); + $stmt->execute($params); + $stmt->closeCursor(); + } + + return $token; } - return $token; - } - - public static function removeToken($token) - { - self::cleanTokens(); - - try + public static function removeToken($token) { - $conn = connection::getPDOConnection(); - $sql = 'DELETE FROM tokens WHERE value = :token'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':token' => $token)); - $stmt->closeCursor(); + self::cleanTokens(); - return true; - } - catch (Exception $e) - { + try { + $conn = connection::getPDOConnection(); + $sql = 'DELETE FROM tokens WHERE value = :token'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':token' => $token)); + $stmt->closeCursor(); + return true; + } catch (Exception $e) { + + } + + return false; } - return false; - } - - public static function updateToken($token, $datas) - { - try + public static function updateToken($token, $datas) { - $conn = connection::getPDOConnection(); + try { + $conn = connection::getPDOConnection(); - $sql = 'UPDATE tokens SET datas = :datas + $sql = 'UPDATE tokens SET datas = :datas WHERE value = :token'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':datas' => $datas, ':token' => $token)); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':datas' => $datas, ':token' => $token)); + $stmt->closeCursor(); - return true; + return true; + } catch (Exception $e) { + + } + + return false; } - catch (Exception $e) + + public static function helloToken($token) { + self::cleanTokens(); - } - - return false; - } - - public static function helloToken($token) - { - self::cleanTokens(); - - $conn = connection::getPDOConnection(); - $sql = 'SELECT * FROM tokens + $conn = connection::getPDOConnection(); + $sql = 'SELECT * FROM tokens WHERE value = :token AND (expire_on > NOW() OR expire_on IS NULL)'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':token' => $token)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':token' => $token)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (!$row) - throw new Exception_NotFound('Token not found'); - - return $row; - } + if ( ! $row) + throw new Exception_NotFound('Token not found'); + return $row; + } } diff --git a/lib/classes/record/Interface.class.php b/lib/classes/record/Interface.class.php index c9d9775908..4bcbe4e7a6 100644 --- a/lib/classes/record/Interface.class.php +++ b/lib/classes/record/Interface.class.php @@ -17,91 +17,92 @@ */ interface record_Interface { - public function get_creation_date(); - public function get_uuid(); + public function get_creation_date(); - public function get_modification_date(); + public function get_uuid(); - public function get_number(); + public function get_modification_date(); - public function set_number($number); + public function get_number(); - public function set_type($type); + public function set_number($number); - public function is_grouping(); + public function set_type($type); - public function get_base_id(); + public function is_grouping(); - public function get_record_id(); + public function get_base_id(); - public function get_databox(); + public function get_record_id(); - public function get_thumbnail(); + public function get_databox(); - public function get_embedable_medias(); + public function get_thumbnail(); - public function get_status_icons(); + public function get_embedable_medias(); - public function get_type(); + public function get_status_icons(); - public function get_formated_duration(); + public function get_type(); - public function get_duration(); + public function get_formated_duration(); - public function move_to_collection(collection &$collection, appbox &$appbox); + public function get_duration(); - public function get_rollover_thumbnail(); + public function move_to_collection(collection &$collection, appbox &$appbox); - public function get_sha256(); + public function get_rollover_thumbnail(); - public function get_mime(); + public function get_sha256(); - public function get_status(); + public function get_mime(); - public function get_subdef($name); + public function get_status(); - public function get_subdefs(); + public function get_subdef($name); - public function get_collection_logo(); + public function get_subdefs(); - public function get_technical_infos($data = false); + public function get_collection_logo(); - public function get_caption(); + public function get_technical_infos($data = false); - public function get_original_name(); + public function get_caption(); - public function get_title($highlight = false, searchEngine_adapter $searchEngine = null); + public function get_original_name(); - public function get_preview(); + public function get_title($highlight = false, searchEngine_adapter $searchEngine = null); - public function has_preview(); + public function get_preview(); - public function get_serialize_key(); + public function has_preview(); - public function get_sbas_id(); + public function get_serialize_key(); - public function substitute_subdef($name, system_file $pathfile); + public function get_sbas_id(); - public function set_metadatas(Array $metadatas, $force_readonly = false); + public function substitute_subdef($name, system_file $pathfile); - public function reindex(); + public function set_metadatas(Array $metadatas, $force_readonly = false); - public function rebuild_subdefs(); + public function reindex(); - public function write_metas(); + public function rebuild_subdefs(); - public function set_binary_status($status); + public function write_metas(); - public function get_hd_file(); + public function set_binary_status($status); - public function delete(); + public function get_hd_file(); - public function generate_subdefs(databox $databox, Array $wanted_subdefs = null); + public function delete(); - public function log_view($log_id, $referrer, $gv_sit); + public function generate_subdefs(databox $databox, Array $wanted_subdefs = null); - public function rotate_subdefs($angle); + public function log_view($log_id, $referrer, $gv_sit); - public function get_container_baskets(); + public function rotate_subdefs($angle); + + public function get_container_baskets(); } diff --git a/lib/classes/record/adapter.class.php b/lib/classes/record/adapter.class.php index e617ec37ee..59d3612094 100644 --- a/lib/classes/record/adapter.class.php +++ b/lib/classes/record/adapter.class.php @@ -17,7 +17,6 @@ */ class record_adapter implements record_Interface, cache_cacheableInterface { - /** * * @var @@ -132,13 +131,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ protected $modification_date; - const CACHE_ORIGINAL_NAME = 'originalname'; + const CACHE_ORIGINAL_NAME = 'originalname'; const CACHE_TECHNICAL_DATAS = 'technical_datas'; - const CACHE_MIME = 'mime'; - const CACHE_SHA256 = 'sha256'; - const CACHE_SUBDEFS = 'subdefs'; - const CACHE_GROUPING = 'grouping'; - const CACHE_STATUS = 'status'; + const CACHE_MIME = 'mime'; + const CACHE_SHA256 = 'sha256'; + const CACHE_SUBDEFS = 'subdefs'; + const CACHE_GROUPING = 'grouping'; + const CACHE_STATUS = 'status'; /** * @@ -161,8 +160,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface protected function load() { - try - { + try { $datas = $this->get_data_from_cache(); $this->mime = $datas['mime']; @@ -177,23 +175,20 @@ class record_adapter implements record_Interface, cache_cacheableInterface $this->base_id = $datas['base_id']; return $this; - } - catch (Exception $e) - { + } catch (Exception $e) { } $connbas = $this->databox->get_connection(); - $sql = 'SELECT coll_id, record_id,credate , uuid, moddate, parent_record_id + $sql = 'SELECT coll_id, record_id,credate , uuid, moddate, parent_record_id , type, originalname, bitly, sha256, mime FROM record WHERE record_id = :record_id'; - $stmt = $connbas->prepare($sql); + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->record_id)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); + $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - if ( ! $row) - { + if ( ! $row) { throw new Exception_Record_AdapterNotFound('Record ' . $this->record_id . ' on database ' . $this->databox->get_sbas_id() . ' not found '); } @@ -210,16 +205,16 @@ class record_adapter implements record_Interface, cache_cacheableInterface $this->mime = $row['mime']; $datas = array( - 'mime' => $this->mime - , 'sha256' => $this->sha256 - , 'bitly_link' => $this->bitly_link - , 'original_name' => $this->original_name - , 'type' => $this->type - , 'grouping' => $this->grouping - , 'uuid' => $this->uuid - , 'modification_date' => $this->modification_date - , 'creation_date' => $this->creation_date - , 'base_id' => $this->base_id + 'mime' => $this->mime + , 'sha256' => $this->sha256 + , 'bitly_link' => $this->bitly_link + , 'original_name' => $this->original_name + , 'type' => $this->type + , 'grouping' => $this->grouping + , 'uuid' => $this->uuid + , 'modification_date' => $this->modification_date + , 'creation_date' => $this->creation_date + , 'base_id' => $this->base_id ); $this->set_data_to_cache($datas); @@ -287,14 +282,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface $old_type = $this->get_type(); - if ( ! in_array($type, array('document', 'audio', 'video', 'image', 'flash', 'map'))) - { + if ( ! in_array($type, array('document', 'audio', 'video', 'image', 'flash', 'map'))) { throw new Exception('unrecognized document type'); } $connbas = connection::getPDOConnection($this->get_sbas_id()); - $sql = 'UPDATE record SET type = :type WHERE record_id = :record_id'; + $sql = 'UPDATE record SET type = :type WHERE record_id = :record_id'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':type' => $type, ':record_id' => $this->get_record_id())); $stmt->closeCursor(); @@ -373,66 +367,56 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $dstatus = databox_status::getDisplayStatus(); $sbas_id = $this->get_sbas_id(); - $appbox = appbox::get_instance(\bootstrap::getCore()); + $appbox = appbox::get_instance(\bootstrap::getCore()); $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); $status = ''; - if (isset($dstatus[$sbas_id])) - { - foreach ($dstatus[$sbas_id] as $n => $statbit) - { + if (isset($dstatus[$sbas_id])) { + foreach ($dstatus[$sbas_id] as $n => $statbit) { if ($statbit['printable'] == '0' && - ! $user->ACL()->has_right_on_base($this->base_id, 'chgstatus')) - { + ! $user->ACL()->has_right_on_base($this->base_id, 'chgstatus')) { continue; } $x = (substr((strrev($this->get_status())), $n, 1)); $source0 = "/skins/icons/spacer.gif"; - $style0 = "visibility:hidden;display:none;"; + $style0 = "visibility:hidden;display:none;"; $source1 = "/skins/icons/spacer.gif"; - $style1 = "visibility:hidden;display:none;"; - if ($statbit["img_on"]) - { + $style1 = "visibility:hidden;display:none;"; + if ($statbit["img_on"]) { $source1 = $statbit["img_on"]; - $style1 = "visibility:auto;display:none;"; + $style1 = "visibility:auto;display:none;"; } - if ($statbit["img_off"]) - { + if ($statbit["img_off"]) { $source0 = $statbit["img_off"]; - $style0 = "visibility:auto;display:none;"; + $style0 = "visibility:auto;display:none;"; } - if ($x == '1') - { - if ($statbit["img_on"]) - { + if ($x == '1') { + if ($statbit["img_on"]) { $style1 = "visibility:auto;display:inline;"; } - } - else - { - if ($statbit["img_off"]) - { + } else { + if ($statbit["img_off"]) { $style0 = "visibility:auto;display:inline;"; } } $status .= ''; + 'class="STAT_' . $this->base_id . '_' + . $this->record_id . '_' . $n . '_1" ' . + 'src="' . $source1 . '" title="' . + (isset($statbit["labelon"]) ? + $statbit["labelon"] : + $statbit["lib"]) . '"/>'; $status .= ''; + 'class="STAT_' . $this->base_id . '_' + . $this->record_id . '_' . $n . '_0" ' . + 'src="' . $source0 . '" title="' . + (isset($statbit["labeloff"]) ? + $statbit["labeloff"] : + ("non-" . $statbit["lib"])) . '"/>'; } } @@ -466,8 +450,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_duration() { - if ( ! $this->duration) - { + if ( ! $this->duration) { $this->duration = $this->get_technical_infos(system_file::TC_DATAS_DURATION); } @@ -485,8 +468,8 @@ class record_adapter implements record_Interface, cache_cacheableInterface $sql = "UPDATE record SET coll_id = :coll_id WHERE record_id =:record_id"; $params = array( - ':coll_id' => $collection->get_coll_id(), - ':record_id' => $this->get_record_id() + ':coll_id' => $collection->get_coll_id(), + ':record_id' => $this->get_record_id() ); $stmt = $this->get_databox()->get_connection()->prepare($sql); @@ -496,7 +479,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $this->base_id = $collection->get_base_id(); $appbox->get_session()->get_logger($this->get_databox()) - ->log($this, Session_Logger::EVENT_MOVE, $collection->get_coll_id(), ''); + ->log($this, Session_Logger::EVENT_MOVE, $collection->get_coll_id(), ''); $this->delete_data_from_cache(); @@ -509,17 +492,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_rollover_thumbnail() { - if ($this->get_type() != 'video') - { + if ($this->get_type() != 'video') { return null; } - try - { + try { return $this->get_subdef('thumbnailGIF'); - } - catch (Exception $e) - { + } catch (Exception $e) { } @@ -550,8 +529,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_status() { - if ( ! $this->status) - { + if ( ! $this->status) { $this->status = $this->retrieve_status(); } @@ -564,30 +542,25 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ protected function retrieve_status() { - try - { + try { return $this->get_data_from_cache(self::CACHE_STATUS); - } - catch (Exception $e) - { + } catch (Exception $e) { } - $sql = 'SELECT BIN(status) as status FROM record + $sql = 'SELECT BIN(status) as status FROM record WHERE record_id = :record_id'; $stmt = $this->get_databox()->get_connection()->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); + $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - if ( ! $row) - { + if ( ! $row) { throw new Exception('status not found'); } $status = $row['status']; - $n = strlen($status); - while ($n < 64) - { + $n = strlen($status); + while ($n < 64) { $status = '0' . $status; $n ++; } @@ -611,18 +584,15 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $name = strtolower($name); - if ( ! in_array($name, $this->get_available_subdefs())) - { + if ( ! in_array($name, $this->get_available_subdefs())) { throw new Exception_Media_SubdefNotFound (); } - if (isset($this->subdefs[$name])) - { + if (isset($this->subdefs[$name])) { return $this->subdefs[$name]; } - if ( ! $this->subdefs) - { + if ( ! $this->subdefs) { $this->subdefs = array(); } @@ -637,14 +607,12 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_subdefs() { - if ( ! $this->subdefs) - { + if ( ! $this->subdefs) { $this->subdefs = array(); } $subdefs = $this->get_available_subdefs(); - foreach ($subdefs as $name) - { + foreach ($subdefs as $name) { $this->get_subdef($name); } @@ -657,12 +625,9 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ protected function get_available_subdefs() { - try - { + try { return $this->get_data_from_cache(self::CACHE_SUBDEFS); - } - catch (Exception $e) - { + } catch (Exception $e) { } @@ -673,16 +638,15 @@ class record_adapter implements record_Interface, cache_cacheableInterface $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $subdefs = array('preview', 'thumbnail'); - foreach ($rs as $row) - { + foreach ($rs as $row) { $subdefs[] = $row['name']; } - $subdefs = array_unique($subdefs); + $subdefs = array_unique($subdefs); $this->set_data_to_cache($subdefs, self::CACHE_SUBDEFS); return $subdefs; @@ -705,26 +669,20 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function get_technical_infos($data = false) { - if ( ! $this->technical_datas) - { - try - { + if ( ! $this->technical_datas) { + try { $this->technical_datas = $this->get_data_from_cache(self::CACHE_TECHNICAL_DATAS); - } - catch (Exception $e) - { + } catch (Exception $e) { $this->technical_datas = array(); $connbas = $this->get_databox()->get_connection(); - $sql = 'SELECT name, value FROM technical_datas WHERE record_id = :record_id'; - $stmt = $connbas->prepare($sql); + $sql = 'SELECT name, value FROM technical_datas WHERE record_id = :record_id'; + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach ($rs as $row) - { - switch ($row['name']) - { + foreach ($rs as $row) { + switch ($row['name']) { case 'size': case system_file::TC_DATAS_WIDTH: case system_file::TC_DATAS_COLORDEPTH: @@ -759,14 +717,10 @@ class record_adapter implements record_Interface, cache_cacheableInterface } } - if ($data) - { - if (isset($this->technical_datas[$data])) - { + if ($data) { + if (isset($this->technical_datas[$data])) { return $this->technical_datas[$data]; - } - else - { + } else { return false; } } @@ -790,12 +744,9 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_original_name($removeExtension = null) { - if ($removeExtension) - { + if ($removeExtension) { return pathinfo($this->original_name, PATHINFO_FILENAME); - } - else - { + } else { return $this->original_name; } } @@ -804,36 +755,30 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $this->original_name = $original_name; - foreach ($this->get_databox()->get_meta_structure()->get_elements() as $data_field) - { - if ($data_field->get_metadata_source() != metadata_description_PHRASEANET_tffilename::get_source()) - { + foreach ($this->get_databox()->get_meta_structure()->get_elements() as $data_field) { + if ($data_field->get_metadata_source() != metadata_description_PHRASEANET_tffilename::get_source()) { continue; } /** * Replacing original name in multi values is non sense */ - if ( ! $data_field->is_multi()) - { + if ( ! $data_field->is_multi()) { continue; } - try - { - $field = $this->get_caption()->get_field($data_field->get_name())->get_meta_id(); - $value = array_pop($field->get_values()); + try { + $field = $this->get_caption()->get_field($data_field->get_name())->get_meta_id(); + $value = array_pop($field->get_values()); $meta_id = $value->getId(); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $meta_id = null; } $metas = array( - 'meta_struct_id' => $field->get_meta_struct_id() - , 'meta_id' => $meta_id - , 'value' => $original_name + 'meta_struct_id' => $field->get_meta_struct_id() + , 'meta_id' => $meta_id + , 'value' => $original_name ); $this->set_metadatas($metas, true); @@ -843,8 +788,8 @@ class record_adapter implements record_Interface, cache_cacheableInterface SET originalname = :originalname WHERE record_id = :record_id'; $params = array( - ':originalname' => $original_name - , ':record_id' => $this->get_record_id() + ':originalname' => $original_name + , ':record_id' => $this->get_record_id() ); $stmt = $this->get_databox()->get_connection()->prepare($sql); @@ -862,37 +807,32 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_title($highlight = false, searchEngine_adapter $searchEngine = null, $removeExtension = null) { - $title = ''; - $appbox = appbox::get_instance(\bootstrap::getCore()); + $title = ''; + $appbox = appbox::get_instance(\bootstrap::getCore()); $session = $appbox->get_session(); $fields = $this->get_databox()->get_meta_structure(); $fields_to_retrieve = array(); - foreach ($fields as $field) - { - if (in_array($field->get_thumbtitle(), array('1', $session->get_I18n()))) - { + foreach ($fields as $field) { + if (in_array($field->get_thumbtitle(), array('1', $session->get_I18n()))) { $fields_to_retrieve [] = $field->get_name(); } } - if (count($fields_to_retrieve) > 0) - { + if (count($fields_to_retrieve) > 0) { $retrieved_fields = $this->get_caption()->get_highlight_fields($highlight, $fields_to_retrieve, $searchEngine); - $titles = array(); - foreach ($retrieved_fields as $key => $value) - { + $titles = array(); + foreach ($retrieved_fields as $key => $value) { if (trim($value['value'] === '')) continue; $titles[] = $value['value']; } - $title = trim(implode(' - ', $titles)); + $title = trim(implode(' - ', $titles)); } - if (trim($title) === '') - { + if (trim($title) === '') { $title = trim($this->get_original_name($removeExtension)); } @@ -916,14 +856,11 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function has_preview() { - try - { + try { $this->get_subdef('preview'); return $this->get_subdef('preview')->is_physically_present(); - } - catch (Exception $e) - { + } catch (Exception $e) { unset($e); } @@ -957,14 +894,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function substitute_subdef($name, system_file $pathfile) { $newfilename = $this->record_id . '_0_' . $name - . '.' . $pathfile->get_extension(); + . '.' . $pathfile->get_extension(); $base_url = ''; - $original_file = $subdef_def = false; + $original_file = $subdef_def = false; - if ($name == 'document') - { + if ($name == 'document') { $baseprefs = $this->get_databox()->get_sxml_structure(); $pathhd = p4string::addEndSlash((string) ($baseprefs->path)); @@ -977,45 +913,36 @@ class record_adapter implements record_Interface, cache_cacheableInterface $system_file = new system_file($pathhd . $filehd); $meta_writable = true; - } - else - { + } else { $subdef_def = $this->get_databox()->get_subdef_structure()->get_subdef($this->get_type(), $name); - if ($this->has_subdef($name) && ! $this->get_subdef($name)->is_substituted()) - { - $value = $this->get_subdef($name); + if ($this->has_subdef($name) && ! $this->get_subdef($name)->is_substituted()) { + $value = $this->get_subdef($name); $original_file = p4string::addEndSlash($value->get_path()) . $value->get_file(); unlink($original_file); $this->clearSubdefCache($name); - } - else - { - $path = databox::dispatch($subdef_def->get_path()); + } else { + $path = databox::dispatch($subdef_def->get_path()); system_file::mkdir($path); $original_file = $path . $newfilename; } $path_file_dest = $original_file; - if (trim($subdef_def->get_baseurl()) !== '') - { + if (trim($subdef_def->get_baseurl()) !== '') { $base_url = str_replace( - array($subdef_def->get_path(), $newfilename) - , array($subdef_def->get_baseurl(), '') - , $path_file_dest + array($subdef_def->get_path(), $newfilename) + , array($subdef_def->get_baseurl(), '') + , $path_file_dest ); } - try - { + try { $Core = \bootstrap::getCore(); $Core['media-alchemyst']->open($pathfile->getPathname()) - ->turnInto($path_file_dest, $subdef_def->getSpecs()) - ->close(); - } - catch (\MediaAlchemyst\Exception\Exception $e) - { + ->turnInto($path_file_dest, $subdef_def->getSpecs()) + ->close(); + } catch (\MediaAlchemyst\Exception\Exception $e) { return $this; } @@ -1025,9 +952,8 @@ class record_adapter implements record_Interface, cache_cacheableInterface $meta_writable = $subdef_def->meta_writeable(); } - try - { - $appbox = \appbox::get_instance(\bootstrap::getCore()); + try { + $appbox = \appbox::get_instance(\bootstrap::getCore()); $session = $appbox->get_session(); $connbas = connection::getPDOConnection($this->get_sbas_id()); @@ -1048,15 +974,15 @@ class record_adapter implements record_Interface, cache_cacheableInterface $stmt = $connbas->prepare($sql); $stmt->execute(array( - ':record_id' => $this->record_id, - ':name' => $name, - ':baseurl' => $base_url, - ':filename' => $system_file->getFilename(), - ':width' => $image_size[system_file::TC_DATAS_WIDTH], - ':height' => $image_size[system_file::TC_DATAS_HEIGHT], - ':mime' => $system_file->get_mime(), - ':path' => $system_file->getPath(), - ':filesize' => $system_file->getSize() + ':record_id' => $this->record_id, + ':name' => $name, + ':baseurl' => $base_url, + ':filename' => $system_file->getFilename(), + ':width' => $image_size[system_file::TC_DATAS_WIDTH], + ':height' => $image_size[system_file::TC_DATAS_HEIGHT], + ':mime' => $system_file->get_mime(), + ':path' => $system_file->getPath(), + ':filesize' => $system_file->getSize() )); $subdef = $this->get_subdef($name); @@ -1064,22 +990,18 @@ class record_adapter implements record_Interface, cache_cacheableInterface $this->delete_data_from_cache(self::CACHE_SUBDEFS); - if ($meta_writable) - { + if ($meta_writable) { $this->write_metas(); } - if ($name == 'document') - { + if ($name == 'document') { $this->rebuild_subdefs(); } $type = $name == 'document' ? 'HD' : $name; $session->get_logger($this->get_databox()) - ->log($this, Session_Logger::EVENT_SUBSTITUTE, $type, ''); - } - catch (Exception $e) - { + ->log($this, Session_Logger::EVENT_SUBSTITUTE, $type, ''); + } catch (Exception $e) { } @@ -1094,13 +1016,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface protected function set_xml(DOMDocument $dom_doc) { $connbas = $this->get_databox()->get_connection(); - $sql = 'UPDATE record SET xml = :xml WHERE record_id= :record_id'; - $stmt = $connbas->prepare($sql); + $sql = 'UPDATE record SET xml = :xml WHERE record_id= :record_id'; + $stmt = $connbas->prepare($sql); $stmt->execute( - array( - ':xml' => $dom_doc->saveXML(), - ':record_id' => $this->record_id - ) + array( + ':xml' => $dom_doc->saveXML(), + ':record_id' => $this->record_id + ) ); $this->reindex(); @@ -1118,16 +1040,13 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $mandatoryParams = array('meta_struct_id', 'meta_id', 'value'); - foreach ($mandatoryParams as $param) - { - if ( ! array_key_exists($param, $params)) - { + foreach ($mandatoryParams as $param) { + if ( ! array_key_exists($param, $params)) { throw new Exception_InvalidArgument(sprintf('Invalid metadata, missing key %s', $param)); } } - if ( ! is_scalar($params['value'])) - { + if ( ! is_scalar($params['value'])) { throw new Exception('Metadata value should be scalar'); } @@ -1135,45 +1054,34 @@ class record_adapter implements record_Interface, cache_cacheableInterface $caption_field = new caption_field($databox_field, $this); - $vocab = $vocab_id = null; + $vocab = $vocab_id = null; - if (isset($params['vocabularyId']) && $databox_field->getVocabularyControl()) - { - try - { - $vocab = $databox_field->getVocabularyControl(); + if (isset($params['vocabularyId']) && $databox_field->getVocabularyControl()) { + try { + $vocab = $databox_field->getVocabularyControl(); $vocab_id = $params['vocabularyId']; $vocab->validate($vocab_id); - } - catch (\Exception $e) - { - $vocab = $vocab_id = null; + } catch (\Exception $e) { + $vocab = $vocab_id = null; } } - if (trim($params['meta_id']) !== '') - { + if (trim($params['meta_id']) !== '') { $tmp_val = trim($params['value']); $caption_field_value = $caption_field->get_value($params['meta_id']); - if ($tmp_val === '') - { + if ($tmp_val === '') { $caption_field_value->delete(); unset($caption_field_value); - } - else - { + } else { $caption_field_value->set_value($params['value']); - if ($vocab && $vocab_id) - { + if ($vocab && $vocab_id) { $caption_field_value->setVocab($vocab, $vocab_id); } } - } - else - { + } else { $caption_field_value = caption_Field_Value::create($databox_field, $this, $params['value'], $vocab, $vocab_id); } @@ -1190,17 +1098,14 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function set_metadatas(Array $metadatas, $force_readonly = false) { - foreach ($metadatas as $param) - { - if ( ! is_array($param)) - { + foreach ($metadatas as $param) { + if ( ! is_array($param)) { throw new Exception_InvalidArgument('Invalid metadatas argument'); } $db_field = \databox_field::get_instance($this->get_databox(), $param['meta_struct_id']); - if ($db_field->is_readonly() === true && ! $force_readonly) - { + if ($db_field->is_readonly() === true && ! $force_readonly) { continue; } @@ -1229,9 +1134,9 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function reindex() { $connbas = connection::getPDOConnection($this->get_sbas_id()); - $sql = 'UPDATE record SET status=(status & ~7 | 4) + $sql = 'UPDATE record SET status=(status & ~7 | 4) WHERE record_id= :record_id'; - $stmt = $connbas->prepare($sql); + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->record_id)); $this->delete_data_from_cache(self::CACHE_STATUS); @@ -1245,8 +1150,8 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function rebuild_subdefs() { $connbas = connection::getPDOConnection($this->get_sbas_id()); - $sql = 'UPDATE record SET jeton=(jeton | ' . JETON_MAKE_SUBDEF . ') WHERE record_id = :record_id'; - $stmt = $connbas->prepare($sql); + $sql = 'UPDATE record SET jeton=(jeton | ' . JETON_MAKE_SUBDEF . ') WHERE record_id = :record_id'; + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); return $this; @@ -1259,10 +1164,10 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function write_metas() { $connbas = connection::getPDOConnection($this->get_sbas_id()); - $sql = 'UPDATE record + $sql = 'UPDATE record SET jeton = ' . (JETON_WRITE_META_DOC | JETON_WRITE_META_SUBDEF) . ' WHERE record_id= :record_id'; - $stmt = $connbas->prepare($sql); + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->record_id)); return $this; @@ -1278,40 +1183,35 @@ class record_adapter implements record_Interface, cache_cacheableInterface $connbas = connection::getPDOConnection($this->get_sbas_id()); $registry = registry::get_instance(); - $sql = 'UPDATE record SET status = 0b' . $status . ' + $sql = 'UPDATE record SET status = 0b' . $status . ' WHERE record_id= :record_id'; - $stmt = $connbas->prepare($sql); + $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->record_id)); - $sql = 'REPLACE INTO status (id, record_id, name, value) VALUES (null, :record_id, :name, :value)'; + $sql = 'REPLACE INTO status (id, record_id, name, value) VALUES (null, :record_id, :name, :value)'; $stmt = $connbas->prepare($sql); $status = strrev($status); - for ($i = 4; $i < strlen($status); $i ++ ) - { + for ($i = 4; $i < strlen($status); $i ++ ) { $stmt->execute(array( - ':record_id' => $this->get_record_id(), - ':name' => $i, - ':value' => $status[$i] + ':record_id' => $this->get_record_id(), + ':name' => $i, + ':value' => $status[$i] )); } $stmt->closeCursor(); - try - { + try { $sphinx = sphinxrt::get_instance($registry); $sbas_params = phrasea::sbas_params(); - $sbas_id = $this->get_sbas_id(); - if (isset($sbas_params[$sbas_id])) - { - $params = $sbas_params[$sbas_id]; + $sbas_id = $this->get_sbas_id(); + 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->update_status(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_en", "metadatas" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc), $this->get_sbas_id(), $this->get_record_id(), strrev($status)); } - } - catch (Exception $e) - { + } catch (Exception $e) { } $this->delete_data_from_cache(self::CACHE_STATUS); @@ -1332,23 +1232,18 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $type = $system_file->get_phrasea_type(); - if ($is_grouping) - { - $uuid = uuid::generate_v4(); + if ($is_grouping) { + $uuid = uuid::generate_v4(); $sha256 = null; - } - else - { + } else { $uuid = $system_file->read_uuid(); - if ( ! uuid::is_valid($uuid)) - { - $uuid = uuid::generate_v4(); + if ( ! uuid::is_valid($uuid)) { + $uuid = uuid::generate_v4(); } $sha256 = $system_file->get_sha256(); } - if ( ! $original_name) - { + if ( ! $original_name) { $original_name = $system_file->getFilename(); } @@ -1368,37 +1263,34 @@ class record_adapter implements record_Interface, cache_cacheableInterface $stmt = $connbas->prepare($sql); $stmt->execute(array( - ':coll_id' => $coll_id - , ':parent_record_id' => ($is_grouping ? 1 : 0) - , ':type' => $type - , ':sha256' => $sha256 - , ':uuid' => $uuid - , ':originalname' => $original_name - , ':mime' => $system_file->get_mime() + ':coll_id' => $coll_id + , ':parent_record_id' => ($is_grouping ? 1 : 0) + , ':type' => $type + , ':sha256' => $sha256 + , ':uuid' => $uuid + , ':originalname' => $original_name + , ':mime' => $system_file->get_mime() )); $record_id = $connbas->lastInsertId(); - $record = new self($sbas_id, $record_id); + $record = new self($sbas_id, $record_id); - try - { - $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + $appbox = appbox::get_instance(\bootstrap::getCore()); $session = $appbox->get_session(); - $log_id = $session->get_logger($databox)->get_id(); + $log_id = $session->get_logger($databox)->get_id(); - $sql = 'INSERT INTO log_docs (id, log_id, date, record_id, action, final, comment) + $sql = 'INSERT INTO log_docs (id, log_id, date, record_id, action, final, comment) VALUES (null, :log_id, now(), :record_id, "add", :coll_id,"")'; $stmt = $connbas->prepare($sql); $stmt->execute(array( - ':log_id' => $log_id, - ':record_id' => $record_id, - ':coll_id' => $coll_id + ':log_id' => $log_id, + ':record_id' => $record_id, + ':coll_id' => $coll_id )); $stmt->closeCursor(); - } - catch (Exception $e) - { + } catch (Exception $e) { unset($e); } @@ -1408,8 +1300,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface system_file::mkdir($pathhd); $newname = $record->get_record_id() . "_document." . $system_file->get_extension(); - if ( ! copy($system_file->getPathname(), $pathhd . $newname)) - { + if ( ! copy($system_file->getPathname(), $pathhd . $newname)) { throw new Exception('Unable to write file'); } @@ -1422,28 +1313,25 @@ class record_adapter implements record_Interface, cache_cacheableInterface $tc_datas = $system_file->get_technical_datas(); - $sql = 'REPLACE INTO technical_datas (id, record_id, name, value) + $sql = 'REPLACE INTO technical_datas (id, record_id, name, value) VALUES (null, :record_id, :name, :value)'; $stmt = $connbas->prepare($sql); - foreach ($tc_datas as $name => $value) - { + foreach ($tc_datas as $name => $value) { if (is_null($value)) continue; $stmt->execute(array( - ':record_id' => $record_id - , ':name' => $name - , ':value' => $value + ':record_id' => $record_id + , ':name' => $name + , ':value' => $value )); } $stmt->closeCursor(); - foreach ($record->get_databox()->get_meta_structure()->get_elements() as $data_field) - { - if ($data_field->get_metadata_source() != metadata_description_PHRASEANET_tfrecordid::get_source()) - { + foreach ($record->get_databox()->get_meta_structure()->get_elements() as $data_field) { + if ($data_field->get_metadata_source() != metadata_description_PHRASEANET_tfrecordid::get_source()) { continue; } @@ -1451,28 +1339,24 @@ class record_adapter implements record_Interface, cache_cacheableInterface /** * Replacing record_id in multi values is non sense */ - if ( ! $data_field->is_multi()) - { + if ( ! $data_field->is_multi()) { continue; } - try - { - $field = $record->get_caption()->get_field($data_field->get_name())->get_meta_id(); - $value = array_pop($field->get_values()); + try { + $field = $record->get_caption()->get_field($data_field->get_name())->get_meta_id(); + $value = array_pop($field->get_values()); $meta_id = $value->getId(); - } - catch (\Exception $e) - { + } catch (\Exception $e) { $meta_id = null; } $metas = array( - array( - 'meta_struct_id' => $data_field->get_id() - , 'meta_id' => $meta_id - , 'value' => array($record->get_record_id()) - ) + array( + 'meta_struct_id' => $data_field->get_id() + , 'meta_id' => $meta_id + , 'value' => array($record->get_record_id()) + ) ); $record->set_metadatas($metas, true); @@ -1500,22 +1384,20 @@ class record_adapter implements record_Interface, cache_cacheableInterface $params = array(':sha256' => $sha256); - if ( ! is_null($record_id)) - { + if ( ! is_null($record_id)) { $sql .= ' AND record_id = :record_id'; $params[':record_id'] = $record_id; } $stmt = $conn->prepare($sql); $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $records = array(); - foreach ($rs as $row) - { - $k = count($records); + foreach ($rs as $row) { + $k = count($records); $records[$k] = new record_adapter($sbas_id, $row['record_id']); } @@ -1530,8 +1412,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $hd = $this->get_subdef('document'); - if ($hd->is_physically_present()) - { + if ($hd->is_physically_present()) { return new system_file(p4string::addEndSlash($hd->get_path()) . $hd->get_file()); } @@ -1544,25 +1425,24 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function delete() { - $connbas = $this->get_databox()->get_connection(); - $sbas_id = $this->get_databox()->get_sbas_id(); - $appbox = appbox::get_instance(\bootstrap::getCore()); + $connbas = $this->get_databox()->get_connection(); + $sbas_id = $this->get_databox()->get_sbas_id(); + $appbox = appbox::get_instance(\bootstrap::getCore()); $registry = $appbox->get_registry(); - $conn = $appbox->get_connection(); + $conn = $appbox->get_connection(); $ftodel = array(); - foreach ($this->get_subdefs() as $subdef) - { + foreach ($this->get_subdefs() as $subdef) { if ( ! $subdef->is_physically_present()) continue; - $ftodel[] = $subdef->get_pathfile(); + $ftodel[] = $subdef->get_pathfile(); $watermark = $subdef->get_path() . 'watermark_' . $subdef->get_file(); if (file_exists($watermark)) - $ftodel[] = $watermark; - $stamp = $subdef->get_path() . 'stamp_' . $subdef->get_file(); + $ftodel[] = $watermark; + $stamp = $subdef->get_path() . 'stamp_' . $subdef->get_file(); if (file_exists($stamp)) - $ftodel[] = $stamp; + $ftodel[] = $stamp; } $origcoll = phrasea::collFromBas($this->get_base_id()); @@ -1570,85 +1450,80 @@ class record_adapter implements record_Interface, cache_cacheableInterface $xml = $this->get_caption()->serialize(\caption_record::SERIALIZE_XML); $appbox->get_session()->get_logger($this->get_databox()) - ->log($this, Session_Logger::EVENT_DELETE, $origcoll, $xml); + ->log($this, Session_Logger::EVENT_DELETE, $origcoll, $xml); - $sql = "DELETE FROM record WHERE record_id = :record_id"; + $sql = "DELETE FROM record WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = 'SELECT id FROM metadatas WHERE record_id = :record_id'; + $sql = 'SELECT id FROM metadatas WHERE record_id = :record_id'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); - $rs = $stmt->fetchAll(); + $rs = $stmt->fetchAll(); $stmt->closeCursor(); - try - { + try { $sphinx_rt = sphinxrt::get_instance($registry); $sbas_params = phrasea::sbas_params(); - if (isset($sbas_params[$sbas_id])) - { - $params = $sbas_params[$sbas_id]; + 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']))); - foreach ($rs as $row) - { + foreach ($rs as $row) { $sphinx_rt->delete(array("metadatas" . $sbas_crc, "metadatas" . $sbas_crc . "_stemmed_en", "metadatas" . $sbas_crc . "_stemmed_fr"), "metas_realtime" . $sbas_crc, $row['id']); } $sphinx_rt->delete(array("documents" . $sbas_crc, "documents" . $sbas_crc . "_stemmed_fr", "documents" . $sbas_crc . "_stemmed_en"), "docs_realtime" . $sbas_crc, $this->get_record_id()); } - } - catch (Exception $e) - { + } catch (Exception $e) { unset($e); } - $sql = "DELETE FROM metadatas WHERE record_id = :record_id"; + $sql = "DELETE FROM metadatas WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM prop WHERE record_id = :record_id"; + $sql = "DELETE FROM prop WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM idx WHERE record_id = :record_id"; + $sql = "DELETE FROM idx WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM permalinks + $sql = "DELETE FROM permalinks WHERE subdef_id IN (SELECT subdef_id FROM subdef WHERE record_id=:record_id)"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM subdef WHERE record_id = :record_id"; + $sql = "DELETE FROM subdef WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM technical_datas WHERE record_id = :record_id"; + $sql = "DELETE FROM technical_datas WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM thit WHERE record_id = :record_id"; + $sql = "DELETE FROM thit WHERE record_id = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM regroup WHERE rid_parent = :record_id"; + $sql = "DELETE FROM regroup WHERE rid_parent = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); - $sql = "DELETE FROM regroup WHERE rid_child = :record_id"; + $sql = "DELETE FROM regroup WHERE rid_child = :record_id"; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); @@ -1658,8 +1533,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $repository = $em->getRepository('\Entities\BasketElement'); /* @var $repository \Repositories\BasketElementRepository */ - foreach ($repository->findElementsByRecord($this) as $basket_element) - { + foreach ($repository->findElementsByRecord($this) as $basket_element) { $em->remove($basket_element); } @@ -1693,31 +1567,26 @@ class record_adapter implements record_Interface, cache_cacheableInterface $Core = bootstrap::getCore(); - if ( ! $subdefs) - { + if ( ! $subdefs) { $Core['monolog']->addInfo(sprintf('Nothing to do for %s', $this->get_type())); return; } - foreach ($subdefs as $subdef) - { + foreach ($subdefs as $subdef) { $subdefname = $subdef->get_name(); - if ($wanted_subdefs && ! in_array($subdefname, $wanted_subdefs)) - { + if ($wanted_subdefs && ! in_array($subdefname, $wanted_subdefs)) { continue; } $pathdest = null; - if ($this->has_subdef($subdefname) && $this->get_subdef($subdefname)->is_physically_present()) - { + if ($this->has_subdef($subdefname) && $this->get_subdef($subdefname)->is_physically_present()) { $pathdest = $this->get_subdef($subdefname)->get_pathfile(); - if ( ! is_file($pathdest) && is_writeable($pathdest)) - { + if ( ! is_file($pathdest) && is_writeable($pathdest)) { unlink($pathdest); $this->clearSubdefCache($subdefname); @@ -1728,8 +1597,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $this->generate_subdef($subdef, $pathdest); - if (file_exists($pathdest)) - { + if (file_exists($pathdest)) { $baseurl = $subdef->get_baseurl() ? $subdef->get_baseurl() . substr(dirname($pathdest), strlen($subdef->get_path()) + 1) : ''; media_subdef::create($this, $subdef->get_name(), new system_file($pathdest), $baseurl); @@ -1743,14 +1611,12 @@ class record_adapter implements record_Interface, cache_cacheableInterface protected function clearSubdefCache($subdefname) { - if ($this->has_subdef($subdefname)) - { + if ($this->has_subdef($subdefname)) { $this->get_subdef($subdefname)->delete_data_from_cache(); $permalink = $this->get_subdef($subdefname)->get_permalink(); - if ($permalink instanceof media_Permalink_Adapter) - { + if ($permalink instanceof media_Permalink_Adapter) { $permalink->delete_data_from_cache(); } } @@ -1768,14 +1634,11 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $Core = \bootstrap::getCore(); - try - { + try { $Core['media-alchemyst']->open($this->get_hd_file()->getPathname()); $Core['media-alchemyst']->turnInto($pathdest, $subdef_class->getSpecs()); $Core['media-alchemyst']->close(); - } - catch (\MediaAlchemyst\Exception\Exception $e) - { + } catch (\MediaAlchemyst\Exception\Exception $e) { $Core['monolog']->addError(sprintf('Subdef generation failed with message %s', $e->getMessage())); } @@ -1784,12 +1647,9 @@ class record_adapter implements record_Interface, cache_cacheableInterface protected function generateSubdefPathname(databox_subdef $subdef, $oldVersion = null) { - if ($oldVersion) - { + if ($oldVersion) { $pathdest = p4string::addEndSlash(pathinfo($oldVersion, PATHINFO_DIRNAME)); - } - else - { + } else { $pathdest = databox::dispatch($subdef->get_path()); } @@ -1800,8 +1660,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $extension = null; - switch (true) - { + switch (true) { case $spec->getType() === MediaAlchemyst\Specification\Specification::TYPE_IMAGE: $extension = 'jpg'; break; @@ -1826,8 +1685,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $extension = null; - switch ($audioCodec) - { + switch ($audioCodec) { case 'flac': $extension = 'flac'; break; @@ -1843,8 +1701,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $extension = null; - switch ($videoCodec) - { + switch ($videoCodec) { case 'libtheora': $extension = 'ogv'; break; @@ -1880,8 +1737,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function delete_data_from_cache($option = null) { - switch ($option) - { + switch ($option) { case self::CACHE_STATUS: $this->status = null; break; @@ -1907,12 +1763,12 @@ class record_adapter implements record_Interface, cache_cacheableInterface (null, :log_id, now(), :rec, :referrer, :site)'; $params = array( - ':log_id' => $log_id - , ':rec' => $this->get_record_id() - , ':referrer' => $referrer - , ':site' => $gv_sit + ':log_id' => $log_id + , ':rec' => $this->get_record_id() + , ':referrer' => $referrer + , ':site' => $gv_sit ); - $stmt = $connbas->prepare($sql); + $stmt = $connbas->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); @@ -1922,24 +1778,19 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function rotate_subdefs($angle) { $registry = registry::get_instance(); - foreach ($this->get_subdefs() as $name => $subdef) - { + foreach ($this->get_subdefs() as $name => $subdef) { if ($name == 'document') continue; - try - { + try { $subdef->rotate($registry, $angle); - } - catch (Exception $e) - { + } catch (Exception $e) { } } return $this; } - /** * * @var Array @@ -1953,7 +1804,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function get_container_baskets() { $Core = bootstrap::getCore(); - $em = $Core->getEntityManager(); + $em = $Core->getEntityManager(); $repo = $em->getRepository('\Entities\Basket'); @@ -1972,20 +1823,19 @@ class record_adapter implements record_Interface, cache_cacheableInterface public static function get_records_by_originalname(databox $databox, $original_name, $offset_start = 0, $how_many = 10) { $offset_start = (int) ($offset_start < 0 ? 0 : $offset_start); - $how_many = (int) (($how_many > 20 || $how_many < 1) ? 10 : $how_many); + $how_many = (int) (($how_many > 20 || $how_many < 1) ? 10 : $how_many); $sql = sprintf('SELECT record_id FROM record WHERE original_name = :original_name LIMIT %d, %d' - , $offset_start, $how_many); + , $offset_start, $how_many); $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(array(':original_name' => $original_name)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $records = array(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $records[] = $databox->get_record($row['record_id']); } @@ -1998,8 +1848,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface */ public function get_children() { - if ( ! $this->is_grouping()) - { + if ( ! $this->is_grouping()) { throw new Exception('This record is not a grouping'); } @@ -2019,20 +1868,19 @@ class record_adapter implements record_Interface, cache_cacheableInterface ORDER BY g.ord ASC, dateadd ASC, record_id ASC'; $params = array( - ':GV_site' => $appbox->get_registry()->get('GV_sit') - , ':usr_id' => $appbox->get_session()->get_usr_id() - , ':record_id' => $this->get_record_id() + ':GV_site' => $appbox->get_registry()->get('GV_sit') + , ':usr_id' => $appbox->get_session()->get_usr_id() + , ':record_id' => $this->get_record_id() ); $stmt = $this->get_databox()->get_connection()->prepare($sql); $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $set = new set_selection(); - $i = 1; - foreach ($rs as $row) - { + $i = 1; + foreach ($rs as $row) { $set->add_element(new record_adapter($this->get_sbas_id(), $row['record_id'], $i)); $i ++; } @@ -2063,19 +1911,18 @@ class record_adapter implements record_Interface, cache_cacheableInterface $params = array( - ':GV_site' => $appbox->get_registry()->get('GV_sit') - , ':usr_id' => $appbox->get_session()->get_usr_id() - , ':record_id' => $this->get_record_id() + ':GV_site' => $appbox->get_registry()->get('GV_sit') + , ':usr_id' => $appbox->get_session()->get_usr_id() + , ':record_id' => $this->get_record_id() ); $stmt = $this->get_databox()->get_connection()->prepare($sql); $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $set = new set_selection(); - foreach ($rs as $row) - { + foreach ($rs as $row) { $set->add_element(new record_adapter($this->get_sbas_id(), $row['record_id'])); } @@ -2089,8 +1936,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function appendChild(\record_adapter $record) { - if ( ! $this->is_grouping()) - { + if ( ! $this->is_grouping()) { throw new \Exception('Only stories can append children'); } @@ -2109,8 +1955,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $stmt->closeCursor(); - if ($row) - { + if ($row) { $ord = is_null($row["ord"]) ? 0 : $row["ord"]; } @@ -2118,9 +1963,9 @@ class record_adapter implements record_Interface, cache_cacheableInterface VALUES (null, :parent_record_id, :record_id, NOW(), :ord)'; $params = array( - ':parent_record_id' => $this->get_record_id() - , ':record_id' => $record->get_record_id() - , ':ord' => $ord + ':parent_record_id' => $this->get_record_id() + , ':record_id' => $record->get_record_id() + , ':ord' => $ord ); $stmt = $connbas->prepare($sql); @@ -2128,7 +1973,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $stmt->closeCursor(); - $sql = 'UPDATE record SET moddate = NOW() WHERE record_id = :record_id'; + $sql = 'UPDATE record SET moddate = NOW() WHERE record_id = :record_id'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); @@ -2140,8 +1985,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface public function removeChild(\record_adapter $record) { - if ( ! $this->is_grouping()) - { + if ( ! $this->is_grouping()) { throw new \Exception('Only stories can append children'); } @@ -2151,15 +1995,15 @@ class record_adapter implements record_Interface, cache_cacheableInterface AND rid_child = :record_id"; $params = array( - ':parent_record_id' => $this->get_record_id() - , ':record_id' => $record->get_record_id() + ':parent_record_id' => $this->get_record_id() + , ':record_id' => $record->get_record_id() ); $stmt = $connbas->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); - $sql = 'UPDATE record SET moddate = NOW() WHERE record_id = :record_id'; + $sql = 'UPDATE record SET moddate = NOW() WHERE record_id = :record_id'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':record_id' => $this->get_record_id())); $stmt->closeCursor(); @@ -2168,5 +2012,4 @@ class record_adapter implements record_Interface, cache_cacheableInterface return $this; } - } diff --git a/lib/classes/record/exportElement.class.php b/lib/classes/record/exportElement.class.php index 4cd3df14a2..97b691145c 100644 --- a/lib/classes/record/exportElement.class.php +++ b/lib/classes/record/exportElement.class.php @@ -17,304 +17,283 @@ */ class record_exportElement extends record_adapter { + /** + * + * @var Array + */ + protected $downloadable; - /** - * - * @var Array - */ - protected $downloadable; - /** - * - * @var Array - */ - protected $orderable; - /** - * - * @var Array - */ - protected $size; - /** - * - * @var int - */ - protected $remain_hd; - /** - * - * @var string - */ - protected $directory; + /** + * + * @var Array + */ + protected $orderable; - /** - * - * @param int $base_id - * @param int $record_id - * @param string $directory - * @param int $remain_hd - * @return record_exportElement - */ - function __construct($sbas_id, $record_id, $directory='', $remain_hd=false) - { - $this->directory = $directory; - $this->remain_hd = $remain_hd; - $this->size = array(); - parent::__construct($sbas_id, $record_id); + /** + * + * @var Array + */ + protected $size; - $this->get_actions($remain_hd); + /** + * + * @var int + */ + protected $remain_hd; - return $this; - } + /** + * + * @var string + */ + protected $directory; - /** - * - * @return record_exportElement - */ - protected function get_actions() - { - $this->downloadable = $downloadable = array(); - $this->orderable = $orderable = array(); - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - - $sd = $this->get_subdefs(); - - $sbas_id = phrasea::sbasFromBas($this->base_id); - - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - $subdefgroups = $appbox->get_databox($sbas_id)->get_subdef_structure(); - - $subdefs = array(); - - foreach ($subdefgroups as $subdef_type => $subdefs_obj) + /** + * + * @param int $base_id + * @param int $record_id + * @param string $directory + * @param int $remain_hd + * @return record_exportElement + */ + function __construct($sbas_id, $record_id, $directory = '', $remain_hd = false) { - if ($subdef_type == $this->get_type()) - { - $subdefs = $subdefs_obj; - break; - } + $this->directory = $directory; + $this->remain_hd = $remain_hd; + $this->size = array(); + parent::__construct($sbas_id, $record_id); + + $this->get_actions($remain_hd); + + return $this; } - $go_dl = array( - 'document' => false, - 'preview' => false, - 'thumbnail' => true - ); - - if ($user->ACL()->has_right_on_base($this->get_base_id(), 'candwnldhd')) + /** + * + * @return record_exportElement + */ + protected function get_actions() { - $go_dl['document'] = true; - } - if ($user->ACL()->has_right_on_base($this->get_base_id(), 'candwnldpreview')) - { - $go_dl['preview'] = true; - } - if ($user->ACL()->has_hd_grant($this)) - { - $go_dl['document'] = true; - $go_dl['preview'] = true; - } - if ($user->ACL()->has_preview_grant($this)) - { - $go_dl['preview'] = true; - } + $this->downloadable = $downloadable = array(); + $this->orderable = $orderable = array(); - $query = new User_Query($appbox); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); - $masters = $query->on_base_ids(array($this->base_id)) - ->who_have_right(array('order_master')) - ->execute()->get_results(); + $sd = $this->get_subdefs(); - $go_cmd = (count($masters) > 0 && $user->ACL()->has_right_on_base($this->base_id, 'cancmd')); + $sbas_id = phrasea::sbasFromBas($this->base_id); - $orderable['document'] = false; - $downloadable['document'] = false; + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - if (isset($sd['document']) && is_file($sd['document']->get_pathfile())) - { - if ($go_dl['document'] === true) - { - if ($user->ACL()->is_restricted_download($this->base_id)) - { - $this->remain_hd--; - if ($this->remain_hd >= 0) - $downloadable['document'] = array( - 'class' => 'document', - 'label' => _('document original') + $subdefgroups = $appbox->get_databox($sbas_id)->get_subdef_structure(); + + $subdefs = array(); + + foreach ($subdefgroups as $subdef_type => $subdefs_obj) { + if ($subdef_type == $this->get_type()) { + $subdefs = $subdefs_obj; + break; + } + } + + $go_dl = array( + 'document' => false, + 'preview' => false, + 'thumbnail' => true + ); + + if ($user->ACL()->has_right_on_base($this->get_base_id(), 'candwnldhd')) { + $go_dl['document'] = true; + } + if ($user->ACL()->has_right_on_base($this->get_base_id(), 'candwnldpreview')) { + $go_dl['preview'] = true; + } + if ($user->ACL()->has_hd_grant($this)) { + $go_dl['document'] = true; + $go_dl['preview'] = true; + } + if ($user->ACL()->has_preview_grant($this)) { + $go_dl['preview'] = true; + } + + $query = new User_Query($appbox); + + $masters = $query->on_base_ids(array($this->base_id)) + ->who_have_right(array('order_master')) + ->execute()->get_results(); + + $go_cmd = (count($masters) > 0 && $user->ACL()->has_right_on_base($this->base_id, 'cancmd')); + + $orderable['document'] = false; + $downloadable['document'] = false; + + if (isset($sd['document']) && is_file($sd['document']->get_pathfile())) { + if ($go_dl['document'] === true) { + if ($user->ACL()->is_restricted_download($this->base_id)) { + $this->remain_hd --; + if ($this->remain_hd >= 0) + $downloadable['document'] = array( + 'class' => 'document', + 'label' => _('document original') + ); + } + else + $downloadable['document'] = array( + 'class' => 'document', + 'label' => _('document original') + ); + } + if ($go_cmd === true) { + $orderable['document'] = true; + } + + $this->add_count('document', $sd['document']->get_size()); + } + + + foreach ($subdefs as $subdef) { + $name = $subdef->get_name(); + $class = $subdef->get_class(); + + + $subdef_label = $name; + foreach ($subdef->get_labels() as $lang => $label) { + if (trim($label) == '') + continue; + + if ($lang == $session->get_I18n()) { + $subdef_label = $label; + break; + } + $subdef_label = $label; + } + + $downloadable[$name] = false; + + $downloadable_settings = $subdef->is_downloadable(); + + if ( ! $downloadable_settings || $go_dl[$class] === false) { + continue; + } + + if ($go_dl[$class]) { + if (isset($sd[$name]) && is_file($sd[$name]->get_pathfile())) { + if ($class == 'document') { + + if ($user->ACL()->is_restricted_download($this->base_id)) { + $this->remain_hd --; + if ($this->remain_hd >= 0) + $downloadable[$name] = array( + 'class' => $class, + 'label' => $subdef_label + ); + } + else + $downloadable[$name] = array( + 'class' => $class, + 'label' => $subdef_label + ); + } + else { + $downloadable[$name] = array( + 'class' => $class, + 'label' => $subdef_label + ); + } + + $this->add_count($name, $sd[$name]->get_size()); + } + } + } + + $xml = $this->get_caption()->serialize(caption_record::SERIALIZE_XML); + + if ($xml) { + $downloadable['caption'] = array( + 'class' => 'caption', + 'label' => _('caption XML') ); + $this->add_count('caption', strlen($xml)); + $downloadable['caption-yaml'] = array( + 'class' => 'caption', + 'label' => _('caption YAML') + ); + $this->add_count('caption-yaml', strlen(strip_tags($xml))); + } + + $this->downloadable = $downloadable; + $this->orderable = $orderable; + + return $this; + } + + /** + * + * @param string $name + * @param int $size + * @return record_exportElement + */ + private function add_count($name, $size) + { + if ( ! $this->size) { + $objectsize = array(); } else - $downloadable['document'] = array( - 'class' => 'document', - 'label' => _('document original') - ); - } - if ($go_cmd === true) - { - $orderable['document'] = true; - } + $objectsize = $this->size; - $this->add_count('document', $sd['document']->get_size()); + $objectsize[$name] = $size; + + $this->size = $objectsize; + + return $this; } - - foreach ($subdefs as $subdef) + /** + * + * @param string $name + * @return mixed content + */ + public function get_size($name = false) { - $name = $subdef->get_name(); - $class = $subdef->get_class(); - - - $subdef_label = $name; - foreach ($subdef->get_labels() as $lang => $label) - { - if (trim($label) == '') - continue; - - if ($lang == $session->get_I18n()) - { - $subdef_label = $label; - break; - } - $subdef_label = $label; - } - - $downloadable[$name] = false; - - $downloadable_settings = $subdef->is_downloadable(); - - if (!$downloadable_settings || $go_dl[$class] === false) - { - continue; - } - - if ($go_dl[$class]) - { - if (isset($sd[$name]) && is_file($sd[$name]->get_pathfile())) - { - if ($class == 'document') - { - - if ($user->ACL()->is_restricted_download($this->base_id)) - { - $this->remain_hd--; - if ($this->remain_hd >= 0) - $downloadable[$name] = array( - 'class' => $class, - 'label' => $subdef_label - ); - } - else - $downloadable[$name] = array( - 'class' => $class, - 'label' => $subdef_label - ); - } - else - { - $downloadable[$name] = array( - 'class' => $class, - 'label' => $subdef_label - ); - } - - $this->add_count($name, $sd[$name]->get_size()); - } - } + if ($name) + return $this->size[$name]; + else + return $this->size; } - $xml = $this->get_caption()->serialize(caption_record::SERIALIZE_XML); - - if ($xml) + /** + * + * @return Array + */ + public function get_orderable() { - $downloadable['caption'] = array( - 'class' => 'caption', - 'label' => _('caption XML') - ); - $this->add_count('caption', strlen($xml)); - $downloadable['caption-yaml'] = array( - 'class' => 'caption', - 'label' => _('caption YAML') - ); - $this->add_count('caption-yaml', strlen(strip_tags($xml))); + return $this->orderable; } - $this->downloadable = $downloadable; - $this->orderable = $orderable; - - return $this; - } - - /** - * - * @param string $name - * @param int $size - * @return record_exportElement - */ - private function add_count($name, $size) - { - if (!$this->size) + /** + * + * @return Array + */ + public function get_downloadable() { - $objectsize = array(); + return $this->downloadable; } - else - $objectsize = $this->size; - $objectsize[$name] = $size; - - $this->size = $objectsize; - - return $this; - } - - /** - * - * @param string $name - * @return mixed content - */ - public function get_size($name = false) - { - if ($name) - - return $this->size[$name]; - else - - return $this->size; - } - - /** - * - * @return Array - */ - public function get_orderable() - { - return $this->orderable; - } - - /** - * - * @return Array - */ - public function get_downloadable() - { - return $this->downloadable; - } - - /** - * - * @return int - */ - public function get_remain_hd() - { - return $this->remain_hd; - } - - /** - * - * @return string - */ - public function get_directory() - { - return $this->directory; - } + /** + * + * @return int + */ + public function get_remain_hd() + { + return $this->remain_hd; + } + /** + * + * @return string + */ + public function get_directory() + { + return $this->directory; + } } diff --git a/lib/classes/record/orderElement.class.php b/lib/classes/record/orderElement.class.php index bc9623e842..b78a32868c 100644 --- a/lib/classes/record/orderElement.class.php +++ b/lib/classes/record/orderElement.class.php @@ -17,69 +17,67 @@ */ class record_orderElement extends record_adapter { + /** + * + * @var boolean + */ + protected $deny; - /** - * - * @var boolean - */ - protected $deny; - /** - * - * @var int - */ - protected $order_master_id; + /** + * + * @var int + */ + protected $order_master_id; - /** - * - * @param int $base_id - * @param int $record_id - * @param boolean $deny - * @param int $order_master_id - */ - public function __construct($sbas_id, $record_id, $deny, $order_master_id) - { - $this->deny = !!$deny; - $this->order_master_id = $order_master_id; - - parent::__construct($sbas_id, $record_id); - - $this->get_subdefs(); - - return $this; - } - - /** - * - * @return string - */ - public function get_order_master_name() - { - if ($this->order_master_id) + /** + * + * @param int $base_id + * @param int $record_id + * @param boolean $deny + * @param int $order_master_id + */ + public function __construct($sbas_id, $record_id, $deny, $order_master_id) { - $user = User_Adapter::getInstance($this->order_master_id, appbox::get_instance(\bootstrap::getCore())); + $this->deny = ! ! $deny; + $this->order_master_id = $order_master_id; - return $user->get_display_name(); + parent::__construct($sbas_id, $record_id); + + $this->get_subdefs(); + + return $this; } - return ''; - } + /** + * + * @return string + */ + public function get_order_master_name() + { + if ($this->order_master_id) { + $user = User_Adapter::getInstance($this->order_master_id, appbox::get_instance(\bootstrap::getCore())); - /** - * - * @return int - */ - public function get_order_master_id() - { - return $this->order_master_id; - } + return $user->get_display_name(); + } - /** - * - * @return boolean - */ - public function get_deny() - { - return $this->deny; - } + return ''; + } + /** + * + * @return int + */ + public function get_order_master_id() + { + return $this->order_master_id; + } + + /** + * + * @return boolean + */ + public function get_deny() + { + return $this->deny; + } } diff --git a/lib/classes/record/preview.class.php b/lib/classes/record/preview.class.php index f16e35c5ef..3400fb0c29 100644 --- a/lib/classes/record/preview.class.php +++ b/lib/classes/record/preview.class.php @@ -17,639 +17,598 @@ */ class record_preview extends record_adapter { + /** + * + * @var string + */ + protected $env; - /** - * - * @var string - */ - protected $env; + /** + * + * @var int + */ + protected $total; - /** - * - * @var int - */ - protected $total; + /** + * + * @var string + */ + protected $name; - /** - * - * @var string - */ - protected $name; + /** + * + * @var mixed content + */ + protected $container; - /** - * - * @var mixed content - */ - protected $container; + /** + * + * @var mixed content + */ + protected $train; - /** - * - * @var mixed content - */ - protected $train; + /** + * + * @var string + */ + protected $title; - /** - * - * @var string - */ - protected $title; + /** + * + * @var Array + */ + protected $short_history; - /** - * - * @var Array - */ - protected $short_history; + /** + * + * @var media + */ + protected $view_popularity; - /** - * - * @var media - */ - protected $view_popularity; + /** + * + * @var media + */ + protected $refferer_popularity; - /** - * - * @var media - */ - protected $refferer_popularity; + /** + * + * @var media + */ + protected $download_popularity; - /** - * - * @var media - */ - protected $download_popularity; - - /** - * - * @param string $env - * @param int $pos - * @param mixed content $contId - * @param boolean $reload_train - * @return record_preview - */ - public function __construct($env, $pos, $contId, $reload_train, searchEngine_adapter $search_engine = null, $query = '') - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $Core = bootstrap::getCore(); - $number = null; - $this->env = $env; - - switch ($env) + /** + * + * @param string $env + * @param int $pos + * @param mixed content $contId + * @param boolean $reload_train + * @return record_preview + */ + public function __construct($env, $pos, $contId, $reload_train, searchEngine_adapter $search_engine = null, $query = '') { - case "RESULT": - $results = $search_engine->query_per_offset($query, (int) ($pos), 1); - $mypreview = array(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $Core = bootstrap::getCore(); + $number = null; + $this->env = $env; - if ($results->get_datas()->is_empty()) - { - throw new Exception('Record introuvable'); - } - foreach ($results->get_datas() as $record) - { - $number = $pos; - $sbas_id = $record->get_sbas_id(); - $record_id = $record->get_record_id(); - break; - } - break; - case "REG": - $contId = explode('_', $contId); - $sbas_id = $contId[0]; - $record_id = $contId[1]; + switch ($env) { + case "RESULT": + $results = $search_engine->query_per_offset($query, (int) ($pos), 1); + $mypreview = array(); - $this->container = new record_adapter($sbas_id, $record_id); - if ($pos == 0) - { - $number = 0; - $title = _('preview:: regroupement '); - } - else - { + if ($results->get_datas()->is_empty()) { + throw new Exception('Record introuvable'); + } + foreach ($results->get_datas() as $record) { + $number = $pos; + $sbas_id = $record->get_sbas_id(); + $record_id = $record->get_record_id(); + break; + } + break; + case "REG": + $contId = explode('_', $contId); + $sbas_id = $contId[0]; + $record_id = $contId[1]; + + $this->container = new record_adapter($sbas_id, $record_id); + if ($pos == 0) { + $number = 0; + $title = _('preview:: regroupement '); + } else { // $this->container = new record_adapter($sbas_id, $record_id); - $children = $this->container->get_children(); - foreach ($children as $child) - { - $sbas_id = $child->get_sbas_id(); - $record_id = $child->get_record_id(); - if ($child->get_number() == $pos) - break; - } - $number = $pos; - $this->total = $children->get_count(); + $children = $this->container->get_children(); + foreach ($children as $child) { + $sbas_id = $child->get_sbas_id(); + $record_id = $child->get_record_id(); + if ($child->get_number() == $pos) + break; + } + $number = $pos; + $this->total = $children->get_count(); + } + + break; + case "BASK": + $em = $Core->getEntityManager(); + $repository = $em->getRepository('\Entities\Basket'); + + /* @var $repository \Repositories\BasketRepository */ + $Basket = $repository->findUserBasket($contId, $Core->getAuthenticatedUser(), false); + + /* @var $Basket \Entities\Basket */ + $this->container = $Basket; + $this->total = $Basket->getElements()->count(); + $i = 0; + $first = true; + + foreach ($Basket->getElements() as $element) { + /* @var $element \Entities\BasketElement */ + $i ++; + if ($first) { + $sbas_id = $element->getRecord()->get_sbas_id(); + $record_id = $element->getRecord()->get_record_id(); + $this->name = $Basket->getName(); + $number = $element->getOrd(); + } + $first = false; + + if ($element->getOrd() == $pos) { + $sbas_id = $element->getRecord()->get_sbas_id(); + $record_id = $element->getRecord()->get_record_id(); + $this->name = $Basket->getName(); + $number = $element->getOrd(); + } + } + break; + case "FEED": + $entry = Feed_Entry_Adapter::load_from_id($appbox, $contId); + + $this->container = $entry; + $this->total = count($entry->get_content()); + $i = 0; + $first = true; + + foreach ($entry->get_content() as $element) { + $i ++; + if ($first) { + $sbas_id = $element->get_record()->get_sbas_id(); + $record_id = $element->get_record()->get_record_id(); + $this->name = $entry->get_title(); + $number = $element->get_ord(); + } + $first = false; + + if ($element->get_ord() == $pos) { + $sbas_id = $element->get_record()->get_sbas_id(); + $record_id = $element->get_record()->get_record_id(); + $this->name = $entry->get_title(); + $number = $element->get_ord(); + } + } + break; } + parent::__construct($sbas_id, $record_id, $number); - break; - case "BASK": - $em = $Core->getEntityManager(); - $repository = $em->getRepository('\Entities\Basket'); - - /* @var $repository \Repositories\BasketRepository */ - $Basket = $repository->findUserBasket($contId, $Core->getAuthenticatedUser(), false); - - /* @var $Basket \Entities\Basket */ - $this->container = $Basket; - $this->total = $Basket->getElements()->count(); - $i = 0; - $first = true; - - foreach ($Basket->getElements() as $element) - { - /* @var $element \Entities\BasketElement */ - $i++; - if ($first) - { - $sbas_id = $element->getRecord()->get_sbas_id(); - $record_id = $element->getRecord()->get_record_id(); - $this->name = $Basket->getName(); - $number = $element->getOrd(); - } - $first = false; - - if ($element->getOrd() == $pos) - { - $sbas_id = $element->getRecord()->get_sbas_id(); - $record_id = $element->getRecord()->get_record_id(); - $this->name = $Basket->getName(); - $number = $element->getOrd(); - } - } - break; - case "FEED": - $entry = Feed_Entry_Adapter::load_from_id($appbox, $contId); - - $this->container = $entry; - $this->total = count($entry->get_content()); - $i = 0; - $first = true; - - foreach ($entry->get_content() as $element) - { - $i++; - if ($first) - { - $sbas_id = $element->get_record()->get_sbas_id(); - $record_id = $element->get_record()->get_record_id(); - $this->name = $entry->get_title(); - $number = $element->get_ord(); - } - $first = false; - - if ($element->get_ord() == $pos) - { - $sbas_id = $element->get_record()->get_sbas_id(); - $record_id = $element->get_record()->get_record_id(); - $this->name = $entry->get_title(); - $number = $element->get_ord(); - } - } - break; + return $this; } - parent::__construct($sbas_id, $record_id, $number); - return $this; - } - - public function get_train($pos = 0, $query = '', searchEngine_adapter $search_engine = null) - { - if ($this->train) - - return $this->train; - - switch ($this->env) + public function get_train($pos = 0, $query = '', searchEngine_adapter $search_engine = null) { - case 'RESULT': - $perPage = 56; - $index = ($pos - 3) < 0 ? 0 : ($pos - 3); - $page = (int) ceil($pos / $perPage); - $results = $search_engine->query_per_offset($query, $index, $perPage); + if ($this->train) + return $this->train; - $this->train = $results->get_datas(); - break; - case 'BASK': - $this->train = $this->container->getElements(); - break; - case 'REG': - $this->train = $this->container->get_children(); - break; - } + switch ($this->env) { + case 'RESULT': + $perPage = 56; + $index = ($pos - 3) < 0 ? 0 : ($pos - 3); + $page = (int) ceil($pos / $perPage); + $results = $search_engine->query_per_offset($query, $index, $perPage); - return $this->train; - } - - /** - * - * @return boolean - */ - public function is_from_result() - { - return $this->env == 'RESULT'; - } - - public function is_from_feed() - { - return $this->env == 'FEED'; - } - - /** - * - * @return boolean - */ - public function is_from_basket() - { - return $this->env == 'BASK'; - } - - /** - * - * @return boolean - */ - public function is_from_reg() - { - return $this->env == 'REG'; - } - - /** - * - * @return String - */ - public function get_title($highlight = '', searchEngine_adapter $search_engine = null) - { - if ($this->title) - - return $this->title; - - $this->title = collection::getLogo($this->get_base_id()) . ' '; - - switch ($this->env) - { - - case "RESULT": - $this->title .= sprintf( - _('preview:: resultat numero %s '), '' . ($this->number + 1) - . ' : ' - ); - - $this->title .= parent::get_title($highlight, $search_engine); - break; - case "BASK": - $this->title .= $this->name . ' - ' . parent::get_title($highlight, $search_engine) - . ' (' . $this->get_number() . '/' . $this->total . ') '; - break; - case "REG": - $title = parent::get_title(); - if ($this->get_number() == 0) - { - $this->title .= $title; + $this->train = $results->get_datas(); + break; + case 'BASK': + $this->train = $this->container->getElements(); + break; + case 'REG': + $this->train = $this->container->get_children(); + break; } - else - { - $this->title .= sprintf( - '%s %s', $title, $this->get_number() . '/' . $this->total - ); - } - break; - default: - $this->title .= parent::get_title($highlight, $search_engine); - break; + + return $this->train; } - return $this->title; - } - - /** - * - * @return mixed content - */ - public function get_container() - { - return $this->container; - } - - /** - * - * @return Array - */ - public function get_short_history() - { - if (!is_null($this->short_history)) + /** + * + * @return boolean + */ + public function is_from_result() { - return $this->short_history; + return $this->env == 'RESULT'; } - $tab = array(); + public function is_from_feed() + { + return $this->env == 'FEED'; + } - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + /** + * + * @return boolean + */ + public function is_from_basket() + { + return $this->env == 'BASK'; + } - $report = $user->ACL()->has_right_on_base($this->get_base_id(), 'canreport'); + /** + * + * @return boolean + */ + public function is_from_reg() + { + return $this->env == 'REG'; + } - $connsbas = connection::getPDOConnection($this->get_sbas_id()); + /** + * + * @return String + */ + public function get_title($highlight = '', searchEngine_adapter $search_engine = null) + { + if ($this->title) + return $this->title; - $sql = 'SELECT d . * , l.user, l.usrid as usr_id, l.site + $this->title = collection::getLogo($this->get_base_id()) . ' '; + + switch ($this->env) { + + case "RESULT": + $this->title .= sprintf( + _('preview:: resultat numero %s '), '' . ($this->number + 1) + . ' : ' + ); + + $this->title .= parent::get_title($highlight, $search_engine); + break; + case "BASK": + $this->title .= $this->name . ' - ' . parent::get_title($highlight, $search_engine) + . ' (' . $this->get_number() . '/' . $this->total . ') '; + break; + case "REG": + $title = parent::get_title(); + if ($this->get_number() == 0) { + $this->title .= $title; + } else { + $this->title .= sprintf( + '%s %s', $title, $this->get_number() . '/' . $this->total + ); + } + break; + default: + $this->title .= parent::get_title($highlight, $search_engine); + break; + } + + return $this->title; + } + + /** + * + * @return mixed content + */ + public function get_container() + { + return $this->container; + } + + /** + * + * @return Array + */ + public function get_short_history() + { + if ( ! is_null($this->short_history)) { + return $this->short_history; + } + + $tab = array(); + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + + $report = $user->ACL()->has_right_on_base($this->get_base_id(), 'canreport'); + + $connsbas = connection::getPDOConnection($this->get_sbas_id()); + + $sql = 'SELECT d . * , l.user, l.usrid as usr_id, l.site FROM log_docs d, log l WHERE d.log_id = l.id AND d.record_id = :record_id '; - $params = array(':record_id' => $this->get_record_id()); - - if (!$report) - { - $sql .= ' AND ((l.usrid = :usr_id AND l.site= :site) OR action="add")'; - $params[':usr_id'] = $session->get_usr_id(); - $params[':site'] = $registry->get('GV_sit'); - } - - $sql .= 'ORDER BY d.date, usrid DESC'; - - $stmt = $connsbas->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) - { - $hour = phraseadate::getPrettyString(new DateTime($row['date'])); - - if (!isset($tab[$hour])) - $tab[$hour] = array(); - - $site = $row['site']; - - if (!isset($tab[$hour][$site])) - $tab[$hour][$site] = array(); - - $action = $row['action']; - - if (!isset($tab[$hour][$site][$action])) - $tab[$hour][$site][$action] = array(); - - if (!isset($tab[$hour][$site][$action][$row['usr_id']])) - { - $user = null; - - try - { - $user = \User_Adapter::getInstance($row['usr_id'], $appbox); - } - catch (Exception $e) - { + $params = array(':record_id' => $this->get_record_id()); + if ( ! $report) { + $sql .= ' AND ((l.usrid = :usr_id AND l.site= :site) OR action="add")'; + $params[':usr_id'] = $session->get_usr_id(); + $params[':site'] = $registry->get('GV_sit'); } - $tab[$hour][$site][$action][$row['usr_id']] = - array( - 'final' => array() - , 'comment' => array() - , 'user' => $user - ); - } + $sql .= 'ORDER BY d.date, usrid DESC'; - if (!in_array($row['final'], $tab[$hour][$site][$action][$row['usr_id']]['final'])) - $tab[$hour][$site][$action][$row['usr_id']]['final'][] = - $row['final']; + $stmt = $connsbas->prepare($sql); + $stmt->execute($params); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (!in_array($row['comment'], $tab[$hour][$site][$action][$row['usr_id']]['comment'])) - $tab[$hour][$site][$action][$row['usr_id']]['comment'][] = - $row['comment']; + foreach ($rs as $row) { + $hour = phraseadate::getPrettyString(new DateTime($row['date'])); + + if ( ! isset($tab[$hour])) + $tab[$hour] = array(); + + $site = $row['site']; + + if ( ! isset($tab[$hour][$site])) + $tab[$hour][$site] = array(); + + $action = $row['action']; + + if ( ! isset($tab[$hour][$site][$action])) + $tab[$hour][$site][$action] = array(); + + if ( ! isset($tab[$hour][$site][$action][$row['usr_id']])) { + $user = null; + + try { + $user = \User_Adapter::getInstance($row['usr_id'], $appbox); + } catch (Exception $e) { + + } + + $tab[$hour][$site][$action][$row['usr_id']] = + array( + 'final' => array() + , 'comment' => array() + , 'user' => $user + ); + } + + if ( ! in_array($row['final'], $tab[$hour][$site][$action][$row['usr_id']]['final'])) + $tab[$hour][$site][$action][$row['usr_id']]['final'][] = + $row['final']; + + if ( ! in_array($row['comment'], $tab[$hour][$site][$action][$row['usr_id']]['comment'])) + $tab[$hour][$site][$action][$row['usr_id']]['comment'][] = + $row['comment']; + } + + $this->short_history = array_reverse($tab); + + return $this->short_history; } - $this->short_history = array_reverse($tab); - - return $this->short_history; - } - - /** - * - * @return media_image - */ - public function get_view_popularity() - { - if (!is_null($this->view_popularity)) + /** + * + * @return media_image + */ + public function get_view_popularity() { - return $this->view_popularity; - } + if ( ! is_null($this->view_popularity)) { + return $this->view_popularity; + } - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $report = $user->ACL()->has_right_on_base( - $this->get_base_id(), 'canreport'); - $registry = $appbox->get_registry(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $report = $user->ACL()->has_right_on_base( + $this->get_base_id(), 'canreport'); + $registry = $appbox->get_registry(); - if (!$report && !$registry->get('GV_google_api')) - { - $this->view_popularity = false; + if ( ! $report && ! $registry->get('GV_google_api')) { + $this->view_popularity = false; - return $this->view_popularity; - } + return $this->view_popularity; + } - $views = $dwnls = array(); - $top = 1; - $day = 30; - $min = 0; - $average = 0; + $views = $dwnls = array(); + $top = 1; + $day = 30; + $min = 0; + $average = 0; - while ($day >= 0) - { + while ($day >= 0) { - $datetime = new DateTime('-' . $day . ' days'); - $date = date_format($datetime, 'Y-m-d'); - $views[$date] = $dwnls[$date] = 0; - $day--; - } + $datetime = new DateTime('-' . $day . ' days'); + $date = date_format($datetime, 'Y-m-d'); + $views[$date] = $dwnls[$date] = 0; + $day --; + } - $sql = 'SELECT count(id) as views, DATE(date) as datee + $sql = 'SELECT count(id) as views, DATE(date) as datee FROM `log_view` WHERE record_id = :record_id AND date > (NOW() - INTERVAL 1 MONTH) AND site_id = :site GROUP BY datee ORDER BY datee ASC'; - $connsbas = connection::getPDOConnection($this->get_sbas_id()); - $stmt = $connsbas->prepare($sql); - $stmt->execute( - array( - ':record_id' => $this->get_record_id(), - ':site' => $registry->get('GV_sit') - ) - ); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $connsbas = connection::getPDOConnection($this->get_sbas_id()); + $stmt = $connsbas->prepare($sql); + $stmt->execute( + array( + ':record_id' => $this->get_record_id(), + ':site' => $registry->get('GV_sit') + ) + ); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - foreach ($rs as $row) - { - if (isset($views[$row['datee']])) - { - $views[$row['datee']] = (int) $row['views']; - $top = max((int) $row['views'], $top); - $min = isset($min) ? min($row['views'], $min) : $row['views']; - $average += $row['views']; - } + foreach ($rs as $row) { + if (isset($views[$row['datee']])) { + $views[$row['datee']] = (int) $row['views']; + $top = max((int) $row['views'], $top); + $min = isset($min) ? min($row['views'], $min) : $row['views']; + $average += $row['views']; + } + } + + $topScale = round($top * 1.2); + + $average = $average / 30; + $max = round(($top) * 100 / ($topScale)); + $min = round($min * 100 / ($topScale)); + $average = round($average * 100 / ($topScale)); + + $width = 350; + $height = 150; + $url = 'http://chart.apis.google.com/chart?' . + 'chs=' . $width . 'x' . $height . + '&chd=t:' . implode(',', $views) . + '&cht=lc' . + '&chf=bg,s,00000000' . + '&chxt=x,y,r' . + '&chds=0,' . $topScale . + '&chls=2.0&chxtc=2,-350' . + '&chxl=0:|' . date_format(new DateTime('-30 days'), 'd M') . '|' + . date_format(new DateTime('-15 days'), 'd M') . '|' + . date_format(new DateTime(), 'd M') . '|1:|0|' + . round($top / 2, 2) . '|' . $top + . '|2:|min|average|max' . + '&chxp=2,' . $min . ',' . $average . ',' . $max; + + + $this->view_popularity = new media_adapter($url, $width, $height); + + return $this->view_popularity; } - $topScale = round($top * 1.2); - - $average = $average / 30; - $max = round(($top) * 100 / ($topScale)); - $min = round($min * 100 / ($topScale)); - $average = round($average * 100 / ($topScale)); - - $width = 350; - $height = 150; - $url = 'http://chart.apis.google.com/chart?' . - 'chs=' . $width . 'x' . $height . - '&chd=t:' . implode(',', $views) . - '&cht=lc' . - '&chf=bg,s,00000000' . - '&chxt=x,y,r' . - '&chds=0,' . $topScale . - '&chls=2.0&chxtc=2,-350' . - '&chxl=0:|' . date_format(new DateTime('-30 days'), 'd M') . '|' - . date_format(new DateTime('-15 days'), 'd M') . '|' - . date_format(new DateTime(), 'd M') . '|1:|0|' - . round($top / 2, 2) . '|' . $top - . '|2:|min|average|max' . - '&chxp=2,' . $min . ',' . $average . ',' . $max; - - - $this->view_popularity = new media_adapter($url, $width, $height); - - return $this->view_popularity; - } - - /** - * - * @return media - */ - public function get_refferer_popularity() - { - if (!is_null($this->refferer_popularity)) + /** + * + * @return media + */ + public function get_refferer_popularity() { - return $this->refferer_popularity; - } + if ( ! is_null($this->refferer_popularity)) { + return $this->refferer_popularity; + } - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $report = $user->ACL()->has_right_on_base( - $this->get_base_id(), 'canreport'); - $registry = $appbox->get_registry(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $report = $user->ACL()->has_right_on_base( + $this->get_base_id(), 'canreport'); + $registry = $appbox->get_registry(); - if (!$report && !$registry->get('GV_google_api')) - { - $this->refferer_popularity = false; + if ( ! $report && ! $registry->get('GV_google_api')) { + $this->refferer_popularity = false; - return $this->refferer_popularity; - } + return $this->refferer_popularity; + } - $connsbas = connection::getPDOConnection($this->get_sbas_id()); + $connsbas = connection::getPDOConnection($this->get_sbas_id()); - $sql = 'SELECT count( id ) AS views, referrer + $sql = 'SELECT count( id ) AS views, referrer FROM `log_view` WHERE record_id = :record_id AND date > ( NOW( ) - INTERVAL 1 MONTH ) GROUP BY referrer ORDER BY referrer ASC'; - $stmt = $connsbas->prepare($sql); - $stmt->execute(array(':record_id' => $this->get_record_id())); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connsbas->prepare($sql); + $stmt->execute(array(':record_id' => $this->get_record_id())); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $referrers = array(); + $referrers = array(); - foreach ($rs as $row) - { - if ($row['referrer'] == 'NO REFERRER') - $row['referrer'] = _('report::acces direct'); - if ($row['referrer'] == $registry->get('GV_ServerName') . 'prod/') - $row['referrer'] = _('admin::monitor: module production'); - if ($row['referrer'] == $registry->get('GV_ServerName') . 'client/') - $row['referrer'] = _('admin::monitor: module client'); - if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'login/') !== false) - $row['referrer'] = _('report:: page d\'accueil'); - if (strpos($row['referrer'], 'http://apps.cooliris.com/') !== false) - $row['referrer'] = _('report:: visualiseur cooliris'); + foreach ($rs as $row) { + if ($row['referrer'] == 'NO REFERRER') + $row['referrer'] = _('report::acces direct'); + if ($row['referrer'] == $registry->get('GV_ServerName') . 'prod/') + $row['referrer'] = _('admin::monitor: module production'); + if ($row['referrer'] == $registry->get('GV_ServerName') . 'client/') + $row['referrer'] = _('admin::monitor: module client'); + if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'login/') !== false) + $row['referrer'] = _('report:: page d\'accueil'); + if (strpos($row['referrer'], 'http://apps.cooliris.com/') !== false) + $row['referrer'] = _('report:: visualiseur cooliris'); - if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'document/') !== false) - { - if (strpos($row['referrer'], '/view/') !== false) - $row['referrer'] = _('report::presentation page preview'); - else - $row['referrer'] = _('report::acces direct'); - } - if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'permalink/') !== false) - { - if (strpos($row['referrer'], '/view/') !== false) - $row['referrer'] = _('report::presentation page preview'); - else - $row['referrer'] = _('report::acces direct'); - } - if (!isset($referrers[$row['referrer']])) - $referrers[$row['referrer']] = 0; - $referrers[$row['referrer']] += (int) $row['views']; + if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'document/') !== false) { + if (strpos($row['referrer'], '/view/') !== false) + $row['referrer'] = _('report::presentation page preview'); + else + $row['referrer'] = _('report::acces direct'); + } + if (strpos($row['referrer'], $registry->get('GV_ServerName') . 'permalink/') !== false) { + if (strpos($row['referrer'], '/view/') !== false) + $row['referrer'] = _('report::presentation page preview'); + else + $row['referrer'] = _('report::acces direct'); + } + if ( ! isset($referrers[$row['referrer']])) + $referrers[$row['referrer']] = 0; + $referrers[$row['referrer']] += (int) $row['views']; + } + + $width = 550; + $height = 100; + + $url = 'http://chart.apis.google.com/chart?' + . 'cht=p3&chf=bg,s,00000000&chd=t:' + . implode(',', $referrers) + . '&chs=' . $width . 'x' . $height + . '&chl=' + . urlencode(implode('|', array_keys($referrers))) . ''; + + $this->refferer_popularity = new media_adapter($url, $width, $height); + + return $this->refferer_popularity; } - $width = 550; - $height = 100; - - $url = 'http://chart.apis.google.com/chart?' - . 'cht=p3&chf=bg,s,00000000&chd=t:' - . implode(',', $referrers) - . '&chs=' . $width . 'x' . $height - . '&chl=' - . urlencode(implode('|', array_keys($referrers))) . ''; - - $this->refferer_popularity = new media_adapter($url, $width, $height); - - return $this->refferer_popularity; - } - - /** - * - * @return media - */ - public function get_download_popularity() - { - - if (!is_null($this->download_popularity)) - { - return $this->download_popularity; - } - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $registry = $appbox->get_registry(); - $report = $user->ACL()->has_right_on_base( - $this->get_base_id(), 'canreport'); - - $ret = false; - if (!$report && !$registry->get('GV_google_api')) - { - $this->download_popularity = false; - - return $this->download_popularity; - } - - $views = $dwnls = array(); - $top = 1; - $day = 30; - $min = 0; - $average = 0; - - while ($day >= 0) + /** + * + * @return media + */ + public function get_download_popularity() { - $datetime = new DateTime('-' . $day . ' days'); - $date = date_format($datetime, 'Y-m-d'); - $views[$date] = $dwnls[$date] = 0; - $day--; - } + if ( ! is_null($this->download_popularity)) { + return $this->download_popularity; + } - $sql = 'SELECT count(d.id) as dwnl, DATE(d.date) as datee + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $registry = $appbox->get_registry(); + $report = $user->ACL()->has_right_on_base( + $this->get_base_id(), 'canreport'); + + $ret = false; + if ( ! $report && ! $registry->get('GV_google_api')) { + $this->download_popularity = false; + + return $this->download_popularity; + } + + $views = $dwnls = array(); + $top = 1; + $day = 30; + $min = 0; + $average = 0; + + while ($day >= 0) { + + $datetime = new DateTime('-' . $day . ' days'); + $date = date_format($datetime, 'Y-m-d'); + $views[$date] = $dwnls[$date] = 0; + $day --; + } + + $sql = 'SELECT count(d.id) as dwnl, DATE(d.date) as datee FROM `log_docs` d, log l WHERE action="download" AND log_id=l.id @@ -658,46 +617,43 @@ class record_preview extends record_adapter AND site= :site GROUP BY datee ORDER BY datee ASC'; - $connsbas = connection::getPDOConnection($this->get_sbas_id()); - $stmt = $connsbas->prepare($sql); - $stmt->execute( - array( - ':record_id' => $this->get_record_id(), - ':site' => $registry->get('GV_sit') - ) - ); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $connsbas = connection::getPDOConnection($this->get_sbas_id()); + $stmt = $connsbas->prepare($sql); + $stmt->execute( + array( + ':record_id' => $this->get_record_id(), + ':site' => $registry->get('GV_sit') + ) + ); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $top = 10; + $top = 10; - foreach ($rs as $row) - { - if (isset($dwnls[$row['datee']])) - { - $dwnls[$row['datee']] = (int) $row['dwnl']; - $top = max(((int) $row['dwnl'] + 10), $top); - } + foreach ($rs as $row) { + if (isset($dwnls[$row['datee']])) { + $dwnls[$row['datee']] = (int) $row['dwnl']; + $top = max(((int) $row['dwnl'] + 10), $top); + } + } + + $width = 250; + $height = 150; + $url = 'http://chart.apis.google.com/chart?' . + 'chs=' . $width . 'x' . $height . + '&chd=t:' . implode(',', $dwnls) . + '&cht=lc' . + '&chf=bg,s,00000000' . + '&chxt=x,y' . + '&chds=0,' . $top . + '&chxl=0:|' . date_format(new DateTime('-30 days'), 'd M') . '|' + . date_format(new DateTime('-15 days'), 'd M') . '|' + . date_format(new DateTime(), 'd M') . '|1:|0|' + . round($top / 2) . '|' . $top . ''; + + $ret = new media_adapter($url, $width, $height); + $this->download_popularity = $ret; + + return $this->download_popularity; } - - $width = 250; - $height = 150; - $url = 'http://chart.apis.google.com/chart?' . - 'chs=' . $width . 'x' . $height . - '&chd=t:' . implode(',', $dwnls) . - '&cht=lc' . - '&chf=bg,s,00000000' . - '&chxt=x,y' . - '&chds=0,' . $top . - '&chxl=0:|' . date_format(new DateTime('-30 days'), 'd M') . '|' - . date_format(new DateTime('-15 days'), 'd M') . '|' - . date_format(new DateTime(), 'd M') . '|1:|0|' - . round($top / 2) . '|' . $top . ''; - - $ret = new media_adapter($url, $width, $height); - $this->download_popularity = $ret; - - return $this->download_popularity; - } - } diff --git a/lib/classes/recordutils.class.php b/lib/classes/recordutils.class.php index 75befebc5e..870385e3e1 100644 --- a/lib/classes/recordutils.class.php +++ b/lib/classes/recordutils.class.php @@ -12,35 +12,34 @@ class recordutils { - public function __construct($bas, $rec) - { + public function __construct($bas, $rec) + { - } + } - public function __destruct() - { + public function __destruct() + { - } + } - public static function watermark($bas, $rec) - { + public static function watermark($bas, $rec) + { - } + } - public static function stamp($bas, $rec) - { + public static function stamp($bas, $rec) + { - } + } - public function embed_preview() - { + public function embed_preview() + { - } + } - public function binary_datas($type, $bas, $rec, $usr=false, $ses=false) - { - - return false; - } + public function binary_datas($type, $bas, $rec, $usr = false, $ses = false) + { + return false; + } } diff --git a/lib/classes/recordutils/image.class.php b/lib/classes/recordutils/image.class.php index 92bc2fb577..0d57589644 100644 --- a/lib/classes/recordutils/image.class.php +++ b/lib/classes/recordutils/image.class.php @@ -18,522 +18,460 @@ class recordutils_image extends recordutils { - /** - * - * @param int $fontSize - * @param int $angle - * @param string $fontFace - * @param string $string - * @param int $width - * @return Array - */ - protected function wrap($fontSize, $angle, $fontFace, $string, $width) - { - $ret = array(); - - // str 'Op' used to calculate linespace - $testbox = imagettfbbox($fontSize, $angle, $fontFace, 'Op'); - $height = abs($testbox[1] - ($dy = $testbox[7])); - - foreach (explode("\n", $string) as $lig) + /** + * + * @param int $fontSize + * @param int $angle + * @param string $fontFace + * @param string $string + * @param int $width + * @return Array + */ + protected function wrap($fontSize, $angle, $fontFace, $string, $width) { - if ($lig == '') - { - $ret[] = ''; - } - else - { - $buff = ''; - foreach (explode(' ', $lig) as $wrd) - { - $test = $buff . ($buff ? ' ' : '') . $wrd; - $testbox = imagettfbbox($fontSize, $angle, $fontFace, $test); - if (abs($testbox[2] - $testbox[0]) > $width) - { - if ($buff == '') - { - $ret[] = $test; + $ret = array(); + + // str 'Op' used to calculate linespace + $testbox = imagettfbbox($fontSize, $angle, $fontFace, 'Op'); + $height = abs($testbox[1] - ($dy = $testbox[7])); + + foreach (explode("\n", $string) as $lig) { + if ($lig == '') { + $ret[] = ''; + } else { + $buff = ''; + foreach (explode(' ', $lig) as $wrd) { + $test = $buff . ($buff ? ' ' : '') . $wrd; + $testbox = imagettfbbox($fontSize, $angle, $fontFace, $test); + if (abs($testbox[2] - $testbox[0]) > $width) { + if ($buff == '') { + $ret[] = $test; + } else { + $ret[] = $buff; + $buff = $wrd; + } + } else { + $buff = $test; + } + } + if ($buff != '') + $ret[] = $buff; } - else - { - $ret[] = $buff; - $buff = $wrd; - } - } - else - { - $buff = $test; - } } - if ($buff != '') - $ret[] = $buff; - } + + return(array('l' => $ret, 'h' => $height, 'dy' => $dy)); } - return(array('l' => $ret, 'h' => $height, 'dy' => $dy)); - } + /** + * + * @param int $bas + * @param int $rec + * @param boolean $hd + * @return string + */ + public static function stamp($bas, $rec, $hd = false) + { + $registry = registry::get_instance(); + $debug = false; - /** - * - * @param int $bas - * @param int $rec - * @param boolean $hd - * @return string - */ - public static function stamp($bas, $rec, $hd=false) - { - $registry = registry::get_instance(); - $debug = false; + if ( ! $registry->get('GV_imagick')) + return false; - if (!$registry->get('GV_imagick')) + $sbas_id = phrasea::sbasFromBas($bas); - return false; + if ( ! isset($sbas_id)) + return false; - $sbas_id = phrasea::sbasFromBas($bas); + $connSbas = connection::getPDOConnection($sbas_id); - if (!isset($sbas_id)) + $sdname = 'preview'; + if ($hd) + $sdname = 'document'; - return false; - - $connSbas = connection::getPDOConnection($sbas_id); - - $sdname = 'preview'; - if ($hd) - $sdname = 'document'; - - $sql = "SELECT path, file, s.mime, type, xml, prefs + $sql = "SELECT path, file, s.mime, type, xml, prefs FROM subdef s, record r, coll c WHERE r.record_id = :record_id AND r.record_id = s.record_id AND name = :name AND c.coll_id=r.coll_id"; - $stmt = $connSbas->prepare($sql); - $stmt->execute(array(':record_id' => $rec, ':name' => $sdname)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connSbas->prepare($sql); + $stmt->execute(array(':record_id' => $rec, ':name' => $sdname)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $sxprefs = $sxxml = $domprefs = FALSE; + $sxprefs = $sxxml = $domprefs = FALSE; - if ($row) - { - $domprefs = new DOMDocument(); - if (!($domprefs->loadXML($row['prefs']))) - $domprefs = FALSE; + if ($row) { + $domprefs = new DOMDocument(); + if ( ! ($domprefs->loadXML($row['prefs']))) + $domprefs = FALSE; - $sxxml = simplexml_load_string($row['xml']); - $file = array( - 'type' => $row['type'] - , 'path' => p4string::addEndSlash($row['path']) - , 'file' => $row['file'] - , 'mime' => $row['mime'] - ); - } + $sxxml = simplexml_load_string($row['xml']); + $file = array( + 'type' => $row['type'] + , 'path' => p4string::addEndSlash($row['path']) + , 'file' => $row['file'] + , 'mime' => $row['mime'] + ); + } - if ($domprefs === FALSE || $sxxml === FALSE) + if ($domprefs === FALSE || $sxxml === FALSE) + return false; - return false; + $xpprefs = new DOMXPath($domprefs); - $xpprefs = new DOMXPath($domprefs); - - $pathIn = $file['path'] . $file['file']; - $pathOut = $file['path'] . 'stamp_' . $file['file']; - $pathTmpStamp = $registry->get('GV_RootPath') . 'tmp/' + $pathIn = $file['path'] . $file['file']; + $pathOut = $file['path'] . 'stamp_' . $file['file']; + $pathTmpStamp = $registry->get('GV_RootPath') . 'tmp/' . time() . '-stamptmp_' . $file['file']; - if (!is_file($pathIn)) + if ( ! is_file($pathIn)) + return false; - return false; - - if ($file['type'] != 'image' || - $xpprefs->query('/baseprefs/stamp')->length == 0) - { - return $pathIn; - } - - $vars = $xpprefs->query('/baseprefs/stamp/*/var'); - for ($i = 0; $i < $vars->length; $i++) - { - $varval = ''; - $n = $vars->item($i); - switch (strtoupper($n->getAttribute('name'))) - { - case 'DATE': - if (!($format = $n->getAttribute('format'))) - $format = 'Y/m/d H:i:s'; - $varval = date($format); - @unlink($pathOut); // since date is included, invalidate cache - break; - case 'RECORD_ID': - $varval = $rec; - break; - } - $n->parentNode->replaceChild($domprefs->createTextNode($varval), $n); - } - - // ------------- CACHING ! - if (is_file($pathOut)) - - return $pathOut; - - $fields = $xpprefs->query('/baseprefs/stamp/*/field'); - for ($i = 0; $i < $fields->length; $i++) - { - $fldval = ''; - $n = $fields->item($i); - $fieldname = $n->getAttribute('name'); - - $x = $sxxml->description->{$fieldname}; - if (is_array($x)) - { - foreach ($x as $v) - $fldval .= ( $fldval ? '; ' : '') . (string) $v; - } - else - { - $fldval .= ( $fldval ? '; ' : '') . (string) $x; - } - $n->parentNode->replaceChild($domprefs->createTextNode($fldval), $n); - } - - $domprefs->normalizeDocument(); - - $collname = phrasea::bas_names($bas); - - if (!($tailleimg = @getimagesize($pathIn))) - - return false; - - - $image_width = $tailleimg[0]; - $image_height = $tailleimg[1]; - - $text_xpos = 0; - $text_width = $image_width; - - $logofile = $registry->get('GV_RootPath') . 'config/stamp/' . $bas; - $logopos = null; - $imlogo = null; // gd image - $logo_phywidth = $logo_phyheight = 0; // physical size - $logo_reswidth = $logo_resheight = 0; // resized size - - if (is_array($logosize = @getimagesize($logofile))) - { - $logo_reswidth = $logo_phywidth = $logosize[0]; - $logo_resheight = $logo_phyheight = $logosize[1]; - - $v = $xpprefs->query('/baseprefs/stamp/logo'); - if ($v->length > 0) - { - $logopos = @strtoupper($v->item(0)->getAttribute('position')); - if (($logowidth = trim($v->item(0)->getAttribute('width'))) != '') - { - if (substr($logowidth, -1) == '%') - $logo_reswidth = (int) ($logowidth * $image_width / 100); - else - $logo_reswidth = (int) $logowidth; - $logo_resheight = (int) ($logo_phyheight * - ($logo_reswidth / $logo_phywidth)); + if ($file['type'] != 'image' || + $xpprefs->query('/baseprefs/stamp')->length == 0) { + return $pathIn; } - if (($logopos == 'LEFT' || $logopos == 'RIGHT') && - $logo_phywidth > 0 && $logo_phyheight > 0) - { - switch ($logosize['mime']) - { - case 'image/gif': - $imlogo = @imagecreatefromgif($logofile); - break; - case 'image/png': - $imlogo = @imagecreatefrompng($logofile); - break; - case 'image/jpeg': - case 'image/pjpeg': - $imlogo = @imagecreatefromjpeg($logofile); - break; - } - if ($imlogo) - { - if ($logo_reswidth > $image_width / 2) - { - // logo too large, resize please - $logo_reswidth = (int) ($image_width / 2); - $logo_resheight = (int) ($logo_phyheight * - ($logo_reswidth / $logo_phywidth)); + $vars = $xpprefs->query('/baseprefs/stamp/*/var'); + for ($i = 0; $i < $vars->length; $i ++ ) { + $varval = ''; + $n = $vars->item($i); + switch (strtoupper($n->getAttribute('name'))) { + case 'DATE': + if ( ! ($format = $n->getAttribute('format'))) + $format = 'Y/m/d H:i:s'; + $varval = date($format); + @unlink($pathOut); // since date is included, invalidate cache + break; + case 'RECORD_ID': + $varval = $rec; + break; + } + $n->parentNode->replaceChild($domprefs->createTextNode($varval), $n); + } + + // ------------- CACHING ! + if (is_file($pathOut)) + return $pathOut; + + $fields = $xpprefs->query('/baseprefs/stamp/*/field'); + for ($i = 0; $i < $fields->length; $i ++ ) { + $fldval = ''; + $n = $fields->item($i); + $fieldname = $n->getAttribute('name'); + + $x = $sxxml->description->{$fieldname}; + if (is_array($x)) { + foreach ($x as $v) + $fldval .= ( $fldval ? '; ' : '') . (string) $v; + } else { + $fldval .= ( $fldval ? '; ' : '') . (string) $x; + } + $n->parentNode->replaceChild($domprefs->createTextNode($fldval), $n); + } + + $domprefs->normalizeDocument(); + + $collname = phrasea::bas_names($bas); + + if ( ! ($tailleimg = @getimagesize($pathIn))) + return false; + + + $image_width = $tailleimg[0]; + $image_height = $tailleimg[1]; + + $text_xpos = 0; + $text_width = $image_width; + + $logofile = $registry->get('GV_RootPath') . 'config/stamp/' . $bas; + $logopos = null; + $imlogo = null; // gd image + $logo_phywidth = $logo_phyheight = 0; // physical size + $logo_reswidth = $logo_resheight = 0; // resized size + + if (is_array($logosize = @getimagesize($logofile))) { + $logo_reswidth = $logo_phywidth = $logosize[0]; + $logo_resheight = $logo_phyheight = $logosize[1]; + + $v = $xpprefs->query('/baseprefs/stamp/logo'); + if ($v->length > 0) { + $logopos = @strtoupper($v->item(0)->getAttribute('position')); + if (($logowidth = trim($v->item(0)->getAttribute('width'))) != '') { + if (substr($logowidth, -1) == '%') + $logo_reswidth = (int) ($logowidth * $image_width / 100); + else + $logo_reswidth = (int) $logowidth; + $logo_resheight = (int) ($logo_phyheight * + ($logo_reswidth / $logo_phywidth)); + } + + if (($logopos == 'LEFT' || $logopos == 'RIGHT') && + $logo_phywidth > 0 && $logo_phyheight > 0) { + switch ($logosize['mime']) { + case 'image/gif': + $imlogo = @imagecreatefromgif($logofile); + break; + case 'image/png': + $imlogo = @imagecreatefrompng($logofile); + break; + case 'image/jpeg': + case 'image/pjpeg': + $imlogo = @imagecreatefromjpeg($logofile); + break; + } + if ($imlogo) { + if ($logo_reswidth > $image_width / 2) { + // logo too large, resize please + $logo_reswidth = (int) ($image_width / 2); + $logo_resheight = (int) ($logo_phyheight * + ($logo_reswidth / $logo_phywidth)); + } + + $text_width -= ( $text_xpos = $logo_reswidth); + } + } + } + } + $txth = 0; + $txtblock = array(); + $texts = $xpprefs->query('/baseprefs/stamp/text'); + $fontsize = "100%"; + for ($i = 0; $i < $texts->length; $i ++ ) { + if (($tmpfontsize = trim($texts->item($i)->getAttribute('size'))) != '') { + if (substr($tmpfontsize, -1) == '%') + $tmpfontsize = (int) ($tmpfontsize * $image_width / 4000); + else + $tmpfontsize = (int) $tmpfontsize; + $fontsize = $tmpfontsize; } - $text_width -= ( $text_xpos = $logo_reswidth); - } + if ($fontsize < 2) + $fontsize = 2; + elseif ($fontsize > 300) + $fontsize = 300; + + $txtline = $texts->item($i)->nodeValue; + + if ($txtline != '') { + $txtlines = recordutils_image::wrap( + $fontsize, 0, __DIR__ . '/arial.ttf', $txtline, $text_width + ); + + foreach ($txtlines['l'] as $txtline) { + $txtblock[] = array( + 'x' => $text_xpos, + 'dy' => $txtlines['dy'], + 'w' => $text_width, + 'h' => $txtlines['h'], + 't' => $txtline, + 's' => $fontsize + ); + $txth += $txtlines['h']; + } + } } - } - } - $txth = 0; - $txtblock = array(); - $texts = $xpprefs->query('/baseprefs/stamp/text'); - $fontsize = "100%"; - for ($i = 0; $i < $texts->length; $i++) - { - if (($tmpfontsize = trim($texts->item($i)->getAttribute('size'))) != '') - { - if (substr($tmpfontsize, -1) == '%') - $tmpfontsize = (int) ($tmpfontsize * $image_width / 4000); - else - $tmpfontsize = (int) $tmpfontsize; - $fontsize = $tmpfontsize; - } - if ($fontsize < 2) - $fontsize = 2; - elseif ($fontsize > 300) - $fontsize = 300; + $stampheight = max($logo_resheight, $txth); - $txtline = $texts->item($i)->nodeValue; + $im = imagecreatetruecolor($image_width, $stampheight); - if ($txtline != '') - { - $txtlines = recordutils_image::wrap( - $fontsize, - 0, - __DIR__ . '/arial.ttf', - $txtline, - $text_width - ); + $white = imagecolorallocate($im, 255, 255, 255); + imagefilledrectangle($im, 0, 0, $image_width, $stampheight, $white); + imagecolordeallocate($im, $white); - foreach ($txtlines['l'] as $txtline) - { - $txtblock[] = array( - 'x' => $text_xpos, - 'dy' => $txtlines['dy'], - 'w' => $text_width, - 'h' => $txtlines['h'], - 't' => $txtline, - 's' => $fontsize - ); - $txth += $txtlines['h']; + if ($imlogo) { + if ($logo_reswidth != $logo_phywidth) { + imagecopyresampled($im, $imlogo, 0, 0, // dst_x, dst_y + 0, 0, // src_x, src_y + $logo_reswidth, // dst_w + $logo_resheight, // dst_h + $logo_phywidth, // src_w + $logo_phyheight // src_h + ); + } else { + imagecopy($im, $imlogo, 0, 0, // dst_x, dst_y + 0, 0, // src_x, src_y + $logo_phywidth, // src_w + $logo_phyheight // src_h + ); + } } - } - } - $stampheight = max($logo_resheight, $txth); + if (count($txtblock) >= 0) { + $black = imagecolorallocate($im, 0, 0, 0); + $txt_ypos = 0; //$txtblock[0]['h']; + foreach ($txtblock as $block) { + imagettftext($im, $block['s'], 0, $block['x'], $txt_ypos - $block['dy'], $black, __DIR__ . '/arial.ttf', $block['t']); + $txt_ypos += $block['h']; + } + imagecolordeallocate($im, $black); + } + imagejpeg($im, $pathTmpStamp, 80); - $im = imagecreatetruecolor($image_width, $stampheight); + imagedestroy($im); - $white = imagecolorallocate($im, 255, 255, 255); - imagefilledrectangle($im, 0, 0, $image_width, $stampheight, $white); - imagecolordeallocate($im, $white); - - if ($imlogo) - { - if ($logo_reswidth != $logo_phywidth) - { - imagecopyresampled($im, $imlogo, - 0, 0, // dst_x, dst_y - 0, 0, // src_x, src_y - $logo_reswidth, // dst_w - $logo_resheight, // dst_h - $logo_phywidth, // src_w - $logo_phyheight // src_h - ); - } - else - { - imagecopy($im, $imlogo, - 0, 0, // dst_x, dst_y - 0, 0, // src_x, src_y - $logo_phywidth, // src_w - $logo_phyheight // src_h - ); - } - } - - if (count($txtblock) >= 0) - { - $black = imagecolorallocate($im, 0, 0, 0); - $txt_ypos = 0; //$txtblock[0]['h']; - foreach ($txtblock as $block) - { - imagettftext($im, $block['s'], 0, $block['x'], - $txt_ypos - $block['dy'], $black, - __DIR__ . '/arial.ttf', $block['t']); - $txt_ypos += $block['h']; - } - imagecolordeallocate($im, $black); - } - imagejpeg($im, $pathTmpStamp, 80); - - imagedestroy($im); - - $newh = $image_height + $stampheight; + $newh = $image_height + $stampheight; - $cmd = $registry->get('GV_imagick'); - $cmd .= ' -extent "' . $image_width . 'x' . $newh + $cmd = $registry->get('GV_imagick'); + $cmd .= ' -extent "' . $image_width . 'x' . $newh . '" -draw "image SrcOver 0,' . $image_height . ' ' . $image_width . ',' . $stampheight . '\'' . $pathTmpStamp . '\'"'; - $cmd.= " \"" . $pathIn . "\""; # <<-- le doc original - $cmd.= " \"" . $pathOut . "\""; # <-- le doc stampe + $cmd.= " \"" . $pathIn . "\""; # <<-- le doc original + $cmd.= " \"" . $pathOut . "\""; # <-- le doc stampe - exec($cmd); + exec($cmd); - unlink($pathTmpStamp); + unlink($pathTmpStamp); - if (is_file($pathOut)) + if (is_file($pathOut)) + return $pathOut; - return $pathOut; + return false; + } - return false; - } + /** + * + * @param int $bas + * @param int $rec + * @param boolean $hd + * @return string + */ + public static function watermark($bas, $rec, $hd = false) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $registry = $appbox->get_registry(); - /** - * - * @param int $bas - * @param int $rec - * @param boolean $hd - * @return string - */ - public static function watermark($bas, $rec, $hd=false) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $registry = $appbox->get_registry(); + $sbas_id = phrasea::sbasFromBas($bas); - $sbas_id = phrasea::sbasFromBas($bas); + if ( ! isset($sbas_id)) + return false; - if (!isset($sbas_id)) + $connSbas = connection::getPDOConnection($sbas_id); - return false; - - $connSbas = connection::getPDOConnection($sbas_id); - - $sql = "SELECT s.path, s.file, s.mime, r.type, r.xml + $sql = "SELECT s.path, s.file, s.mime, r.type, r.xml FROM subdef s, record r WHERE r.record_id = :record_id AND r.record_id = s.record_id AND name='preview'"; - $stmt = $connSbas->prepare($sql); - $stmt->execute(array(':record_id' => $rec)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connSbas->prepare($sql); + $stmt->execute(array(':record_id' => $rec)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (!$row) + if ( ! $row) + return false; - return false; + $file = array( + 'type' => $row['type'] + , 'path' => p4string::addEndSlash($row['path']) + , 'file' => $row['file'] + , 'mime' => $row['mime'] + ); - $file = array( - 'type' => $row['type'] - , 'path' => p4string::addEndSlash($row['path']) - , 'file' => $row['file'] - , 'mime' => $row['mime'] - ); + $pathIn = $file['path'] . $file['file']; - $pathIn = $file['path'] . $file['file']; + $pathOut = $file['path'] . 'watermark_' . $file['file']; - $pathOut = $file['path'] . 'watermark_' . $file['file']; + if ( ! is_file($pathIn)) + return false; - if (!is_file($pathIn)) - - return false; - - if (is_file($pathOut)) - - return $pathOut; + if (is_file($pathOut)) + return $pathOut; - if ($registry->get('GV_pathcomposite') && - file_exists($registry->get('GV_RootPath') . 'config/wm/' . $bas)) // si il y a un WM - { - $cmd = $registry->get('GV_pathcomposite') . " "; - $cmd .= $registry->get('GV_RootPath') . 'config/wm/' . $bas . " "; - $cmd .= " \"" . $pathIn . "\" "; # <<-- la preview original - $cmd .= " -strip -watermark 90% -gravity center "; - $cmd .= " \"" . $pathOut . "\""; # <-- la preview temporaire + if ($registry->get('GV_pathcomposite') && + file_exists($registry->get('GV_RootPath') . 'config/wm/' . $bas)) { // si il y a un WM + $cmd = $registry->get('GV_pathcomposite') . " "; + $cmd .= $registry->get('GV_RootPath') . 'config/wm/' . $bas . " "; + $cmd .= " \"" . $pathIn . "\" "; # <<-- la preview original + $cmd .= " -strip -watermark 90% -gravity center "; + $cmd .= " \"" . $pathOut . "\""; # <-- la preview temporaire - $descriptorspec = array(0 => array("pipe", "r"), - 1 => array("pipe", "w"), - 2 => array("pipe", "w") - ); - $process = proc_open($cmd, $descriptorspec, $pipes); - if (is_resource($process)) - { - fclose($pipes[0]); - $err = ""; - while (!feof($pipes[1])) - $out = fgets($pipes[1], 1024); - fclose($pipes[1]); - while (!feof($pipes[2])) - $err .= fgets($pipes[2], 1024); - fclose($pipes[2]); - $return_value = proc_close($process); - } + $descriptorspec = array(0 => array("pipe", "r"), + 1 => array("pipe", "w"), + 2 => array("pipe", "w") + ); + $process = proc_open($cmd, $descriptorspec, $pipes); + if (is_resource($process)) { + fclose($pipes[0]); + $err = ""; + while ( ! feof($pipes[1])) + $out = fgets($pipes[1], 1024); + fclose($pipes[1]); + while ( ! feof($pipes[2])) + $err .= fgets($pipes[2], 1024); + fclose($pipes[2]); + $return_value = proc_close($process); + } + } elseif ($registry->get('GV_imagick')) { + $collname = phrasea::bas_names($bas); + $cmd = $registry->get('GV_imagick'); + $tailleimg = @getimagesize($pathIn); + $max = ($tailleimg[0] > $tailleimg[1] ? $tailleimg[0] : $tailleimg[1]); + + $tailleText = (int) ($max / 30); + + if ($tailleText < 8) + $tailleText = 8; + + if ($tailleText > 12) + $decalage = 2; + else + $decalage = 1; + + $cmd .= " -fill white -draw \"line 0,0 " + . $tailleimg[0] . "," . $tailleimg[1] . "\""; + $cmd .= " -fill black -draw \"line 1,0 " + . ($tailleimg[0] + 1) . "," . ($tailleimg[1]) . "\""; + + $cmd .= " -fill white -draw \"line " + . $tailleimg[0] . ",0 0," . $tailleimg[1] . "\""; + $cmd .= " -fill black -draw \"line " + . ($tailleimg[0] + 1) . ",0 1," . ($tailleimg[1]) . "\""; + + $cmd .= " -fill white -gravity NorthWest -pointsize " + . " $tailleText -draw \"text 0,0 '$collname'\""; + $cmd .= " -fill black -gravity NorthWest -pointsize " + . " $tailleText -draw \"text $decalage,1 '$collname'\""; + + $cmd .= " -fill white -gravity center -pointsize " + . " $tailleText -draw \"text 0,0 '$collname'\""; + $cmd .= " -fill black -gravity center -pointsize " + . " $tailleText -draw \"text $decalage,1 '$collname'\""; + + $cmd .= " -fill white -gravity SouthEast -pointsize " + . " $tailleText -draw \"text 0,0 '$collname'\""; + $cmd .= " -fill black -gravity SouthEast -pointsize " + . " $tailleText -draw \"text $decalage,1 '$collname'\""; + + + $cmd.= " \"" . $pathIn . "\""; # <<-- la preview original + $cmd.= " \"" . $pathOut . "\""; # <-- la preview temporaire + + $descriptorspec = array(0 => array("pipe", "r"), + 1 => array("pipe", "w"), + 2 => array("pipe", "w") + ); + $process = proc_open($cmd, $descriptorspec, $pipes); + if (is_resource($process)) { + fclose($pipes[0]); + $err = ""; + while ( ! feof($pipes[1])) + $out = fgets($pipes[1], 1024); + fclose($pipes[1]); + while ( ! feof($pipes[2])) + $err .= fgets($pipes[2], 1024); + fclose($pipes[2]); + $return_value = proc_close($process); + } + } + + if (is_file($pathOut)) + return $pathOut; + + return false; } - elseif ($registry->get('GV_imagick')) - { - $collname = phrasea::bas_names($bas); - $cmd = $registry->get('GV_imagick'); - $tailleimg = @getimagesize($pathIn); - $max = ($tailleimg[0] > $tailleimg[1] ? $tailleimg[0] : $tailleimg[1]); - - $tailleText = (int) ($max / 30); - - if ($tailleText < 8) - $tailleText = 8; - - if ($tailleText > 12) - $decalage = 2; - else - $decalage=1; - - $cmd .= " -fill white -draw \"line 0,0 " - . $tailleimg[0] . "," . $tailleimg[1] . "\""; - $cmd .= " -fill black -draw \"line 1,0 " - . ($tailleimg[0] + 1) . "," . ($tailleimg[1]) . "\""; - - $cmd .= " -fill white -draw \"line " - . $tailleimg[0] . ",0 0," . $tailleimg[1] . "\""; - $cmd .= " -fill black -draw \"line " - . ($tailleimg[0] + 1) . ",0 1," . ($tailleimg[1]) . "\""; - - $cmd .= " -fill white -gravity NorthWest -pointsize " - . " $tailleText -draw \"text 0,0 '$collname'\""; - $cmd .= " -fill black -gravity NorthWest -pointsize " - . " $tailleText -draw \"text $decalage,1 '$collname'\""; - - $cmd .= " -fill white -gravity center -pointsize " - . " $tailleText -draw \"text 0,0 '$collname'\""; - $cmd .= " -fill black -gravity center -pointsize " - . " $tailleText -draw \"text $decalage,1 '$collname'\""; - - $cmd .= " -fill white -gravity SouthEast -pointsize " - . " $tailleText -draw \"text 0,0 '$collname'\""; - $cmd .= " -fill black -gravity SouthEast -pointsize " - . " $tailleText -draw \"text $decalage,1 '$collname'\""; - - - $cmd.= " \"" . $pathIn . "\""; # <<-- la preview original - $cmd.= " \"" . $pathOut . "\""; # <-- la preview temporaire - - $descriptorspec = array(0 => array("pipe", "r"), - 1 => array("pipe", "w"), - 2 => array("pipe", "w") - ); - $process = proc_open($cmd, $descriptorspec, $pipes); - if (is_resource($process)) - { - fclose($pipes[0]); - $err = ""; - while (!feof($pipes[1])) - $out = fgets($pipes[1], 1024); - fclose($pipes[1]); - while (!feof($pipes[2])) - $err .= fgets($pipes[2], 1024); - fclose($pipes[2]); - $return_value = proc_close($process); - } - } - - if (is_file($pathOut)) - - return $pathOut; - - return false; - } - } diff --git a/lib/classes/registry.class.php b/lib/classes/registry.class.php index e3715a641e..f3e3a7768d 100644 --- a/lib/classes/registry.class.php +++ b/lib/classes/registry.class.php @@ -17,213 +17,199 @@ */ class registry implements registryInterface { + /** + * + * @var \Alchemy\Phrasea\Cache\Cache + */ + protected $cache; - /** - * - * @var \Alchemy\Phrasea\Cache\Cache - */ - protected $cache; + /** + * + * @var registry + */ + protected static $_instance; - /** - * - * @var registry - */ - protected static $_instance; + const TYPE_BOOLEAN = 'boolean'; + const TYPE_ARRAY = 'array'; + const TYPE_ENUM_MULTI = 'enum_multi'; + const TYPE_INTEGER = 'integer'; + const TYPE_STRING = 'string'; - const TYPE_BOOLEAN = 'boolean'; - const TYPE_ARRAY = 'array'; - const TYPE_ENUM_MULTI = 'enum_multi'; - const TYPE_INTEGER = 'integer'; - const TYPE_STRING = 'string'; - - /** - * - * @return registry - */ - public static function get_instance() - { - if (!self::$_instance instanceof self) + /** + * + * @return registry + */ + public static function get_instance() { - self::$_instance = new self(); + if ( ! self::$_instance instanceof self) { + self::$_instance = new self(); + } + + return self::$_instance; } - return self::$_instance; - } - - /** - * - * @param \Alchemy\Phrasea\Cache\Cache $cache - * @return registry - */ - protected function __construct() - { - $this->cache = new Alchemy\Phrasea\Cache\ArrayCache(); - - $configuration = \Alchemy\Phrasea\Core\Configuration::build(); - - $this->cache->save('GV_RootPath', dirname(dirname(__DIR__)) . '/'); - if ($configuration->isInstalled()) + /** + * + * @param \Alchemy\Phrasea\Cache\Cache $cache + * @return registry + */ + protected function __construct() { - $this->cache->save('GV_ServerName', $configuration->getPhraseanet()->get('servername')); - $this->cache->save('GV_debug', $configuration->isDebug()); - $this->cache->save('GV_maintenance', $configuration->isMaintained()); + $this->cache = new Alchemy\Phrasea\Cache\ArrayCache(); + + $configuration = \Alchemy\Phrasea\Core\Configuration::build(); + + $this->cache->save('GV_RootPath', dirname(dirname(__DIR__)) . '/'); + if ($configuration->isInstalled()) { + $this->cache->save('GV_ServerName', $configuration->getPhraseanet()->get('servername')); + $this->cache->save('GV_debug', $configuration->isDebug()); + $this->cache->save('GV_maintenance', $configuration->isMaintained()); + } + + return $this; } - return $this; - } - - /** - * - * @return registry - */ - protected function load() - { - if ($this->cache->fetch('registry_loaded') !== true) + /** + * + * @return registry + */ + protected function load() { - $rs = array(); - $loaded = false; - try - { + if ($this->cache->fetch('registry_loaded') !== true) { + $rs = array(); + $loaded = false; + try { + $conn = connection::getPDOConnection(); + $sql = 'SELECT `key`, `value`, `type` FROM registry'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + $loaded = true; + } catch (Exception $e) { + + } + foreach ($rs as $row) { + if (in_array($row['key'], array('GV_ServerName', 'GV_debug', 'GV_maintenance'))) { + continue; + } + + switch ($row['type']) { + case self::TYPE_BOOLEAN: + $value = ! ! $row['value']; + break; + case self::TYPE_INTEGER: + $value = (int) $row['value']; + break; + case self::TYPE_ENUM_MULTI: + case self::TYPE_ARRAY: + $value = unserialize($row['value']); + break; + case self::TYPE_STRING: + default: + $value = $row['value']; + break; + } + + $this->cache->save($row['key'], $value); + } + if ($loaded === true) + $this->cache->save('registry_loaded', true); + } + + + return $this; + } + + /** + * + * @param string $key + * @return mixed + */ + public function get($key, $defaultvalue = null) + { + if ( ! $this->cache->contains($key)) + $this->load(); + + if ( ! $this->cache->contains($key) && ! is_null($defaultvalue)) + return $defaultvalue; + else + return $this->cache->fetch($key); + } + + /** + * + * @param string $key + * @param mixed $value + * @return registry + */ + public function set($key, $value, $type) + { + $this->load(); + + switch ($type) { + case self::TYPE_ARRAY: + case self::TYPE_ENUM_MULTI: + $sql_value = serialize($value); + $value = (array) $value; + break; + case self::TYPE_STRING; + default: + $sql_value = (string) $value; + $value = (string) $value; + break; + case self::TYPE_BOOLEAN: + $sql_value = $value ? '1' : '0'; + $value = ! ! $value; + break; + case self::TYPE_INTEGER: + $sql_value = (int) $value; + $value = (int) $value; + break; + } + $conn = connection::getPDOConnection(); - $sql = 'SELECT `key`, `value`, `type` FROM registry'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $loaded = true; - } - catch (Exception $e) - { - } - foreach ($rs as $row) - { - if(in_array($row['key'], array('GV_ServerName', 'GV_debug', 'GV_maintenance'))) - { - continue; - } - - switch ($row['type']) - { - case self::TYPE_BOOLEAN: - $value = !!$row['value']; - break; - case self::TYPE_INTEGER: - $value = (int) $row['value']; - break; - case self::TYPE_ENUM_MULTI: - case self::TYPE_ARRAY: - $value = unserialize($row['value']); - break; - case self::TYPE_STRING: - default: - $value = $row['value']; - break; - } - - $this->cache->save($row['key'], $value); - } - if ($loaded === true) - $this->cache->save('registry_loaded', true); - } - - - return $this; - } - - /** - * - * @param string $key - * @return mixed - */ - public function get($key, $defaultvalue = null) - { - if (!$this->cache->contains($key)) - $this->load(); - - if (!$this->cache->contains($key) && !is_null($defaultvalue)) - - return $defaultvalue; - else - - return $this->cache->fetch($key); - } - - /** - * - * @param string $key - * @param mixed $value - * @return registry - */ - public function set($key, $value, $type) - { - $this->load(); - - switch ($type) - { - case self::TYPE_ARRAY: - case self::TYPE_ENUM_MULTI: - $sql_value = serialize($value); - $value = (array) $value; - break; - case self::TYPE_STRING; - default: - $sql_value = (string) $value; - $value = (string) $value; - break; - case self::TYPE_BOOLEAN: - $sql_value = $value ? '1' : '0'; - $value = !!$value; - break; - case self::TYPE_INTEGER: - $sql_value = (int) $value; - $value = (int) $value; - break; - } - - $conn = connection::getPDOConnection(); - - $sql = 'REPLACE INTO registry (`id`, `key`, `value`, `type`) + $sql = 'REPLACE INTO registry (`id`, `key`, `value`, `type`) VALUES (null, :key, :value, :type)'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':key' => $key, ':value' => $sql_value, ':type' => $type)); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':key' => $key, ':value' => $sql_value, ':type' => $type)); + $stmt->closeCursor(); - $this->cache->save($key, $value); + $this->cache->save($key, $value); - return $this; - } + return $this; + } - /** - * - * @param string $key - * @return mixed - */ - public function is_set($key) - { - $this->load(); + /** + * + * @param string $key + * @return mixed + */ + public function is_set($key) + { + $this->load(); - return $this->cache->contains($key); - } + return $this->cache->contains($key); + } - /** - * - * @param string $key - * @return registry - */ - public function un_set($key) - { - $this->load(); - $conn = connection::getPDOConnection(); + /** + * + * @param string $key + * @return registry + */ + public function un_set($key) + { + $this->load(); + $conn = connection::getPDOConnection(); - $sql = 'DELETE FROM registry WHERE `key` = :key'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':key' => $key)); - $stmt->closeCursor(); + $sql = 'DELETE FROM registry WHERE `key` = :key'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':key' => $key)); + $stmt->closeCursor(); - $this->cache->delete($key); - - return $this; - } + $this->cache->delete($key); + return $this; + } } diff --git a/lib/classes/registryInterface.class.php b/lib/classes/registryInterface.class.php index 3b0dfecc8e..e82a2356e1 100644 --- a/lib/classes/registryInterface.class.php +++ b/lib/classes/registryInterface.class.php @@ -17,11 +17,12 @@ */ interface registryInterface { - public function get($key, $defaultvalue = null); - public function set($key, $value, $type); + public function get($key, $defaultvalue = null); - public function is_set($key); + public function set($key, $value, $type); - public function un_set($key); + public function is_set($key); + + public function un_set($key); } diff --git a/lib/classes/searchEngine/adapter.class.php b/lib/classes/searchEngine/adapter.class.php index 240061441a..dd72c66323 100644 --- a/lib/classes/searchEngine/adapter.class.php +++ b/lib/classes/searchEngine/adapter.class.php @@ -17,147 +17,142 @@ */ class searchEngine_adapter { + /** + * + * @var searchEngine_adapter_interface + */ + protected $search_engine; - /** - * - * @var searchEngine_adapter_interface - */ - protected $search_engine; - /** - * - * @var searchEngine_adapter_options - */ - protected $search_options; - /** - * - * @var boolean - */ - protected $first_page = false; + /** + * + * @var searchEngine_adapter_options + */ + protected $search_options; - /** - * - * @param registryInterface $registry - * @return searchEngine_adapter - */ - public function __construct(registryInterface $registry) - { - if ($registry->get('GV_sphinx')) + /** + * + * @var boolean + */ + protected $first_page = false; + + /** + * + * @param registryInterface $registry + * @return searchEngine_adapter + */ + public function __construct(registryInterface $registry) { - $this->search_engine = new searchEngine_adapter_sphinx_engine(); - } - elseif (function_exists('phrasea_query2')) - { - $this->search_engine = new searchEngine_adapter_phrasea_engine(); - } - else - { - throw new Exception('No search engine available, try phrasea2 or sphinx'); + if ($registry->get('GV_sphinx')) { + $this->search_engine = new searchEngine_adapter_sphinx_engine(); + } elseif (function_exists('phrasea_query2')) { + $this->search_engine = new searchEngine_adapter_phrasea_engine(); + } else { + throw new Exception('No search engine available, try phrasea2 or sphinx'); + } + + return $this; } - return $this; - } + /** + * + * @param searchEngine_options $options + * @return searchEngine_adapter + */ + public function set_options(searchEngine_options $options) + { + $this->search_options = $options; + $this->search_engine->set_options($options); - /** - * - * @param searchEngine_options $options - * @return searchEngine_adapter - */ - public function set_options(searchEngine_options $options) - { - $this->search_options = $options; - $this->search_engine->set_options($options); + return $this; + } - return $this; - } + /** + * + * @param boolean $boolean + * @return searchEngine_adapter + */ + public function set_is_first_page($boolean) + { + $this->first_page = ! ! $boolean; - /** - * - * @param boolean $boolean - * @return searchEngine_adapter - */ - public function set_is_first_page($boolean) - { - $this->first_page = !!$boolean; + return $this; + } - return $this; - } + /** + * + * @return boolean + */ + public function is_first_page() + { + return $this->first_page; + } - /** - * - * @return boolean - */ - public function is_first_page() - { - return $this->first_page; - } + /** + * + * @return string + */ + public function get_query() + { + return $this->search_engine->get_parsed_query(); + } - /** - * - * @return string - */ - public function get_query() - { - return $this->search_engine->get_parsed_query(); - } + /** + * + * @return searchEngine_adapter + */ + public function reset_cache() + { + $this->search_engine->reset_cache(); - /** - * - * @return searchEngine_adapter - */ - public function reset_cache() - { - $this->search_engine->reset_cache(); + return $this; + } - return $this; - } + /** + * + * @param string $query + * @param int $page + * @param int $perPage + * @return searchEngine_results + */ + public function query_per_page($query, $page, $perPage) + { + assert(is_int($page)); + assert($page > 0); + assert(is_int($perPage)); + assert($perPage > 0); + $offset = ($page - 1) * $perPage; - /** - * - * @param string $query - * @param int $page - * @param int $perPage - * @return searchEngine_results - */ - public function query_per_page($query, $page, $perPage) - { - assert(is_int($page)); - assert($page > 0); - assert(is_int($perPage)); - assert($perPage > 0); - $offset = ($page - 1) * $perPage; + return $this->search_engine->results($query, $offset, $perPage); + } - return $this->search_engine->results($query, $offset, $perPage); - } + /** + * + * @param string $query + * @param int $offset + * @param int $perPage + * @return searchEngine_results + */ + public function query_per_offset($query, $offset, $perPage) + { + assert(is_int($offset)); + assert($offset >= 0); + assert(is_int($perPage)); + assert($perPage > 0); - /** - * - * @param string $query - * @param int $offset - * @param int $perPage - * @return searchEngine_results - */ - public function query_per_offset($query, $offset, $perPage) - { - assert(is_int($offset)); - assert($offset >= 0); - assert(is_int($perPage)); - assert($perPage > 0); + return $this->search_engine->results($query, $offset, $perPage); + } - return $this->search_engine->results($query, $offset, $perPage); - } - - /** - * - * @return array - */ - public function get_status() - { - return $this->search_engine->get_status(); - } - - public function build_excerpt($query, array $fields, record_adapter $record) - { - return $this->search_engine->build_excerpt($query, $fields, $record); - } + /** + * + * @return array + */ + public function get_status() + { + return $this->search_engine->get_status(); + } + public function build_excerpt($query, array $fields, record_adapter $record) + { + return $this->search_engine->build_excerpt($query, $fields, $record); + } } diff --git a/lib/classes/searchEngine/adapter/abstract.class.php b/lib/classes/searchEngine/adapter/abstract.class.php index 58fb61eca7..ea2d86e0cd 100644 --- a/lib/classes/searchEngine/adapter/abstract.class.php +++ b/lib/classes/searchEngine/adapter/abstract.class.php @@ -17,174 +17,183 @@ */ abstract class searchEngine_adapter_abstract { + /** + * + * @var int + */ + protected $current_page; - /** - * - * @var int - */ - protected $current_page; - /** - * - * @var int - */ - protected $total_results; - /** - * - * @var int - */ - protected $perPage; - /** - * - * @var string - */ - protected $query; - /** - * - * @var string - */ - protected $error = ''; - /** - * - * @var string - */ - protected $warning = ''; - /** - * - * @var int - */ - protected $total_available; - /** - * - * @var float - */ - protected $total_time; - /** - * - * @var int - */ - protected $offset_start; - /** - * - * @var boolean - */ - protected $use_stemming = true; - /** - * - * @var string - */ - protected $locale; - /** - * - * @var string - */ - protected $current_index = ''; + /** + * + * @var int + */ + protected $total_results; - /** - * - * @return int - */ - public function get_available_results() - { - return $this->total_available; - } + /** + * + * @var int + */ + protected $perPage; - /** - * - * @return float - */ - public function get_time() - { - return $this->total_time; - } + /** + * + * @var string + */ + protected $query; - /** - * - * @return string - */ - public function get_error() - { - return $this->error; - } + /** + * + * @var string + */ + protected $error = ''; - /** - * - * @return string - */ - public function get_warning() - { - return $this->warning; - } + /** + * + * @var string + */ + protected $warning = ''; - /** - * - * @return string - */ - public function get_propositions() - { - return null; - } + /** + * + * @var int + */ + protected $total_available; - /** - * - * @return searchEngine_adapter_abstract - */ - public function reset_cache() - { - return $this; - } + /** + * + * @var float + */ + protected $total_time; - /** - * - * @return int - */ - public function get_per_page() - { - return $this->perPage; - } + /** + * + * @var int + */ + protected $offset_start; - /** - * - * @return int - */ - public function get_total_results() - { - return $this->total_results; - } + /** + * + * @var boolean + */ + protected $use_stemming = true; - /** - * - * @return int - */ - public function get_total_pages() - { - return (int) ceil($this->get_available_results() / $this->get_per_page()); - } + /** + * + * @var string + */ + protected $locale; - /** - * - * @return int - */ - public function get_current_page() - { - return $this->current_page; - } + /** + * + * @var string + */ + protected $current_index = ''; - /** - * - * @return int - */ - public function get_offset_start() - { - return $this->offset_start; - } + /** + * + * @return int + */ + public function get_available_results() + { + return $this->total_available; + } - /** - * - * @return string - */ - public function get_current_indexes() - { - return $this->current_index; - } + /** + * + * @return float + */ + public function get_time() + { + return $this->total_time; + } + /** + * + * @return string + */ + public function get_error() + { + return $this->error; + } + + /** + * + * @return string + */ + public function get_warning() + { + return $this->warning; + } + + /** + * + * @return string + */ + public function get_propositions() + { + return null; + } + + /** + * + * @return searchEngine_adapter_abstract + */ + public function reset_cache() + { + return $this; + } + + /** + * + * @return int + */ + public function get_per_page() + { + return $this->perPage; + } + + /** + * + * @return int + */ + public function get_total_results() + { + return $this->total_results; + } + + /** + * + * @return int + */ + public function get_total_pages() + { + return (int) ceil($this->get_available_results() / $this->get_per_page()); + } + + /** + * + * @return int + */ + public function get_current_page() + { + return $this->current_page; + } + + /** + * + * @return int + */ + public function get_offset_start() + { + return $this->offset_start; + } + + /** + * + * @return string + */ + public function get_current_indexes() + { + return $this->current_index; + } } diff --git a/lib/classes/searchEngine/adapter/interface.class.php b/lib/classes/searchEngine/adapter/interface.class.php index d1487fb564..f901439200 100644 --- a/lib/classes/searchEngine/adapter/interface.class.php +++ b/lib/classes/searchEngine/adapter/interface.class.php @@ -17,41 +17,42 @@ */ interface searchEngine_adapter_interface { - public function __construct(); - public function set_options(searchEngine_options $options); + public function __construct(); - public function reset_cache(); + public function set_options(searchEngine_options $options); - public function get_time(); + public function reset_cache(); - public function get_total_pages(); + public function get_time(); - public function get_offset_start(); + public function get_total_pages(); - public function get_current_page(); + public function get_offset_start(); - public function get_per_page(); + public function get_current_page(); - public function get_total_results(); + public function get_per_page(); - public function get_available_results(); + public function get_total_results(); - public function get_propositions(); + public function get_available_results(); - public function get_parsed_query(); + public function get_propositions(); - public function get_suggestions(Session_Handler $session); + public function get_parsed_query(); - public function get_error(); + public function get_suggestions(Session_Handler $session); - public function get_warning(); + public function get_error(); - public function get_current_indexes(); + public function get_warning(); - public function get_status(); + public function get_current_indexes(); - public function results($query, $page, $perPage); + public function get_status(); - public function build_excerpt($query, array $fields, record_adapter $record); + public function results($query, $page, $perPage); + + public function build_excerpt($query, array $fields, record_adapter $record); } diff --git a/lib/classes/searchEngine/adapter/phrasea/engine.class.php b/lib/classes/searchEngine/adapter/phrasea/engine.class.php index dbe5937d20..9a17ab8199 100644 --- a/lib/classes/searchEngine/adapter/phrasea/engine.class.php +++ b/lib/classes/searchEngine/adapter/phrasea/engine.class.php @@ -17,667 +17,620 @@ */ class searchEngine_adapter_phrasea_engine extends searchEngine_adapter_abstract implements searchEngine_adapter_interface { + /** + * + * @var array + */ + protected $queries = array(); - /** - * - * @var array - */ - protected $queries = array(); + /** + * + * @var array + */ + protected $colls = array(); - /** - * - * @var array - */ - protected $colls = array(); + /** + * + * @var array + */ + protected $qp = array(); - /** - * - * @var array - */ - protected $qp = array(); + /** + * + * @var array + */ + protected $answers = array(); - /** - * - * @var array - */ - protected $answers = array(); + /** + * + * @var array + */ + protected $needthesaurus = array(); - /** - * - * @var array - */ - protected $needthesaurus = array(); + /** + * + * @var array + */ + protected $indep_treeq = array(); - /** - * - * @var array - */ - protected $indep_treeq = array(); + /** + * + * @var searchEngine_options + */ + protected $options = false; - /** - * - * @var searchEngine_options - */ - protected $options = false; + /** + * + * @var array + */ + protected $arrayq = array(); - /** - * - * @var array - */ - protected $arrayq = array(); + /** + * + * @var array + */ + protected $results = array(); - /** - * - * @var array - */ - protected $results = array(); + /** + * + * @var boolean + */ + protected $reseted = false; - /** - * - * @var boolean - */ - protected $reseted = false; + /** + * + * @var int + */ + protected $opt_search_type; - /** - * - * @var int - */ - protected $opt_search_type; + /** + * + * @var array + */ + protected $opt_bases = array(); - /** - * - * @var array - */ - protected $opt_bases = array(); + /** + * + * @var array + */ + protected $opt_fields = array(); - /** - * - * @var array - */ - protected $opt_fields = array(); + /** + * + * @var array + */ + protected $opt_status = array(); - /** - * - * @var array - */ - protected $opt_status = array(); + /** + * + * @var array + */ + protected $opt_date_field; - /** - * - * @var array - */ - protected $opt_date_field; + /** + * + * @var DateTime + */ + protected $opt_min_date; - /** - * - * @var DateTime - */ - protected $opt_min_date; + /** + * + * @var DateTime + */ + protected $opt_max_date; - /** - * - * @var DateTime - */ - protected $opt_max_date; + /** + * + * @var string + */ + protected $opt_record_type; - /** - * - * @var string - */ - protected $opt_record_type; - - /** - * - * @return searchEngine_adapter_phrasea_engine - */ - function __construct() - { - return $this; - } - - /** - * - * @param searchEngine_options $options - * @return searchEngine_adapter_phrasea_engine - */ - public function set_options(searchEngine_options $options) - { - $this->options = $options; - - $this->opt_search_type = (int) $options->get_search_type(); - $this->opt_bases = $options->get_bases(); - $this->opt_fields = $options->get_fields(); - $this->opt_date_field = $options->get_date_fields(); - $this->opt_max_date = $options->get_max_date(); - $this->opt_min_date = $options->get_min_date(); - - if (in_array($options->get_record_type(), array('image', 'video', 'audio', 'document', 'flash'))) - $this->opt_record_type = $options->get_record_type(); - - foreach ($options->get_fields() as $field) + /** + * + * @return searchEngine_adapter_phrasea_engine + */ + function __construct() { - if (trim($field) === 'phraseanet--all--fields') - { - $this->opt_fields = array(); - break; - } + return $this; } - $this->opt_status = $options->get_status(); - - - return $this; - } - - /** - * - * @param $proposals - * @return string - */ - protected static function proposalsToHTML($proposals) - { - - $html = ''; - $b = true; - foreach ($proposals["BASES"] as $zbase) + /** + * + * @param searchEngine_options $options + * @return searchEngine_adapter_phrasea_engine + */ + public function set_options(searchEngine_options $options) { - if ((int) (count($proposals["BASES"]) > 1) && count($zbase["TERMS"]) > 0) - { - $style = $b ? 'style="margin-top:0px;"' : ''; - $b = false; - $html .= "

              " . sprintf(_('reponses::propositions pour la base %s'), $zbase["NAME"]) . "

              "; - } - $t = true; - foreach ($zbase["TERMS"] as $path => $props) - { - $style = $t ? 'style="margin-top:0px;"' : ''; - $t = false; - $html .= "

              " . sprintf(_('reponses::propositions pour le terme %s'), $props["TERM"]) . "

              "; - $html .= $props["HTML"]; - } - } - $html .= ''; + $this->options = $options; - return($html); - } + $this->opt_search_type = (int) $options->get_search_type(); + $this->opt_bases = $options->get_bases(); + $this->opt_fields = $options->get_fields(); + $this->opt_date_field = $options->get_date_fields(); + $this->opt_max_date = $options->get_max_date(); + $this->opt_min_date = $options->get_min_date(); - /** - * - * @return string - */ - public function get_propositions() - { - if (isset($this->qp['main'])) - { - $proposals = self::proposalsToHTML($this->qp['main']->proposals); - if (trim($proposals) !== '') - { - return "
              " . $this->qp['main']->proposals["QRY"] - . "
              " . $proposals . "
              "; - } + if (in_array($options->get_record_type(), array('image', 'video', 'audio', 'document', 'flash'))) + $this->opt_record_type = $options->get_record_type(); + + foreach ($options->get_fields() as $field) { + if (trim($field) === 'phraseanet--all--fields') { + $this->opt_fields = array(); + break; + } + } + + $this->opt_status = $options->get_status(); + + + return $this; } - return null; - } - - /** - * - * @param int $query - * @param int $offset - * @param int $perPage - * @return searchEngine_results - */ - function results($query, $offset, $perPage) - { - - assert(is_int($offset)); - assert($offset >= 0); - assert(is_int($perPage)); - - $page = floor($offset / $perPage) + 1; - - $this->current_page = $page; - $this->perPage = $perPage; - - $page = $this->get_current_page(); - - if (trim($query) === '') - $query = "all"; - if ($this->opt_record_type != '') + /** + * + * @param $proposals + * @return string + */ + protected static function proposalsToHTML($proposals) { - $query .= ' AND recordtype=' . $this->opt_record_type; + + $html = ''; + $b = true; + foreach ($proposals["BASES"] as $zbase) { + if ((int) (count($proposals["BASES"]) > 1) && count($zbase["TERMS"]) > 0) { + $style = $b ? 'style="margin-top:0px;"' : ''; + $b = false; + $html .= "

              " . sprintf(_('reponses::propositions pour la base %s'), $zbase["NAME"]) . "

              "; + } + $t = true; + foreach ($zbase["TERMS"] as $path => $props) { + $style = $t ? 'style="margin-top:0px;"' : ''; + $t = false; + $html .= "

              " . sprintf(_('reponses::propositions pour le terme %s'), $props["TERM"]) . "

              "; + $html .= $props["HTML"]; + } + } + $html .= ''; + + return($html); } - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - - $sql = 'SELECT query, query_time FROM cache WHERE session_id = :ses_id'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(array(':ses_id' => $session->get_ses_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $date_obj = new DateTime('-10 min'); - $date_quest = new DateTime($row['query_time']); - - $reseted = $this->reseted; - - $reseted = false; - if ($this->reseted) - $reseted = true; - if ($query != $row['query']) - $reseted = true; - if ($date_obj > $date_quest) - $reseted = true; - - if ($reseted === true) + /** + * + * @return string + */ + public function get_propositions() { - $this->reset_cache(); - self::addQuery($query); - self::query(); - } - else - { - $this->total_available = $this->total_results = $session->get_session_prefs('phrasea_engine_n_results'); + if (isset($this->qp['main'])) { + $proposals = self::proposalsToHTML($this->qp['main']->proposals); + if (trim($proposals) !== '') { + return "
              " . $this->qp['main']->proposals["QRY"] + . "
              " . $proposals . "
              "; + } + } + + return null; } - $results = new set_result(); - - - $perPage = $this->get_per_page(); - $page = $this->get_current_page(); - $this->offset_start = $courcahnum = (($page - 1) * $perPage); - - $res = phrasea_fetch_results( - $session->get_ses_id(), (int) (($page - 1) * $perPage) + 1, $perPage, false - ); - - $rs = array(); - if (isset($res['results']) && is_array($res['results'])) - $rs = $res['results']; - - foreach ($rs as $irec => $data) + /** + * + * @param int $query + * @param int $offset + * @param int $perPage + * @return searchEngine_results + */ + function results($query, $offset, $perPage) { - try - { - $sbas_id = phrasea::sbasFromBas($data['base_id']); - $record = new record_adapter( - $sbas_id, - $data['record_id'], - $courcahnum + assert(is_int($offset)); + assert($offset >= 0); + assert(is_int($perPage)); + + $page = floor($offset / $perPage) + 1; + + $this->current_page = $page; + $this->perPage = $perPage; + + $page = $this->get_current_page(); + + if (trim($query) === '') + $query = "all"; + if ($this->opt_record_type != '') { + $query .= ' AND recordtype=' . $this->opt_record_type; + } + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + + $sql = 'SELECT query, query_time FROM cache WHERE session_id = :ses_id'; + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(array(':ses_id' => $session->get_ses_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $date_obj = new DateTime('-10 min'); + $date_quest = new DateTime($row['query_time']); + + $reseted = $this->reseted; + + $reseted = false; + if ($this->reseted) + $reseted = true; + if ($query != $row['query']) + $reseted = true; + if ($date_obj > $date_quest) + $reseted = true; + + if ($reseted === true) { + $this->reset_cache(); + self::addQuery($query); + self::query(); + } else { + $this->total_available = $this->total_results = $session->get_session_prefs('phrasea_engine_n_results'); + } + + $results = new set_result(); + + + $perPage = $this->get_per_page(); + $page = $this->get_current_page(); + $this->offset_start = $courcahnum = (($page - 1) * $perPage); + + $res = phrasea_fetch_results( + $session->get_ses_id(), (int) (($page - 1) * $perPage) + 1, $perPage, false ); - $results->add_element($record); - } - catch (Exception $e) - { + $rs = array(); + if (isset($res['results']) && is_array($res['results'])) + $rs = $res['results']; - } - $courcahnum ++; + foreach ($rs as $irec => $data) { + try { + $sbas_id = phrasea::sbasFromBas($data['base_id']); + + $record = new record_adapter( + $sbas_id, + $data['record_id'], + $courcahnum + ); + + $results->add_element($record); + } catch (Exception $e) { + + } + $courcahnum ++; + } + + return new searchEngine_results($results, $this); } - return new searchEngine_results($results, $this); - } - - /** - * - * @return searchEngine_adapter_phrasea_engine - */ - public function reset_cache() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - phrasea_clear_cache($session->get_ses_id()); - $this->reseted = true; - - return $this; - } - - /** - * - * @return array - */ - public function get_status() - { - $infos = phrasea_info(); - - $status = array(); - foreach ($infos as $key => $value) + /** + * + * @return searchEngine_adapter_phrasea_engine + */ + public function reset_cache() { - $status[] = array($key, $value); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + phrasea_clear_cache($session->get_ses_id()); + $this->reseted = true; + + return $this; } - return $status; - } - - /** - * - * @param Session_Handler $session - * @return array - */ - public function get_suggestions(Session_Handler $session) - { - $props = array(); - foreach ($this->qp['main']->proposals['QUERIES'] as $prop) + /** + * + * @return array + */ + public function get_status() { - $props[] = array( - 'value' => $prop - , 'current' => false - , 'hits' => null - ); + $infos = phrasea_info(); + + $status = array(); + foreach ($infos as $key => $value) { + $status[] = array($key, $value); + } + + return $status; } - return $props; - } + /** + * + * @param Session_Handler $session + * @return array + */ + public function get_suggestions(Session_Handler $session) + { + $props = array(); + foreach ($this->qp['main']->proposals['QUERIES'] as $prop) { + $props[] = array( + 'value' => $prop + , 'current' => false + , 'hits' => null + ); + } - /** - * - * @return string - */ - public function get_parsed_query() - { - return $this->query; - } + return $props; + } - /** - * - * @return searchEngine_adapter_phrasea_engine - */ - protected function query() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); + /** + * + * @return string + */ + public function get_parsed_query() + { + return $this->query; + } - $dateLog = date("Y-m-d H:i:s"); - $nbanswers = 0; + /** + * + * @return searchEngine_adapter_phrasea_engine + */ + protected function query() + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); - $sql = 'UPDATE cache SET query = :query, query_time = NOW() + $dateLog = date("Y-m-d H:i:s"); + $nbanswers = 0; + + $sql = 'UPDATE cache SET query = :query, query_time = NOW() WHERE session_id = :ses_id'; - $params = array( - 'query' => $this->get_parsed_query() - , ':ses_id' => $session->get_ses_id() - ); + $params = array( + 'query' => $this->get_parsed_query() + , ':ses_id' => $session->get_ses_id() + ); - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $total_time = 0; + $total_time = 0; - $sort = ''; + $sort = ''; - if ($this->options->get_sortby()) - { - switch ($this->options->get_sortord()) - { - case searchEngine_options::SORT_MODE_ASC: - $sort = '+'; - break; - case searchEngine_options::SORT_MODE_DESC: - default: - $sort = '-'; - break; - } - $sort .= '0' . $this->options->get_sortby(); - } + if ($this->options->get_sortby()) { + switch ($this->options->get_sortord()) { + case searchEngine_options::SORT_MODE_ASC: + $sort = '+'; + break; + case searchEngine_options::SORT_MODE_DESC: + default: + $sort = '-'; + break; + } + $sort .= '0' . $this->options->get_sortby(); + } - foreach ($this->queries as $sbas_id => $qry) - { - $BF = array(); + foreach ($this->queries as $sbas_id => $qry) { + $BF = array(); - foreach ($this->options->get_business_fields() as $base_id) - { - $BF[] = phrasea::collFromBas($base_id); - } + foreach ($this->options->get_business_fields() as $base_id) { + $BF[] = phrasea::collFromBas($base_id); + } - $this->results[$sbas_id] = phrasea_query2( - $session->get_ses_id() - , $sbas_id - , $this->colls[$sbas_id] - , $this->arrayq[$sbas_id] - , $registry->get('GV_sit') - , (string) $session->get_usr_id() - , false - , $this->opt_search_type == 1 ? PHRASEA_MULTIDOC_REGONLY : PHRASEA_MULTIDOC_DOCONLY - , $sort - , $BF - ); + $this->results[$sbas_id] = phrasea_query2( + $session->get_ses_id() + , $sbas_id + , $this->colls[$sbas_id] + , $this->arrayq[$sbas_id] + , $registry->get('GV_sit') + , (string) $session->get_usr_id() + , false + , $this->opt_search_type == 1 ? PHRASEA_MULTIDOC_REGONLY : PHRASEA_MULTIDOC_DOCONLY + , $sort + , $BF + ); - $total_time += $this->results[$sbas_id]['time_all']; + $total_time += $this->results[$sbas_id]['time_all']; - if ($this->results[$sbas_id]) - $nbanswers += $this->results[$sbas_id]["nbanswers"]; + if ($this->results[$sbas_id]) + $nbanswers += $this->results[$sbas_id]["nbanswers"]; - $logger = $session->get_logger(databox::get_instance($sbas_id)); + $logger = $session->get_logger(databox::get_instance($sbas_id)); - $conn2 = connection::getPDOConnection($sbas_id); + $conn2 = connection::getPDOConnection($sbas_id); - $sql3 = "INSERT INTO log_search + $sql3 = "INSERT INTO log_search (id, log_id, date, search, results, coll_id ) VALUES (null, :log_id, :date, :query, :nbresults, :colls)"; - $params = array( - ':log_id' => $logger->get_id() - , ':date' => $dateLog - , ':query' => $this->query - , ':nbresults' => $this->results[$sbas_id]["nbanswers"] - , ':colls' => implode(',', $this->colls[$sbas_id]) - ); + $params = array( + ':log_id' => $logger->get_id() + , ':date' => $dateLog + , ':query' => $this->query + , ':nbresults' => $this->results[$sbas_id]["nbanswers"] + , ':colls' => implode(',', $this->colls[$sbas_id]) + ); - $stmt = $conn2->prepare($sql3); - $stmt->execute($params); - $stmt->closeCursor(); - } - - $this->total_time = $total_time; - - User_Adapter::saveQuery($this->query); - - $session->set_session_prefs('phrasea_engine_n_results', $nbanswers); - - $this->total_available = $this->total_results = $nbanswers; - - return $this; - } - - /** - * - * @param int $sbas - * @return searchEngine_adapter_phrasea_engine - */ - protected function singleParse($sbas) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $this->qp[$sbas] = new searchEngine_adapter_phrasea_queryParser(Session_Handler::get_locale()); - $this->qp[$sbas]->debug = false; - if ($sbas == 'main') - $simple_treeq = $this->qp[$sbas]->parsequery($this->query); - else - $simple_treeq = $this->qp[$sbas]->parsequery($this->queries[$sbas]); - - $this->qp[$sbas]->priority_opk($simple_treeq); - $this->qp[$sbas]->distrib_opk($simple_treeq); - $this->needthesaurus[$sbas] = false; - - $this->indep_treeq[$sbas] = $this->qp[$sbas]->extendThesaurusOnTerms($simple_treeq, true, true, false); - $this->needthesaurus[$sbas] = $this->qp[$sbas]->containsColonOperator($this->indep_treeq[$sbas]); - - return $this; - } - - /** - * - * @param string $query - * @return searchEngine_adapter_phrasea_engine - */ - protected function addQuery($query) - { - $qry = ''; - if (trim($query) != '') - { - $qry .= trim($query); - } - - $appbox = appbox::get_instance(\bootstrap::getCore()); - - foreach ($appbox->get_databoxes() as $databox) - { - foreach ($databox->get_collections() as $coll) - { - if (in_array($coll->get_base_id(), $this->opt_bases)) - { - $this->queries[$databox->get_sbas_id()] = $qry; - break; + $stmt = $conn2->prepare($sql3); + $stmt->execute($params); + $stmt->closeCursor(); } - } + + $this->total_time = $total_time; + + User_Adapter::saveQuery($this->query); + + $session->set_session_prefs('phrasea_engine_n_results', $nbanswers); + + $this->total_available = $this->total_results = $nbanswers; + + return $this; } - $this->query = $qry; - foreach ($this->queries as $sbas => $qs) + /** + * + * @param int $sbas + * @return searchEngine_adapter_phrasea_engine + */ + protected function singleParse($sbas) { - if ($sbas === 'main') - continue; - if (count($this->opt_status) > 0) - { - $requestStat = 'xxxx'; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $this->qp[$sbas] = new searchEngine_adapter_phrasea_queryParser(Session_Handler::get_locale()); + $this->qp[$sbas]->debug = false; + if ($sbas == 'main') + $simple_treeq = $this->qp[$sbas]->parsequery($this->query); + else + $simple_treeq = $this->qp[$sbas]->parsequery($this->queries[$sbas]); - for ($i = 4; ($i <= 64); $i ++ ) - { - if ( ! isset($this->opt_status[$i])) - { - $requestStat = 'x' . $requestStat; - continue; - } - $set = false; - $val = ''; - if (isset($this->opt_status[$i][$sbas]) && $this->opt_status[$i][$sbas] == '0') - { - $set = true; - $val = '0'; - } - if (isset($this->opt_status[$i][$sbas]) && $this->opt_status[$i][$sbas] == '1') - { - if ($set) - $val = 'x'; - else - $val = '1'; - } - $requestStat = ( $val != '' ? $val : 'x' ) . $requestStat; + $this->qp[$sbas]->priority_opk($simple_treeq); + $this->qp[$sbas]->distrib_opk($simple_treeq); + $this->needthesaurus[$sbas] = false; + + $this->indep_treeq[$sbas] = $this->qp[$sbas]->extendThesaurusOnTerms($simple_treeq, true, true, false); + $this->needthesaurus[$sbas] = $this->qp[$sbas]->containsColonOperator($this->indep_treeq[$sbas]); + + return $this; + } + + /** + * + * @param string $query + * @return searchEngine_adapter_phrasea_engine + */ + protected function addQuery($query) + { + $qry = ''; + if (trim($query) != '') { + $qry .= trim($query); } - $requestStat = trim(ltrim($requestStat, 'x')); - if ($requestStat !== '') - $this->queries[$sbas] .= ' and (recordstatus=' . $requestStat . ')'; - } - if (count($this->opt_fields) > 0) - { - $this->queries[$sbas] .= ' dans (' . implode(' ou ', $this->opt_fields) . ')'; - } - if (($this->opt_min_date || $this->opt_max_date) && $this->opt_date_field != '') - { - if ($this->opt_min_date) - $this->queries[$sbas] .= ' AND ( ' . implode(' >= ' . $this->opt_min_date->format('Y-m-d') . ' OR ', $this->opt_date_field) . ' >= ' . $this->opt_min_date->format('Y-m-d') . ' ) '; - if ($this->opt_max_date) - $this->queries[$sbas] .= ' AND ( ' . implode(' <= ' . $this->opt_max_date->format('Y-m-d') . ' OR ', $this->opt_date_field) . ' <= ' . $this->opt_max_date->format('Y-m-d') . ' ) '; - } - } - $this->singleParse('main'); - foreach ($this->queries as $sbas => $qryBas) - $this->singleParse($sbas); + $appbox = appbox::get_instance(\bootstrap::getCore()); - foreach ($appbox->get_databoxes() as $databox) - { - if ( ! isset($this->queries[$databox->get_sbas_id()])) - continue; - - //$databox = databox::get_instance($sbas_id); - $sbas_id = $databox->get_sbas_id(); - $this->colls[$sbas_id] = array(); - foreach ($databox->get_collections() as $coll) - { - if (in_array($coll->get_base_id(), $this->opt_bases)) - $this->colls[$sbas_id][] = (int) $coll->get_base_id(); - } - if (sizeof($this->colls[$sbas_id]) <= 0) - continue; - if ($this->needthesaurus[$sbas_id]) - { - $domthesaurus = $databox->get_dom_thesaurus(); - - if ($domthesaurus) - { - $this->qp[$sbas_id]->thesaurus2($this->indep_treeq[$sbas_id], $sbas_id, $databox->get_dbname(), $domthesaurus, true); - $this->qp['main']->thesaurus2($this->indep_treeq['main'], $sbas_id, $databox->get_dbname(), $domthesaurus, true); + foreach ($appbox->get_databoxes() as $databox) { + foreach ($databox->get_collections() as $coll) { + if (in_array($coll->get_base_id(), $this->opt_bases)) { + $this->queries[$databox->get_sbas_id()] = $qry; + break; + } + } } - } + $this->query = $qry; - if ($this->qp[$sbas_id]->errmsg != "") - { - $this->error .= ' ' . $this->qp[$sbas_id]->errmsg; - } + foreach ($this->queries as $sbas => $qs) { + if ($sbas === 'main') + continue; + if (count($this->opt_status) > 0) { + $requestStat = 'xxxx'; - $emptyw = false; - - $this->qp[$sbas_id]->set_default($this->indep_treeq[$sbas_id], $emptyw); - $this->qp[$sbas_id]->distrib_in($this->indep_treeq[$sbas_id]); - $this->qp[$sbas_id]->factor_or($this->indep_treeq[$sbas_id]); - $this->qp[$sbas_id]->setNumValue($this->indep_treeq[$sbas_id], $databox->get_sxml_structure()); - $this->qp[$sbas_id]->thesaurus2_apply($this->indep_treeq[$sbas_id], $sbas_id); - $this->arrayq[$sbas_id] = $this->qp[$sbas_id]->makequery($this->indep_treeq[$sbas_id]); - $this->results[$sbas_id] = NULL; - } - - return $this; - } - - public function build_excerpt($query, array $fields, record_adapter $record) - { - $ret = array(); - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $res = phrasea_fetch_results( - $session->get_ses_id(), ($record->get_number() + 1), 1, true, "[[em]]", "[[/em]]" - ); - - if ( ! isset($res['results']) || ! is_array($res['results'])) - - return array(); - $rs = $res['results']; - $res = array_shift($rs); - if ( ! isset($res['xml'])) - { - return array(); - } - - $sxe = simplexml_load_string($res['xml']); - - foreach ($fields as $name => $field) - { - if ($sxe->description->$name) - { - $val = array(); - foreach ($sxe->description->$name as $value) - { - $val[] = str_replace(array('[[em]]', '[[/em]]'), array('', ''), (string) $value); + for ($i = 4; ($i <= 64); $i ++ ) { + if ( ! isset($this->opt_status[$i])) { + $requestStat = 'x' . $requestStat; + continue; + } + $set = false; + $val = ''; + if (isset($this->opt_status[$i][$sbas]) && $this->opt_status[$i][$sbas] == '0') { + $set = true; + $val = '0'; + } + if (isset($this->opt_status[$i][$sbas]) && $this->opt_status[$i][$sbas] == '1') { + if ($set) + $val = 'x'; + else + $val = '1'; + } + $requestStat = ( $val != '' ? $val : 'x' ) . $requestStat; + } + $requestStat = trim(ltrim($requestStat, 'x')); + if ($requestStat !== '') + $this->queries[$sbas] .= ' and (recordstatus=' . $requestStat . ')'; + } + if (count($this->opt_fields) > 0) { + $this->queries[$sbas] .= ' dans (' . implode(' ou ', $this->opt_fields) . ')'; + } + if (($this->opt_min_date || $this->opt_max_date) && $this->opt_date_field != '') { + if ($this->opt_min_date) + $this->queries[$sbas] .= ' AND ( ' . implode(' >= ' . $this->opt_min_date->format('Y-m-d') . ' OR ', $this->opt_date_field) . ' >= ' . $this->opt_min_date->format('Y-m-d') . ' ) '; + if ($this->opt_max_date) + $this->queries[$sbas] .= ' AND ( ' . implode(' <= ' . $this->opt_max_date->format('Y-m-d') . ' OR ', $this->opt_date_field) . ' <= ' . $this->opt_max_date->format('Y-m-d') . ' ) '; + } } - $separator = $field['separator'] ? $field['separator'][0] : ''; - $val = implode(' ' . $separator . ' ', $val); - } - else - { - $val = $field['value']; - } - $ret[] = $val; + $this->singleParse('main'); + foreach ($this->queries as $sbas => $qryBas) + $this->singleParse($sbas); + + foreach ($appbox->get_databoxes() as $databox) { + if ( ! isset($this->queries[$databox->get_sbas_id()])) + continue; + + //$databox = databox::get_instance($sbas_id); + $sbas_id = $databox->get_sbas_id(); + $this->colls[$sbas_id] = array(); + foreach ($databox->get_collections() as $coll) { + if (in_array($coll->get_base_id(), $this->opt_bases)) + $this->colls[$sbas_id][] = (int) $coll->get_base_id(); + } + if (sizeof($this->colls[$sbas_id]) <= 0) + continue; + if ($this->needthesaurus[$sbas_id]) { + $domthesaurus = $databox->get_dom_thesaurus(); + + if ($domthesaurus) { + $this->qp[$sbas_id]->thesaurus2($this->indep_treeq[$sbas_id], $sbas_id, $databox->get_dbname(), $domthesaurus, true); + $this->qp['main']->thesaurus2($this->indep_treeq['main'], $sbas_id, $databox->get_dbname(), $domthesaurus, true); + } + } + + if ($this->qp[$sbas_id]->errmsg != "") { + $this->error .= ' ' . $this->qp[$sbas_id]->errmsg; + } + + $emptyw = false; + + $this->qp[$sbas_id]->set_default($this->indep_treeq[$sbas_id], $emptyw); + $this->qp[$sbas_id]->distrib_in($this->indep_treeq[$sbas_id]); + $this->qp[$sbas_id]->factor_or($this->indep_treeq[$sbas_id]); + $this->qp[$sbas_id]->setNumValue($this->indep_treeq[$sbas_id], $databox->get_sxml_structure()); + $this->qp[$sbas_id]->thesaurus2_apply($this->indep_treeq[$sbas_id], $sbas_id); + $this->arrayq[$sbas_id] = $this->qp[$sbas_id]->makequery($this->indep_treeq[$sbas_id]); + $this->results[$sbas_id] = NULL; + } + + return $this; } - return $ret; - } + public function build_excerpt($query, array $fields, record_adapter $record) + { + $ret = array(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $res = phrasea_fetch_results( + $session->get_ses_id(), ($record->get_number() + 1), 1, true, "[[em]]", "[[/em]]" + ); + + if ( ! isset($res['results']) || ! is_array($res['results'])) + return array(); + $rs = $res['results']; + $res = array_shift($rs); + if ( ! isset($res['xml'])) { + return array(); + } + + $sxe = simplexml_load_string($res['xml']); + + foreach ($fields as $name => $field) { + if ($sxe->description->$name) { + $val = array(); + foreach ($sxe->description->$name as $value) { + $val[] = str_replace(array('[[em]]', '[[/em]]'), array('', ''), (string) $value); + } + $separator = $field['separator'] ? $field['separator'][0] : ''; + $val = implode(' ' . $separator . ' ', $val); + } else { + $val = $field['value']; + } + + $ret[] = $val; + } + + return $ret; + } } diff --git a/lib/classes/searchEngine/adapter/phrasea/queryParser.class.php b/lib/classes/searchEngine/adapter/phrasea/queryParser.class.php index 41cf1c9ca6..9b4be59b74 100644 --- a/lib/classes/searchEngine/adapter/phrasea/queryParser.class.php +++ b/lib/classes/searchEngine/adapter/phrasea/queryParser.class.php @@ -17,957 +17,866 @@ */ class searchEngine_adapter_phrasea_queryParser { - - var $ops = array( - "et" => array("NODETYPE" => PHRASEA_OP_AND, "CANNUM" => false), - "and" => array("NODETYPE" => PHRASEA_OP_AND, "CANNUM" => false), - "ou" => array("NODETYPE" => PHRASEA_OP_OR, "CANNUM" => false), - "or" => array("NODETYPE" => PHRASEA_OP_OR, "CANNUM" => false), - "sauf" => array("NODETYPE" => PHRASEA_OP_EXCEPT, "CANNUM" => false), - "except" => array("NODETYPE" => PHRASEA_OP_EXCEPT, "CANNUM" => false), - "pres" => array("NODETYPE" => PHRASEA_OP_NEAR, "CANNUM" => true), - "near" => array("NODETYPE" => PHRASEA_OP_NEAR, "CANNUM" => true), - "avant" => array("NODETYPE" => PHRASEA_OP_BEFORE, "CANNUM" => true), - "before" => array("NODETYPE" => PHRASEA_OP_BEFORE, "CANNUM" => true), - "apres" => array("NODETYPE" => PHRASEA_OP_AFTER, "CANNUM" => true), - "after" => array("NODETYPE" => PHRASEA_OP_AFTER, "CANNUM" => true), - "dans" => array("NODETYPE" => PHRASEA_OP_IN, "CANNUM" => false), - "in" => array("NODETYPE" => PHRASEA_OP_IN, "CANNUM" => false) - ); - var $opk = array( - "<" => array("NODETYPE" => PHRASEA_OP_LT, "CANNUM" => false), - ">" => array("NODETYPE" => PHRASEA_OP_GT, "CANNUM" => false), - "<=" => array("NODETYPE" => PHRASEA_OP_LEQT, "CANNUM" => false), - ">=" => array("NODETYPE" => PHRASEA_OP_GEQT, "CANNUM" => false), - "<>" => array("NODETYPE" => PHRASEA_OP_NOTEQU, "CANNUM" => false), - "=" => array("NODETYPE" => PHRASEA_OP_EQUAL, "CANNUM" => false), - ":" => array("NODETYPE" => PHRASEA_OP_COLON, "CANNUM" => false) - ); - var $spw = array( - "all" => array( - "CLASS" => "PHRASEA_KW_ALL", "NODETYPE" => PHRASEA_KW_ALL, "CANNUM" => false - ), - "last" => array( - "CLASS" => "PHRASEA_KW_LAST", "NODETYPE" => PHRASEA_KW_LAST, "CANNUM" => true - ), - // "first" => array("CLASS"=>PHRASEA_KW_FIRST, "CANNUM"=>true), - // "premiers" => array("CLASS"=>PHRASEA_KW_FIRST, "CANNUM"=>true), - "tout" => array( - "CLASS" => "PHRASEA_KW_ALL", "NODETYPE" => PHRASEA_KW_ALL, "CANNUM" => false - ), - "derniers" => array( - "CLASS" => "PHRASEA_KW_LAST", "NODETYPE" => PHRASEA_KW_LAST, "CANNUM" => true - ) - ); - var $quoted_defaultop = array( - "VALUE" => "default_avant", "NODETYPE" => PHRASEA_OP_BEFORE, "PNUM" => 0 - ); - var $defaultop = array( - "VALUE" => "and", "NODETYPE" => PHRASEA_OP_AND, "PNUM" => NULL - ); - var $defaultlast = 12; - var $phq; - var $errmsg = ""; - - /** - * - * @var boolean - */ - var $debug = false; - - /** - * un tableau qui contiendra des propositions de thesaurus - * pour les termes de l'arbre simple - * - * @var array - */ - var $proposals = Array("QRY" => "", "BASES" => array(), "QUERIES" => array()); - - /** - * Current language for thesaurus - * @var - */ - var $lng = null; - protected $unicode; - - function __construct($lng = "???") - { - $this->lng = $lng; - $this->unicode = new unicode(); - - return $this; - } - - function mb_trim($s, $encoding) - { - return(trim($s)); - } - - function mb_ltrim($s, $encoding) - { - return(ltrim($s)); - } - - function parsequery($phq) - { - if ($this->debug) - { - for ($i = 0; $i < mb_strlen($phq, 'UTF-8'); $i++) - { - $c = mb_substr($phq, $i, 1, 'UTF-8'); - printf("// %s : '%s' (%d octets)\n", $i, $c, strlen($c)); - } - } - - $this->proposals = Array("QRY" => "", "BASES" => array(), "QUERIES" => array()); - $this->phq = $this->mb_trim($phq, 'UTF-8'); - if ($this->phq != "") - - return($this->maketree(0)); - else - { - if ($this->errmsg != "") - $this->errmsg .= sprintf("\\n"); - $this->errmsg .= _('qparser::la question est vide'); - - return(null); - } - } - - function astext($tree) - { - switch ($tree["CLASS"]) - { - case "SIMPLE": - if (is_array($tree["VALUE"])) - - return(implode(" ", $tree["VALUE"])); - else - - return($tree["VALUE"]); - break; - case "QSIMPLE": - if (is_array($tree["VALUE"])) - - return("\"" . implode(" ", $tree["VALUE"]) . "\""); - else - - return("\"" . $tree["VALUE"] . "\""); - break; - case "PHRASEA_KW_ALL": - return($tree["VALUE"][0]); - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - - return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); - else - - return($tree["VALUE"][0]); - break; - case "OPS": - case "OPK": - if (isset($tree["PNUM"])) - - return("(" . $this->astext($tree["LB"]) . " " . $tree["VALUE"] . "[" . $tree["PNUM"] . "] " . $this->astext($tree["RB"]) . ")"); - else - - return("(" . $this->astext($tree["LB"]) . " " . $tree["VALUE"] . " " . $this->astext($tree["RB"]) . ")"); - break; - } - } - - function astable(&$tree) - { - $this->calc_complexity($tree); - $txt = ""; - $this->astable2($txt, $tree); - $txt = "\n\n" . $txt . "\n
              \n"; - - return($txt); - } - - function calc_complexity(&$tree) - { - if ($tree) - { - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - - return($tree["COMPLEXITY"] = $this->calc_complexity($tree["LB"]) + $this->calc_complexity($tree["RB"])); - else - - return($tree["COMPLEXITY"] = 1); - } - } - - function astable2(&$out, &$tree, $depth = 0) - { - switch ($tree["CLASS"]) - { - case "SIMPLE": - if (is_array($tree["VALUE"])) - $txt = implode(" ", $tree["VALUE"]); - else - $txt = $tree["VALUE"]; - $out .= "\t" . $txt . "\n"; - break; - case "QSIMPLE": - if (is_array($tree["VALUE"])) - $txt = implode(" ", $tree["VALUE"]); - else - $txt = $tree["VALUE"]; - $out .= "\t"" . $txt . ""\n"; - break; - case "PHRASEA_KW_ALL": - $out .= "\t" . $tree["VALUE"][0] . "\n"; - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - $out .= "\t" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]" . "\n"; - else - $out .= "\t" . $tree["VALUE"][0] . "\n"; - break; - case "OPS": - case "OPK": - $op = $tree["VALUE"]; - if (isset($tree["PNUM"])) - $op .= "[" . $tree["PNUM"] . "]"; - $out .= "\t$op\n"; - $this->astable2($out, $tree["LB"], $depth + 1); - $this->astable2($out, $tree["RB"], $depth + 1); - $out .= "\n\n"; - break; - } - } - - function dumpDiv(&$tree) - { - print("
              \n"); - $this->dumpDiv2($tree); - print("
              \n"); - } - - function dumpDiv2(&$tree, $depth = 0) - { - switch ($tree["CLASS"]) - { - case "SIMPLE": - if (is_array($tree["VALUE"])) - $s = implode(" , ", $tree["VALUE"]); - else - $s = $tree["VALUE"]; - print(str_repeat("\t", $depth) . "" . $s . "\n"); - case "QSIMPLE": - $s = ""; - if (is_array($tree["VALUE"])) - $s = implode(" , ", $tree["VALUE"]); - else - $s = $tree["VALUE"]; - print(str_repeat("\t", $depth) . """ . $s . ""\n"); - break; - case "PHRASEA_KW_ALL": - printf(str_repeat("\t", $depth) . "%s\n", $tree["VALUE"][0]); - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - printf(str_repeat("\t", $depth) . "%s %s\n", $tree["VALUE"][0], $tree["PNUM"]); - else - printf(str_repeat("\t", $depth) . "%s\n", $tree["VALUE"][0]); - break; - // case PHRASEA_KW_FIRST: - // if($tree["PNUM"]!==null) - // printf("%s %s", $tree["VALUE"], $tree["PNUM"]); - // else - // printf("%s", $tree["VALUE"]); - // break; - case "OPS": - case "OPK": - print(str_repeat("\t", $depth) . "
              \n"); - $this->dumpDiv2($tree["LB"], $depth + 1); - print(str_repeat("\t", $depth) . "
              \n"); - print(str_repeat("\t", $depth) . "
              \n"); - if (isset($tree["PNUM"])) - printf(str_repeat("\t", $depth + 1) . " %s[%s]\n", $tree["VALUE"], $tree["PNUM"]); - else - printf(str_repeat("\t", $depth + 1) . " %s\n", $tree["VALUE"]); - print(str_repeat("\t", $depth) . "
              \n"); - print(str_repeat("\t", $depth) . "
              \n"); - $this->dumpDiv2($tree["RB"], $depth + 1); - print(str_repeat("\t", $depth) . "
              \n"); - - break; - } - } - - function dump($tree) - { - switch ($tree["CLASS"]) - { - case "SIMPLE": - if (is_array($tree["VALUE"])) - $s = implode("
              , ", $tree["VALUE"]); - else - $s = $tree["VALUE"]; - print("" . $s . ""); - break; - case "QSIMPLE": - if (is_array($tree["VALUE"])) - $s = implode(" , ", $tree["VALUE"]); - else - $s = $tree["VALUE"]; - print(""" . $s . """); - break; - case "PHRASEA_KW_ALL": - printf("%s", $tree["VALUE"][0]); - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - printf("%s %s", $tree["VALUE"][0], $tree["PNUM"]); - else - printf("%s", $tree["VALUE"][0]); - break; - // case PHRASEA_KW_FIRST: - // if($tree["PNUM"]!==null) - // printf("%s %s", $tree["VALUE"], $tree["PNUM"]); - // else - // printf("%s", $tree["VALUE"]); - // break; - case "OPS": - case "OPK": - print(""); - print(""); - print(""); - print(""); - print(""); - print(""); - print(""); - print(""); - print("
              "); - if (isset($tree["PNUM"])) - printf(" %s[%s] ", $tree["VALUE"], $tree["PNUM"]); - else - printf(" %s ", $tree["VALUE"]); - print("
              "); - print($this->dump($tree["LB"])); - print(""); - print($this->dump($tree["RB"])); - print("
              "); - break; - } - } - - function priority_opk(&$tree, $depth = 0) - { - if (!$tree) - - return; - if ($tree["CLASS"] == "OPK" && ($tree["LB"]["CLASS"] == "OPS" || $tree["LB"]["CLASS"] == "OPK")) - { - // on a un truc du genre ((a ou b) < 5), on le transforme en (a ou (b < 5)) - $t = $tree["LB"]; - $tree["LB"] = $t["RB"]; - $t["RB"] = $tree; - $tree = $t; - } - if (isset($tree["LB"])) - $this->priority_opk($tree["LB"], $depth + 1); - if (isset($tree["RB"])) - $this->priority_opk($tree["RB"], $depth + 1); - } - - function distrib_opk(&$tree, $depth = 0) - { - if (!$tree) - - return; - if ($tree["CLASS"] == "OPK" && ($tree["RB"]["CLASS"] == "OPS")) - { - // on a un truc du genre (a = (5 ou 6)), on le transforme en ((a = 5) ou (a = 6)) - $tmp = array("CLASS" => $tree["CLASS"], - "NODETYPE" => $tree["NODETYPE"], - "VALUE" => $tree["VALUE"], - "PNUM" => $tree["PNUM"], - "LB" => $tree["LB"], - "RB" => $tree["RB"]["RB"], - "DEPTH" => $tree["LB"]["DEPTH"]); - $t = $tree["RB"]; - $tree["RB"] = $t["LB"]; - $t["LB"] = $tree; - $t["RB"] = $tmp; - $tree = $t; - } - if (isset($tree["LB"])) - $this->distrib_opk($tree["LB"], $depth + 1); - if (isset($tree["RB"])) - $this->distrib_opk($tree["RB"], $depth + 1); - } - - function thesaurus2_apply(&$tree, $bid) - { - if (!$tree) - - return; - if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE") && isset($tree["SREF"]) && isset($tree["SREF"]["TIDS"])) - { - $tids = array(); - foreach ($tree["SREF"]["TIDS"] as $tid) - { - if ($tid["bid"] == $bid) - $tids[] = $tid["pid"]; - } - if (count($tids) >= 1) - { - /* - if(count($tids)==1) - { - // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finit par '%') - $val = str_replace(".", "d", $tids[0]) . "d%"; - $tree["VALUE"] = array($val); - } - else - { - // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle méme la syntaxe car la value finit par '$' - $val = ""; - foreach($tids as $tid) - $val .= ($val?"|":"") . "(" . str_replace(".", "d", $tid) . "d.*)"; - $tree["VALUE"] = array("^" . $val); - } - */ - $tree["VALUE"] = array(); - foreach ($tids as $tid) - $tree["VALUE"][] = str_replace(".", "d", $tid) . "d%";; - } - else - { - // le mot n'est pas dans le thesaurus - } - /* - */ - } - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - $this->thesaurus2_apply($tree["LB"], $bid); - $this->thesaurus2_apply($tree["RB"], $bid); - } - } - - // étend (ou remplace) la recherche sur les termes simples en recherche sur thesaurus - // ex: (a et b) - // full-text only : ==> (a et b) - // thesaurus only : ==> ((th:a) et (th:b)) - // ft et thesaurus : ==> ((a ou (th:a)) et (b ou (th:b))) - // RETOURNE l'arbre résultat sans modifier l'arbre d'origine - function extendThesaurusOnTerms(&$tree, $useFullText, $useThesaurus, $keepfuzzy) - { - $copy = $tree; - $this->_extendThesaurusOnTerms($tree, $copy, $useFullText, $useThesaurus, $keepfuzzy, 0, ""); - - $this->proposals["QRY"] = "" . $this->_queryAsHTML($tree) . ""; - - return($copy); - } - - function _extendThesaurusOnTerms(&$tree, &$copy, $useFullText, $useThesaurus, $keepfuzzy, $depth, $path) - { - if ($depth == 0) - $ret = $tree; - if (!$useThesaurus) - - return; // full-text only : inchangé - if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE")) - { - if (isset($tree["CONTEXT"])) - $copy = $this->_extendToThesaurus_Simple($tree, false, $keepfuzzy, $path); - else - $copy = $this->_extendToThesaurus_Simple($tree, $useFullText, $keepfuzzy, $path); - } - else - { - if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON) - { - // on a 'field:value' , on traite 'value' - $tree["RB"]["PATH"] = $copy["RB"]["PATH"] = $path . "R"; - if (isset($tree["RB"]["CONTEXT"])) - $copy["CONTEXT"] = $tree["CONTEXT"] = $tree["RB"]["CONTEXT"]; - else - if (!$keepfuzzy) - $copy["CONTEXT"] = $tree["CONTEXT"] = "*"; - - $copy["RB"]["SREF"] = &$tree["RB"]; - } - else - { - $recursL = $recursR = false; - if ($tree["CLASS"] == "OPS" && ($tree["NODETYPE"] == PHRASEA_OP_AND || $tree["NODETYPE"] == PHRASEA_OP_OR || $tree["NODETYPE"] == PHRASEA_OP_EXCEPT)) - { - // on a une branche à gauche de 'ET', 'OU', 'SAUF' - $recursL = true; - } - if ($tree["CLASS"] == "OPS" && ($tree["NODETYPE"] == PHRASEA_OP_AND || $tree["NODETYPE"] == PHRASEA_OP_OR || $tree["NODETYPE"] == PHRASEA_OP_EXCEPT)) - { - // on a une branche à droite de 'ET', 'OU', 'SAUF' - $recursR = true; - } - if ($recursL) - $this->_extendThesaurusOnTerms($tree["LB"], $copy["LB"], $useFullText, $useThesaurus, $keepfuzzy, $depth + 1, $path . "L"); - if ($recursR) - $this->_extendThesaurusOnTerms($tree["RB"], $copy["RB"], $useFullText, $useThesaurus, $keepfuzzy, $depth + 1, $path . "R"); - } - } - } - - // étend (ou remplace) un terme cherché en 'full-text' à une recherche thesaurus (champ non spécifié, tout le thésaurus = '*') - // le contexte éventuel est rapporté à l'opérateur ':' - // ex : a[k] ==> (a ou (TH :[k] a)) - function _extendToThesaurus_Simple(&$simple, $keepFullText, $keepfuzzy, $path) - { - $simple["PATH"] = $path; - $context = null; - if (isset($simple["CONTEXT"])) - { - $context = $simple["CONTEXT"]; - // unset($simple["CONTEXT"]); - } - if ($keepFullText) - { - // on fait un OU entre la recherche ft et une recherche th - $tmp = array("CLASS" => "OPS", - "NODETYPE" => PHRASEA_OP_OR, - "VALUE" => "OR", - "PNUM" => null, - "DEPTH" => $simple["DEPTH"], - "LB" => $simple, - "RB" => array("CLASS" => "OPK", - "NODETYPE" => PHRASEA_OP_COLON, - "VALUE" => ":", - // "CONTEXT"=>$context, - "PNUM" => null, - "DEPTH" => $simple["DEPTH"] + 1, - "LB" => array("CLASS" => "SIMPLE", - "NODETYPE" => PHRASEA_KEYLIST, - "VALUE" => array("*"), - "DEPTH" => $simple["DEPTH"] + 2 - ), - "RB" => $simple - ) - ); - // on vire le contexte du coté fulltext - unset($tmp["LB"]["CONTEXT"]); - // ajoute le contexte si nécéssaire - if ($context !== null) - $tmp["RB"]["CONTEXT"] = $context; - else - if (!$keepfuzzy) - $tmp["RB"]["CONTEXT"] = "*"; - // corrige les profondeurs des 2 copies du 'simple' d'origine - $tmp["LB"]["DEPTH"] += 1; - $tmp["RB"]["RB"]["DEPTH"] += 2; - // note une référence vers le terme d'origine - $tmp["RB"]["RB"]["SREF"] = &$simple; - $tmp["RB"]["RB"]["PATH"] = $path; - } - else - { - // on remplace le ft par du th - $tmp = array("CLASS" => "OPK", - "NODETYPE" => PHRASEA_OP_COLON, - "VALUE" => ":", - // "CONTEXT"=>$context, - "PNUM" => null, - "DEPTH" => $simple["DEPTH"] + 1, - "LB" => array("CLASS" => "SIMPLE", - "NODETYPE" => PHRASEA_KEYLIST, - "VALUE" => array("*"), - "DEPTH" => $simple["DEPTH"] + 1 + var $ops = array( + "et" => array("NODETYPE" => PHRASEA_OP_AND, "CANNUM" => false), + "and" => array("NODETYPE" => PHRASEA_OP_AND, "CANNUM" => false), + "ou" => array("NODETYPE" => PHRASEA_OP_OR, "CANNUM" => false), + "or" => array("NODETYPE" => PHRASEA_OP_OR, "CANNUM" => false), + "sauf" => array("NODETYPE" => PHRASEA_OP_EXCEPT, "CANNUM" => false), + "except" => array("NODETYPE" => PHRASEA_OP_EXCEPT, "CANNUM" => false), + "pres" => array("NODETYPE" => PHRASEA_OP_NEAR, "CANNUM" => true), + "near" => array("NODETYPE" => PHRASEA_OP_NEAR, "CANNUM" => true), + "avant" => array("NODETYPE" => PHRASEA_OP_BEFORE, "CANNUM" => true), + "before" => array("NODETYPE" => PHRASEA_OP_BEFORE, "CANNUM" => true), + "apres" => array("NODETYPE" => PHRASEA_OP_AFTER, "CANNUM" => true), + "after" => array("NODETYPE" => PHRASEA_OP_AFTER, "CANNUM" => true), + "dans" => array("NODETYPE" => PHRASEA_OP_IN, "CANNUM" => false), + "in" => array("NODETYPE" => PHRASEA_OP_IN, "CANNUM" => false) + ); + var $opk = array( + "<" => array("NODETYPE" => PHRASEA_OP_LT, "CANNUM" => false), + ">" => array("NODETYPE" => PHRASEA_OP_GT, "CANNUM" => false), + "<=" => array("NODETYPE" => PHRASEA_OP_LEQT, "CANNUM" => false), + ">=" => array("NODETYPE" => PHRASEA_OP_GEQT, "CANNUM" => false), + "<>" => array("NODETYPE" => PHRASEA_OP_NOTEQU, "CANNUM" => false), + "=" => array("NODETYPE" => PHRASEA_OP_EQUAL, "CANNUM" => false), + ":" => array("NODETYPE" => PHRASEA_OP_COLON, "CANNUM" => false) + ); + var $spw = array( + "all" => array( + "CLASS" => "PHRASEA_KW_ALL", "NODETYPE" => PHRASEA_KW_ALL, "CANNUM" => false ), - "RB" => $simple - ); - // ajoute le contexte si nécéssaire - if ($context !== null) - $tmp["CONTEXT"] = $context; - else - if (!$keepfuzzy) - $tmp["CONTEXT"] = "*"; - // corrige la profondeur de la copie du 'simple' d'origine - $tmp["RB"]["DEPTH"] += 1; - // note une référence vers le terme d'origine - $tmp["RB"]["SREF"] = &$simple; - $tmp["RB"]["PATH"] = $path; + "last" => array( + "CLASS" => "PHRASEA_KW_LAST", "NODETYPE" => PHRASEA_KW_LAST, "CANNUM" => true + ), + // "first" => array("CLASS"=>PHRASEA_KW_FIRST, "CANNUM"=>true), + // "premiers" => array("CLASS"=>PHRASEA_KW_FIRST, "CANNUM"=>true), + "tout" => array( + "CLASS" => "PHRASEA_KW_ALL", "NODETYPE" => PHRASEA_KW_ALL, "CANNUM" => false + ), + "derniers" => array( + "CLASS" => "PHRASEA_KW_LAST", "NODETYPE" => PHRASEA_KW_LAST, "CANNUM" => true + ) + ); + var $quoted_defaultop = array( + "VALUE" => "default_avant", "NODETYPE" => PHRASEA_OP_BEFORE, "PNUM" => 0 + ); + var $defaultop = array( + "VALUE" => "and", "NODETYPE" => PHRASEA_OP_AND, "PNUM" => NULL + ); + var $defaultlast = 12; + var $phq; + var $errmsg = ""; + + /** + * + * @var boolean + */ + var $debug = false; + + /** + * un tableau qui contiendra des propositions de thesaurus + * pour les termes de l'arbre simple + * + * @var array + */ + var $proposals = Array("QRY" => "", "BASES" => array(), "QUERIES" => array()); + + /** + * Current language for thesaurus + * @var + */ + var $lng = null; + protected $unicode; + + function __construct($lng = "???") + { + $this->lng = $lng; + $this->unicode = new unicode(); + + return $this; } - return($tmp); - } - - function thesaurus2(&$tree, $bid, $name, &$domthe, $searchsynonyms = true, $depth = 0) - { - if ($this->debug) - print("thesaurus2:\n\$tree=" . var_export($tree, true) . "\n"); - - if ($depth == 0) - $this->proposals["BASES"]["b$bid"] = array("BID" => $bid, "NAME" => $name, "TERMS" => array()); - - if (!$tree) - - return(0); - - $ambigus = 0; - if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON) + function mb_trim($s, $encoding) { -// $ambigus = $this->setTids($tree, $tree["RB"], $bid, $domthe, $searchsynonyms); - $ambigus = $this->setTids($tree, $bid, $domthe, $searchsynonyms); - } - elseif ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - $ambigus += $this->thesaurus2($tree["LB"], $bid, $name, $domthe, $searchsynonyms, $depth + 1); - $ambigus += $this->thesaurus2($tree["RB"], $bid, $name, $domthe, $searchsynonyms, $depth + 1); + return(trim($s)); } - return($ambigus); - } - - function propAsHTML(&$node, &$html, $path, $depth = 0) - { - global $parm; - if ($depth > 0) + function mb_ltrim($s, $encoding) { - $tsy = array(); - $lngfound = "?"; - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "sy") - { - $lng = $n->getAttribute("lng"); - if (!array_key_exists($lng, $tsy)) - $tsy[$lng] = array(); - $zsy = array("v" => $n->getAttribute("v"), "w" => $n->getAttribute("w"), "k" => $n->getAttribute("k")); - - if ($lngfound == "?" || ($lng == $this->lng && $lngfound != $lng)) - { - $lngfound = $lng; - $syfound = $zsy; - } - else - { - - } - $tsy[$lng][] = $zsy; - } - } - $alt = ""; - foreach ($tsy as $lng => $tsy2) - { - foreach ($tsy2 as $sy) - { - $alt .= $alt ? "\n" : ""; - $alt .= "" . $lng . ": " . p4string::MakeString($sy["v"], "js"); - } - } - - $this->proposals['QUERIES'][$syfound["w"]] = $syfound["w"]; - - $thtml = $syfound["v"]; - $kjs = $syfound["k"] ? ("'" . p4string::MakeString($syfound["k"], "js") . "'") : "null"; - $wjs = "'" . p4string::MakeString($syfound["w"], "js") . "'"; - - if ($node->getAttribute("term")) - { - $thtml = "" . $thtml . ""; - $node->removeAttribute("term"); - } - - $tab = str_repeat("\t", $depth); - $html .= $tab . "
              \n"; - $html .= $tab . "\t" . $thtml . "\n"; + return(ltrim($s)); } - $tsort = array(); - for ($n = $node->firstChild; $n; $n = $n->nextSibling) + function parsequery($phq) { - if ($n->nodeType == XML_ELEMENT_NODE && $n->getAttribute("marked")) // only 'te' marked - { - $lngfound = '?'; - $syfound = '?'; - for ($n2 = $n->firstChild; $n2; $n2 = $n2->nextSibling) - { - if ($n2->nodeName == 'sy') - { - $lng = $n2->getAttribute('lng'); - if ($lngfound == "?" || ($lng == $this->lng && $lngfound != $lng)) - { - $lngfound = $lng; - $syfound = $n2->getAttribute('w'); + if ($this->debug) { + for ($i = 0; $i < mb_strlen($phq, 'UTF-8'); $i ++ ) { + $c = mb_substr($phq, $i, 1, 'UTF-8'); + printf("// %s : '%s' (%d octets)\n", $i, $c, strlen($c)); } - } } - $n->removeAttribute("marked"); - for ($i = 0; array_key_exists($syfound . $i, $tsort) && $i < 9999; $i++) - ; - $tsort[$syfound . $i] = $n; - } - } - ksort($tsort); - foreach ($tsort as $n) - { - $this->propAsHTML($n, $html, $path, $depth + 1); + $this->proposals = Array("QRY" => "", "BASES" => array(), "QUERIES" => array()); + $this->phq = $this->mb_trim($phq, 'UTF-8'); + if ($this->phq != "") + return($this->maketree(0)); + else { + if ($this->errmsg != "") + $this->errmsg .= sprintf("\\n"); + $this->errmsg .= _('qparser::la question est vide'); + + return(null); + } } - if ($depth > 0) - $html .= $tab . "
              \n"; - } - - function _queryAsHTML($tree, $depth = 0) - { - if ($depth == 0) + function astext($tree) { - $ambiguites = array("n" => 0, "refs" => array()); + switch ($tree["CLASS"]) { + case "SIMPLE": + if (is_array($tree["VALUE"])) + return(implode(" ", $tree["VALUE"])); + else + return($tree["VALUE"]); + break; + case "QSIMPLE": + if (is_array($tree["VALUE"])) + return("\"" . implode(" ", $tree["VALUE"]) . "\""); + else + return("\"" . $tree["VALUE"] . "\""); + break; + case "PHRASEA_KW_ALL": + return($tree["VALUE"][0]); + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); + else + return($tree["VALUE"][0]); + break; + case "OPS": + case "OPK": + if (isset($tree["PNUM"])) + return("(" . $this->astext($tree["LB"]) . " " . $tree["VALUE"] . "[" . $tree["PNUM"] . "] " . $this->astext($tree["RB"]) . ")"); + else + return("(" . $this->astext($tree["LB"]) . " " . $tree["VALUE"] . " " . $this->astext($tree["RB"]) . ")"); + break; + } } - switch ($tree["CLASS"]) + + function astable(&$tree) { - case "SIMPLE": - case "QSIMPLE": - $w = is_array($tree["VALUE"]) ? implode(' ', $tree["VALUE"]) : $tree["VALUE"]; - if (isset($tree["PATH"])) - { - $path = $tree["PATH"]; - if (isset($tree["CONTEXT"])) - $w .= ' [' . $tree["CONTEXT"] . ']'; - $txt = '"' . $w . '"'; - } - else - { - if (isset($tree["CONTEXT"])) - $w .= '[' . $tree["CONTEXT"] . ']'; - if ($tree["CLASS"] == "QSIMPLE") - $txt = '"' . $w . '"'; - else - $txt = $w; - } + $this->calc_complexity($tree); + $txt = ""; + $this->astable2($txt, $tree); + $txt = "\n\n" . $txt . "\n
              \n"; return($txt); - break; - case "PHRASEA_KW_ALL": - return($tree["VALUE"][0]); - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - - return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); - else - - return($tree["VALUE"][0]); - break; - case "OPS": - case "OPK": - if (isset($tree["PNUM"])) - - return('(' . $this->_queryAsHTML($tree["LB"], $depth + 1) . ' ' . $tree["VALUE"] . '[' . $tree["PNUM"] . '] ' . $this->_queryAsHTML($tree["RB"], $depth + 1) . ')'); - else - - return('(' . $this->_queryAsHTML($tree["LB"], $depth + 1) . ' ' . $tree["VALUE"] . ' ' . $this->_queryAsHTML($tree["RB"], $depth + 1) . ')'); - break; } - } - function setTids(&$tree, $bid, &$domthe, $searchsynonyms) - { - if ($this->debug) - print("============================ setTids:\n\$tree=" . var_export($tree, true) . "\n"); - - // $this->proposals["BASES"]["b$bid"] = array("BID"=>$bid, "TERMS"=>array()); - - $ambigus = 0; - if (is_array($w = $tree["RB"]["VALUE"])) - $t = $w = implode(" ", $w); - - if (isset($tree["CONTEXT"])) + function calc_complexity(&$tree) { - if (!$tree["CONTEXT"]) + if ($tree) { + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") + return($tree["COMPLEXITY"] = $this->calc_complexity($tree["LB"]) + $this->calc_complexity($tree["RB"])); + else + return($tree["COMPLEXITY"] = 1); + } + } + + function astable2(&$out, &$tree, $depth = 0) + { + switch ($tree["CLASS"]) { + case "SIMPLE": + if (is_array($tree["VALUE"])) + $txt = implode(" ", $tree["VALUE"]); + else + $txt = $tree["VALUE"]; + $out .= "\t" . $txt . "\n"; + break; + case "QSIMPLE": + if (is_array($tree["VALUE"])) + $txt = implode(" ", $tree["VALUE"]); + else + $txt = $tree["VALUE"]; + $out .= "\t"" . $txt . ""\n"; + break; + case "PHRASEA_KW_ALL": + $out .= "\t" . $tree["VALUE"][0] . "\n"; + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + $out .= "\t" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]" . "\n"; + else + $out .= "\t" . $tree["VALUE"][0] . "\n"; + break; + case "OPS": + case "OPK": + $op = $tree["VALUE"]; + if (isset($tree["PNUM"])) + $op .= "[" . $tree["PNUM"] . "]"; + $out .= "\t$op\n"; + $this->astable2($out, $tree["LB"], $depth + 1); + $this->astable2($out, $tree["RB"], $depth + 1); + $out .= "\n\n"; + break; + } + } + + function dumpDiv(&$tree) + { + print("
              \n"); + $this->dumpDiv2($tree); + print("
              \n"); + } + + function dumpDiv2(&$tree, $depth = 0) + { + switch ($tree["CLASS"]) { + case "SIMPLE": + if (is_array($tree["VALUE"])) + $s = implode("
              , ", $tree["VALUE"]); + else + $s = $tree["VALUE"]; + print(str_repeat("\t", $depth) . "" . $s . "\n"); + case "QSIMPLE": + $s = ""; + if (is_array($tree["VALUE"])) + $s = implode(" , ", $tree["VALUE"]); + else + $s = $tree["VALUE"]; + print(str_repeat("\t", $depth) . """ . $s . ""\n"); + break; + case "PHRASEA_KW_ALL": + printf(str_repeat("\t", $depth) . "%s\n", $tree["VALUE"][0]); + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + printf(str_repeat("\t", $depth) . "%s %s\n", $tree["VALUE"][0], $tree["PNUM"]); + else + printf(str_repeat("\t", $depth) . "%s\n", $tree["VALUE"][0]); + break; + // case PHRASEA_KW_FIRST: + // if($tree["PNUM"]!==null) + // printf("%s %s", $tree["VALUE"], $tree["PNUM"]); + // else + // printf("%s", $tree["VALUE"]); + // break; + case "OPS": + case "OPK": + print(str_repeat("\t", $depth) . "
              \n"); + $this->dumpDiv2($tree["LB"], $depth + 1); + print(str_repeat("\t", $depth) . "
              \n"); + print(str_repeat("\t", $depth) . "
              \n"); + if (isset($tree["PNUM"])) + printf(str_repeat("\t", $depth + 1) . " %s[%s]\n", $tree["VALUE"], $tree["PNUM"]); + else + printf(str_repeat("\t", $depth + 1) . " %s\n", $tree["VALUE"]); + print(str_repeat("\t", $depth) . "
              \n"); + print(str_repeat("\t", $depth) . "
              \n"); + $this->dumpDiv2($tree["RB"], $depth + 1); + print(str_repeat("\t", $depth) . "
              \n"); + + break; + } + } + + function dump($tree) + { + switch ($tree["CLASS"]) { + case "SIMPLE": + if (is_array($tree["VALUE"])) + $s = implode("
              , ", $tree["VALUE"]); + else + $s = $tree["VALUE"]; + print("" . $s . ""); + break; + case "QSIMPLE": + if (is_array($tree["VALUE"])) + $s = implode(" , ", $tree["VALUE"]); + else + $s = $tree["VALUE"]; + print(""" . $s . """); + break; + case "PHRASEA_KW_ALL": + printf("%s", $tree["VALUE"][0]); + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + printf("%s %s", $tree["VALUE"][0], $tree["PNUM"]); + else + printf("%s", $tree["VALUE"][0]); + break; + // case PHRASEA_KW_FIRST: + // if($tree["PNUM"]!==null) + // printf("%s %s", $tree["VALUE"], $tree["PNUM"]); + // else + // printf("%s", $tree["VALUE"]); + // break; + case "OPS": + case "OPK": + print(""); + print(""); + print(""); + print(""); + print(""); + print(""); + print(""); + print(""); + print("
              "); + if (isset($tree["PNUM"])) + printf(" %s[%s] ", $tree["VALUE"], $tree["PNUM"]); + else + printf(" %s ", $tree["VALUE"]); + print("
              "); + print($this->dump($tree["LB"])); + print(""); + print($this->dump($tree["RB"])); + print("
              "); + break; + } + } + + function priority_opk(&$tree, $depth = 0) + { + if ( ! $tree) + return; + if ($tree["CLASS"] == "OPK" && ($tree["LB"]["CLASS"] == "OPS" || $tree["LB"]["CLASS"] == "OPK")) { + // on a un truc du genre ((a ou b) < 5), on le transforme en (a ou (b < 5)) + $t = $tree["LB"]; + $tree["LB"] = $t["RB"]; + $t["RB"] = $tree; + $tree = $t; + } + if (isset($tree["LB"])) + $this->priority_opk($tree["LB"], $depth + 1); + if (isset($tree["RB"])) + $this->priority_opk($tree["RB"], $depth + 1); + } + + function distrib_opk(&$tree, $depth = 0) + { + if ( ! $tree) + return; + if ($tree["CLASS"] == "OPK" && ($tree["RB"]["CLASS"] == "OPS")) { + // on a un truc du genre (a = (5 ou 6)), on le transforme en ((a = 5) ou (a = 6)) + $tmp = array("CLASS" => $tree["CLASS"], + "NODETYPE" => $tree["NODETYPE"], + "VALUE" => $tree["VALUE"], + "PNUM" => $tree["PNUM"], + "LB" => $tree["LB"], + "RB" => $tree["RB"]["RB"], + "DEPTH" => $tree["LB"]["DEPTH"]); + $t = $tree["RB"]; + $tree["RB"] = $t["LB"]; + $t["LB"] = $tree; + $t["RB"] = $tmp; + $tree = $t; + } + if (isset($tree["LB"])) + $this->distrib_opk($tree["LB"], $depth + 1); + if (isset($tree["RB"])) + $this->distrib_opk($tree["RB"], $depth + 1); + } + + function thesaurus2_apply(&$tree, $bid) + { + if ( ! $tree) + return; + if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE") && isset($tree["SREF"]) && isset($tree["SREF"]["TIDS"])) { + $tids = array(); + foreach ($tree["SREF"]["TIDS"] as $tid) { + if ($tid["bid"] == $bid) + $tids[] = $tid["pid"]; + } + if (count($tids) >= 1) { + /* + if(count($tids)==1) + { + // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finit par '%') + $val = str_replace(".", "d", $tids[0]) . "d%"; + $tree["VALUE"] = array($val); + } + else + { + // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle méme la syntaxe car la value finit par '$' + $val = ""; + foreach($tids as $tid) + $val .= ($val?"|":"") . "(" . str_replace(".", "d", $tid) . "d.*)"; + $tree["VALUE"] = array("^" . $val); + } + */ + $tree["VALUE"] = array(); + foreach ($tids as $tid) + $tree["VALUE"][] = str_replace(".", "d", $tid) . "d%";; + } else { + // le mot n'est pas dans le thesaurus + } + /* + */ + } + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + $this->thesaurus2_apply($tree["LB"], $bid); + $this->thesaurus2_apply($tree["RB"], $bid); + } + } + + // étend (ou remplace) la recherche sur les termes simples en recherche sur thesaurus + // ex: (a et b) + // full-text only : ==> (a et b) + // thesaurus only : ==> ((th:a) et (th:b)) + // ft et thesaurus : ==> ((a ou (th:a)) et (b ou (th:b))) + // RETOURNE l'arbre résultat sans modifier l'arbre d'origine + function extendThesaurusOnTerms(&$tree, $useFullText, $useThesaurus, $keepfuzzy) + { + $copy = $tree; + $this->_extendThesaurusOnTerms($tree, $copy, $useFullText, $useThesaurus, $keepfuzzy, 0, ""); + + $this->proposals["QRY"] = "" . $this->_queryAsHTML($tree) . ""; + + return($copy); + } + + function _extendThesaurusOnTerms(&$tree, &$copy, $useFullText, $useThesaurus, $keepfuzzy, $depth, $path) + { + if ($depth == 0) + $ret = $tree; + if ( ! $useThesaurus) + return; // full-text only : inchangé + if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE")) { + if (isset($tree["CONTEXT"])) + $copy = $this->_extendToThesaurus_Simple($tree, false, $keepfuzzy, $path); + else + $copy = $this->_extendToThesaurus_Simple($tree, $useFullText, $keepfuzzy, $path); + } + else { + if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON) { + // on a 'field:value' , on traite 'value' + $tree["RB"]["PATH"] = $copy["RB"]["PATH"] = $path . "R"; + if (isset($tree["RB"]["CONTEXT"])) + $copy["CONTEXT"] = $tree["CONTEXT"] = $tree["RB"]["CONTEXT"]; + else + if ( ! $keepfuzzy) + $copy["CONTEXT"] = $tree["CONTEXT"] = "*"; + + $copy["RB"]["SREF"] = &$tree["RB"]; + } + else { + $recursL = $recursR = false; + if ($tree["CLASS"] == "OPS" && ($tree["NODETYPE"] == PHRASEA_OP_AND || $tree["NODETYPE"] == PHRASEA_OP_OR || $tree["NODETYPE"] == PHRASEA_OP_EXCEPT)) { + // on a une branche à gauche de 'ET', 'OU', 'SAUF' + $recursL = true; + } + if ($tree["CLASS"] == "OPS" && ($tree["NODETYPE"] == PHRASEA_OP_AND || $tree["NODETYPE"] == PHRASEA_OP_OR || $tree["NODETYPE"] == PHRASEA_OP_EXCEPT)) { + // on a une branche à droite de 'ET', 'OU', 'SAUF' + $recursR = true; + } + if ($recursL) + $this->_extendThesaurusOnTerms($tree["LB"], $copy["LB"], $useFullText, $useThesaurus, $keepfuzzy, $depth + 1, $path . "L"); + if ($recursR) + $this->_extendThesaurusOnTerms($tree["RB"], $copy["RB"], $useFullText, $useThesaurus, $keepfuzzy, $depth + 1, $path . "R"); + } + } + } + + // étend (ou remplace) un terme cherché en 'full-text' à une recherche thesaurus (champ non spécifié, tout le thésaurus = '*') + // le contexte éventuel est rapporté à l'opérateur ':' + // ex : a[k] ==> (a ou (TH :[k] a)) + function _extendToThesaurus_Simple(&$simple, $keepFullText, $keepfuzzy, $path) + { + $simple["PATH"] = $path; + $context = null; + if (isset($simple["CONTEXT"])) { + $context = $simple["CONTEXT"]; + // unset($simple["CONTEXT"]); + } + if ($keepFullText) { + // on fait un OU entre la recherche ft et une recherche th + $tmp = array("CLASS" => "OPS", + "NODETYPE" => PHRASEA_OP_OR, + "VALUE" => "OR", + "PNUM" => null, + "DEPTH" => $simple["DEPTH"], + "LB" => $simple, + "RB" => array("CLASS" => "OPK", + "NODETYPE" => PHRASEA_OP_COLON, + "VALUE" => ":", + // "CONTEXT"=>$context, + "PNUM" => null, + "DEPTH" => $simple["DEPTH"] + 1, + "LB" => array("CLASS" => "SIMPLE", + "NODETYPE" => PHRASEA_KEYLIST, + "VALUE" => array("*"), + "DEPTH" => $simple["DEPTH"] + 2 + ), + "RB" => $simple + ) + ); + // on vire le contexte du coté fulltext + unset($tmp["LB"]["CONTEXT"]); + // ajoute le contexte si nécéssaire + if ($context !== null) + $tmp["RB"]["CONTEXT"] = $context; + else + if ( ! $keepfuzzy) + $tmp["RB"]["CONTEXT"] = "*"; + // corrige les profondeurs des 2 copies du 'simple' d'origine + $tmp["LB"]["DEPTH"] += 1; + $tmp["RB"]["RB"]["DEPTH"] += 2; + // note une référence vers le terme d'origine + $tmp["RB"]["RB"]["SREF"] = &$simple; + $tmp["RB"]["RB"]["PATH"] = $path; + } + else { + // on remplace le ft par du th + $tmp = array("CLASS" => "OPK", + "NODETYPE" => PHRASEA_OP_COLON, + "VALUE" => ":", + // "CONTEXT"=>$context, + "PNUM" => null, + "DEPTH" => $simple["DEPTH"] + 1, + "LB" => array("CLASS" => "SIMPLE", + "NODETYPE" => PHRASEA_KEYLIST, + "VALUE" => array("*"), + "DEPTH" => $simple["DEPTH"] + 1 + ), + "RB" => $simple + ); + // ajoute le contexte si nécéssaire + if ($context !== null) + $tmp["CONTEXT"] = $context; + else + if ( ! $keepfuzzy) + $tmp["CONTEXT"] = "*"; + // corrige la profondeur de la copie du 'simple' d'origine + $tmp["RB"]["DEPTH"] += 1; + // note une référence vers le terme d'origine + $tmp["RB"]["SREF"] = &$simple; + $tmp["RB"]["PATH"] = $path; + } + + return($tmp); + } + + function thesaurus2(&$tree, $bid, $name, &$domthe, $searchsynonyms = true, $depth = 0) + { + if ($this->debug) + print("thesaurus2:\n\$tree=" . var_export($tree, true) . "\n"); + + if ($depth == 0) + $this->proposals["BASES"]["b$bid"] = array("BID" => $bid, "NAME" => $name, "TERMS" => array()); + + if ( ! $tree) + return(0); + + $ambigus = 0; + if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON) { +// $ambigus = $this->setTids($tree, $tree["RB"], $bid, $domthe, $searchsynonyms); + $ambigus = $this->setTids($tree, $bid, $domthe, $searchsynonyms); + } elseif ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + $ambigus += $this->thesaurus2($tree["LB"], $bid, $name, $domthe, $searchsynonyms, $depth + 1); + $ambigus += $this->thesaurus2($tree["RB"], $bid, $name, $domthe, $searchsynonyms, $depth + 1); + } + + return($ambigus); + } + + function propAsHTML(&$node, &$html, $path, $depth = 0) + { + global $parm; + if ($depth > 0) { + $tsy = array(); + $lngfound = "?"; + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "sy") { + $lng = $n->getAttribute("lng"); + if ( ! array_key_exists($lng, $tsy)) + $tsy[$lng] = array(); + $zsy = array("v" => $n->getAttribute("v"), "w" => $n->getAttribute("w"), "k" => $n->getAttribute("k")); + + if ($lngfound == "?" || ($lng == $this->lng && $lngfound != $lng)) { + $lngfound = $lng; + $syfound = $zsy; + } else { + + } + $tsy[$lng][] = $zsy; + } + } + $alt = ""; + foreach ($tsy as $lng => $tsy2) { + foreach ($tsy2 as $sy) { + $alt .= $alt ? "\n" : ""; + $alt .= "" . $lng . ": " . p4string::MakeString($sy["v"], "js"); + } + } + + $this->proposals['QUERIES'][$syfound["w"]] = $syfound["w"]; + + $thtml = $syfound["v"]; + $kjs = $syfound["k"] ? ("'" . p4string::MakeString($syfound["k"], "js") . "'") : "null"; + $wjs = "'" . p4string::MakeString($syfound["w"], "js") . "'"; + + if ($node->getAttribute("term")) { + $thtml = "" . $thtml . ""; + $node->removeAttribute("term"); + } + + $tab = str_repeat("\t", $depth); + $html .= $tab . "
              \n"; + $html .= $tab . "\t" . $thtml . "\n"; + } + + $tsort = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeType == XML_ELEMENT_NODE && $n->getAttribute("marked")) { // only 'te' marked + $lngfound = '?'; + $syfound = '?'; + for ($n2 = $n->firstChild; $n2; $n2 = $n2->nextSibling) { + if ($n2->nodeName == 'sy') { + $lng = $n2->getAttribute('lng'); + if ($lngfound == "?" || ($lng == $this->lng && $lngfound != $lng)) { + $lngfound = $lng; + $syfound = $n2->getAttribute('w'); + } + } + } + $n->removeAttribute("marked"); + for ($i = 0; array_key_exists($syfound . $i, $tsort) && $i < 9999; $i ++ ) + ; + $tsort[$syfound . $i] = $n; + } + } + ksort($tsort); + + foreach ($tsort as $n) { + $this->propAsHTML($n, $html, $path, $depth + 1); + } + + if ($depth > 0) + $html .= $tab . "
              \n"; + } + + function _queryAsHTML($tree, $depth = 0) + { + if ($depth == 0) { + $ambiguites = array("n" => 0, "refs" => array()); + } + switch ($tree["CLASS"]) { + case "SIMPLE": + case "QSIMPLE": + $w = is_array($tree["VALUE"]) ? implode(' ', $tree["VALUE"]) : $tree["VALUE"]; + if (isset($tree["PATH"])) { + $path = $tree["PATH"]; + if (isset($tree["CONTEXT"])) + $w .= ' [' . $tree["CONTEXT"] . ']'; + $txt = '"' . $w . '"'; + } + else { + if (isset($tree["CONTEXT"])) + $w .= '[' . $tree["CONTEXT"] . ']'; + if ($tree["CLASS"] == "QSIMPLE") + $txt = '"' . $w . '"'; + else + $txt = $w; + } + + return($txt); + break; + case "PHRASEA_KW_ALL": + return($tree["VALUE"][0]); + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); + else + return($tree["VALUE"][0]); + break; + case "OPS": + case "OPK": + if (isset($tree["PNUM"])) + return('(' . $this->_queryAsHTML($tree["LB"], $depth + 1) . ' ' . $tree["VALUE"] . '[' . $tree["PNUM"] . '] ' . $this->_queryAsHTML($tree["RB"], $depth + 1) . ')'); + else + return('(' . $this->_queryAsHTML($tree["LB"], $depth + 1) . ' ' . $tree["VALUE"] . ' ' . $this->_queryAsHTML($tree["RB"], $depth + 1) . ')'); + break; + } + } + + function setTids(&$tree, $bid, &$domthe, $searchsynonyms) + { + if ($this->debug) + print("============================ setTids:\n\$tree=" . var_export($tree, true) . "\n"); + + // $this->proposals["BASES"]["b$bid"] = array("BID"=>$bid, "TERMS"=>array()); + + $ambigus = 0; + if (is_array($w = $tree["RB"]["VALUE"])) + $t = $w = implode(" ", $w); + + if (isset($tree["CONTEXT"])) { + if ( ! $tree["CONTEXT"]) { + $x0 = "@w=\"" . $w . "\" and not(@k)"; + } else { + if ($tree["CONTEXT"] == "*") { + $x0 = "@w=\"" . $w . "\""; + } else { + $x0 = "@w=\"" . $w . "\" and @k=\"" . $tree["CONTEXT"] . "\""; + $t .= " (" . $tree["CONTEXT"] . ")"; + } + } + } else { + $x0 = "@w=\"" . $w . "\""; + } + + $x = "/thesaurus//sy[" . $x0 . "]"; + + if ($this->debug) + printf("searching thesaurus with xpath='%s'
              \n", $x); + + $dxp = new DOMXPath($domthe); + $nodes = $dxp->query($x); + + if ( ! isset($tree["RB"]["SREF"]["TIDS"])) + $tree["RB"]["SREF"]["TIDS"] = array(); + if ($nodes->length >= 1) { + if ($nodes->length == 1) { + // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finira par '%') + $this->addtoTIDS($tree["RB"], $bid, $nodes->item(0)); + // $this->thesaurusDOMNodes[] = $nodes->item(0); + } else { + // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle meme la syntaxe car la value finira par '$') + $val = ""; + foreach ($nodes as $node) { + if ( ! isset($tree["CONTEXT"])) + $ambigus ++; + $this->addtoTIDS($tree["RB"], $bid, $node); + } + } + $path = $tree["RB"]["SREF"]["PATH"]; + $prophtml = ""; + $this->propAsHTML($domthe->documentElement, $prophtml, $path); + $this->proposals["BASES"]["b$bid"]["TERMS"][$path]["HTML"] = $prophtml; + } + else { + // le mot n'est pas dans le thesaurus + } + + return($ambigus); + } + /* + function dead_setTids(&$tree, &$simple, $bid, &$domthe, $searchsynonyms) { - $x0 = "@w=\"" . $w . "\" and not(@k)"; + // if($this->debug) + print("setTids:\n\$tree=" . var_export($tree, true) . "\n"); + + $ambigus = 0; + if(is_array($w = $simple["VALUE"])) + $t = $w = implode(" ", $w); + + if(isset($tree["CONTEXT"])) + { + if(!$tree["CONTEXT"]) + { + $x0 = "@w=\"" . $w ."\" and not(@k)"; } else { - if ($tree["CONTEXT"] == "*") - { - $x0 = "@w=\"" . $w . "\""; - } - else - { - $x0 = "@w=\"" . $w . "\" and @k=\"" . $tree["CONTEXT"] . "\""; - $t .= " (" . $tree["CONTEXT"] . ")"; - } + if($tree["CONTEXT"]=="*") + { + $x0 = "@w=\"" . $w ."\""; + } + else + { + $x0 = "@w=\"" . $w ."\" and @k=\"" . $tree["CONTEXT"] . "\""; + $t .= " (" . $tree["CONTEXT"] . ")"; + } + } + } + else + { + $x0 = "@w=\"" . $w ."\""; } - } - else - { - $x0 = "@w=\"" . $w . "\""; - } - $x = "/thesaurus//sy[" . $x0 . "]"; + $x = "/thesaurus//sy[" . $x0 ."]"; - if ($this->debug) + if($this->debug) printf("searching thesaurus with xpath='%s'
              \n", $x); - $dxp = new DOMXPath($domthe); - $nodes = $dxp->query($x); + $dxp = new DOMXPath($domthe); + $nodes = $dxp->query($x); - if (!isset($tree["RB"]["SREF"]["TIDS"])) + if(!isset($tree["RB"]["SREF"]["TIDS"])) $tree["RB"]["SREF"]["TIDS"] = array(); - if ($nodes->length >= 1) - { - if ($nodes->length == 1) + if($nodes->length >= 1) { - // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finira par '%') - $this->addtoTIDS($tree["RB"], $bid, $nodes->item(0)); - // $this->thesaurusDOMNodes[] = $nodes->item(0); + if($nodes->length == 1) + { + // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finira par '%') + $this->addtoTIDS($tree["RB"], $bid, $nodes->item(0)); + // $this->thesaurusDOMNodes[] = $nodes->item(0); } else { - // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle meme la syntaxe car la value finira par '$') - $val = ""; - foreach ($nodes as $node) - { - if (!isset($tree["CONTEXT"])) - $ambigus++; - $this->addtoTIDS($tree["RB"], $bid, $node); - } + // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle meme la syntaxe car la value finira par '$') + $val = ""; + foreach($nodes as $node) + { + if(!isset($tree["CONTEXT"])) + $ambigus++; + $this->addtoTIDS($tree["RB"], $bid, $node); } - $path = $tree["RB"]["SREF"]["PATH"]; + } + $path = $tree["RB"]["SREF"]["PATH"]; $prophtml = ""; $this->propAsHTML($domthe->documentElement, $prophtml, $path); - $this->proposals["BASES"]["b$bid"]["TERMS"][$path]["HTML"] = $prophtml; - } - else - { - // le mot n'est pas dans le thesaurus - } - - return($ambigus); - } - - /* - function dead_setTids(&$tree, &$simple, $bid, &$domthe, $searchsynonyms) - { - // if($this->debug) - print("setTids:\n\$tree=" . var_export($tree, true) . "\n"); - - $ambigus = 0; - if(is_array($w = $simple["VALUE"])) - $t = $w = implode(" ", $w); - - if(isset($tree["CONTEXT"])) - { - if(!$tree["CONTEXT"]) - { - $x0 = "@w=\"" . $w ."\" and not(@k)"; - } - else - { - if($tree["CONTEXT"]=="*") - { - $x0 = "@w=\"" . $w ."\""; - } - else - { - $x0 = "@w=\"" . $w ."\" and @k=\"" . $tree["CONTEXT"] . "\""; - $t .= " (" . $tree["CONTEXT"] . ")"; - } - } - } - else - { - $x0 = "@w=\"" . $w ."\""; - } - - $x = "/thesaurus//sy[" . $x0 ."]"; - - if($this->debug) - printf("searching thesaurus with xpath='%s'
              \n", $x); - - $dxp = new DOMXPath($domthe); - $nodes = $dxp->query($x); - - if(!isset($tree["RB"]["SREF"]["TIDS"])) - $tree["RB"]["SREF"]["TIDS"] = array(); - if($nodes->length >= 1) - { - if($nodes->length == 1) - { - // on cherche un id simple, on utilisera la syntaxe sql 'like' (l'extension repérera elle méme la syntaxe car la value finira par '%') - $this->addtoTIDS($tree["RB"], $bid, $nodes->item(0)); - // $this->thesaurusDOMNodes[] = $nodes->item(0); - } - else - { - // on cherche plusieurs id's, on utilisera la syntaxe 'regexp' (l'extension repérera elle meme la syntaxe car la value finira par '$') - $val = ""; - foreach($nodes as $node) - { - if(!isset($tree["CONTEXT"])) - $ambigus++; - $this->addtoTIDS($tree["RB"], $bid, $node); - } - } - $path = $tree["RB"]["SREF"]["PATH"]; - $prophtml = ""; - $this->propAsHTML($domthe->documentElement, $prophtml, $path); - $this->proposals["TERMS"][$path]["HTML"] = $prophtml; - } - else - { - // le mot n'est pas dans le thesaurus - } - - return($ambigus); - } - */ - - function containsColonOperator(&$tree) - { - if (!$tree) - - return(false); - if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE")) - - return(true); - $ret = false; - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - $ret |= $this->containsColonOperator($tree["LB"]); - $ret |= $this->containsColonOperator($tree["RB"]); - } - - return($ret); - } - - function addtoTIDS(&$extendednode, $bid, $DOMnode) // ajoute un tid en évitant les doublons - { - $id = $DOMnode->getAttribute("id"); - $pid = $DOMnode->parentNode->getAttribute("id"); - $lng = $DOMnode->getAttribute("lng"); - $w = $DOMnode->getAttribute("w"); - $k = $DOMnode->getAttribute("k"); - $p = $DOMnode->parentNode->getAttribute("v"); // le terme général (pére) du terme recherché : utile pour la levée d'ambiguité - - $path = $extendednode["SREF"]["PATH"]; - if ($this->debug) - printf("found node id='%s', v='%s' w='%s', k='%s', p='%s' for node-path=%s \n", $id, $DOMnode->getAttribute("v"), $w, $k, $p, $path); - - if (!$k) - $k = null; - - $found = false; - foreach ($extendednode["SREF"]["TIDS"] as $ztid) - { - if ($ztid["bid"] != $bid) - continue; - if ($ztid["pid"] == $pid) - { - $found = true; + $this->proposals["TERMS"][$path]["HTML"] = $prophtml; } else { + // le mot n'est pas dans le thesaurus + } + + return($ambigus); + } + */ + + function containsColonOperator(&$tree) + { + if ( ! $tree) + return(false); + if ($tree["CLASS"] == "OPK" && $tree["NODETYPE"] == PHRASEA_OP_COLON && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE")) + return(true); + $ret = false; + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + $ret |= $this->containsColonOperator($tree["LB"]); + $ret |= $this->containsColonOperator($tree["RB"]); + } + + return($ret); + } + + function addtoTIDS(&$extendednode, $bid, $DOMnode) // ajoute un tid en évitant les doublons + { + $id = $DOMnode->getAttribute("id"); + $pid = $DOMnode->parentNode->getAttribute("id"); + $lng = $DOMnode->getAttribute("lng"); + $w = $DOMnode->getAttribute("w"); + $k = $DOMnode->getAttribute("k"); + $p = $DOMnode->parentNode->getAttribute("v"); // le terme général (pére) du terme recherché : utile pour la levée d'ambiguité + + $path = $extendednode["SREF"]["PATH"]; + if ($this->debug) + printf("found node id='%s', v='%s' w='%s', k='%s', p='%s' for node-path=%s \n", $id, $DOMnode->getAttribute("v"), $w, $k, $p, $path); + + if ( ! $k) + $k = null; + + $found = false; + foreach ($extendednode["SREF"]["TIDS"] as $ztid) { + if ($ztid["bid"] != $bid) + continue; + if ($ztid["pid"] == $pid) { + $found = true; + } else { // if($ztid["w"]==$w && $ztid["k"]==$k && $ztid["lng"]==$lng) // { // // FATAL : il y a un doublon réel dans le thesaurus de cette base (méme terme, méme contexte) @@ -975,1222 +884,1068 @@ class searchEngine_adapter_phrasea_queryParser // $found = true; // break; // } - } - } - if (!$found) - $extendednode["SREF"]["TIDS"][] = array("bid" => $bid, "pid" => $pid, "id" => $id, "w" => $w, "k" => $k, "lng" => $lng, "p" => $p); + } + } + if ( ! $found) + $extendednode["SREF"]["TIDS"][] = array("bid" => $bid, "pid" => $pid, "id" => $id, "w" => $w, "k" => $k, "lng" => $lng, "p" => $p); - // on liste les propositions de thésaurus pour ce node (dans l'arbre simple) - if (!isset($this->proposals["BASES"]["b$bid"]["TERMS"][$path])) - { - // $this->proposals["TERMS"][$path] = array("TERM"=>implode(" ", $extendednode["VALUE"]), "PROPOSALS"=>array()); - $term = implode(" ", $extendednode["VALUE"]); - if (isset($extendednode["CONTEXT"]) && $extendednode["CONTEXT"]) - { - $term .= " (" . $extendednode["CONTEXT"] . ")"; - } - $this->proposals["BASES"]["b$bid"]["TERMS"][$path] = array("TERM" => $term); // , "PROPOSALS"=>array() ); //, "PROPOSALS_TREE"=>new DOMDocument("1.0", "UTF-8")); - } + // on liste les propositions de thésaurus pour ce node (dans l'arbre simple) + if ( ! isset($this->proposals["BASES"]["b$bid"]["TERMS"][$path])) { + // $this->proposals["TERMS"][$path] = array("TERM"=>implode(" ", $extendednode["VALUE"]), "PROPOSALS"=>array()); + $term = implode(" ", $extendednode["VALUE"]); + if (isset($extendednode["CONTEXT"]) && $extendednode["CONTEXT"]) { + $term .= " (" . $extendednode["CONTEXT"] . ")"; + } + $this->proposals["BASES"]["b$bid"]["TERMS"][$path] = array("TERM" => $term); // , "PROPOSALS"=>array() ); //, "PROPOSALS_TREE"=>new DOMDocument("1.0", "UTF-8")); + } // printf("<%s id='%s'>
              \n", $DOMnode->tagName, $DOMnode->getAttribute("id")); // printf("found node <%s id='%s' w='%s' k='%s'>
              \n", $DOMnode->nodeName, $DOMnode->getAttribute('id'), $DOMnode->getAttribute('w'), $DOMnode->getAttribute('k')); - // on marque le terme principal - $DOMnode->parentNode->setAttribute("term", "1"); - // on commence par marquer les fils directs. rappel:$DOMnode pointe sur un sy - for ($node = $DOMnode->parentNode->firstChild; $node; $node = $node->nextSibling) - { - if ($node->nodeName == "te") - { - $node->setAttribute("marked", "1"); - } - } - // puis par remonter au père - for ($node = $DOMnode->parentNode; $node && $node->nodeType == XML_ELEMENT_NODE && $node->parentNode; $node = $node->parentNode) - { - $id = $node->getAttribute("id"); - if (!$id) - break; // on a dépassé la racine du thésaurus - $node->setAttribute("marked", "1"); - } - } - - function astext_ambigu($tree, &$ambiguites, $mouseCallback = "void", $depth = 0) - { - if ($depth == 0) - { - $ambiguites = array("n" => 0, "refs" => array()); - } - switch ($tree["CLASS"]) - { - case "SIMPLE": - case "QSIMPLE": - $prelink = $postlink = ""; - $w = is_array($tree["VALUE"]) ? implode(" ", $tree["VALUE"]) : $tree["VALUE"]; - $tab = "\n" . str_repeat("\t", $depth); - if (isset($tree["TIDS"]) && count($tree["TIDS"]) > 1) - { - $ambiguites["refs"][$n = $ambiguites["n"]] = &$tree; - $txt = $tab . ""; - $txt .= $tab . "\t\"" . $w . ""; - $txt .= $tab . "\t\""; - $txt .= $tab . "\n"; - $ambiguites["n"]++; - } - else - { - if (isset($tree["CONTEXT"])) - $w .= "[" . $tree["CONTEXT"] . "]"; - if ($tree["CLASS"] == "QSIMPLE") - $txt = $tab . "\"" . $w . "\"\n"; - else - $txt = $tab . "" . $w . "\n"; - } - - return($txt); - break; - case "PHRASEA_KW_ALL": - return($tree["VALUE"][0]); - break; - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== null) - - return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); - else - - return($tree["VALUE"][0]); - break; - case "OPS": - case "OPK": - if (isset($tree["PNUM"])) - - return("(" . $this->astext_ambigu($tree["LB"], $ambiguites, $mouseCallback, $depth + 1) . " " . $tree["VALUE"] . "[" . $tree["PNUM"] . "] " . $this->astext_ambigu($tree["RB"], $ambiguites, $mouseCallback, $depth + 1) . ")"); - else - - return("(" . $this->astext_ambigu($tree["LB"], $ambiguites, $mouseCallback, $depth + 1) . " " . $tree["VALUE"] . " " . $this->astext_ambigu($tree["RB"], $ambiguites, $mouseCallback, $depth + 1) . ")"); - break; - } - } - - function get_ambigu(&$tree, $mouseCallback = "void", $depth = 0) - { - if (!$tree) - - return(""); - unset($tree["DEPTH"]); - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - $this->get_ambigu($tree["LB"], $mouseCallback, $depth + 1); - $this->get_ambigu($tree["RB"], $mouseCallback, $depth + 1); - } - else - { - - } - if ($depth == 0) - { - $t_ambiguites = array(); - $r = ($this->astext_ambigu($tree, $t_ambiguites, $mouseCallback)); - $t_ambiguites["query"] = $r; - - return($t_ambiguites); - } - } - - function set_default(&$tree, &$emptyw, $depth = 0) - { - if (!$tree) - - return(true); - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - if ($tree["CLASS"] == "OPS") - { - if (!$this->set_default($tree["LB"], $emptyw, $depth + 1)) - - return(false); - if (!$this->set_default($tree["RB"], $emptyw, $depth + 1)) - - return(false); - } - else // OPK ! - { - // jy 20041223 : ne pas appliquer d'op. par def. derriere un op arith. - // ex : "d < 1/2/2003" : grouper la liste "1","2","2004" en "mot" unique - if (!$tree["LB"] || ($tree["LB"]["CLASS"] != "SIMPLE" && $tree["LB"]["CLASS"] != "QSIMPLE") || (is_array($tree["LB"]["VALUE"]) && count($tree["LB"]["VALUE"]) != 1)) - { - // un op. arith. doit étre précédé d'un seul nom de champ - if ($this->errmsg != "") - $this->errmsg .= sprintf("\\n"); - $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, un nom de champs est attendu avant l operateur %s'), $tree["VALUE"]); - - return(false); - } - if (!$tree["RB"] || ($tree["RB"]["CLASS"] != "SIMPLE" && $tree["RB"]["CLASS"] != "QSIMPLE")) - { - // un op. arith. doit étre suivi d'une valeur - if ($this->errmsg != "") - $this->errmsg .= sprintf("\\n"); - $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, une valeur est attendue apres l operateur %s'), $tree["VALUE"]); - - return(false); - } - if (is_array($tree["RB"]["VALUE"])) - { - $lw = ""; - foreach ($tree["RB"]["VALUE"] as $w) - $lw .= ( $lw == "" ? "" : " ") . $w; - $tree["RB"]["VALUE"] = $lw; - } - } - - /** gestion des branches null - * a revoir car ca ppete pas d'erreur mais corrige automatiquement - * ** */ - if (!isset($tree["RB"])) - $tree = $tree["LB"]; - else - if (!isset($tree["LB"])) - $tree = $tree["RB"]; - } - else - { - if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE")) - { - if (is_array($tree["VALUE"])) - { - $treetmp = null; - $pnum = 0; - for ($i = 0; $i < count($tree["VALUE"]); $i++) - { - // gestion mot vide - if (isset($emptyw[$tree["VALUE"][$i]]) || $tree["VALUE"][$i] == "?" || $tree["VALUE"][$i] == "*") - { - // on a forcé les '?' ou '*' isolés comme des mots vides - $pnum++; + // on marque le terme principal + $DOMnode->parentNode->setAttribute("term", "1"); + // on commence par marquer les fils directs. rappel:$DOMnode pointe sur un sy + for ($node = $DOMnode->parentNode->firstChild; $node; $node = $node->nextSibling) { + if ($node->nodeName == "te") { + $node->setAttribute("marked", "1"); } - else - { - if ($treetmp == null) - { - $treetmp = array("CLASS" => $tree["CLASS"], - "NODETYPE" => $tree["NODETYPE"], - "VALUE" => $tree["VALUE"][$i], - "PNUM" => $tree["PNUM"], - "DEPTH" => $tree["DEPTH"]); - $pnum = 0; - } - else - { - $dop = $tree["CLASS"] == "QSIMPLE" ? $this->quoted_defaultop : $this->defaultop; - $treetmp = array("CLASS" => "OPS", - "VALUE" => $dop["VALUE"], - "NODETYPE" => $dop["NODETYPE"], - "PNUM" => $pnum, // peut-être écrasé par defaultop - "DEPTH" => $depth, - "LB" => $treetmp, - "RB" => array("CLASS" => $tree["CLASS"], - "NODETYPE" => $tree["NODETYPE"], - "VALUE" => $tree["VALUE"][$i], - "PNUM" => $tree["PNUM"], - "DEPTH" => $tree["DEPTH"]) - ); - if (array_key_exists("PNUM", $dop)) - $treetmp["PNUM"] = $dop["PNUM"]; - $pnum = 0; - } - } - } - $tree = $treetmp; } - } + // puis par remonter au père + for ($node = $DOMnode->parentNode; $node && $node->nodeType == XML_ELEMENT_NODE && $node->parentNode; $node = $node->parentNode) { + $id = $node->getAttribute("id"); + if ( ! $id) + break; // on a dépassé la racine du thésaurus + $node->setAttribute("marked", "1"); + } } - return(true); - } - - function factor_or(&$tree) - { - do - $n = $this->factor_or2($tree); - while ($n > 0); - } - - function factor_or2(&$tree, $depth = 0) - { - $nmodif = 0; - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") + function astext_ambigu($tree, &$ambiguites, $mouseCallback = "void", $depth = 0) { - if ($tree["NODETYPE"] == PHRASEA_OP_OR && ($tree["LB"]["CLASS"] == "SIMPLE" || $tree["LB"]["CLASS"] == "QSIMPLE") && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE")) - { - $tree["CLASS"] = "SIMPLE"; - $tree["NODETYPE"] = PHRASEA_KEYLIST; - $tree["VALUE"] = is_array($tree["LB"]["VALUE"]) ? $tree["LB"]["VALUE"] : array($tree["LB"]["VALUE"]); - if (is_array($tree["RB"]["VALUE"])) - { - foreach ($tree["RB"]["VALUE"] as $v) - $tree["VALUE"][] = $v; + if ($depth == 0) { + $ambiguites = array("n" => 0, "refs" => array()); } - else - $tree["VALUE"][] = $tree["RB"]["VALUE"]; - unset($tree["LB"]); - unset($tree["RB"]); - unset($tree["PNUM"]); - $nmodif++; - } - else - { - $nmodif += $this->factor_or2($tree["LB"], $depth + 1); - $nmodif += $this->factor_or2($tree["RB"], $depth + 1); - } - } - - return($nmodif); - } - - function setNumValue(&$tree, SimpleXMLElement $sxml_struct, $depth = 0) - { - if ($tree["CLASS"] == "OPK") - { - if (isset($tree["RB"]) && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") && ($tree["LB"]["CLASS"] == "SIMPLE" || $tree["LB"]["CLASS"] == "QSIMPLE")) - { - $z = $sxml_struct->xpath('/record/description'); - if ($z && is_array($z)) - { - foreach ($z[0] as $ki => $vi) - { - $champ = null; - if (is_array($tree["LB"]["VALUE"])) - $champ = $tree["LB"]["VALUE"][0]; - else - $champ = $tree["LB"]["VALUE"]; - if ($champ && strtoupper($ki) == strtoupper($champ)) - { - foreach ($vi->attributes() as $propname => $val) - { - if (strtoupper($propname) == strtoupper("type")) - { - if ($tree["NODETYPE"] == PHRASEA_OP_EQUAL) // cas particulier du "=" sur une date - $this->changeNodeEquals($tree, $val); - else - $this->setNumValue2($tree["RB"], $val); + switch ($tree["CLASS"]) { + case "SIMPLE": + case "QSIMPLE": + $prelink = $postlink = ""; + $w = is_array($tree["VALUE"]) ? implode(" ", $tree["VALUE"]) : $tree["VALUE"]; + $tab = "\n" . str_repeat("\t", $depth); + if (isset($tree["TIDS"]) && count($tree["TIDS"]) > 1) { + $ambiguites["refs"][$n = $ambiguites["n"]] = &$tree; + $txt = $tab . ""; + $txt .= $tab . "\t\"" . $w . ""; + $txt .= $tab . "\t\""; + $txt .= $tab . "\n"; + $ambiguites["n"] ++; + } else { + if (isset($tree["CONTEXT"])) + $w .= "[" . $tree["CONTEXT"] . "]"; + if ($tree["CLASS"] == "QSIMPLE") + $txt = $tab . "\"" . $w . "\"\n"; + else + $txt = $tab . "" . $w . "\n"; } - } - } - } + + return($txt); + break; + case "PHRASEA_KW_ALL": + return($tree["VALUE"][0]); + break; + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== null) + return("" . $tree["VALUE"][0] . "[" . $tree["PNUM"] . "]"); + else + return($tree["VALUE"][0]); + break; + case "OPS": + case "OPK": + if (isset($tree["PNUM"])) + return("(" . $this->astext_ambigu($tree["LB"], $ambiguites, $mouseCallback, $depth + 1) . " " . $tree["VALUE"] . "[" . $tree["PNUM"] . "] " . $this->astext_ambigu($tree["RB"], $ambiguites, $mouseCallback, $depth + 1) . ")"); + else + return("(" . $this->astext_ambigu($tree["LB"], $ambiguites, $mouseCallback, $depth + 1) . " " . $tree["VALUE"] . " " . $this->astext_ambigu($tree["RB"], $ambiguites, $mouseCallback, $depth + 1) . ")"); + break; } - } } - if (isset($tree["LB"])) - $this->setNumValue($tree["LB"], $sxml_struct, $depth + 1); - if (isset($tree["RB"])) - $this->setNumValue($tree["RB"], $sxml_struct, $depth + 1); - } - function changeNodeEquals(&$branch, $type) - { - if (strtoupper($type) == strtoupper("Date")) + function get_ambigu(&$tree, $mouseCallback = "void", $depth = 0) { - $branch = $this->changeNodeEquals2($branch); - } - } + if ( ! $tree) + return(""); + unset($tree["DEPTH"]); + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + $this->get_ambigu($tree["LB"], $mouseCallback, $depth + 1); + $this->get_ambigu($tree["RB"], $mouseCallback, $depth + 1); + } else { - function changeNodeEquals2($oneBranch) - { - ## creation branche gauche avec ">=" + } + if ($depth == 0) { + $t_ambiguites = array(); + $r = ($this->astext_ambigu($tree, $t_ambiguites, $mouseCallback)); + $t_ambiguites["query"] = $r; + + return($t_ambiguites); + } + } + + function set_default(&$tree, &$emptyw, $depth = 0) + { + if ( ! $tree) + return(true); + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + if ($tree["CLASS"] == "OPS") { + if ( ! $this->set_default($tree["LB"], $emptyw, $depth + 1)) + return(false); + if ( ! $this->set_default($tree["RB"], $emptyw, $depth + 1)) + return(false); + } + else { // OPK ! + // jy 20041223 : ne pas appliquer d'op. par def. derriere un op arith. + // ex : "d < 1/2/2003" : grouper la liste "1","2","2004" en "mot" unique + if ( ! $tree["LB"] || ($tree["LB"]["CLASS"] != "SIMPLE" && $tree["LB"]["CLASS"] != "QSIMPLE") || (is_array($tree["LB"]["VALUE"]) && count($tree["LB"]["VALUE"]) != 1)) { + // un op. arith. doit étre précédé d'un seul nom de champ + if ($this->errmsg != "") + $this->errmsg .= sprintf("\\n"); + $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, un nom de champs est attendu avant l operateur %s'), $tree["VALUE"]); + + return(false); + } + if ( ! $tree["RB"] || ($tree["RB"]["CLASS"] != "SIMPLE" && $tree["RB"]["CLASS"] != "QSIMPLE")) { + // un op. arith. doit étre suivi d'une valeur + if ($this->errmsg != "") + $this->errmsg .= sprintf("\\n"); + $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, une valeur est attendue apres l operateur %s'), $tree["VALUE"]); + + return(false); + } + if (is_array($tree["RB"]["VALUE"])) { + $lw = ""; + foreach ($tree["RB"]["VALUE"] as $w) + $lw .= ( $lw == "" ? "" : " ") . $w; + $tree["RB"]["VALUE"] = $lw; + } + } + + /** gestion des branches null + * a revoir car ca ppete pas d'erreur mais corrige automatiquement + * ** */ + if ( ! isset($tree["RB"])) + $tree = $tree["LB"]; + else + if ( ! isset($tree["LB"])) + $tree = $tree["RB"]; + } + else { + if (($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE")) { + if (is_array($tree["VALUE"])) { + $treetmp = null; + $pnum = 0; + for ($i = 0; $i < count($tree["VALUE"]); $i ++ ) { + // gestion mot vide + if (isset($emptyw[$tree["VALUE"][$i]]) || $tree["VALUE"][$i] == "?" || $tree["VALUE"][$i] == "*") { + // on a forcé les '?' ou '*' isolés comme des mots vides + $pnum ++; + } else { + if ($treetmp == null) { + $treetmp = array("CLASS" => $tree["CLASS"], + "NODETYPE" => $tree["NODETYPE"], + "VALUE" => $tree["VALUE"][$i], + "PNUM" => $tree["PNUM"], + "DEPTH" => $tree["DEPTH"]); + $pnum = 0; + } else { + $dop = $tree["CLASS"] == "QSIMPLE" ? $this->quoted_defaultop : $this->defaultop; + $treetmp = array("CLASS" => "OPS", + "VALUE" => $dop["VALUE"], + "NODETYPE" => $dop["NODETYPE"], + "PNUM" => $pnum, // peut-être écrasé par defaultop + "DEPTH" => $depth, + "LB" => $treetmp, + "RB" => array("CLASS" => $tree["CLASS"], + "NODETYPE" => $tree["NODETYPE"], + "VALUE" => $tree["VALUE"][$i], + "PNUM" => $tree["PNUM"], + "DEPTH" => $tree["DEPTH"]) + ); + if (array_key_exists("PNUM", $dop)) + $treetmp["PNUM"] = $dop["PNUM"]; + $pnum = 0; + } + } + } + $tree = $treetmp; + } + } + } + + return(true); + } + + function factor_or(&$tree) + { + do + $n = $this->factor_or2($tree); while ($n > 0); + } + + function factor_or2(&$tree, $depth = 0) + { + $nmodif = 0; + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + if ($tree["NODETYPE"] == PHRASEA_OP_OR && ($tree["LB"]["CLASS"] == "SIMPLE" || $tree["LB"]["CLASS"] == "QSIMPLE") && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE")) { + $tree["CLASS"] = "SIMPLE"; + $tree["NODETYPE"] = PHRASEA_KEYLIST; + $tree["VALUE"] = is_array($tree["LB"]["VALUE"]) ? $tree["LB"]["VALUE"] : array($tree["LB"]["VALUE"]); + if (is_array($tree["RB"]["VALUE"])) { + foreach ($tree["RB"]["VALUE"] as $v) + $tree["VALUE"][] = $v; + } + else + $tree["VALUE"][] = $tree["RB"]["VALUE"]; + unset($tree["LB"]); + unset($tree["RB"]); + unset($tree["PNUM"]); + $nmodif ++; + } + else { + $nmodif += $this->factor_or2($tree["LB"], $depth + 1); + $nmodif += $this->factor_or2($tree["RB"], $depth + 1); + } + } + + return($nmodif); + } + + function setNumValue(&$tree, SimpleXMLElement $sxml_struct, $depth = 0) + { + if ($tree["CLASS"] == "OPK") { + if (isset($tree["RB"]) && ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") && ($tree["LB"]["CLASS"] == "SIMPLE" || $tree["LB"]["CLASS"] == "QSIMPLE")) { + $z = $sxml_struct->xpath('/record/description'); + if ($z && is_array($z)) { + foreach ($z[0] as $ki => $vi) { + $champ = null; + if (is_array($tree["LB"]["VALUE"])) + $champ = $tree["LB"]["VALUE"][0]; + else + $champ = $tree["LB"]["VALUE"]; + if ($champ && strtoupper($ki) == strtoupper($champ)) { + foreach ($vi->attributes() as $propname => $val) { + if (strtoupper($propname) == strtoupper("type")) { + if ($tree["NODETYPE"] == PHRASEA_OP_EQUAL) // cas particulier du "=" sur une date + $this->changeNodeEquals($tree, $val); + else + $this->setNumValue2($tree["RB"], $val); + } + } + } + } + } + } + } + if (isset($tree["LB"])) + $this->setNumValue($tree["LB"], $sxml_struct, $depth + 1); + if (isset($tree["RB"])) + $this->setNumValue($tree["RB"], $sxml_struct, $depth + 1); + } + + function changeNodeEquals(&$branch, $type) + { + if (strtoupper($type) == strtoupper("Date")) { + $branch = $this->changeNodeEquals2($branch); + } + } + + function changeNodeEquals2($oneBranch) + { + ## creation branche gauche avec ">=" // print("changeNodeEquals2\n"); // print("creation branche gauche ( '>=' ) \n"); - $newTreeLB = array("CLASS" => "OPK", - "VALUE" => ">=", - "NODETYPE" => PHRASEA_OP_GEQT, - "PNUM" => NULL, - "DEPTH" => 0, - "LB" => $oneBranch["LB"], - "RB" => array("CLASS" => "SIMPLE", - "VALUE" => $this->isoDate($oneBranch["RB"]["VALUE"], false), - "NODETYPE" => PHRASEA_KEYLIST, - "PNUM" => NULL, - "DEPTH" => 0) - ); + $newTreeLB = array("CLASS" => "OPK", + "VALUE" => ">=", + "NODETYPE" => PHRASEA_OP_GEQT, + "PNUM" => NULL, + "DEPTH" => 0, + "LB" => $oneBranch["LB"], + "RB" => array("CLASS" => "SIMPLE", + "VALUE" => $this->isoDate($oneBranch["RB"]["VALUE"], false), + "NODETYPE" => PHRASEA_KEYLIST, + "PNUM" => NULL, + "DEPTH" => 0) + ); - $newTreeRB = array("CLASS" => "OPK", - "VALUE" => "<=", - "NODETYPE" => PHRASEA_OP_LEQT, - "PNUM" => NULL, - "DEPTH" => 0, - "LB" => $oneBranch["LB"], - "RB" => array("CLASS" => "SIMPLE", - "VALUE" => $this->isoDate($oneBranch["RB"]["VALUE"], true), - "NODETYPE" => PHRASEA_KEYLIST, - "PNUM" => NULL, - "DEPTH" => 0) - ); + $newTreeRB = array("CLASS" => "OPK", + "VALUE" => "<=", + "NODETYPE" => PHRASEA_OP_LEQT, + "PNUM" => NULL, + "DEPTH" => 0, + "LB" => $oneBranch["LB"], + "RB" => array("CLASS" => "SIMPLE", + "VALUE" => $this->isoDate($oneBranch["RB"]["VALUE"], true), + "NODETYPE" => PHRASEA_KEYLIST, + "PNUM" => NULL, + "DEPTH" => 0) + ); // print("fin creation branche droite avec '<=' \n"); - ## fin creation branche droite ( "<=" ) + ## fin creation branche droite ( "<=" ) - $tree = array("CLASS" => "OPS", - "VALUE" => "et", - "NODETYPE" => PHRASEA_OP_AND, - "PNUM" => NULL, - "DEPTH" => 0, - "LB" => $newTreeLB, - "RB" => $newTreeRB); + $tree = array("CLASS" => "OPS", + "VALUE" => "et", + "NODETYPE" => PHRASEA_OP_AND, + "PNUM" => NULL, + "DEPTH" => 0, + "LB" => $newTreeLB, + "RB" => $newTreeRB); - return $tree; - } - - function setNumValue2(&$branch, $type) - { - if (strtoupper($type) == strtoupper("Date")) - { - $dateEnIso = $this->isoDate($branch["VALUE"]); - $branch["VALUE"] = $dateEnIso; - } - } - - function isoDate($onedate, $max = false) - { - $v_y = "1900"; - $v_m = "01"; - $v_d = "01"; - - $v_h = $v_minutes = $v_s = "00"; - if ($max) - { - $v_h = $v_minutes = $v_s = "99"; - } - $tmp = $onedate; - - if (!is_array($tmp)) - $tmp = explode(" ", $tmp); - - switch (sizeof($tmp)) - { - // on a une date complete séparé avec des espaces, slash ou tiret - case 3 : - if (strlen($tmp[0]) == 4) - { - $v_y = $tmp[0]; - $v_m = $tmp[1]; - $v_d = $tmp[2]; - // on a l'année en premier, on suppose alors que c'est de la forme YYYY MM DD - } - elseif (strlen($tmp[2]) == 4) - { - // on a l'année en dernier, on suppose alors que c'est de la forme DD MM YYYY - $v_y = $tmp[2]; - $v_m = $tmp[1]; - $v_d = $tmp[0]; - } - else - { - // l'année est sur un 2 chiffre et pas 4 - // ca fou la zone - - $v_d = $tmp[0]; - $v_m = $tmp[1]; - if ($tmp[2] < 20) - $v_y = "20" . $tmp[2]; - else - $v_y = "19" . $tmp[2]; - } - break; - - case 2 : - // On supposerait n'avoir que le mois et l'année - if (strlen($tmp[0]) == 4) - { - $v_y = $tmp[0]; - $v_m = $tmp[1]; - // on a l'année en premier, on suppose alors que c'est de la forme YYYY MM DD - if ($max) - $v_d = "99"; - else - $v_d = "00"; - } - elseif (strlen($tmp[1]) == 4) - { - // on a l'année en premier, on suppose alors que c'est de la forme DD MM YYYY - $v_y = $tmp[1]; - $v_m = $tmp[0]; - if ($max) - $v_d = "99"; - else - $v_d = "00"; - } - else - { - // on a l'anné sur 2 chiffres - if ($tmp[1] < 20) - $v_y = "20" . $tmp[1]; - else - $v_y = "19" . $tmp[1]; - $v_m = $tmp[0]; - if ($max) - $v_d = "99"; - else - $v_d = "00"; - } - break; - - - // lé ca devient la zone pour savoir si on a que l'année ou si c'est une date sans espaces,slash ou tiret - case 1 : - switch (strlen($tmp[0])) - { - case 14 : - // date iso YYYYMMDDHHMMSS - $v_y = substr($tmp[0], 0, 4); - $v_m = substr($tmp[0], 4, 2); - $v_d = substr($tmp[0], 6, 2); - $v_h = substr($tmp[0], 8, 2); - $v_minutes = substr($tmp[0], 10, 2); - $v_s = substr($tmp[0], 12, 2); - break; - case 8 : - // date iso YYYYMMDD - $v_y = substr($tmp[0], 0, 4); - $v_m = substr($tmp[0], 4, 2); - $v_d = substr($tmp[0], 6, 2); - break; - case 6 : - // date iso YYYYMM - $v_y = substr($tmp[0], 0, 4); - $v_m = substr($tmp[0], 4, 2); - if ($max) - $v_d = "99"; - else - $v_d = "00"; - break; - case 4 : - // date iso YYYY - $v_y = $tmp[0]; - - if ($max) - $v_m = "99"; - else - $v_m = "00"; - - if ($max) - $v_d = "99"; - else - $v_d = "00"; - break; - case 2 : - // date iso YY - if ($tmp[0] < 20) - $v_y = "20" . $tmp[0]; - else - $v_y = "19" . $tmp[0]; - - if ($max) - $v_m = "99"; - else - $v_m = "00"; - - if ($max) - $v_d = "99"; - else - $v_d = "00"; - break; - } - - - - break; + return $tree; } - return("" . $v_y . $v_m . $v_d . $v_h . $v_minutes . $v_s); - } - - function distrib_in(&$tree, $depth = 0) - { - $opdistrib = array(PHRASEA_OP_AND, PHRASEA_OP_OR, PHRASEA_OP_EXCEPT, PHRASEA_OP_NEAR, PHRASEA_OP_BEFORE, PHRASEA_OP_AFTER); // ces opérateurs sont 'distribuables' autour d'un 'IN' - - if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") + function setNumValue2(&$branch, $type) { - if ($tree["NODETYPE"] == PHRASEA_OP_IN || $tree["CLASS"] == "OPK") - { - if ($tree["LB"]["CLASS"] == "OPK") - { - // on a un truc du genre '(t1 = t2) dans t3' - // ... on ne fait rien + if (strtoupper($type) == strtoupper("Date")) { + $dateEnIso = $this->isoDate($branch["VALUE"]); + $branch["VALUE"] = $dateEnIso; } - if ($tree["LB"]["CLASS"] == "OPS" && in_array($tree["LB"]["NODETYPE"], $opdistrib)) - { - // on a un truc du genre '(t1 op t2) {dans|=} t3', on distribue le dans é t1 et t2 - // ==> ((t1 dans t3) op (t2 dans t3)) - $m_v = $tree["VALUE"]; - $m_t = $tree["CLASS"]; - $m_o = $tree["NODETYPE"]; - $m_n = $tree["PNUM"]; - - $tree["CLASS"] = $tree["LB"]["CLASS"]; - $tree["NODETYPE"] = $tree["LB"]["NODETYPE"]; - $tree["VALUE"] = $tree["LB"]["VALUE"]; - $tree["PNUM"] = $tree["LB"]["PNUM"]; - - $tree["LB"]["CLASS"] = $m_t; - $tree["LB"]["NODETYPE"] = $m_o; - $tree["LB"]["VALUE"] = $m_v; - $tree["LB"]["PNUM"] = $m_n; - - $tree["RB"] = array("CLASS" => $m_t, - "NODETYPE" => $m_o, - "VALUE" => $m_v, - "PNUM" => $m_n, - "LB" => $tree["LB"]["RB"], - "RB" => $tree["RB"]); - - $tree["LB"]["RB"] = $tree["RB"]["RB"]; - // return; - } - - - if ($tree["RB"]["CLASS"] == "OPS" && in_array($tree["RB"]["NODETYPE"], $opdistrib)) - { - - // on a un truc du genre 't1 {dans|=} (t2 op t3)', on distribue le dans é t2 et t3 - // ==> ((t1 dans t2) ou (t1 dans t3)) - $m_v = $tree["VALUE"]; - $m_t = $tree["CLASS"]; - $m_o = $tree["NODETYPE"]; - $m_n = $tree["PNUM"]; - - $tree["CLASS"] = $tree["RB"]["CLASS"]; - $tree["NODETYPE"] = $tree["RB"]["NODETYPE"]; - $tree["VALUE"] = $tree["RB"]["VALUE"]; - $tree["PNUM"] = $tree["RB"]["PNUM"]; - - $tree["RB"]["CLASS"] = $m_t; - $tree["RB"]["NODETYPE"] = $m_o; - $tree["RB"]["VALUE"] = $m_v; - $tree["RB"]["PNUM"] = $m_n; - - $tree["LB"] = array("CLASS" => $m_t, - "NODETYPE" => $m_o, - "VALUE" => $m_v, - "PNUM" => $m_n, - "LB" => $tree["LB"], - "RB" => $tree["RB"]["LB"]); - - $tree["RB"]["LB"] = $tree["LB"]["LB"]; - } - } - $this->distrib_in($tree["LB"], $depth + 1); - $this->distrib_in($tree["RB"], $depth + 1); - } - } - - function makequery($tree) - { - $a = array($tree["NODETYPE"]); - switch ($tree["CLASS"]) - { - case "PHRASEA_KW_LAST": - if ($tree["PNUM"] !== NULL) - $a[] = $tree["PNUM"]; - break; - case "PHRASEA_KW_ALL": - break; - case "SIMPLE": - case "QSIMPLE": - // pas de tid, c'est un terme normal - if (is_array($tree["VALUE"])) - { - foreach ($tree["VALUE"] as $k => $v) - $a[] = $v; - } - else - { - $a[] = $tree["VALUE"]; - } - break; - case "OPK": - if ($tree["LB"] !== NULL) - $a[] = $this->makequery($tree["LB"]); - if ($tree["RB"] !== NULL) - $a[] = $this->makequery($tree["RB"]); - break; - case "OPS": - if ($tree["PNUM"] !== NULL) - $a[] = intval($tree["PNUM"]); - if ($tree["LB"] !== NULL) - $a[] = $this->makequery($tree["LB"]); - if ($tree["RB"] !== NULL) - $a[] = $this->makequery($tree["RB"]); - break; } - return($a); - } + function isoDate($onedate, $max = false) + { + $v_y = "1900"; + $v_m = "01"; + $v_d = "01"; - function maketree($depth, $inquote = false) - { + $v_h = $v_minutes = $v_s = "00"; + if ($max) { + $v_h = $v_minutes = $v_s = "99"; + } + $tmp = $onedate; + + if ( ! is_array($tmp)) + $tmp = explode(" ", $tmp); + + switch (sizeof($tmp)) { + // on a une date complete séparé avec des espaces, slash ou tiret + case 3 : + if (strlen($tmp[0]) == 4) { + $v_y = $tmp[0]; + $v_m = $tmp[1]; + $v_d = $tmp[2]; + // on a l'année en premier, on suppose alors que c'est de la forme YYYY MM DD + } elseif (strlen($tmp[2]) == 4) { + // on a l'année en dernier, on suppose alors que c'est de la forme DD MM YYYY + $v_y = $tmp[2]; + $v_m = $tmp[1]; + $v_d = $tmp[0]; + } else { + // l'année est sur un 2 chiffre et pas 4 + // ca fou la zone + + $v_d = $tmp[0]; + $v_m = $tmp[1]; + if ($tmp[2] < 20) + $v_y = "20" . $tmp[2]; + else + $v_y = "19" . $tmp[2]; + } + break; + + case 2 : + // On supposerait n'avoir que le mois et l'année + if (strlen($tmp[0]) == 4) { + $v_y = $tmp[0]; + $v_m = $tmp[1]; + // on a l'année en premier, on suppose alors que c'est de la forme YYYY MM DD + if ($max) + $v_d = "99"; + else + $v_d = "00"; + } + elseif (strlen($tmp[1]) == 4) { + // on a l'année en premier, on suppose alors que c'est de la forme DD MM YYYY + $v_y = $tmp[1]; + $v_m = $tmp[0]; + if ($max) + $v_d = "99"; + else + $v_d = "00"; + } + else { + // on a l'anné sur 2 chiffres + if ($tmp[1] < 20) + $v_y = "20" . $tmp[1]; + else + $v_y = "19" . $tmp[1]; + $v_m = $tmp[0]; + if ($max) + $v_d = "99"; + else + $v_d = "00"; + } + break; + + + // lé ca devient la zone pour savoir si on a que l'année ou si c'est une date sans espaces,slash ou tiret + case 1 : + switch (strlen($tmp[0])) { + case 14 : + // date iso YYYYMMDDHHMMSS + $v_y = substr($tmp[0], 0, 4); + $v_m = substr($tmp[0], 4, 2); + $v_d = substr($tmp[0], 6, 2); + $v_h = substr($tmp[0], 8, 2); + $v_minutes = substr($tmp[0], 10, 2); + $v_s = substr($tmp[0], 12, 2); + break; + case 8 : + // date iso YYYYMMDD + $v_y = substr($tmp[0], 0, 4); + $v_m = substr($tmp[0], 4, 2); + $v_d = substr($tmp[0], 6, 2); + break; + case 6 : + // date iso YYYYMM + $v_y = substr($tmp[0], 0, 4); + $v_m = substr($tmp[0], 4, 2); + if ($max) + $v_d = "99"; + else + $v_d = "00"; + break; + case 4 : + // date iso YYYY + $v_y = $tmp[0]; + + if ($max) + $v_m = "99"; + else + $v_m = "00"; + + if ($max) + $v_d = "99"; + else + $v_d = "00"; + break; + case 2 : + // date iso YY + if ($tmp[0] < 20) + $v_y = "20" . $tmp[0]; + else + $v_y = "19" . $tmp[0]; + + if ($max) + $v_m = "99"; + else + $v_m = "00"; + + if ($max) + $v_d = "99"; + else + $v_d = "00"; + break; + } + + + + break; + } + + return("" . $v_y . $v_m . $v_d . $v_h . $v_minutes . $v_s); + } + + function distrib_in(&$tree, $depth = 0) + { + $opdistrib = array(PHRASEA_OP_AND, PHRASEA_OP_OR, PHRASEA_OP_EXCEPT, PHRASEA_OP_NEAR, PHRASEA_OP_BEFORE, PHRASEA_OP_AFTER); // ces opérateurs sont 'distribuables' autour d'un 'IN' + + if ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + if ($tree["NODETYPE"] == PHRASEA_OP_IN || $tree["CLASS"] == "OPK") { + if ($tree["LB"]["CLASS"] == "OPK") { + // on a un truc du genre '(t1 = t2) dans t3' + // ... on ne fait rien + } + if ($tree["LB"]["CLASS"] == "OPS" && in_array($tree["LB"]["NODETYPE"], $opdistrib)) { + // on a un truc du genre '(t1 op t2) {dans|=} t3', on distribue le dans é t1 et t2 + // ==> ((t1 dans t3) op (t2 dans t3)) + $m_v = $tree["VALUE"]; + $m_t = $tree["CLASS"]; + $m_o = $tree["NODETYPE"]; + $m_n = $tree["PNUM"]; + + $tree["CLASS"] = $tree["LB"]["CLASS"]; + $tree["NODETYPE"] = $tree["LB"]["NODETYPE"]; + $tree["VALUE"] = $tree["LB"]["VALUE"]; + $tree["PNUM"] = $tree["LB"]["PNUM"]; + + $tree["LB"]["CLASS"] = $m_t; + $tree["LB"]["NODETYPE"] = $m_o; + $tree["LB"]["VALUE"] = $m_v; + $tree["LB"]["PNUM"] = $m_n; + + $tree["RB"] = array("CLASS" => $m_t, + "NODETYPE" => $m_o, + "VALUE" => $m_v, + "PNUM" => $m_n, + "LB" => $tree["LB"]["RB"], + "RB" => $tree["RB"]); + + $tree["LB"]["RB"] = $tree["RB"]["RB"]; + // return; + } + + + if ($tree["RB"]["CLASS"] == "OPS" && in_array($tree["RB"]["NODETYPE"], $opdistrib)) { + + // on a un truc du genre 't1 {dans|=} (t2 op t3)', on distribue le dans é t2 et t3 + // ==> ((t1 dans t2) ou (t1 dans t3)) + $m_v = $tree["VALUE"]; + $m_t = $tree["CLASS"]; + $m_o = $tree["NODETYPE"]; + $m_n = $tree["PNUM"]; + + $tree["CLASS"] = $tree["RB"]["CLASS"]; + $tree["NODETYPE"] = $tree["RB"]["NODETYPE"]; + $tree["VALUE"] = $tree["RB"]["VALUE"]; + $tree["PNUM"] = $tree["RB"]["PNUM"]; + + $tree["RB"]["CLASS"] = $m_t; + $tree["RB"]["NODETYPE"] = $m_o; + $tree["RB"]["VALUE"] = $m_v; + $tree["RB"]["PNUM"] = $m_n; + + $tree["LB"] = array("CLASS" => $m_t, + "NODETYPE" => $m_o, + "VALUE" => $m_v, + "PNUM" => $m_n, + "LB" => $tree["LB"], + "RB" => $tree["RB"]["LB"]); + + $tree["RB"]["LB"] = $tree["LB"]["LB"]; + } + } + $this->distrib_in($tree["LB"], $depth + 1); + $this->distrib_in($tree["RB"], $depth + 1); + } + } + + function makequery($tree) + { + $a = array($tree["NODETYPE"]); + switch ($tree["CLASS"]) { + case "PHRASEA_KW_LAST": + if ($tree["PNUM"] !== NULL) + $a[] = $tree["PNUM"]; + break; + case "PHRASEA_KW_ALL": + break; + case "SIMPLE": + case "QSIMPLE": + // pas de tid, c'est un terme normal + if (is_array($tree["VALUE"])) { + foreach ($tree["VALUE"] as $k => $v) + $a[] = $v; + } else { + $a[] = $tree["VALUE"]; + } + break; + case "OPK": + if ($tree["LB"] !== NULL) + $a[] = $this->makequery($tree["LB"]); + if ($tree["RB"] !== NULL) + $a[] = $this->makequery($tree["RB"]); + break; + case "OPS": + if ($tree["PNUM"] !== NULL) + $a[] = intval($tree["PNUM"]); + if ($tree["LB"] !== NULL) + $a[] = $this->makequery($tree["LB"]); + if ($tree["RB"] !== NULL) + $a[] = $this->makequery($tree["RB"]); + break; + } + + return($a); + } + + function maketree($depth, $inquote = false) + { // printf("\n\n"); - $tree = null; - while ($t = $this->nexttoken($inquote)) - { - if ($this->debug) - printf("got token %s of class %s\n", $t["VALUE"], $t["CLASS"]); - switch ($t["CLASS"]) - { - case "TOK_RP": - if ($inquote) - { - // quand on est entre guillements les tokens perdent leur signification - $tree = $this->addtotree($tree, $t, $depth, $inquote); - if (!$tree) + $tree = null; + while ($t = $this->nexttoken($inquote)) { + if ($this->debug) + printf("got token %s of class %s\n", $t["VALUE"], $t["CLASS"]); + switch ($t["CLASS"]) { + case "TOK_RP": + if ($inquote) { + // quand on est entre guillements les tokens perdent leur signification + $tree = $this->addtotree($tree, $t, $depth, $inquote); + if ( ! $tree) + return(null); + } + else { + if ($depth <= 0) { // ')' : retour de récursivité + if ($this->errmsg != "") + $this->errmsg .= sprintf("\\n"); + $this->errmsg .= _('qparser:: erreur : trop de parentheses fermantes'); - return(null); - } - else - { - if ($depth <= 0) // ')' : retour de récursivité - { - if ($this->errmsg != "") + return(null); + } + + return($tree); + } + break; + case "TOK_LP": + if ($inquote) { + // quand on est entre guillements les tokens perdent leur signification + $tree = $this->addtotree($tree, $t, $depth, $inquote); + if ( ! $tree) + return(null); + } + else { // '(' : appel récursif + if ( ! $tree) + $tree = $this->maketree($depth + 1); + else { + if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) { + $tree["RB"] = $this->maketree($depth + 1); + if ( ! $tree["RB"]) + $tree = null; + } + else { + // ici on applique l'opérateur par défaut + $tree = array("CLASS" => "OPS", + "VALUE" => $this->defaultop["VALUE"], + "NODETYPE" => $this->defaultop["NODETYPE"], + "PNUM" => $this->defaultop["PNUM"], + "DEPTH" => $depth, + "LB" => $tree, + "RB" => $this->maketree($depth + 1)); + } + } + if ( ! $tree) + return(null); + } + break; + case "TOK_VOID": + // ce token est entre guillemets : on le saute + break; + case "TOK_QUOTE": + // une expr entre guillemets est 'comme entre parenthéses', + // sinon "a b" OU "x y" -> (((a B0 b) OU x) B0 y) au lieu de + // "a b" OU "x y" -> ((a B0 b) OU (x B0 y)) + if ($inquote) { + if ($this->debug) { + print("CLOSING QUOTE!\n"); + } + // fermeture des guillemets -> retour de récursivité + if ($depth <= 0) { // ')' : retour de récursivité + print("\nguillemets fermants en trop
              "); + + return(null); + } + + return($tree); + } else { + if ($this->debug) { + print("OPENING QUOTE!
              "); + } + // ouverture des guillemets -> récursivité + if ( ! $tree) + $tree = $this->maketree($depth + 1, true); + else { + if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) { + $tree["RB"] = $this->maketree($depth + 1, true); + if ( ! $tree["RB"]) + $tree = null; + } + else { + // ici on applique l'opérateur par défaut + $tree = array("CLASS" => "OPS", + "VALUE" => $this->defaultop["VALUE"], + "NODETYPE" => $this->defaultop["NODETYPE"], + "PNUM" => $this->defaultop["PNUM"], + "DEPTH" => $depth, + "LB" => $tree, + "RB" => $this->maketree($depth + 1, true)); + } + } + if ( ! $tree) + return(null); + } + break; + default: + $tree = $this->addtotree($tree, $t, $depth, $inquote); + if ($this->debug) { + print("---- après addtotree ----\n"); + var_dump($tree); + print("-------------------------\n"); + } + if ( ! $tree) + return(null); + break; + } + } + if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) { + if ($this->errmsg != "") $this->errmsg .= sprintf("\\n"); - $this->errmsg .= _('qparser:: erreur : trop de parentheses fermantes'); + $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, une valeur est attendu apres %s'), $tree["VALUE"]); + $tree = $tree["LB"]; + } - return(null); - } + return($tree); + } - return($tree); - } - break; - case "TOK_LP": - if ($inquote) - { - // quand on est entre guillements les tokens perdent leur signification - $tree = $this->addtotree($tree, $t, $depth, $inquote); - if (!$tree) - - return(null); - } - else // '(' : appel récursif - { - if (!$tree) - $tree = $this->maketree($depth + 1); - else - { - if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) - { - $tree["RB"] = $this->maketree($depth + 1); - if (!$tree["RB"]) - $tree = null; - } - else - { - // ici on applique l'opérateur par défaut - $tree = array("CLASS" => "OPS", - "VALUE" => $this->defaultop["VALUE"], - "NODETYPE" => $this->defaultop["NODETYPE"], - "PNUM" => $this->defaultop["PNUM"], - "DEPTH" => $depth, - "LB" => $tree, - "RB" => $this->maketree($depth + 1)); - } - } - if (!$tree) - - return(null); - } - break; - case "TOK_VOID": - // ce token est entre guillemets : on le saute - break; - case "TOK_QUOTE": - // une expr entre guillemets est 'comme entre parenthéses', - // sinon "a b" OU "x y" -> (((a B0 b) OU x) B0 y) au lieu de - // "a b" OU "x y" -> ((a B0 b) OU (x B0 y)) - if ($inquote) - { - if ($this->debug) - { - print("CLOSING QUOTE!\n"); - } - // fermeture des guillemets -> retour de récursivité - if ($depth <= 0) // ')' : retour de récursivité - { - print("\nguillemets fermants en trop
              "); - - return(null); - } - - return($tree); - } - else - { - if ($this->debug) - { - print("OPENING QUOTE!
              "); - } - // ouverture des guillemets -> récursivité - if (!$tree) - $tree = $this->maketree($depth + 1, true); - else - { - if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) - { - $tree["RB"] = $this->maketree($depth + 1, true); - if (!$tree["RB"]) - $tree = null; - } - else - { - // ici on applique l'opérateur par défaut - $tree = array("CLASS" => "OPS", - "VALUE" => $this->defaultop["VALUE"], - "NODETYPE" => $this->defaultop["NODETYPE"], - "PNUM" => $this->defaultop["PNUM"], - "DEPTH" => $depth, - "LB" => $tree, - "RB" => $this->maketree($depth + 1, true)); - } - } - if (!$tree) - - return(null); - } - break; - default: - $tree = $this->addtotree($tree, $t, $depth, $inquote); - if ($this->debug) - { - print("---- après addtotree ----\n"); + function addtotree($tree, $t, $depth, $inquote) + { + if ($this->debug) { + printf("addtotree({tree}, \$t[CLASS]='%s', \$t[VALUE]='%s', \$depth=%d, inquote=%s)\n", $t["CLASS"], $t["VALUE"], $depth, $inquote ? "true" : "false"); + print("---- avant addtotree ----\n"); var_dump($tree); print("-------------------------\n"); - } - if (!$tree) + } - return(null); - break; - } - } - if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) - { - if ($this->errmsg != "") - $this->errmsg .= sprintf("\\n"); - $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, une valeur est attendu apres %s'), $tree["VALUE"]); - $tree = $tree["LB"]; - } - - return($tree); - } - - function addtotree($tree, $t, $depth, $inquote) - { - if ($this->debug) - { - printf("addtotree({tree}, \$t[CLASS]='%s', \$t[VALUE]='%s', \$depth=%d, inquote=%s)\n", $t["CLASS"], $t["VALUE"], $depth, $inquote ? "true" : "false"); - print("---- avant addtotree ----\n"); - var_dump($tree); - print("-------------------------\n"); - } - - if (!$t) - - return($tree); - switch ($t["CLASS"]) - { - case "TOK_CONTEXT": + if ( ! $t) + return($tree); + switch ($t["CLASS"]) { + case "TOK_CONTEXT": // if($this->debug) // { // printf("addtotree({tree}, \$t='%s', \$depth=%d, inquote=%s)\n", $t["VALUE"], $depth, $inquote?"true":"false"); // } - if ($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE") - { - // un [xxx] suit un terme : il introduit un contexte - $tree["CONTEXT"] = $t["VALUE"]; + if ($tree["CLASS"] == "SIMPLE" || $tree["CLASS"] == "QSIMPLE") { + // un [xxx] suit un terme : il introduit un contexte + $tree["CONTEXT"] = $t["VALUE"]; + } elseif ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") { + if ( ! isset($tree["RB"]) || ! $tree["RB"]) { + // un [xxx] peut suivre un opérateur, c'est un paramétre normalement numérique + $tree["PNUM"] = $t["VALUE"]; + } else { + // [xxx] suit un terme déjé en branche droite ? (ex: a ou b[k]) + if ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") + $tree["RB"]["CONTEXT"] = $t["VALUE"]; + else { + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf("le contexte [%s] ne peut suivre qu'un terme ou un opérateur
              ", $t["VALUE"]); + + return(null); + } + } + } + else { + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf("le contexte [%s] ne peut suivre qu'un terme ou un opérateur
              ", $t["VALUE"]); + + return(null); + } + + return($tree); + break; + case "TOK_CMP": + // < > <= >= <> = : sont des opérateurs de comparaison + if ( ! $tree) { + // printf("\nUne question ne peut commencer par '" . $t["VALUE"] . "'
              "); + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf(_('qparser::erreur : une question ne peut commencer par %s'), $t["VALUE"]); + + return(null); + } + if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) { + // printf("'" . $t["VALUE"] . "' ne peut suivre un opérateur
              "); + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, ne peut suivre un operateur : %s'), $t["VALUE"]); + + return(null); + } + + return(array("CLASS" => "OPK", "VALUE" => $t["VALUE"], "NODETYPE" => $this->opk[$t["VALUE"]]["NODETYPE"], "PNUM" => null, "DEPTH" => $depth, "LB" => $tree, "RB" => null)); + break; + case "TOK_WORD": + if ($t["CLASS"] == "TOK_WORD" && isset($this->ops[$t["VALUE"]]) && ! $inquote) { + // ce mot est un opérateur phrasea + if ( ! $tree) { + // printf("\n581 : Une question ne peut commencer par un opérateur
              "); + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf(_('qparser::erreur : une question ne peut commencer par %s'), $t["VALUE"]); + + return(null); + } + if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) { + + // printf("\n586 : Un opérateur ne peut suivre un opérateur
              "); + if ($this->errmsg != "") + $this->errmsg .= "\\n"; + $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, %s ne peut suivre un operateur'), $t["VALUE"]); + + return(null); + } + $pnum = null; + if ($this->ops[$t["VALUE"]]["CANNUM"]) { + // cet opérateur peut étre suivi d'un nombre ('near', 'before', 'after') + if ($tn = $this->nexttoken()) { + if ($tn["CLASS"] == "TOK_WORD" && is_numeric($tn["VALUE"])) + $pnum = (int) $tn["VALUE"]; + else + $this->ungettoken($tn["VALUE"]); + } + } + + return(array("CLASS" => "OPS", "VALUE" => $t["VALUE"], "NODETYPE" => $this->ops[$t["VALUE"]]["NODETYPE"], "PNUM" => $pnum, "DEPTH" => $depth, "LB" => $tree, "RB" => null)); + } + else { + // ce mot n'est pas un opérateur + $pnum = null; + $nodetype = PHRASEA_KEYLIST; + if ($t["CLASS"] == "TOK_WORD" && isset($this->spw[$t["VALUE"]]) && ! $inquote) { + // mais c'est un mot 'spécial' de phrasea ('last', 'all') + $type = $this->spw[$t["VALUE"]]["CLASS"]; + $nodetype = $this->spw[$t["VALUE"]]["NODETYPE"]; + if ($this->spw[$t["VALUE"]]["CANNUM"]) { + // 'last' peut étre suivi d'un nombre + if ($tn = $this->nexttoken()) { + if ($tn["CLASS"] == "TOK_WORD" && is_numeric($tn["VALUE"])) + $pnum = (int) $tn["VALUE"]; + else + $this->ungettoken($tn["VALUE"]); + } + } + } + else { + //printf("sdfsdfsdfsd
              "); + $type = $inquote ? "QSIMPLE" : "SIMPLE"; + } + + return($this->addsimple($t, $type, $nodetype, $pnum, $tree, $depth)); + } + break; } - elseif ($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") - { - if (!isset($tree["RB"]) || !$tree["RB"]) - { - // un [xxx] peut suivre un opérateur, c'est un paramétre normalement numérique - $tree["PNUM"] = $t["VALUE"]; - } - else - { - // [xxx] suit un terme déjé en branche droite ? (ex: a ou b[k]) - if ($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") - $tree["RB"]["CONTEXT"] = $t["VALUE"]; - else - { - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf("le contexte [%s] ne peut suivre qu'un terme ou un opérateur
              ", $t["VALUE"]); + } - return(null); - } - } - } - else - { - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf("le contexte [%s] ne peut suivre qu'un terme ou un opérateur
              ", $t["VALUE"]); + function addsimple($t, $type, $nodetype, $pnum, $tree, $depth) + { + $nok = 0; + $registry = registry::get_instance(); + $w = $t["VALUE"]; + if ($w != "?" && $w != "*") { // on laisse passer les 'isolés' pour les traiter plus tard comme des mots vides + for ($i = 0; $i < strlen($w); $i ++ ) { + $c = substr($w, $i, 1); + if ($c == "?" || $c == "*") { + if ($nok < $registry->get('GV_min_letters_truncation')) { + if ($this->errmsg != "") + $this->errmsg .= sprintf("\\n"); + $this->errmsg .= _('qparser:: Formulation incorrecte, necessite plus de caractere : ') . "
              " . $registry->get('GV_min_letters_truncation'); - return(null); - } - - return($tree); - break; - case "TOK_CMP": - // < > <= >= <> = : sont des opérateurs de comparaison - if (!$tree) - { - // printf("\nUne question ne peut commencer par '" . $t["VALUE"] . "'
              "); - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf(_('qparser::erreur : une question ne peut commencer par %s'), $t["VALUE"]); - - return(null); - } - if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) - { - // printf("'" . $t["VALUE"] . "' ne peut suivre un opérateur
              "); - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, ne peut suivre un operateur : %s'), $t["VALUE"]); - - return(null); - } - - return(array("CLASS" => "OPK", "VALUE" => $t["VALUE"], "NODETYPE" => $this->opk[$t["VALUE"]]["NODETYPE"], "PNUM" => null, "DEPTH" => $depth, "LB" => $tree, "RB" => null)); - break; - case "TOK_WORD": - if ($t["CLASS"] == "TOK_WORD" && isset($this->ops[$t["VALUE"]]) && !$inquote) - { - // ce mot est un opérateur phrasea - if (!$tree) - { - // printf("\n581 : Une question ne peut commencer par un opérateur
              "); - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf(_('qparser::erreur : une question ne peut commencer par %s'), $t["VALUE"]); - - return(null); - } - if (($tree["CLASS"] == "OPS" || $tree["CLASS"] == "OPK") && $tree["RB"] == null) - { - - // printf("\n586 : Un opérateur ne peut suivre un opérateur
              "); - if ($this->errmsg != "") - $this->errmsg .= "\\n"; - $this->errmsg .= sprintf(_('qparser::Formulation incorrecte, %s ne peut suivre un operateur'), $t["VALUE"]); - - return(null); - } - $pnum = null; - if ($this->ops[$t["VALUE"]]["CANNUM"]) - { - // cet opérateur peut étre suivi d'un nombre ('near', 'before', 'after') - if ($tn = $this->nexttoken()) - { - if ($tn["CLASS"] == "TOK_WORD" && is_numeric($tn["VALUE"])) - $pnum = (int) $tn["VALUE"]; - else - $this->ungettoken($tn["VALUE"]); - } - } - - return(array("CLASS" => "OPS", "VALUE" => $t["VALUE"], "NODETYPE" => $this->ops[$t["VALUE"]]["NODETYPE"], "PNUM" => $pnum, "DEPTH" => $depth, "LB" => $tree, "RB" => null)); - } - else - { - // ce mot n'est pas un opérateur - $pnum = null; - $nodetype = PHRASEA_KEYLIST; - if ($t["CLASS"] == "TOK_WORD" && isset($this->spw[$t["VALUE"]]) && !$inquote) - { - // mais c'est un mot 'spécial' de phrasea ('last', 'all') - $type = $this->spw[$t["VALUE"]]["CLASS"]; - $nodetype = $this->spw[$t["VALUE"]]["NODETYPE"]; - if ($this->spw[$t["VALUE"]]["CANNUM"]) - { - // 'last' peut étre suivi d'un nombre - if ($tn = $this->nexttoken()) - { - if ($tn["CLASS"] == "TOK_WORD" && is_numeric($tn["VALUE"])) - $pnum = (int) $tn["VALUE"]; + return(null); + } + // $nok = 0; + } else - $this->ungettoken($tn["VALUE"]); - } + $nok ++; } - } - else - { - //printf("sdfsdfsdfsd
              "); - $type = $inquote ? "QSIMPLE" : "SIMPLE"; - } - - return($this->addsimple($t, $type, $nodetype, $pnum, $tree, $depth)); } - break; + if ( ! $tree) { + return(array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth)); + } + switch ($tree["CLASS"]) { + case "SIMPLE": + case "QSIMPLE": + if ($type == "SIMPLE" || $type == "QSIMPLE") + $tree["VALUE"][] = $t["VALUE"]; + else { + $tree = array("CLASS" => "OPS", + "VALUE" => "et", + "NODETYPE" => PHRASEA_OP_AND, + "PNUM" => null, + "DEPTH" => $depth, + "LB" => $tree, + "RB" => array("CLASS" => $type, + "NODETYPE" => $nodetype, + "VALUE" => array($t["VALUE"]), + "PNUM" => $pnum, + "DEPTH" => $depth)); + } + + return($tree); + case "OPS": + case "OPK": + if ($tree["RB"] == null) { + $tree["RB"] = array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth); + + return($tree); + } else { + if (($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") && $tree["RB"]["DEPTH"] == $depth) { + $tree["RB"]["VALUE"][] = $t["VALUE"]; + + return($tree); + } + if (($tree["RB"]["CLASS"] == "PHRASEA_KW_LAST" || $tree["RB"]["CLASS"] == "PHRASEA_KW_ALL") && $tree["RB"]["DEPTH"] == $depth) { + $tree["RB"] = array("CLASS" => "OPS", + "VALUE" => "et", + "NODETYPE" => PHRASEA_OP_AND, + "PNUM" => null, + "DEPTH" => $depth, + "LB" => $tree["RB"], + "RB" => array("CLASS" => $type, + "NODETYPE" => $nodetype, + "VALUE" => array($t["VALUE"]), + "PNUM" => $pnum, + "DEPTH" => $depth)); + + return($tree); + } + + return(array("CLASS" => "OPS", + "VALUE" => $this->defaultop["VALUE"], + "NODETYPE" => $this->defaultop["NODETYPE"], + "PNUM" => $this->defaultop["PNUM"], + "DEPTH" => $depth, + "LB" => $tree, + "RB" => array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth) + )); + } + case "PHRASEA_KW_LAST": + case "PHRASEA_KW_ALL": + return(array("CLASS" => "OPS", + "VALUE" => "et", + "NODETYPE" => PHRASEA_OP_AND, + "PNUM" => null, + "DEPTH" => $depth, + "LB" => $tree, + "RB" => array("CLASS" => $type, + "NODETYPE" => $nodetype, + "VALUE" => array($t["VALUE"]), + "PNUM" => $pnum, + "DEPTH" => $depth))); + } } - } - function addsimple($t, $type, $nodetype, $pnum, $tree, $depth) - { - $nok = 0; - $registry = registry::get_instance(); - $w = $t["VALUE"]; - if ($w != "?" && $w != "*") // on laisse passer les 'isolés' pour les traiter plus tard comme des mots vides + function ungettoken($s) { - for ($i = 0; $i < strlen($w); $i++) - { - $c = substr($w, $i, 1); - if ($c == "?" || $c == "*") - { - if ($nok < $registry->get('GV_min_letters_truncation')) - { - if ($this->errmsg != "") - $this->errmsg .= sprintf("\\n"); - $this->errmsg .= _('qparser:: Formulation incorrecte, necessite plus de caractere : ') . "
              " . $registry->get('GV_min_letters_truncation'); + $this->phq = $s . " " . $this->phq; + } + function nexttoken($inquote = false) + { + if ($this->phq == "") return(null); - } - // $nok = 0; - } - else - $nok++; - } - } - if (!$tree) - { - return(array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth)); - } - switch ($tree["CLASS"]) - { - case "SIMPLE": - case "QSIMPLE": - if ($type == "SIMPLE" || $type == "QSIMPLE") - $tree["VALUE"][] = $t["VALUE"]; - else - { - $tree = array("CLASS" => "OPS", - "VALUE" => "et", - "NODETYPE" => PHRASEA_OP_AND, - "PNUM" => null, - "DEPTH" => $depth, - "LB" => $tree, - "RB" => array("CLASS" => $type, - "NODETYPE" => $nodetype, - "VALUE" => array($t["VALUE"]), - "PNUM" => $pnum, - "DEPTH" => $depth)); - } + switch ($c = substr($this->phq, 0, 1)) { + case "<": + case ">": + if ($inquote) { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return($tree); - case "OPS": - case "OPK": - if ($tree["RB"] == null) - { - $tree["RB"] = array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth); + return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); + } + $c2 = $c . substr($this->phq, 1, 1); + if ($c2 == "<=" || $c2 == ">=" || $c2 == "<>") { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 2, 99999, 'UTF-8'), 'UTF-8'); + $c = $c2; + } else { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + } - return($tree); - } - else - { - if (($tree["RB"]["CLASS"] == "SIMPLE" || $tree["RB"]["CLASS"] == "QSIMPLE") && $tree["RB"]["DEPTH"] == $depth) - { - $tree["RB"]["VALUE"][] = $t["VALUE"]; + return(array("CLASS" => "TOK_CMP", "VALUE" => $c)); + break; + case "=": + if ($inquote) { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return($tree); - } - if (($tree["RB"]["CLASS"] == "PHRASEA_KW_LAST" || $tree["RB"]["CLASS"] == "PHRASEA_KW_ALL") && $tree["RB"]["DEPTH"] == $depth) - { - $tree["RB"] = array("CLASS" => "OPS", - "VALUE" => "et", - "NODETYPE" => PHRASEA_OP_AND, - "PNUM" => null, - "DEPTH" => $depth, - "LB" => $tree["RB"], - "RB" => array("CLASS" => $type, - "NODETYPE" => $nodetype, - "VALUE" => array($t["VALUE"]), - "PNUM" => $pnum, - "DEPTH" => $depth)); + return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); + } + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return($tree); - } + return(array("CLASS" => "TOK_CMP", "VALUE" => "=")); + break; + case ":": + if ($inquote) { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return(array("CLASS" => "OPS", - "VALUE" => $this->defaultop["VALUE"], - "NODETYPE" => $this->defaultop["NODETYPE"], - "PNUM" => $this->defaultop["PNUM"], - "DEPTH" => $depth, - "LB" => $tree, - "RB" => array("CLASS" => $type, "NODETYPE" => $nodetype, "VALUE" => array($t["VALUE"]), "PNUM" => $pnum, "DEPTH" => $depth) - )); - } - case "PHRASEA_KW_LAST": - case "PHRASEA_KW_ALL": - return(array("CLASS" => "OPS", - "VALUE" => "et", - "NODETYPE" => PHRASEA_OP_AND, - "PNUM" => null, - "DEPTH" => $depth, - "LB" => $tree, - "RB" => array("CLASS" => $type, - "NODETYPE" => $nodetype, - "VALUE" => array($t["VALUE"]), - "PNUM" => $pnum, - "DEPTH" => $depth))); - } - } + return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); + } + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - function ungettoken($s) - { - $this->phq = $s . " " . $this->phq; - } + return(array("CLASS" => "TOK_CMP", "VALUE" => ":")); + break; + case "(": + if ($inquote) { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - function nexttoken($inquote = false) - { - if ($this->phq == "") + return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); + } + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return(null); - switch ($c = substr($this->phq, 0, 1)) - { - case "<": - case ">": - if ($inquote) - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + return(array("CLASS" => "TOK_LP", "VALUE" => "(")); + break; + case ")": + if ($inquote) { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); - } - $c2 = $c . substr($this->phq, 1, 1); - if ($c2 == "<=" || $c2 == ">=" || $c2 == "<>") - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 2, 99999, 'UTF-8'), 'UTF-8'); - $c = $c2; - } - else - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - } + return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); + } + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return(array("CLASS" => "TOK_CMP", "VALUE" => $c)); - break; - case "=": - if ($inquote) - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + return(array("CLASS" => "TOK_RP", "VALUE" => ")")); + break; + case "[": + // if($inquote) + // { + // $this->phq = ltrim(substr($this->phq, 1)); + // return(array("CLASS"=>"TOK_VOID", "VALUE"=>$c)); + // } + // un '[' introduit un contexte qu'on lit jusqu'au ']' + $closeb = mb_strpos($this->phq, "]", 1, 'UTF-8'); + if ($closeb !== false) { + $context = $this->mb_trim(mb_substr($this->phq, 1, $closeb - 1, 'UTF-8'), 'UTF-8'); + $this->phq = $this->mb_ltrim(mb_substr($this->phq, $closeb + 1, 99999, 'UTF-8'), 'UTF-8'); + } else { + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + $this->phq = ""; + } + $context = $this->unicode->remove_indexer_chars($context); - return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); - } - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + return(array("CLASS" => "TOK_CONTEXT", "VALUE" => $context)); + break; + /* + case "]": + // if($inquote) + // { + // $this->phq = ltrim(substr($this->phq, 1)); + // return(array("CLASS"=>"TOK_VOID", "VALUE"=>$c)); + // } + $this->phq = ltrim(substr($this->phq, 1)); - return(array("CLASS" => "TOK_CMP", "VALUE" => "=")); - break; - case ":": - if ($inquote) - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); + return(array("CLASS"=>"TOK_RB", "VALUE"=>"]")); + break; + */ + case "\"": + $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); - } - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_CMP", "VALUE" => ":")); - break; - case "(": - if ($inquote) - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); - } - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_LP", "VALUE" => "(")); - break; - case ")": - if ($inquote) - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_VOID", "VALUE" => $c)); - } - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_RP", "VALUE" => ")")); - break; - case "[": - // if($inquote) - // { - // $this->phq = ltrim(substr($this->phq, 1)); - // return(array("CLASS"=>"TOK_VOID", "VALUE"=>$c)); - // } - // un '[' introduit un contexte qu'on lit jusqu'au ']' - $closeb = mb_strpos($this->phq, "]", 1, 'UTF-8'); - if ($closeb !== false) - { - $context = $this->mb_trim(mb_substr($this->phq, 1, $closeb - 1, 'UTF-8'), 'UTF-8'); - $this->phq = $this->mb_ltrim(mb_substr($this->phq, $closeb + 1, 99999, 'UTF-8'), 'UTF-8'); - } - else - { - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - $this->phq = ""; - } - $context = $this->unicode->remove_indexer_chars($context); - - return(array("CLASS" => "TOK_CONTEXT", "VALUE" => $context)); - break; - /* - case "]": - // if($inquote) - // { - // $this->phq = ltrim(substr($this->phq, 1)); - // return(array("CLASS"=>"TOK_VOID", "VALUE"=>$c)); - // } - $this->phq = ltrim(substr($this->phq, 1)); - - return(array("CLASS"=>"TOK_RB", "VALUE"=>"]")); - break; - */ - case "\"": - $this->phq = $this->mb_ltrim(mb_substr($this->phq, 1, 99999, 'UTF-8'), 'UTF-8'); - - return(array("CLASS" => "TOK_QUOTE", "VALUE" => "\"")); - break; - default: - $l = mb_strlen($this->phq, 'UTF-8'); - $t = ""; - $c_utf8 = ""; - for ($i = 0; $i < $l; $i++) - { - if (!$this->unicode->has_indexer_bad_char(($c_utf8 = mb_substr($this->phq, $i, 1, 'UTF-8')))) - { - // $c = mb_strtolower($c); - // $t .= isset($this->noaccent[$c]) ? $this->noaccent[$c] : $c; - $t .= $this->unicode->remove_diacritics(mb_strtolower($c_utf8)); - } - else - break; - } + return(array("CLASS" => "TOK_QUOTE", "VALUE" => "\"")); + break; + default: + $l = mb_strlen($this->phq, 'UTF-8'); + $t = ""; + $c_utf8 = ""; + for ($i = 0; $i < $l; $i ++ ) { + if ( ! $this->unicode->has_indexer_bad_char(($c_utf8 = mb_substr($this->phq, $i, 1, 'UTF-8')))) { + // $c = mb_strtolower($c); + // $t .= isset($this->noaccent[$c]) ? $this->noaccent[$c] : $c; + $t .= $this->unicode->remove_diacritics(mb_strtolower($c_utf8)); + } + else + break; + } // if ($c_utf8 == "(" || $c_utf8 == ")" || $c_utf8 == "[" || $c_utf8 == "]" || $c_utf8 == "=" || $c_utf8 == ":" || $c_utf8 == "<" || $c_utf8 == ">" || $c_utf8 == "\"") - if (in_array($c_utf8, array("(", ")", "[", "]", "=", ":", "<", ">", "\""))) - { - // ces caractéres sont des délimiteurs avec un sens, il faut les garder - $this->phq = $this->mb_ltrim(mb_substr($this->phq, $i, 99999, 'UTF-8'), 'UTF-8'); + if (in_array($c_utf8, array("(", ")", "[", "]", "=", ":", "<", ">", "\""))) { + // ces caractéres sont des délimiteurs avec un sens, il faut les garder + $this->phq = $this->mb_ltrim(mb_substr($this->phq, $i, 99999, 'UTF-8'), 'UTF-8'); + } else { + // le délimiteur était une simple ponctuation, on le saute + $this->phq = $this->mb_ltrim(mb_substr($this->phq, $i + 1, 99999, 'UTF-8'), 'UTF-8'); + } + if ($t != "") + return(array("CLASS" => "TOK_WORD", "VALUE" => $t)); + else + return(array("CLASS" => "TOK_VOID", "VALUE" => $t)); + break; } - else - { - // le délimiteur était une simple ponctuation, on le saute - $this->phq = $this->mb_ltrim(mb_substr($this->phq, $i + 1, 99999, 'UTF-8'), 'UTF-8'); - } - if ($t != "") - - return(array("CLASS" => "TOK_WORD", "VALUE" => $t)); - else - - return(array("CLASS" => "TOK_VOID", "VALUE" => $t)); - break; } - } - } diff --git a/lib/classes/searchEngine/adapter/sphinx/engine.class.php b/lib/classes/searchEngine/adapter/sphinx/engine.class.php index 76dfb1345f..4f2cd0e1fa 100644 --- a/lib/classes/searchEngine/adapter/sphinx/engine.class.php +++ b/lib/classes/searchEngine/adapter/sphinx/engine.class.php @@ -18,420 +18,373 @@ require_once __DIR__ . '/../../../../vendor/sphinx/sphinxapi.php'; */ class searchEngine_adapter_sphinx_engine extends searchEngine_adapter_abstract implements searchEngine_adapter_interface { + /** + * + * @var sphinxClient + */ + protected $sphinx; - /** - * - * @var sphinxClient - */ - protected $sphinx; + /** + * + * @var array + */ + protected $distinct_sbas = array(); - /** - * - * @var array - */ - protected $distinct_sbas = array(); + /** + * + * @var boolean + */ + protected $search_in_field = false; - /** - * - * @var boolean - */ - protected $search_in_field = false; + /** + * + * @var searchEngine_options + */ + protected $options; - /** - * - * @var searchEngine_options - */ - protected $options; + /** + * + * @var boolean + */ + protected $search_unique_record = false; - /** - * - * @var boolean - */ - protected $search_unique_record = false; - - /** - * - * @return searchEngine_adapter_sphinx_engine - */ - public function __construct() - { - $registry = registry::get_instance(); - - $this->sphinx = new SphinxClient (); - $this->sphinx->SetArrayResult(true); - - $this->sphinx->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); - $this->sphinx->SetConnectTimeout(1); - - return $this; - } - - /** - * - * @param searchEngine_options $options - * @return searchEngine_adapter_sphinx_engine - */ - public function set_options(searchEngine_options $options) - { - $this->options = $options; - - $filters = array(); - - $sbas_ids = array(); - - $this->use_stemming = $options->get_use_stemming(); - $this->locale = $options->get_locale(); - - foreach ($options->get_bases() as $bas) + /** + * + * @return searchEngine_adapter_sphinx_engine + */ + public function __construct() { - $this->distinct_sbas[phrasea::sbasFromBas($bas)] = true; - $key = phrasea::sbasFromBas($bas) . '_' . phrasea::collFromBas($bas); - $sbas_id = phrasea::sbasFromBas($bas); - $sbas_ids[$sbas_id] = $sbas_id; - $filters[] = crc32($key); - } + $registry = registry::get_instance(); - if ($filters) - { - $this->sphinx->SetFilter('crc_sbas_coll', $filters); - } + $this->sphinx = new SphinxClient (); + $this->sphinx->SetArrayResult(true); - $this->sphinx->SetFilter('deleted', array(0)); + $this->sphinx->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); + $this->sphinx->SetConnectTimeout(1); - $filters = array(); - - foreach ($sbas_ids as $sbas_id) - { - $databox = databox::get_instance($sbas_id); - $fields = $databox->get_meta_structure(); - - foreach ($fields as $field) - { - if ( ! in_array($field->get_id(), $options->get_fields())) - continue; - - $key = $sbas_id . '_' . $field->get_id(); - $filters[] = crc32($key); - $this->search_in_field = true; - } - } - - $crc_coll_business = array(); - - if ($options->get_business_fields()) - { - $this->search_in_field = true; - - foreach ($options->get_business_fields() as $base_id) - { - $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_1'); - $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_0'); - } - - $non_business = array_diff($options->get_bases(), $options->get_business_fields()); - - foreach ($non_business as $base_id) - { - $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_0'); - } - - $this->sphinx->SetFilter('crc_coll_business', $crc_coll_business); - } - elseif ($this->search_in_field) - { - $this->sphinx->SetFilter('business', array(0)); - } - - - if ($filters) - { - $this->sphinx->SetFilter('crc_struct_id', $filters); + return $this; } /** - * @todo : enhance : check status better + * + * @param searchEngine_options $options + * @return searchEngine_adapter_sphinx_engine */ - foreach ($sbas_ids as $sbas_id) + public function set_options(searchEngine_options $options) { - $databox = databox::get_instance($sbas_id); - $s_status = $databox->get_statusbits(); - $status_opts = $options->get_status(); - foreach ($s_status as $n => $status) - { - if ( ! array_key_exists($n, $status_opts)) - continue; - if ( ! array_key_exists($sbas_id, $status_opts[$n])) - continue; - $crc = crc32($sbas_id . '_' . $n); - $this->sphinx->SetFilter('status', array($crc), ($status_opts[$n][$sbas_id] == '0')); - } - } + $this->options = $options; - $this->sphinx->SetFilter('parent_record_id', array($options->get_search_type())); + $filters = array(); - $filters = array(); + $sbas_ids = array(); - if ($options->get_record_type() != '') - { - $filters[] = crc32($options->get_record_type()); - } + $this->use_stemming = $options->get_use_stemming(); + $this->locale = $options->get_locale(); - if ($filters) - { - $this->sphinx->SetFilter('crc_type', $filters); - } - - $ord = ''; - switch ($options->get_sortord()) - { - case searchEngine_options::SORT_MODE_ASC: - $ord = 'ASC'; - break; - case searchEngine_options::SORT_MODE_DESC: - default: - $ord = 'DESC'; - break; - } - - switch ($options->get_sortby()) - { - case searchEngine_options::SORT_RANDOM: - $sort = '@random'; - break; - case searchEngine_options::SORT_RELEVANCE: - default: - $sort = '@relevance ' . $ord . ', created_on ' . $ord; - break; - case searchEngine_options::SORT_CREATED_ON: - $sort = 'created_on ' . $ord; - break; - } - - $this->sphinx->SetGroupBy('crc_sbas_record', SPH_GROUPBY_ATTR, $sort); - - return $this; - } - - /** - * - * @return array - */ - public function get_status() - { - $status = $this->sphinx->Status(); - if (false === $status) - throw new Exception(_('Sphinx server is offline')); - - return $status; - } - - /** - * - * @return searchEngine_adapter_sphinx_engine - */ - protected function parse_query() - { - $this->query = trim($this->query); - - while (substr($this->query, 0, 1) === '(' && substr($this->query, -1) === ')') - $this->query = substr($this->query, 1, (mb_strlen($this->query) - 2)); - - if ($this->query == 'all') - $this->query = ''; - - while (mb_strpos($this->query, ' ') !== false) - { - $this->query = str_replace(' ', ' ', $this->query); - } - - $preg = preg_match('/\s?recordid\s?=\s?([0-9]+)/i', $this->query, $matches, 0, 0); - - if ($preg > 0) - { - $this->sphinx->SetFilter('record_id', array($matches[1])); - $this->query = ''; - $this->search_unique_record = true; - } - else - { - $offset = 0; - while (($pos = mb_strpos($this->query, '-', $offset)) !== false) - { - $offset = $pos + 1; - if ($pos === 0) - { - continue; + foreach ($options->get_bases() as $bas) { + $this->distinct_sbas[phrasea::sbasFromBas($bas)] = true; + $key = phrasea::sbasFromBas($bas) . '_' . phrasea::collFromBas($bas); + $sbas_id = phrasea::sbasFromBas($bas); + $sbas_ids[$sbas_id] = $sbas_id; + $filters[] = crc32($key); } - if (mb_substr($this->query, ($pos - 1), 1) !== ' ') - { - $this->query = mb_substr($this->query, 0, ($pos)) . ' ' . mb_substr($this->query, $pos + 1); + + if ($filters) { + $this->sphinx->SetFilter('crc_sbas_coll', $filters); } - } - $this->query = str_ireplace(array(' ou ', ' or '), '|', $this->query); - $this->query = str_ireplace(array(' sauf ', ' except '), ' -', $this->query); - $this->query = str_ireplace(array(' and ', ' et '), ' +', $this->query); - } + $this->sphinx->SetFilter('deleted', array(0)); - return $this; - } + $filters = array(); - /** - * - * @param string $query - * @param int $offset - * @param int $perPage - * @return searchEngine_results - */ - public function results($query, $offset, $perPage) - { + foreach ($sbas_ids as $sbas_id) { + $databox = databox::get_instance($sbas_id); + $fields = $databox->get_meta_structure(); - assert(is_int($offset)); - assert($offset >= 0); - assert(is_int($perPage)); - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); + foreach ($fields as $field) { + if ( ! in_array($field->get_id(), $options->get_fields())) + continue; - $page = ceil($offset / $perPage) + 1; - - $this->current_page = $page; - $this->perPage = $perPage; - $this->offset_start = $offset; - $this->query = $query; - - $this->sphinx->SetLimits($offset, $this->perPage); - $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); - $this->parse_query(); - - - $index = '*'; - - $params = phrasea::sbas_params(); - - $index_keys = array(); - foreach ($params as $sbas_id => $params) - { - if ( ! array_key_exists($sbas_id, $this->distinct_sbas)) - continue; - $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname']))); - } - - if (count($index_keys) > 0) - { - if ($this->search_in_field === false) - { - $index = ''; - $found = false; - if ($this->query !== '' && $this->options->get_use_stemming()) - { - if ($session->get_I18n() == 'fr') - { - $index .= ', documents' . implode('_stemmed_fr, documents', $index_keys) . '_stemmed_fr'; - $found = true; - } - elseif ($session->get_I18n() == 'en') - { - $index .= ', documents' . implode('_stemmed_en, documents', $index_keys) . '_stemmed_en'; - $found = true; - } + $key = $sbas_id . '_' . $field->get_id(); + $filters[] = crc32($key); + $this->search_in_field = true; + } } - if ( ! $found) - $index .= 'documents' . implode(', documents', $index_keys); - $index .= ', docs_realtime' . implode(', docs_realtime', $index_keys); - } - else - { - $index = ''; - $found = false; - if ($this->query !== '' && $this->options->get_use_stemming() && $session->get_I18n() == 'fr') - { - if ($session->get_I18n() == 'fr') - { - $index .= ', metadatas' . implode('_stemmed_fr, metadatas', $index_keys) . '_stemmed_fr'; - $found = true; - } - elseif ($session->get_I18n() == 'en') - { - $index .= ', metadatas' . implode('_stemmed_en, metadatas', $index_keys) . '_stemmed_en'; - $found = true; - } + + $crc_coll_business = array(); + + if ($options->get_business_fields()) { + $this->search_in_field = true; + + foreach ($options->get_business_fields() as $base_id) { + $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_1'); + $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_0'); + } + + $non_business = array_diff($options->get_bases(), $options->get_business_fields()); + + foreach ($non_business as $base_id) { + $crc_coll_business[] = crc32(phrasea::collFromBas($base_id) . '_0'); + } + + $this->sphinx->SetFilter('crc_coll_business', $crc_coll_business); + } elseif ($this->search_in_field) { + $this->sphinx->SetFilter('business', array(0)); } - if ( ! $found) - $index = 'metadatas' . implode(',metadatas', $index_keys); - $index .= ', metas_realtime' . implode(', metas_realtime', $index_keys); - } - } - $this->current_index = $index; - $res = $this->sphinx->Query($this->query, $this->current_index); - $results = new set_result(); - - if ($res === false) - { - if ($this->sphinx->IsConnectError() === true) - { - $this->error = _('Sphinx server is offline'); - } - else - { - $this->error = $this->sphinx->GetLastError(); - } - $this->warning = $this->sphinx->GetLastWarning(); - } - else - { - $this->error = $res['error']; - $this->warning = $res['warning']; - - $this->total_time = $res['time']; - $this->total_results = $res['total_found']; - $this->total_available = $res['total']; - - $courcahnum = $this->offset_start; - - if (isset($res['matches'])) - { - foreach ($res['matches'] as $record_id => $match) - { - try - { - $record = - new record_adapter( - $match['attrs']['sbas_id'] - , $match['attrs']['record_id'] - , $courcahnum - ); - - $results->add_element($record); - } - catch (Exception $e) - { - - } - $courcahnum ++; + if ($filters) { + $this->sphinx->SetFilter('crc_struct_id', $filters); } - } + + /** + * @todo : enhance : check status better + */ + foreach ($sbas_ids as $sbas_id) { + $databox = databox::get_instance($sbas_id); + $s_status = $databox->get_statusbits(); + $status_opts = $options->get_status(); + foreach ($s_status as $n => $status) { + if ( ! array_key_exists($n, $status_opts)) + continue; + if ( ! array_key_exists($sbas_id, $status_opts[$n])) + continue; + $crc = crc32($sbas_id . '_' . $n); + $this->sphinx->SetFilter('status', array($crc), ($status_opts[$n][$sbas_id] == '0')); + } + } + + $this->sphinx->SetFilter('parent_record_id', array($options->get_search_type())); + + $filters = array(); + + if ($options->get_record_type() != '') { + $filters[] = crc32($options->get_record_type()); + } + + if ($filters) { + $this->sphinx->SetFilter('crc_type', $filters); + } + + $ord = ''; + switch ($options->get_sortord()) { + case searchEngine_options::SORT_MODE_ASC: + $ord = 'ASC'; + break; + case searchEngine_options::SORT_MODE_DESC: + default: + $ord = 'DESC'; + break; + } + + switch ($options->get_sortby()) { + case searchEngine_options::SORT_RANDOM: + $sort = '@random'; + break; + case searchEngine_options::SORT_RELEVANCE: + default: + $sort = '@relevance ' . $ord . ', created_on ' . $ord; + break; + case searchEngine_options::SORT_CREATED_ON: + $sort = 'created_on ' . $ord; + break; + } + + $this->sphinx->SetGroupBy('crc_sbas_record', SPH_GROUPBY_ATTR, $sort); + + return $this; } - return new searchEngine_results($results, $this); - } + /** + * + * @return array + */ + public function get_status() + { + $status = $this->sphinx->Status(); + if (false === $status) + throw new Exception(_('Sphinx server is offline')); - /** - * - * @param string $keyword - * @return string - */ - function BuildTrigrams($keyword) - { - $t = "__" . $keyword . "__"; + return $status; + } - $trigrams = ""; - for ($i = 0; $i < strlen($t) - 2; $i ++ ) - $trigrams .= substr($t, $i, 3) . " "; + /** + * + * @return searchEngine_adapter_sphinx_engine + */ + protected function parse_query() + { + $this->query = trim($this->query); - return $trigrams; - } + while (substr($this->query, 0, 1) === '(' && substr($this->query, -1) === ')') + $this->query = substr($this->query, 1, (mb_strlen($this->query) - 2)); + + if ($this->query == 'all') + $this->query = ''; + + while (mb_strpos($this->query, ' ') !== false) { + $this->query = str_replace(' ', ' ', $this->query); + } + + $preg = preg_match('/\s?recordid\s?=\s?([0-9]+)/i', $this->query, $matches, 0, 0); + + if ($preg > 0) { + $this->sphinx->SetFilter('record_id', array($matches[1])); + $this->query = ''; + $this->search_unique_record = true; + } else { + $offset = 0; + while (($pos = mb_strpos($this->query, '-', $offset)) !== false) { + $offset = $pos + 1; + if ($pos === 0) { + continue; + } + if (mb_substr($this->query, ($pos - 1), 1) !== ' ') { + $this->query = mb_substr($this->query, 0, ($pos)) . ' ' . mb_substr($this->query, $pos + 1); + } + } + + $this->query = str_ireplace(array(' ou ', ' or '), '|', $this->query); + $this->query = str_ireplace(array(' sauf ', ' except '), ' -', $this->query); + $this->query = str_ireplace(array(' and ', ' et '), ' +', $this->query); + } + + return $this; + } + + /** + * + * @param string $query + * @param int $offset + * @param int $perPage + * @return searchEngine_results + */ + public function results($query, $offset, $perPage) + { + + assert(is_int($offset)); + assert($offset >= 0); + assert(is_int($perPage)); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + + $page = ceil($offset / $perPage) + 1; + + $this->current_page = $page; + $this->perPage = $perPage; + $this->offset_start = $offset; + $this->query = $query; + + $this->sphinx->SetLimits($offset, $this->perPage); + $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); + $this->parse_query(); + + + $index = '*'; + + $params = phrasea::sbas_params(); + + $index_keys = array(); + foreach ($params as $sbas_id => $params) { + if ( ! array_key_exists($sbas_id, $this->distinct_sbas)) + continue; + $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname']))); + } + + if (count($index_keys) > 0) { + if ($this->search_in_field === false) { + $index = ''; + $found = false; + if ($this->query !== '' && $this->options->get_use_stemming()) { + if ($session->get_I18n() == 'fr') { + $index .= ', documents' . implode('_stemmed_fr, documents', $index_keys) . '_stemmed_fr'; + $found = true; + } elseif ($session->get_I18n() == 'en') { + $index .= ', documents' . implode('_stemmed_en, documents', $index_keys) . '_stemmed_en'; + $found = true; + } + } + if ( ! $found) + $index .= 'documents' . implode(', documents', $index_keys); + $index .= ', docs_realtime' . implode(', docs_realtime', $index_keys); + } + else { + $index = ''; + $found = false; + if ($this->query !== '' && $this->options->get_use_stemming() && $session->get_I18n() == 'fr') { + if ($session->get_I18n() == 'fr') { + $index .= ', metadatas' . implode('_stemmed_fr, metadatas', $index_keys) . '_stemmed_fr'; + $found = true; + } elseif ($session->get_I18n() == 'en') { + $index .= ', metadatas' . implode('_stemmed_en, metadatas', $index_keys) . '_stemmed_en'; + $found = true; + } + } + if ( ! $found) + $index = 'metadatas' . implode(',metadatas', $index_keys); + $index .= ', metas_realtime' . implode(', metas_realtime', $index_keys); + } + } + + $this->current_index = $index; + + $res = $this->sphinx->Query($this->query, $this->current_index); + $results = new set_result(); + + if ($res === false) { + if ($this->sphinx->IsConnectError() === true) { + $this->error = _('Sphinx server is offline'); + } else { + $this->error = $this->sphinx->GetLastError(); + } + $this->warning = $this->sphinx->GetLastWarning(); + } else { + $this->error = $res['error']; + $this->warning = $res['warning']; + + $this->total_time = $res['time']; + $this->total_results = $res['total_found']; + $this->total_available = $res['total']; + + $courcahnum = $this->offset_start; + + if (isset($res['matches'])) { + foreach ($res['matches'] as $record_id => $match) { + try { + $record = + new record_adapter( + $match['attrs']['sbas_id'] + , $match['attrs']['record_id'] + , $courcahnum + ); + + $results->add_element($record); + } catch (Exception $e) { + + } + $courcahnum ++; + } + } + } + + return new searchEngine_results($results, $this); + } + + /** + * + * @param string $keyword + * @return string + */ + function BuildTrigrams($keyword) + { + $t = "__" . $keyword . "__"; + + $trigrams = ""; + for ($i = 0; $i < strlen($t) - 2; $i ++ ) + $trigrams .= substr($t, $i, 3) . " "; + + return $trigrams; + } // public function get_index_suggestions($keyword) // { @@ -476,329 +429,287 @@ class searchEngine_adapter_sphinx_engine extends searchEngine_adapter_abstract i // return $ret; // } - protected function get_sugg_trigrams($word) - { - - $trigrams = $this->BuildTrigrams($word); - $query = "\"$trigrams\"/1"; - $len = strlen($word); - - $this->sphinx->ResetGroupBy(); - $this->sphinx->ResetFilters(); - - $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); - $this->sphinx->SetRankingMode(SPH_RANK_WORDCOUNT); - $this->sphinx->SetFilterRange("len", $len - 2, $len + 4); - - $this->sphinx->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC"); - $this->sphinx->SetLimits(0, 10); - - $params = phrasea::sbas_params(); - - $index_keys = array(); - foreach ($params as $sbas_id => $p) - { - if ( ! array_key_exists($sbas_id, $this->distinct_sbas)) - continue; - $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $p['host'], $p['port'], $p['user'], $p['dbname']))); - } - $index = 'suggest' . implode(',suggest', $index_keys); - - $res = $this->sphinx->Query($query, $index); - - if ($this->sphinx->Status() === false) - { - return array(); - } - - if ( ! $res || ! isset($res["matches"])) - { - return array(); - } - - $this->sphinx->ResetGroupBy(); - $this->sphinx->ResetFilters(); - - $this->set_options($this->options); - - $ret = array(); - foreach ($res["matches"] as $match) - $ret[] = $match['attrs']['keyword']; - - return $ret; - } - - /** - * - * @param Session_Handler $session - * @return array - */ - public function get_suggestions(Session_Handler $session, $only_last_word = false) - { - if ( ! $this->current_index) - $this->current_index = '*'; - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $supposed_qry = mb_strtolower($this->query); - $pieces = explode(" ", str_replace(array("all", "last", "et", "ou", "sauf", "and", "or", "except", "in", "dans", "'", '"', "(", ")", "_", "-"), ' ', $supposed_qry)); - - $clef = 'sph_sugg_' . crc32(serialize($this->options) . ' ' . $this->current_index . implode(' ', $pieces) . ' ' . ($only_last_word ? '1' : '0')); - - try - { - return $appbox->get_data_from_cache($clef); - } - catch (Exception $e) + protected function get_sugg_trigrams($word) { - } + $trigrams = $this->BuildTrigrams($word); + $query = "\"$trigrams\"/1"; + $len = strlen($word); - $potential_queries = array(); + $this->sphinx->ResetGroupBy(); + $this->sphinx->ResetFilters(); - $n = 0; + $this->sphinx->SetMatchMode(SPH_MATCH_EXTENDED2); + $this->sphinx->SetRankingMode(SPH_RANK_WORDCOUNT); + $this->sphinx->SetFilterRange("len", $len - 2, $len + 4); - if ($only_last_word) - { - $pieces = array(array_pop($pieces)); - } + $this->sphinx->SetSortMode(SPH_SORT_EXTENDED, "@weight DESC"); + $this->sphinx->SetLimits(0, 10); - $tag = $session->get_I18n(); + $params = phrasea::sbas_params(); - $suggestions = array(); - - $total_chaines = 0; - $propal_n = $this->get_total_results(); - - if (function_exists('enchant_broker_init')) - { - $r = enchant_broker_init(); - if (enchant_broker_dict_exists($r, $tag)) - { - $d = enchant_broker_request_dict($r, $tag); - - foreach ($pieces as $piece) - { - if (trim($piece) === '') - continue; - - $found = false; - $suggs = array($piece); - if (enchant_dict_check($d, $piece) == false) - { - $suggs = array_unique(array_merge($suggs, enchant_dict_suggest($d, $piece))); - } - - $suggestions[$n] = array('original' => $piece, 'suggs' => $suggs); - - $n ++; + $index_keys = array(); + foreach ($params as $sbas_id => $p) { + if ( ! array_key_exists($sbas_id, $this->distinct_sbas)) + continue; + $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $p['host'], $p['port'], $p['user'], $p['dbname']))); } - enchant_broker_free_dict($d); - } - enchant_broker_free($r); + $index = 'suggest' . implode(',suggest', $index_keys); + + $res = $this->sphinx->Query($query, $index); + + if ($this->sphinx->Status() === false) { + return array(); + } + + if ( ! $res || ! isset($res["matches"])) { + return array(); + } + + $this->sphinx->ResetGroupBy(); + $this->sphinx->ResetFilters(); + + $this->set_options($this->options); + + $ret = array(); + foreach ($res["matches"] as $match) + $ret[] = $match['attrs']['keyword']; + + return $ret; } - if ($only_last_word) + /** + * + * @param Session_Handler $session + * @return array + */ + public function get_suggestions(Session_Handler $session, $only_last_word = false) { - foreach ($pieces as $piece) - { - foreach ($this->get_sugg_trigrams($piece) as $tri_sugg) - { - $suggestions[$n] = array('original' => $piece, 'suggs' => array($tri_sugg)); - $n ++; + if ( ! $this->current_index) + $this->current_index = '*'; + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $supposed_qry = mb_strtolower($this->query); + $pieces = explode(" ", str_replace(array("all", "last", "et", "ou", "sauf", "and", "or", "except", "in", "dans", "'", '"', "(", ")", "_", "-"), ' ', $supposed_qry)); + + $clef = 'sph_sugg_' . crc32(serialize($this->options) . ' ' . $this->current_index . implode(' ', $pieces) . ' ' . ($only_last_word ? '1' : '0')); + + try { + return $appbox->get_data_from_cache($clef); + } catch (Exception $e) { + } - } - } - $q_todo = array($supposed_qry); - $n = 0; + $potential_queries = array(); - foreach ($suggestions as $suggestion) - { - $tmp_qq = array(); - foreach ($suggestion['suggs'] as $sugg) - { - foreach ($q_todo as $q_td) - { - $tmp_qq[] = $q_td; - $tmp_data = str_replace($suggestion['original'], $sugg, $q_td); - $tmp_qq[] = $tmp_data; + $n = 0; + + if ($only_last_word) { + $pieces = array(array_pop($pieces)); } - $tmp_qq[] = str_replace($suggestion['original'], $sugg, $supposed_qry); - } - $q_todo = array_unique(array_merge($tmp_qq, array($supposed_qry))); - $n ++; - } + $tag = $session->get_I18n(); - $propals = array( - array( - 'value' => $supposed_qry - , 'current' => true - , 'hits' => $this->get_total_results() - ) - ); + $suggestions = array(); - foreach ($q_todo as $f) - { - if ($f == $supposed_qry) - continue; + $total_chaines = 0; + $propal_n = $this->get_total_results(); - $clef_unique_datas = 'sph_sugg_' . crc32(serialize($this->options) . $this->current_index . $f); + if (function_exists('enchant_broker_init')) { + $r = enchant_broker_init(); + if (enchant_broker_dict_exists($r, $tag)) { + $d = enchant_broker_request_dict($r, $tag); - try - { - $datas = $appbox->get_data_from_cache($clef_unique_datas); - } - catch (Exception $e) - { - $datas = false; - } - if (is_int($datas)) - { - $found = $datas; - $cache = true; - } - else - { - $cache = false; - $found = 0; + foreach ($pieces as $piece) { + if (trim($piece) === '') + continue; - $tmp_res = $this->sphinx->Query($f, $this->current_index); + $found = false; + $suggs = array($piece); + if (enchant_dict_check($d, $piece) == false) { + $suggs = array_unique(array_merge($suggs, enchant_dict_suggest($d, $piece))); + } - if ($tmp_res !== false && isset($tmp_res['total_found'])) - { - $found = (int) $tmp_res['total_found']; + $suggestions[$n] = array('original' => $piece, 'suggs' => $suggs); + + $n ++; + } + enchant_broker_free_dict($d); + } + enchant_broker_free($r); } - $appbox->set_data_to_cache($found, $clef_unique_datas, 3600); - } - if ($found > 0) - { - $propals[] = array( - 'value' => $f - , 'current' => false - , 'hits' => $found - , 'cache' => $cache + if ($only_last_word) { + foreach ($pieces as $piece) { + foreach ($this->get_sugg_trigrams($piece) as $tri_sugg) { + $suggestions[$n] = array('original' => $piece, 'suggs' => array($tri_sugg)); + $n ++; + } + } + } + + $q_todo = array($supposed_qry); + $n = 0; + + foreach ($suggestions as $suggestion) { + $tmp_qq = array(); + foreach ($suggestion['suggs'] as $sugg) { + foreach ($q_todo as $q_td) { + $tmp_qq[] = $q_td; + $tmp_data = str_replace($suggestion['original'], $sugg, $q_td); + $tmp_qq[] = $tmp_data; + } + $tmp_qq[] = str_replace($suggestion['original'], $sugg, $supposed_qry); + } + $q_todo = array_unique(array_merge($tmp_qq, array($supposed_qry))); + + $n ++; + } + + $propals = array( + array( + 'value' => $supposed_qry + , 'current' => true + , 'hits' => $this->get_total_results() + ) ); - } - } - usort($propals, array('self', 'suggestions_hit_sorter')); + foreach ($q_todo as $f) { + if ($f == $supposed_qry) + continue; - $max = 0; + $clef_unique_datas = 'sph_sugg_' . crc32(serialize($this->options) . $this->current_index . $f); - foreach ($propals as $key => $prop) - { - $max = max($max, $prop['hits'] * 1 / 100); - if ($prop['hits'] < $max) - unset($propals[$key]); - } + try { + $datas = $appbox->get_data_from_cache($clef_unique_datas); + } catch (Exception $e) { + $datas = false; + } + if (is_int($datas)) { + $found = $datas; + $cache = true; + } else { + $cache = false; + $found = 0; - $appbox->set_data_to_cache($propals, $clef, 3600); + $tmp_res = $this->sphinx->Query($f, $this->current_index); - return $propals; - } + if ($tmp_res !== false && isset($tmp_res['total_found'])) { + $found = (int) $tmp_res['total_found']; + } + $appbox->set_data_to_cache($found, $clef_unique_datas, 3600); + } - protected static function suggestions_hit_sorter($a, $b) - { - if ($a['hits'] == $b['hits']) - { - return 0; - } - - return ($a['hits'] > $b['hits']) ? -1 : 1; - } - - /** - * - * @return string - */ - public function get_parsed_query() - { - return $this->query; - } - - /** - * - * @param string $query - * @param array $fields - * @param int $selected_sbas_id - * @return array - */ - public function build_excerpt($query, array $fields, record_adapter $record) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $selected_sbas_id = $record->get_sbas_id(); - - $index = ''; - - $params = phrasea::sbas_params(); - - $index_keys = array(); - foreach ($params as $sbas_id => $params) - { - if ($sbas_id != $selected_sbas_id) - continue; - $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname']))); - } - - if (count($index_keys) > 0) - { - if ($this->search_in_field === false) - { - $index = ''; - $found = false; - if ($this->options->get_use_stemming()) - { - if ($session->get_I18n() == 'fr') - { - $index .= 'documents' . implode('_stemmed_fr, documents', $index_keys) . '_stemmed_fr'; - $found = true; - } - elseif ($session->get_I18n() == 'en') - { - $index .= 'documents' . implode('_stemmed_en, documents', $index_keys) . '_stemmed_en'; - $found = true; - } + if ($found > 0) { + $propals[] = array( + 'value' => $f + , 'current' => false + , 'hits' => $found + , 'cache' => $cache + ); + } } - if ( ! $found) - $index .= 'documents' . implode(', documents', $index_keys); - } - else - { - $index = ''; - $found = false; - if ($this->options->get_use_stemming() && $session->get_I18n() == 'fr') - { - if ($session->get_I18n() == 'fr') - { - $index .= 'metadatas' . implode('_stemmed_fr, metadatas', $index_keys) . '_stemmed_fr'; - $found = true; - } - elseif ($session->get_I18n() == 'en') - { - $index .= 'metadatas' . implode('_stemmed_en, metadatas', $index_keys) . '_stemmed_en'; - $found = true; - } + + usort($propals, array('self', 'suggestions_hit_sorter')); + + $max = 0; + + foreach ($propals as $key => $prop) { + $max = max($max, $prop['hits'] * 1 / 100); + if ($prop['hits'] < $max) + unset($propals[$key]); } - if ( ! $found) - $index = 'metadatas' . implode(',metadatas', $index_keys); - } + + $appbox->set_data_to_cache($propals, $clef, 3600); + + return $propals; } - $opts = array( - 'before_match' => "", - 'after_match' => "" - ); - $fields_to_send = array(); - - foreach ($fields as $k => $f) + protected static function suggestions_hit_sorter($a, $b) { - $fields_to_send[$k] = $f['value']; + if ($a['hits'] == $b['hits']) { + return 0; + } + + return ($a['hits'] > $b['hits']) ? -1 : 1; } - return $this->sphinx->BuildExcerpts($fields_to_send, $index, $query, $opts); - } + /** + * + * @return string + */ + public function get_parsed_query() + { + return $this->query; + } + /** + * + * @param string $query + * @param array $fields + * @param int $selected_sbas_id + * @return array + */ + public function build_excerpt($query, array $fields, record_adapter $record) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $selected_sbas_id = $record->get_sbas_id(); + + $index = ''; + + $params = phrasea::sbas_params(); + + $index_keys = array(); + foreach ($params as $sbas_id => $params) { + if ($sbas_id != $selected_sbas_id) + continue; + $index_keys[] = crc32(str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname']))); + } + + if (count($index_keys) > 0) { + if ($this->search_in_field === false) { + $index = ''; + $found = false; + if ($this->options->get_use_stemming()) { + if ($session->get_I18n() == 'fr') { + $index .= 'documents' . implode('_stemmed_fr, documents', $index_keys) . '_stemmed_fr'; + $found = true; + } elseif ($session->get_I18n() == 'en') { + $index .= 'documents' . implode('_stemmed_en, documents', $index_keys) . '_stemmed_en'; + $found = true; + } + } + if ( ! $found) + $index .= 'documents' . implode(', documents', $index_keys); + } + else { + $index = ''; + $found = false; + if ($this->options->get_use_stemming() && $session->get_I18n() == 'fr') { + if ($session->get_I18n() == 'fr') { + $index .= 'metadatas' . implode('_stemmed_fr, metadatas', $index_keys) . '_stemmed_fr'; + $found = true; + } elseif ($session->get_I18n() == 'en') { + $index .= 'metadatas' . implode('_stemmed_en, metadatas', $index_keys) . '_stemmed_en'; + $found = true; + } + } + if ( ! $found) + $index = 'metadatas' . implode(',metadatas', $index_keys); + } + } + $opts = array( + 'before_match' => "", + 'after_match' => "" + ); + + $fields_to_send = array(); + + foreach ($fields as $k => $f) { + $fields_to_send[$k] = $f['value']; + } + + return $this->sphinx->BuildExcerpts($fields_to_send, $index, $query, $opts); + } } diff --git a/lib/classes/searchEngine/options.class.php b/lib/classes/searchEngine/options.class.php index 744a4b68ae..e993f8be7d 100644 --- a/lib/classes/searchEngine/options.class.php +++ b/lib/classes/searchEngine/options.class.php @@ -17,466 +17,448 @@ */ class searchEngine_options implements Serializable { + const RECORD_RECORD = 0; + const RECORD_GROUPING = 1; + const TYPE_IMAGE = 'image'; + const TYPE_VIDEO = 'video'; + const TYPE_AUDIO = 'audio'; + const TYPE_DOCUMENT = 'document'; + const TYPE_FLASH = 'flash'; + const TYPE_ALL = ''; + const SORT_RELEVANCE = 'relevance'; + const SORT_CREATED_ON = 'created_on'; + const SORT_RANDOM = 'random'; + const SORT_MODE_ASC = 'asc'; + const SORT_MODE_DESC = 'desc'; - const RECORD_RECORD = 0; - const RECORD_GROUPING = 1; - const TYPE_IMAGE = 'image'; - const TYPE_VIDEO = 'video'; - const TYPE_AUDIO = 'audio'; - const TYPE_DOCUMENT = 'document'; - const TYPE_FLASH = 'flash'; - const TYPE_ALL = ''; - const SORT_RELEVANCE = 'relevance'; - const SORT_CREATED_ON = 'created_on'; - const SORT_RANDOM = 'random'; - const SORT_MODE_ASC = 'asc'; - const SORT_MODE_DESC = 'desc'; + /** + * + * @var string + */ + protected $record_type; - /** - * - * @var string - */ - protected $record_type; + /** + * + * @var string + */ + protected $search_type = 0; - /** - * - * @var string - */ - protected $search_type = 0; + /** + * + * @var array + */ + protected $bases = array(); - /** - * - * @var array - */ - protected $bases = array(); + /** + * + * @var array + */ + protected $fields = array(); - /** - * - * @var array - */ - protected $fields = array(); + /** + * + * @var array + */ + protected $status = array(); - /** - * - * @var array - */ - protected $status = array(); + /** + * + * @var DateTime + */ + protected $date_min; - /** - * - * @var DateTime - */ - protected $date_min; + /** + * + * @var DateTime + */ + protected $date_max; - /** - * - * @var DateTime - */ - protected $date_max; + /** + * + * @var array + */ + protected $date_fields = array(); - /** - * - * @var array - */ - protected $date_fields = array(); + /** + * + * @var string + */ + protected $i18n; - /** - * - * @var string - */ - protected $i18n; + /** + * + * @var boolean + */ + protected $stemming = true; - /** - * - * @var boolean - */ - protected $stemming = true; + /** + * + * @var string + */ + protected $sort_by = self::SORT_CREATED_ON; - /** - * - * @var string - */ - protected $sort_by = self::SORT_CREATED_ON; + /** + * + * @var string + */ + protected $sort_ord = self::SORT_MODE_DESC; + protected $business_fields = array(); - /** - * - * @var string - */ - protected $sort_ord = self::SORT_MODE_DESC; - protected $business_fields = array(); - - /** - * Constructor - * - * @return searchEngine_options - */ - public function __construct() - { - return $this; - } - - /** - * - * @param string $locale - */ - public function set_locale($locale) - { - $this->i18n = $locale; - } - - /** - * - * @return string - */ - public function get_locale() - { - return $this->i18n; - } - - /** - * - * @param const $sort_by - * @param const $sort_ord - * @return searchEngine_options - */ - public function set_sort($sort_by, $sort_ord = self::SORT_MODE_DESC) - { - $this->sort_by = $sort_by; - $this->sort_ord = $sort_ord; - - return $this; - } - - public function set_business_fields(Array $base_ids) - { - $this->business_fields = $base_ids; - - return $this; - } - - public function get_business_fields() - { - return $this->business_fields; - } - - /** - * - * @return string - */ - public function get_sortby() - { - return $this->sort_by; - } - - /** - * - * @return string - */ - public function get_sortord() - { - return $this->sort_ord; - } - - /** - * - * @param boolean $boolean - * @return searchEngine_options - */ - public function set_use_stemming($boolean) - { - $this->stemming = ! ! $boolean; - - return $this; - } - - /** - * - * @return boolean - */ - public function get_use_stemming() - { - return $this->stemming; - } - - /** - * - * @param int $search_type - * @return searchEngine_options - */ - public function set_search_type($search_type) - { - switch ($search_type) + /** + * Constructor + * + * @return searchEngine_options + */ + public function __construct() { - case self::RECORD_RECORD: - default: - $this->search_type = self::RECORD_RECORD; - break; - case self::RECORD_GROUPING: - $this->search_type = self::RECORD_GROUPING; - break; + return $this; } - return $this; - } - - /** - * - * @return int - */ - public function get_search_type() - { - return $this->search_type; - } - - /** - * - * @param array $base_ids - * @param ACL $ACL - * @return searchEngine_options - */ - public function set_bases(Array $base_ids, ACL $ACL) - { - foreach ($base_ids as $base_id) + /** + * + * @param string $locale + */ + public function set_locale($locale) { - if ($ACL->has_access_to_base($base_id)) - $this->bases[$base_id] = $base_id; + $this->i18n = $locale; } - return $this; - } - - /** - * - * @return array - */ - public function get_bases() - { - return $this->bases; - } - - /** - * - * @param array $fields - * @return searchEngine_options - */ - public function set_fields(Array $fields) - { - $this->fields = $fields; - - return $this; - } - - /** - * - * @return array - */ - public function get_fields() - { - return $this->fields; - } - - /** - * - * @param array $status - * @return searchEngine_options - */ - public function set_status(Array $status) - { - $tmp = array(); - foreach ($status as $n => $options) + /** + * + * @return string + */ + public function get_locale() { - if (count($options) > 1) - continue; - if (isset($options['on'])) - { - foreach ($options['on'] as $sbas_id) - $tmp[$n][$sbas_id] = 1; - } - if (isset($options['off'])) - { - foreach ($options['off'] as $sbas_id) - $tmp[$n][$sbas_id] = 0; - } + return $this->i18n; } - $this->status = $tmp; - - return $this; - } - - /** - * - * @return array - */ - public function get_status() - { - return $this->status; - } - - /** - * - * @param string $record_type - * @return searchEngine_options - */ - public function set_record_type($record_type) - { - switch ($record_type) + /** + * + * @param const $sort_by + * @param const $sort_ord + * @return searchEngine_options + */ + public function set_sort($sort_by, $sort_ord = self::SORT_MODE_DESC) { - case self::TYPE_ALL: - default: - $this->record_type = self::TYPE_ALL; - break; - case self::TYPE_AUDIO: - $this->record_type = self::TYPE_AUDIO; - break; - case self::TYPE_VIDEO: - $this->record_type = self::TYPE_VIDEO; - break; - case self::TYPE_DOCUMENT: - $this->record_type = self::TYPE_DOCUMENT; - break; - case self::TYPE_FLASH: - $this->record_type = self::TYPE_FLASH; - break; - case self::TYPE_IMAGE: - $this->record_type = self::TYPE_IMAGE; - break; + $this->sort_by = $sort_by; + $this->sort_ord = $sort_ord; + + return $this; } - return $this; - } - - /** - * - * @return string - */ - public function get_record_type() - { - return $this->record_type; - } - - /** - * - * @param string $min_date - * @return searchEngine_options - */ - public function set_min_date($min_date) - { - if ( ! is_null($min_date) && trim($min_date) !== '') + public function set_business_fields(Array $base_ids) { - $this->date_min = DateTime::createFromFormat('d/m/Y H:i:s', $min_date . ' 00:00:00'); + $this->business_fields = $base_ids; + + return $this; } - return $this; - } - - /** - * - * @return DateTime - */ - public function get_min_date() - { - return $this->date_min; - } - - /** - * - * @param string $max_date - * @return searchEngine_options - */ - public function set_max_date($max_date) - { - if ( ! is_null($max_date) && trim($max_date) !== '') + public function get_business_fields() { - $this->date_max = DateTime::createFromFormat('d/m/Y H:i:s', $max_date . ' 23:59:59'); + return $this->business_fields; } - return $this; - } - - /** - * - * @return DateTime - */ - public function get_max_date() - { - return $this->date_max; - } - - /** - * - * @param array $fields - * @return searchEngine_options - */ - public function set_date_fields(Array $fields) - { - $this->date_fields = $fields; - - return $this; - } - - /** - * - * @return array - */ - public function get_date_fields() - { - return $this->date_fields; - } - - /** - * - * @return string - */ - public function serialize() - { - $ret = array(); - foreach ($this as $key => $value) + /** + * + * @return string + */ + public function get_sortby() { - if ($value instanceof DateTime) - $value = $value->format('d-m-Y h:i:s'); - - $ret[$key] = $value; + return $this->sort_by; } - return p4string::jsonencode($ret); - } - - /** - * - * @param string $serialized - * @return searchEngine_options - */ - public function unserialize($serialized) - { - $serialized = json_decode($serialized); - - foreach ($serialized as $key => $value) + /** + * + * @return string + */ + public function get_sortord() { - if (is_null($value)) - { - $value = null; - } - elseif (in_array($key, array('date_min', 'date_max'))) - { - $value = new DateTime($value); - } - elseif ($value instanceof stdClass) - { - $tmpvalue = (array) $value; - $value = array(); + return $this->sort_ord; + } - foreach ($tmpvalue as $k => $data) - { - $k = ctype_digit($k) ? (int) $k : $k; - $value[$k] = $data; + /** + * + * @param boolean $boolean + * @return searchEngine_options + */ + public function set_use_stemming($boolean) + { + $this->stemming = ! ! $boolean; + + return $this; + } + + /** + * + * @return boolean + */ + public function get_use_stemming() + { + return $this->stemming; + } + + /** + * + * @param int $search_type + * @return searchEngine_options + */ + public function set_search_type($search_type) + { + switch ($search_type) { + case self::RECORD_RECORD: + default: + $this->search_type = self::RECORD_RECORD; + break; + case self::RECORD_GROUPING: + $this->search_type = self::RECORD_GROUPING; + break; } - } - $this->$key = $value; + return $this; } - return $this; - } + /** + * + * @return int + */ + public function get_search_type() + { + return $this->search_type; + } + /** + * + * @param array $base_ids + * @param ACL $ACL + * @return searchEngine_options + */ + public function set_bases(Array $base_ids, ACL $ACL) + { + foreach ($base_ids as $base_id) { + if ($ACL->has_access_to_base($base_id)) + $this->bases[$base_id] = $base_id; + } + + return $this; + } + + /** + * + * @return array + */ + public function get_bases() + { + return $this->bases; + } + + /** + * + * @param array $fields + * @return searchEngine_options + */ + public function set_fields(Array $fields) + { + $this->fields = $fields; + + return $this; + } + + /** + * + * @return array + */ + public function get_fields() + { + return $this->fields; + } + + /** + * + * @param array $status + * @return searchEngine_options + */ + public function set_status(Array $status) + { + $tmp = array(); + foreach ($status as $n => $options) { + if (count($options) > 1) + continue; + if (isset($options['on'])) { + foreach ($options['on'] as $sbas_id) + $tmp[$n][$sbas_id] = 1; + } + if (isset($options['off'])) { + foreach ($options['off'] as $sbas_id) + $tmp[$n][$sbas_id] = 0; + } + } + + $this->status = $tmp; + + return $this; + } + + /** + * + * @return array + */ + public function get_status() + { + return $this->status; + } + + /** + * + * @param string $record_type + * @return searchEngine_options + */ + public function set_record_type($record_type) + { + switch ($record_type) { + case self::TYPE_ALL: + default: + $this->record_type = self::TYPE_ALL; + break; + case self::TYPE_AUDIO: + $this->record_type = self::TYPE_AUDIO; + break; + case self::TYPE_VIDEO: + $this->record_type = self::TYPE_VIDEO; + break; + case self::TYPE_DOCUMENT: + $this->record_type = self::TYPE_DOCUMENT; + break; + case self::TYPE_FLASH: + $this->record_type = self::TYPE_FLASH; + break; + case self::TYPE_IMAGE: + $this->record_type = self::TYPE_IMAGE; + break; + } + + return $this; + } + + /** + * + * @return string + */ + public function get_record_type() + { + return $this->record_type; + } + + /** + * + * @param string $min_date + * @return searchEngine_options + */ + public function set_min_date($min_date) + { + if ( ! is_null($min_date) && trim($min_date) !== '') { + $this->date_min = DateTime::createFromFormat('d/m/Y H:i:s', $min_date . ' 00:00:00'); + } + + return $this; + } + + /** + * + * @return DateTime + */ + public function get_min_date() + { + return $this->date_min; + } + + /** + * + * @param string $max_date + * @return searchEngine_options + */ + public function set_max_date($max_date) + { + if ( ! is_null($max_date) && trim($max_date) !== '') { + $this->date_max = DateTime::createFromFormat('d/m/Y H:i:s', $max_date . ' 23:59:59'); + } + + return $this; + } + + /** + * + * @return DateTime + */ + public function get_max_date() + { + return $this->date_max; + } + + /** + * + * @param array $fields + * @return searchEngine_options + */ + public function set_date_fields(Array $fields) + { + $this->date_fields = $fields; + + return $this; + } + + /** + * + * @return array + */ + public function get_date_fields() + { + return $this->date_fields; + } + + /** + * + * @return string + */ + public function serialize() + { + $ret = array(); + foreach ($this as $key => $value) { + if ($value instanceof DateTime) + $value = $value->format('d-m-Y h:i:s'); + + $ret[$key] = $value; + } + + return p4string::jsonencode($ret); + } + + /** + * + * @param string $serialized + * @return searchEngine_options + */ + public function unserialize($serialized) + { + $serialized = json_decode($serialized); + + foreach ($serialized as $key => $value) { + if (is_null($value)) { + $value = null; + } elseif (in_array($key, array('date_min', 'date_max'))) { + $value = new DateTime($value); + } elseif ($value instanceof stdClass) { + $tmpvalue = (array) $value; + $value = array(); + + foreach ($tmpvalue as $k => $data) { + $k = ctype_digit($k) ? (int) $k : $k; + $value[$k] = $data; + } + } + + $this->$key = $value; + } + + return $this; + } } diff --git a/lib/classes/searchEngine/results.class.php b/lib/classes/searchEngine/results.class.php index 55046d1788..210baf1740 100644 --- a/lib/classes/searchEngine/results.class.php +++ b/lib/classes/searchEngine/results.class.php @@ -17,132 +17,131 @@ */ class searchEngine_results { + /** + * + * @var set + */ + protected $result; - /** - * - * @var set - */ - protected $result; - /** - * - * @var searchEngine_adapter_interface - */ - protected $engine; + /** + * + * @var searchEngine_adapter_interface + */ + protected $engine; - /** - * - * @param set $result - * @param searchEngine_adapter_interface $engine - * @return searchEngine_results - */ - public function __construct(set_abstract $result, searchEngine_adapter_interface $engine) - { - $this->engine = $engine; - $this->result = $result; + /** + * + * @param set $result + * @param searchEngine_adapter_interface $engine + * @return searchEngine_results + */ + public function __construct(set_abstract $result, searchEngine_adapter_interface $engine) + { + $this->engine = $engine; + $this->result = $result; - return $this; - } + return $this; + } - /** - * - * @return set - */ - public function get_datas() - { - return $this->result; - } + /** + * + * @return set + */ + public function get_datas() + { + return $this->result; + } - /** - * - * @return float - */ - public function get_query_time() - { - return $this->engine->get_time(); - } + /** + * + * @return float + */ + public function get_query_time() + { + return $this->engine->get_time(); + } - /** - * - * @return int - */ - public function get_total_pages() - { - return $this->engine->get_total_pages(); - } + /** + * + * @return int + */ + public function get_total_pages() + { + return $this->engine->get_total_pages(); + } - /** - * - * @return int - */ - public function get_current_page() - { - return (int) $this->engine->get_current_page(); - } + /** + * + * @return int + */ + public function get_current_page() + { + return (int) $this->engine->get_current_page(); + } - /** - * - * @return int - */ - public function get_count_available_results() - { - return (int) $this->engine->get_available_results(); - } + /** + * + * @return int + */ + public function get_count_available_results() + { + return (int) $this->engine->get_available_results(); + } - /** - * - * @return int - */ - public function get_count_total_results() - { - return (int) $this->engine->get_total_results(); - } + /** + * + * @return int + */ + public function get_count_total_results() + { + return (int) $this->engine->get_total_results(); + } - /** - * - * @return string - */ - public function get_error() - { - return $this->engine->get_error(); - } + /** + * + * @return string + */ + public function get_error() + { + return $this->engine->get_error(); + } - /** - * - * @return string - */ - public function get_warning() - { - return $this->engine->get_warning(); - } + /** + * + * @return string + */ + public function get_warning() + { + return $this->engine->get_warning(); + } - /** - * - * @return array - */ - public function get_suggestions() - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); + /** + * + * @return array + */ + public function get_suggestions() + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); - return $this->engine->get_suggestions($session); - } + return $this->engine->get_suggestions($session); + } - /** - * - * @return string - */ - public function get_propositions() - { - return $this->engine->get_propositions(); - } - - /** - * - * @return string - */ - public function get_search_indexes() - { - return $this->engine->get_current_indexes(); - } + /** + * + * @return string + */ + public function get_propositions() + { + return $this->engine->get_propositions(); + } + /** + * + * @return string + */ + public function get_search_indexes() + { + return $this->engine->get_current_indexes(); + } } diff --git a/lib/classes/set/abstract.class.php b/lib/classes/set/abstract.class.php index ae76ce8750..274aee6cbc 100644 --- a/lib/classes/set/abstract.class.php +++ b/lib/classes/set/abstract.class.php @@ -17,175 +17,167 @@ */ abstract class set_abstract implements IteratorAggregate { + /** + * + * @var Array + */ + protected $elements = array(); - /** - * - * @var Array - */ - protected $elements = array(); - - /** - * - * @return ArrayIterator - */ - public function getIterator() - { - $this->load_elements(); - - return new ArrayIterator($this->elements); - } - - /** - * - * @return set - */ - protected function load_elements() - { - return $this; - } - - /** - * - * @param string $offset - * @param string $value - * @return Void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) + /** + * + * @return ArrayIterator + */ + public function getIterator() { - $this->elements[] = $value; - } - else - { - $this->elements[$offset] = $value; - } - } + $this->load_elements(); - /** - * - * @param string $offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->elements[$offset]); - } - - /** - * - * @param string $offset - * @return Void - */ - public function offsetUnset($offset) - { - unset($this->elements[$offset]); - } - - /** - * - * @param string $offset - * @return record_adapter - */ - public function offsetGet($offset) - { - return isset($this->elements[$offset]) ? $this->elements[$offset] : null; - } - - /** - * - * @return int - */ - public function is_empty() - { - return count($this->elements) == 0; - } - - public function __isset($key) - { - trigger_error("Unable to use magic method get for key $key"); - if (isset($this->$key)) - - return true; - return false; - } - - /** - * Get the number of element in the set - * - * @return Int - */ - public function get_count() - { - return count($this->elements); - } - - /** - * - * @return int - */ - public function get_count_groupings() - { - $n = 0; - foreach ($this->elements as $record) - { - if ($record->is_grouping()) - $n++; + return new ArrayIterator($this->elements); } - return $n; - } - - /** - * - * @return Array - */ - public function get_elements() - { - $this->load_elements(); - - return $this->elements; - } - - /** - * - * @param record_Interface $record - * @return set - */ - public function add_element(record_Interface &$record) - { - $this->elements[$record->get_serialize_key()] = $record; - - return $this; - } - - /** - * - * @param record_Interface $record - * @return set - */ - public function remove_element(record_Interface &$record) - { - $key = $record->get_serialize_key(); - if (isset($this->elements[$key])) - unset($this->elements[$key]); - - return $this; - } - - /** - * - * @return string - */ - public function serialize_list() - { - $basrec = array(); - foreach ($this->elements as $record) + /** + * + * @return set + */ + protected function load_elements() { - $basrec[] = $record->get_serialize_key(); + return $this; } - return implode(';', $basrec); - } + /** + * + * @param string $offset + * @param string $value + * @return Void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->elements[] = $value; + } else { + $this->elements[$offset] = $value; + } + } + /** + * + * @param string $offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->elements[$offset]); + } + + /** + * + * @param string $offset + * @return Void + */ + public function offsetUnset($offset) + { + unset($this->elements[$offset]); + } + + /** + * + * @param string $offset + * @return record_adapter + */ + public function offsetGet($offset) + { + return isset($this->elements[$offset]) ? $this->elements[$offset] : null; + } + + /** + * + * @return int + */ + public function is_empty() + { + return count($this->elements) == 0; + } + + public function __isset($key) + { + trigger_error("Unable to use magic method get for key $key"); + if (isset($this->$key)) + return true; + return false; + } + + /** + * Get the number of element in the set + * + * @return Int + */ + public function get_count() + { + return count($this->elements); + } + + /** + * + * @return int + */ + public function get_count_groupings() + { + $n = 0; + foreach ($this->elements as $record) { + if ($record->is_grouping()) + $n ++; + } + + return $n; + } + + /** + * + * @return Array + */ + public function get_elements() + { + $this->load_elements(); + + return $this->elements; + } + + /** + * + * @param record_Interface $record + * @return set + */ + public function add_element(record_Interface &$record) + { + $this->elements[$record->get_serialize_key()] = $record; + + return $this; + } + + /** + * + * @param record_Interface $record + * @return set + */ + public function remove_element(record_Interface &$record) + { + $key = $record->get_serialize_key(); + if (isset($this->elements[$key])) + unset($this->elements[$key]); + + return $this; + } + + /** + * + * @return string + */ + public function serialize_list() + { + $basrec = array(); + foreach ($this->elements as $record) { + $basrec[] = $record->get_serialize_key(); + } + + return implode(';', $basrec); + } } diff --git a/lib/classes/set/export.class.php b/lib/classes/set/export.class.php index eeb0acb55b..8a814fd468 100644 --- a/lib/classes/set/export.class.php +++ b/lib/classes/set/export.class.php @@ -17,262 +17,221 @@ */ class set_export extends set_abstract { + protected $storage = array(); + protected $total_download; + protected $total_order; + protected $total_ftp; + protected $display_orderable; + protected $display_download; + protected $display_ftp; + protected $ftp_datas; + protected $list; + protected $businessFieldsAccess; - protected $storage = array(); - protected $total_download; - protected $total_order; - protected $total_ftp; - protected $display_orderable; - protected $display_download; - protected $display_ftp; - protected $ftp_datas; - protected $list; - protected $businessFieldsAccess; - - /** - * - * @param string $lst - * @param int $sstid - * @return set_export - */ - public function __construct($lst, $sstid, $storyWZid = null) - { - $Core = bootstrap::getCore(); - - $appbox = appbox::get_instance($Core); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - - $user = $Core->getAuthenticatedUser(); - - $download_list = array(); - - $remain_hd = array(); - - if ($storyWZid) + /** + * + * @param string $lst + * @param int $sstid + * @return set_export + */ + public function __construct($lst, $sstid, $storyWZid = null) { - $repository = $Core->getEntityManager()->getRepository('\\Entities\\StoryWZ'); + $Core = bootstrap::getCore(); - $storyWZ = $repository->findByUserAndId($user, $storyWZid); + $appbox = appbox::get_instance($Core); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); - $lst = $storyWZ->getRecord()->get_serialize_key(); - } + $user = $Core->getAuthenticatedUser(); - if ($sstid != "") - { - $em = $Core->getEntityManager(); - $repository = $em->getRepository('\Entities\Basket'); + $download_list = array(); - /* @var $repository \Repositories\BasketRepository */ - $Basket = $repository->findUserBasket($sstid, $user, false); + $remain_hd = array(); - foreach ($Basket->getElements() as $basket_element) - { - /* @var $basket_element \Entities\BasketElement */ - $base_id = $basket_element->getRecord()->get_base_id(); - $record_id = $basket_element->getRecord()->get_record_id(); + if ($storyWZid) { + $repository = $Core->getEntityManager()->getRepository('\\Entities\\StoryWZ'); - if (!isset($remain_hd[$base_id])) - { - if ($user->ACL()->is_restricted_download($base_id)) - { - $remain_hd[$base_id] = $user->ACL()->remaining_download($base_id); - } - else - { - $remain_hd[$base_id] = false; - } + $storyWZ = $repository->findByUserAndId($user, $storyWZid); + + $lst = $storyWZ->getRecord()->get_serialize_key(); } - $current_element = $download_list[] = - new record_exportElement( - $basket_element->getRecord()->get_sbas_id(), - $record_id, - $Basket->getName() . '/', - $remain_hd[$base_id] - ); + if ($sstid != "") { + $em = $Core->getEntityManager(); + $repository = $em->getRepository('\Entities\Basket'); - $remain_hd[$base_id] = $current_element->get_remain_hd(); - } - } - else - { - $tmp_lst = explode(';', $lst); - $n = 1; - foreach ($tmp_lst as $basrec) - { - $basrec = explode('_', $basrec); - if (count($basrec) != 2) - continue; + /* @var $repository \Repositories\BasketRepository */ + $Basket = $repository->findUserBasket($sstid, $user, false); - try - { - $record = new record_adapter($basrec[0], $basrec[1]); - } - catch (Exception_Record_AdapterNotFound $e) - { - continue; + foreach ($Basket->getElements() as $basket_element) { + /* @var $basket_element \Entities\BasketElement */ + $base_id = $basket_element->getRecord()->get_base_id(); + $record_id = $basket_element->getRecord()->get_record_id(); + + if ( ! isset($remain_hd[$base_id])) { + if ($user->ACL()->is_restricted_download($base_id)) { + $remain_hd[$base_id] = $user->ACL()->remaining_download($base_id); + } else { + $remain_hd[$base_id] = false; + } + } + + $current_element = $download_list[] = + new record_exportElement( + $basket_element->getRecord()->get_sbas_id(), + $record_id, + $Basket->getName() . '/', + $remain_hd[$base_id] + ); + + $remain_hd[$base_id] = $current_element->get_remain_hd(); + } + } else { + $tmp_lst = explode(';', $lst); + $n = 1; + foreach ($tmp_lst as $basrec) { + $basrec = explode('_', $basrec); + if (count($basrec) != 2) + continue; + + try { + $record = new record_adapter($basrec[0], $basrec[1]); + } catch (Exception_Record_AdapterNotFound $e) { + continue; + } + + if ($record->is_grouping()) { + foreach ($record->get_children() as $child_basrec) { + $base_id = $child_basrec->get_base_id(); + $record_id = $child_basrec->get_record_id(); + + if ( ! isset($remain_hd[$base_id])) { + if ($user->ACL()->is_restricted_download($base_id)) { + $remain_hd[$base_id] = + $user->ACL()->remaining_download($base_id); + } else { + $remain_hd[$base_id] = false; + } + } + + $current_element = $download_list[] = + new record_exportElement( + $child_basrec->get_sbas_id(), + $record_id, + $record->get_title(null, null, true) . '_' . $n . '/', + $remain_hd[$base_id] + ); + + $remain_hd[$base_id] = $current_element->get_remain_hd(); + } + } else { + $base_id = $record->get_base_id(); + $record_id = $record->get_record_id(); + + if ( ! isset($remain_hd[$base_id])) { + if ($user->ACL()->is_restricted_download($base_id)) { + $remain_hd[$base_id] = + $user->ACL()->remaining_download($base_id); + } else { + $remain_hd[$base_id] = false; + } + } + + $current_element = + $download_list[$basrec[0] . '_' . $basrec[1]] = + new record_exportElement( + $record->get_sbas_id(), + $record_id, + '', + $remain_hd[$base_id] + ); + + $remain_hd[$base_id] = $current_element->get_remain_hd(); + } + $n ++; + } } - if ($record->is_grouping()) - { - foreach ($record->get_children() as $child_basrec) - { - $base_id = $child_basrec->get_base_id(); - $record_id = $child_basrec->get_record_id(); + $this->elements = $download_list; - if (!isset($remain_hd[$base_id])) - { - if ($user->ACL()->is_restricted_download($base_id)) - { - $remain_hd[$base_id] = - $user->ACL()->remaining_download($base_id); - } - else - { - $remain_hd[$base_id] = false; - } + $display_download = array(); + $display_orderable = array(); + + $this->total_download = 0; + $this->total_order = 0; + $this->total_ftp = 0; + + $this->businessFieldsAccess = false; + + foreach ($this->elements as $download_element) { + if ($user->ACL()->has_right_on_base($download_element->get_base_id(), 'canmodifrecord')) { + $this->businessFieldsAccess = true; } - $current_element = $download_list[] = - new record_exportElement( - $child_basrec->get_sbas_id(), - $record_id, - $record->get_title(null, null, true) . '_' . $n . '/', - $remain_hd[$base_id] - ); + foreach ($download_element->get_downloadable() as $name => $properties) { + if ( ! isset($display_download[$name])) { + $display_download[$name] = array( + 'size' => 0, + 'total' => 0, + 'available' => 0, + 'refused' => array() + ); + } - $remain_hd[$base_id] = $current_element->get_remain_hd(); - } - } - else - { - $base_id = $record->get_base_id(); - $record_id = $record->get_record_id(); + $display_download[$name]['total'] ++; - if (!isset($remain_hd[$base_id])) - { - if ($user->ACL()->is_restricted_download($base_id)) - { - $remain_hd[$base_id] = - $user->ACL()->remaining_download($base_id); + if ($properties !== false) { + $display_download[$name]['available'] ++; + $display_download[$name]['label'] = $properties['label']; + $display_download[$name]['class'] = $properties['class']; + $this->total_download ++; + $display_download[$name]['size'] += $download_element->get_size($name); + } else { + $display_download[$name]['refused'][] = $download_element->get_thumbnail(); + } } - else - { - $remain_hd[$base_id] = false; + foreach ($download_element->get_orderable() as $name => $properties) { + if ( ! isset($display_orderable[$name])) { + $display_orderable[$name] = array( + 'total' => 0, + 'available' => 0, + 'refused' => array() + ); + } + + $display_orderable[$name]['total'] ++; + + if ($properties !== false) { + $display_orderable[$name]['available'] ++; + $this->total_order ++; + } else { + $display_orderable[$name]['refused'][] = $download_element->get_thumbnail(); + } } - } - - $current_element = - $download_list[$basrec[0] . '_' . $basrec[1]] = - new record_exportElement( - $record->get_sbas_id(), - $record_id, - '', - $remain_hd[$base_id] - ); - - $remain_hd[$base_id] = $current_element->get_remain_hd(); - } - $n++; - } - } - - $this->elements = $download_list; - - $display_download = array(); - $display_orderable = array(); - - $this->total_download = 0; - $this->total_order = 0; - $this->total_ftp = 0; - - $this->businessFieldsAccess = false; - - foreach ($this->elements as $download_element) - { - if($user->ACL()->has_right_on_base($download_element->get_base_id(), 'canmodifrecord')) - { - $this->businessFieldsAccess = true; - } - - foreach ($download_element->get_downloadable() as $name => $properties) - { - if (!isset($display_download[$name])) - { - $display_download[$name] = array( - 'size' => 0, - 'total' => 0, - 'available' => 0, - 'refused' => array() - ); } - $display_download[$name]['total']++; - - if ($properties !== false) - { - $display_download[$name]['available']++; - $display_download[$name]['label'] = $properties['label']; - $display_download[$name]['class'] = $properties['class']; - $this->total_download++; - $display_download[$name]['size'] += $download_element->get_size($name); - } - else - { - $display_download[$name]['refused'][] = $download_element->get_thumbnail(); - } - } - foreach ($download_element->get_orderable() as $name => $properties) - { - if (!isset($display_orderable[$name])) - { - $display_orderable[$name] = array( - 'total' => 0, - 'available' => 0, - 'refused' => array() - ); + foreach ($display_download as $name => $values) { + $display_download[$name]['size'] = (int) $values['size']; } - $display_orderable[$name]['total']++; + $display_ftp = array(); - if ($properties !== false) - { - $display_orderable[$name]['available']++; - $this->total_order++; - } - else - { - $display_orderable[$name]['refused'][] = $download_element->get_thumbnail(); - } - } - } + $hasadminright = $user->ACL()->has_right('addrecord') + || $user->ACL()->has_right('deleterecord') + || $user->ACL()->has_right('modifyrecord') + || $user->ACL()->has_right('coll_manage') + || $user->ACL()->has_right('coll_modify_struct'); - foreach ($display_download as $name => $values) - { - $display_download[$name]['size'] = (int) $values['size']; - } + $this->ftp_datas = array(); - $display_ftp = array(); + if ($registry->get('GV_activeFTP') && ($hasadminright || $registry->get('GV_ftp_for_user'))) { + $display_ftp = $display_download; + $this->total_ftp = $this->total_download; - $hasadminright = $user->ACL()->has_right('addrecord') - || $user->ACL()->has_right('deleterecord') - || $user->ACL()->has_right('modifyrecord') - || $user->ACL()->has_right('coll_manage') - || $user->ACL()->has_right('coll_modify_struct'); + $lst_base_id = array_keys($user->ACL()->get_granted_base()); - $this->ftp_datas = array(); - - if ($registry->get('GV_activeFTP') && ($hasadminright || $registry->get('GV_ftp_for_user'))) - { - $display_ftp = $display_download; - $this->total_ftp = $this->total_download; - - $lst_base_id = array_keys($user->ACL()->get_granted_base()); - - if ($hasadminright) - { - $sql = "SELECT usr.usr_id,usr_login,usr.addrFTP,usr.loginFTP,usr.sslFTP, + if ($hasadminright) { + $sql = "SELECT usr.usr_id,usr_login,usr.addrFTP,usr.loginFTP,usr.sslFTP, usr.pwdFTP,usr.destFTP,prefixFTPfolder,usr.passifFTP, usr.retryFTP,usr.usr_mail FROM (usr INNER JOIN basusr @@ -284,11 +243,9 @@ class set_export extends set_abstract ) ) GROUP BY usr_id "; - $params = array(); - } - elseif ($registry->get('GV_ftp_for_user')) - { - $sql = "SELECT usr.usr_id,usr_login,usr.addrFTP,usr.loginFTP,usr.sslFTP, + $params = array(); + } elseif ($registry->get('GV_ftp_for_user')) { + $sql = "SELECT usr.usr_id,usr_login,usr.addrFTP,usr.loginFTP,usr.sslFTP, usr.pwdFTP,usr.destFTP,prefixFTPfolder, usr.passifFTP,usr.retryFTP,usr.usr_mail FROM (usr INNER JOIN basusr @@ -300,749 +257,700 @@ class set_export extends set_abstract ) ) GROUP BY usr_id "; - $params = array(':usr_id' => $session->get_usr_id()); - } - - $datas[] = array( - 'name' => _('export::ftp: reglages manuels'), - 'usr_id' => '0', - 'addrFTP' => '', - 'loginFTP' => '', - 'pwdFTP' => '', - 'ssl' => '0', - 'destFTP' => '', - 'prefixFTPfolder' => 'Export_' . date("Y-m-d_H.i.s"), - 'passifFTP' => false, - 'retryFTP' => 5, - 'mailFTP' => '', - 'sendermail' => $user->get_email() - ); - - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) - { - $datas[] = array( - 'name' => $row["usr_login"], - 'usr_id' => $row['usr_id'], - 'addrFTP' => $row['addrFTP'], - 'loginFTP' => $row['loginFTP'], - 'pwdFTP' => $row['pwdFTP'], - 'ssl' => $row['sslFTP'], - 'destFTP' => $row['destFTP'], - 'prefixFTPfolder' => - (strlen(trim($row['prefixFTPfolder'])) > 0 ? - trim($row['prefixFTPfolder']) : - 'Export_' . date("Y-m-d_H.i.s")), - 'passifFTP' => ($row['passifFTP'] > 0), - 'retryFTP' => $row['retryFTP'], - 'mailFTP' => $row['usr_mail'], - 'sendermail' => $user->get_email() - ); - } - - $this->ftp_datas = $datas; - } - - $this->display_orderable = $display_orderable; - $this->display_download = $display_download; - $this->display_ftp = $display_ftp; - - - return $this; - } - - /** - * - * @return Array - */ - public function get_ftp_datas() - { - return $this->ftp_datas; - } - public function has_business_fields_access() - { - return $this->businessFieldsAccess; - } - - /** - * - * @return Array - */ - public function get_display_orderable() - { - return $this->display_orderable; - } - - /** - * - * @return Array - */ - public function get_display_download() - { - return $this->display_download; - } - - /** - * - * @return Array - */ - public function get_display_ftp() - { - return $this->display_ftp; - } - - /** - * - * @return Int - */ - public function get_total_download() - { - return $this->total_download; - } - - /** - * - * @return Int - */ - public function get_total_order() - { - return $this->total_order; - } - - /** - * - * @return Int - */ - public function get_total_ftp() - { - return $this->total_ftp; - } - - /** - * - * @param Array $subdefs - * @param boolean $rename_title - * @return Array - */ - public function prepare_export(Array $subdefs, $rename_title, $includeBusinessFields ) - { - if (!is_array($subdefs)) - { - throw new Exception('No subdefs given'); - } - - $includeBusinessFields = !!$includeBusinessFields; - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $registry = $appbox->get_registry(); - - $unicode = new unicode(); - - $files = array(); - - $n_files = 0; - - $file_names = array(); - - $size = 0; - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - foreach ($this->elements as $download_element) - { - $id = count($files); - - $files[$id] = array( - 'base_id' => $download_element->get_base_id(), - 'record_id' => $download_element->get_record_id(), - 'original_name' => '', - 'export_name' => '', - 'subdefs' => array() - ); - - $rename_done = false; - - $BF = false; - - if($includeBusinessFields && $user->ACL()->has_right_on_base($download_element->get_base_id(), 'canmodifrecord')) - { - $BF = true; - } - - $desc = $download_element->get_caption()->serialize(caption_record::SERIALIZE_XML, $BF); - - $files[$id]['original_name'] = - $files[$id]['export_name'] = - $download_element->get_original_name(true); - - $files[$id]['original_name'] = - trim($files[$id]['original_name']) != '' ? - $files[$id]['original_name'] : $id; - - $infos = pathinfo($files[$id]['original_name']); - - $extension = isset($infos['extension']) ? $infos['extension'] : ''; - - - if ($rename_title) - { - $title = strip_tags($download_element->get_title(null, null, true)); - - $files[$id]['export_name'] = $unicode->remove_nonazAZ09($title, true); - $rename_done = true; - } - else - { - $files[$id]["export_name"] = $infos['filename']; - } - - $sizeMaxAjout = 0; - $sizeMaxExt = 0; - - $sd = $download_element->get_subdefs(); - - foreach ($download_element->get_downloadable() as $name => $properties) - { - if ($properties === false || !in_array($name, $subdefs)) - { - continue; - } - if (!in_array($name, array('caption', 'caption-yaml')) && !isset($sd[$name])) - { - continue; - } - - set_time_limit(100); - $subdef_export = $subdef_alive = false; - - $n_files++; - - $tmp_pathfile = array('path' => null, 'file' => null); - - switch ($properties['class']) - { - case 'caption': - case 'caption-yaml': - $subdef_export = true; - $subdef_alive = true; - break; - case 'thumbnail': - $tmp_pathfile = array( - 'path' => $sd[$name]->get_path() - , 'file' => $sd[$name]->get_file() - ); - $subdef_export = true; - $subdef_alive = true; - break; - case 'document': - $subdef_export = true; - $path = recordutils_image::stamp( - $download_element->get_base_id() - , $download_element->get_record_id() - , true - ); - $tmp_pathfile = array( - 'path' => $sd[$name]->get_path() - , 'file' => $sd[$name]->get_file() - ); - if (file_exists($path)) - { - $tmp_pathfile = array( - 'path' => dirname($path) - , 'file' => basename($path) - ); - $subdef_alive = true; + $params = array(':usr_id' => $session->get_usr_id()); } - break; - case 'preview': - $subdef_export = true; - - $tmp_pathfile = array( - 'path' => $sd[$name]->get_path() - , 'file' => $sd[$name]->get_file() + $datas[] = array( + 'name' => _('export::ftp: reglages manuels'), + 'usr_id' => '0', + 'addrFTP' => '', + 'loginFTP' => '', + 'pwdFTP' => '', + 'ssl' => '0', + 'destFTP' => '', + 'prefixFTPfolder' => 'Export_' . date("Y-m-d_H.i.s"), + 'passifFTP' => false, + 'retryFTP' => 5, + 'mailFTP' => '', + 'sendermail' => $user->get_email() ); - if (!$user->ACL()->has_right_on_base($download_element->get_base_id(), "nowatermark") - && !$user->ACL()->has_preview_grant($download_element) - && $sd[$name]->get_type() == media_subdef::TYPE_IMAGE) - { - $path = recordutils_image::watermark( - $download_element->get_base_id() - , $download_element->get_record_id() - ); - if (file_exists($path)) - { - $tmp_pathfile = array( - 'path' => dirname($path) - , 'file' => basename($path) + + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute($params); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row) { + $datas[] = array( + 'name' => $row["usr_login"], + 'usr_id' => $row['usr_id'], + 'addrFTP' => $row['addrFTP'], + 'loginFTP' => $row['loginFTP'], + 'pwdFTP' => $row['pwdFTP'], + 'ssl' => $row['sslFTP'], + 'destFTP' => $row['destFTP'], + 'prefixFTPfolder' => + (strlen(trim($row['prefixFTPfolder'])) > 0 ? + trim($row['prefixFTPfolder']) : + 'Export_' . date("Y-m-d_H.i.s")), + 'passifFTP' => ($row['passifFTP'] > 0), + 'retryFTP' => $row['retryFTP'], + 'mailFTP' => $row['usr_mail'], + 'sendermail' => $user->get_email() ); - $subdef_alive = true; - } } - else - { - $subdef_alive = true; - } - break; + + $this->ftp_datas = $datas; } - if ($subdef_export === true && $subdef_alive === true) - { - switch ($properties['class']) - { - case 'caption': - if ($name == 'caption-yaml') - { - $suffix = '_captionyaml'; - $extension = 'yml'; - $mime = 'text/x-yaml'; - } - else - { - $suffix = '_caption'; - $extension = 'xml'; - $mime = 'text/xml'; - } + $this->display_orderable = $display_orderable; + $this->display_download = $display_download; + $this->display_ftp = $display_ftp; - $files[$id]["subdefs"][$name]["ajout"] = $suffix; - $files[$id]["subdefs"][$name]["exportExt"] = $extension; - $files[$id]["subdefs"][$name]["label"] = $properties['label']; - $files[$id]["subdefs"][$name]["path"] = null; - $files[$id]["subdefs"][$name]["file"] = null; - $files[$id]["subdefs"][$name]["size"] = 0; - $files[$id]["subdefs"][$name]["folder"] = $download_element->get_directory(); - $files[$id]["subdefs"][$name]["mime"] = $mime; - break; - case 'document': - case 'preview': - case 'thumbnail': - $infos = pathinfo(p4string::addEndSlash($tmp_pathfile["path"]) . - $tmp_pathfile["file"]); + return $this; + } - $files[$id]["subdefs"][$name]["ajout"] = - $properties['class'] == 'document' ? '' : "_" . $name; - $files[$id]["subdefs"][$name]["path"] = $tmp_pathfile["path"]; - $files[$id]["subdefs"][$name]["file"] = $tmp_pathfile["file"]; - $files[$id]["subdefs"][$name]["label"] = $properties['label']; - $files[$id]["subdefs"][$name]["size"] = $sd[$name]->get_size(); - $files[$id]["subdefs"][$name]["mime"] = $sd[$name]->get_mime(); - $files[$id]["subdefs"][$name]["folder"] = - $download_element->get_directory(); - $files[$id]["subdefs"][$name]["exportExt"] = - isset($infos['extension']) ? $infos['extension'] : ''; + /** + * + * @return Array + */ + public function get_ftp_datas() + { + return $this->ftp_datas; + } - $size += $sd[$name]->get_size(); + public function has_business_fields_access() + { + return $this->businessFieldsAccess; + } - break; - } + /** + * + * @return Array + */ + public function get_display_orderable() + { + return $this->display_orderable; + } - $longueurAjoutCourant = - mb_strlen($files[$id]["subdefs"][$name]["ajout"]); - $sizeMaxAjout = max($longueurAjoutCourant, $sizeMaxAjout); + /** + * + * @return Array + */ + public function get_display_download() + { + return $this->display_download; + } - $longueurExtCourant = - mb_strlen($files[$id]["subdefs"][$name]["exportExt"]); - $sizeMaxExt = max($longueurExtCourant, $sizeMaxExt); + /** + * + * @return Array + */ + public function get_display_ftp() + { + return $this->display_ftp; + } + + /** + * + * @return Int + */ + public function get_total_download() + { + return $this->total_download; + } + + /** + * + * @return Int + */ + public function get_total_order() + { + return $this->total_order; + } + + /** + * + * @return Int + */ + public function get_total_ftp() + { + return $this->total_ftp; + } + + /** + * + * @param Array $subdefs + * @param boolean $rename_title + * @return Array + */ + public function prepare_export(Array $subdefs, $rename_title, $includeBusinessFields) + { + if ( ! is_array($subdefs)) { + throw new Exception('No subdefs given'); } - } - $max_length = 31 - $sizeMaxExt - $sizeMaxAjout; + $includeBusinessFields = ! ! $includeBusinessFields; - $name = $files[$id]["export_name"]; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $registry = $appbox->get_registry(); - $start_length = mb_strlen($name); - if ($start_length > $max_length) - $name = mb_substr($name, 0, $max_length); + $unicode = new unicode(); - $n = 1; + $files = array(); - while (in_array(mb_strtolower($name), $file_names)) - { - $n++; - $suffix = "-" . $n; // pour diese si besoin - $max_length = 31 - $sizeMaxExt - $sizeMaxAjout - mb_strlen($suffix); - $name = mb_strtolower($files[$id]["export_name"]); - if ($start_length > $max_length) - $name = mb_substr($name, 0, $max_length) . $suffix; - else - $name = $name . $suffix; - } - $file_names[] = mb_strtolower($name); - $files[$id]["export_name"] = $name; + $n_files = 0; - $files[$id]["export_name"] = $unicode->remove_nonazAZ09($files[$id]["export_name"]); - $files[$id]["original_name"] = $unicode->remove_nonazAZ09($files[$id]["original_name"]); + $file_names = array(); - $i = 0; - $name = utf8_decode($files[$id]["export_name"]); - $tmp_name = ""; - $good_keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', - 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', - '4', '5', '6', '7', '8', '9', '-', '_', '.', '#'); + $size = 0; + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - while (isset($name[$i])) - { - if (!in_array(mb_strtolower($name[$i]), $good_keys)) - $tmp_name .= '_'; - else - $tmp_name .= $name[$i]; + foreach ($this->elements as $download_element) { + $id = count($files); - $tmp_name = str_replace('__', '_', $tmp_name); + $files[$id] = array( + 'base_id' => $download_element->get_base_id(), + 'record_id' => $download_element->get_record_id(), + 'original_name' => '', + 'export_name' => '', + 'subdefs' => array() + ); - $i++; - } - $files[$id]["export_name"] = $tmp_name; + $rename_done = false; - if (in_array('caption', $subdefs)) - { - $caption_dir = $registry->get('GV_RootPath') . 'tmp/desc_tmp/' - . time() . $session->get_usr_id() - . $session->get_ses_id() . '/'; + $BF = false; - system_file::mkdir($caption_dir); - - $desc = $download_element->get_caption()->serialize(\caption_record::SERIALIZE_XML, $BF); - - $file = $files[$id]["export_name"] - . $files[$id]["subdefs"]['caption']["ajout"] . '.' - . $files[$id]["subdefs"]['caption']["exportExt"]; - - $path = $caption_dir; - - file_put_contents($path . $file, $desc); - - $files[$id]["subdefs"]['caption']["path"] = $path; - $files[$id]["subdefs"]['caption']["file"] = $file; - $files[$id]["subdefs"]['caption']["size"] = filesize($path . $file); - $files[$id]["subdefs"]['caption']['businessfields'] = $BF ? '1' : '0'; - } - if (in_array('caption-yaml', $subdefs)) - { - $caption_dir = $registry->get('GV_RootPath') . 'tmp/desc_tmp/' - . time() . $session->get_usr_id() - . $session->get_ses_id() . '/'; - system_file::mkdir($caption_dir); - - $desc = $download_element->get_caption()->serialize(\caption_record::SERIALIZE_YAML, $BF); - - $file = $files[$id]["export_name"] - . $files[$id]["subdefs"]['caption-yaml']["ajout"] . '.' - . $files[$id]["subdefs"]['caption-yaml']["exportExt"]; - - $path = $caption_dir; - - file_put_contents($path . $file, $desc); - - $files[$id]["subdefs"]['caption-yaml']["path"] = $path; - $files[$id]["subdefs"]['caption-yaml']["file"] = $file; - $files[$id]["subdefs"]['caption-yaml']["size"] = filesize($path . $file); - $files[$id]["subdefs"]['caption-yaml']['businessfields'] = $BF ? '1' : '0'; - } - } - - $this->list = array( - 'files' => $files, - 'names' => $file_names, - 'size' => $size, - 'count' => $n_files - ); - - - return $this->list; - } - - /** - * - * @param String $token - * @param Array $list - * @param string $zipFile - * @return string - */ - public static function build_zip($token, Array $list, $zipFile) - { - $zip = new ZipArchiveImproved(); - - if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== true) - { - return false; - } - if (isset($list['complete']) && $list['complete'] === true) - { - return; - } - - $files = $list['files']; - - - $list['complete'] = false; - - random::updateToken($token, serialize($list)); - - $str_in = array("à", "á", "â", "ã", "ä", "å", "ç", "è", "é", "ê", - "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", - "õ", "ö", "ù", "ú", "û", "ü", "ý", "ÿ"); - $str_out = array("a", "a", "a", "a", "a", "a", "c", "e", "e", "e", - "e", "i", "i", "i", "i", "o", "n", "o", "o", "o", - "o", "o", "u", "u", "u", "u", "y", "y"); - - $caption_dirs = $unlinks = array(); - - foreach ($files as $record) - { - if (isset($record["subdefs"])) - { - foreach ($record["subdefs"] as $o => $obj) - { - $path = p4string::addEndSlash($obj["path"]) . $obj["file"]; - if (is_file($path)) - { - $name = $obj["folder"] - . $record["export_name"] - . $obj["ajout"] - . '.' . $obj["exportExt"]; - - $name = str_replace($str_in, $str_out, $name); - - $zip->addFile($path, $name); - - if ($o == 'caption') - { - if (!in_array(dirname($path), $caption_dirs)) - $caption_dirs[] = dirname($path); - $unlinks[] = $path; + if ($includeBusinessFields && $user->ACL()->has_right_on_base($download_element->get_base_id(), 'canmodifrecord')) { + $BF = true; + } + + $desc = $download_element->get_caption()->serialize(caption_record::SERIALIZE_XML, $BF); + + $files[$id]['original_name'] = + $files[$id]['export_name'] = + $download_element->get_original_name(true); + + $files[$id]['original_name'] = + trim($files[$id]['original_name']) != '' ? + $files[$id]['original_name'] : $id; + + $infos = pathinfo($files[$id]['original_name']); + + $extension = isset($infos['extension']) ? $infos['extension'] : ''; + + + if ($rename_title) { + $title = strip_tags($download_element->get_title(null, null, true)); + + $files[$id]['export_name'] = $unicode->remove_nonazAZ09($title, true); + $rename_done = true; + } else { + $files[$id]["export_name"] = $infos['filename']; + } + + $sizeMaxAjout = 0; + $sizeMaxExt = 0; + + $sd = $download_element->get_subdefs(); + + foreach ($download_element->get_downloadable() as $name => $properties) { + if ($properties === false || ! in_array($name, $subdefs)) { + continue; + } + if ( ! in_array($name, array('caption', 'caption-yaml')) && ! isset($sd[$name])) { + continue; + } + + set_time_limit(100); + $subdef_export = $subdef_alive = false; + + $n_files ++; + + $tmp_pathfile = array('path' => null, 'file' => null); + + switch ($properties['class']) { + case 'caption': + case 'caption-yaml': + $subdef_export = true; + $subdef_alive = true; + break; + case 'thumbnail': + $tmp_pathfile = array( + 'path' => $sd[$name]->get_path() + , 'file' => $sd[$name]->get_file() + ); + $subdef_export = true; + $subdef_alive = true; + break; + case 'document': + $subdef_export = true; + $path = recordutils_image::stamp( + $download_element->get_base_id() + , $download_element->get_record_id() + , true + ); + $tmp_pathfile = array( + 'path' => $sd[$name]->get_path() + , 'file' => $sd[$name]->get_file() + ); + if (file_exists($path)) { + $tmp_pathfile = array( + 'path' => dirname($path) + , 'file' => basename($path) + ); + $subdef_alive = true; + } + break; + + case 'preview': + $subdef_export = true; + + $tmp_pathfile = array( + 'path' => $sd[$name]->get_path() + , 'file' => $sd[$name]->get_file() + ); + if ( ! $user->ACL()->has_right_on_base($download_element->get_base_id(), "nowatermark") + && ! $user->ACL()->has_preview_grant($download_element) + && $sd[$name]->get_type() == media_subdef::TYPE_IMAGE) { + $path = recordutils_image::watermark( + $download_element->get_base_id() + , $download_element->get_record_id() + ); + if (file_exists($path)) { + $tmp_pathfile = array( + 'path' => dirname($path) + , 'file' => basename($path) + ); + $subdef_alive = true; + } + } else { + $subdef_alive = true; + } + break; + } + + if ($subdef_export === true && $subdef_alive === true) { + switch ($properties['class']) { + case 'caption': + if ($name == 'caption-yaml') { + $suffix = '_captionyaml'; + $extension = 'yml'; + $mime = 'text/x-yaml'; + } else { + $suffix = '_caption'; + $extension = 'xml'; + $mime = 'text/xml'; + } + + $files[$id]["subdefs"][$name]["ajout"] = $suffix; + $files[$id]["subdefs"][$name]["exportExt"] = $extension; + $files[$id]["subdefs"][$name]["label"] = $properties['label']; + $files[$id]["subdefs"][$name]["path"] = null; + $files[$id]["subdefs"][$name]["file"] = null; + $files[$id]["subdefs"][$name]["size"] = 0; + $files[$id]["subdefs"][$name]["folder"] = $download_element->get_directory(); + $files[$id]["subdefs"][$name]["mime"] = $mime; + + break; + case 'document': + case 'preview': + case 'thumbnail': + $infos = pathinfo(p4string::addEndSlash($tmp_pathfile["path"]) . + $tmp_pathfile["file"]); + + $files[$id]["subdefs"][$name]["ajout"] = + $properties['class'] == 'document' ? '' : "_" . $name; + $files[$id]["subdefs"][$name]["path"] = $tmp_pathfile["path"]; + $files[$id]["subdefs"][$name]["file"] = $tmp_pathfile["file"]; + $files[$id]["subdefs"][$name]["label"] = $properties['label']; + $files[$id]["subdefs"][$name]["size"] = $sd[$name]->get_size(); + $files[$id]["subdefs"][$name]["mime"] = $sd[$name]->get_mime(); + $files[$id]["subdefs"][$name]["folder"] = + $download_element->get_directory(); + $files[$id]["subdefs"][$name]["exportExt"] = + isset($infos['extension']) ? $infos['extension'] : ''; + + $size += $sd[$name]->get_size(); + + break; + } + + $longueurAjoutCourant = + mb_strlen($files[$id]["subdefs"][$name]["ajout"]); + $sizeMaxAjout = max($longueurAjoutCourant, $sizeMaxAjout); + + $longueurExtCourant = + mb_strlen($files[$id]["subdefs"][$name]["exportExt"]); + $sizeMaxExt = max($longueurExtCourant, $sizeMaxExt); + } + } + + $max_length = 31 - $sizeMaxExt - $sizeMaxAjout; + + $name = $files[$id]["export_name"]; + + $start_length = mb_strlen($name); + if ($start_length > $max_length) + $name = mb_substr($name, 0, $max_length); + + $n = 1; + + while (in_array(mb_strtolower($name), $file_names)) { + $n ++; + $suffix = "-" . $n; // pour diese si besoin + $max_length = 31 - $sizeMaxExt - $sizeMaxAjout - mb_strlen($suffix); + $name = mb_strtolower($files[$id]["export_name"]); + if ($start_length > $max_length) + $name = mb_substr($name, 0, $max_length) . $suffix; + else + $name = $name . $suffix; + } + $file_names[] = mb_strtolower($name); + $files[$id]["export_name"] = $name; + + $files[$id]["export_name"] = $unicode->remove_nonazAZ09($files[$id]["export_name"]); + $files[$id]["original_name"] = $unicode->remove_nonazAZ09($files[$id]["original_name"]); + + $i = 0; + $name = utf8_decode($files[$id]["export_name"]); + $tmp_name = ""; + $good_keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '-', '_', '.', '#'); + + while (isset($name[$i])) { + if ( ! in_array(mb_strtolower($name[$i]), $good_keys)) + $tmp_name .= '_'; + else + $tmp_name .= $name[$i]; + + $tmp_name = str_replace('__', '_', $tmp_name); + + $i ++; + } + $files[$id]["export_name"] = $tmp_name; + + if (in_array('caption', $subdefs)) { + $caption_dir = $registry->get('GV_RootPath') . 'tmp/desc_tmp/' + . time() . $session->get_usr_id() + . $session->get_ses_id() . '/'; + + system_file::mkdir($caption_dir); + + $desc = $download_element->get_caption()->serialize(\caption_record::SERIALIZE_XML, $BF); + + $file = $files[$id]["export_name"] + . $files[$id]["subdefs"]['caption']["ajout"] . '.' + . $files[$id]["subdefs"]['caption']["exportExt"]; + + $path = $caption_dir; + + file_put_contents($path . $file, $desc); + + $files[$id]["subdefs"]['caption']["path"] = $path; + $files[$id]["subdefs"]['caption']["file"] = $file; + $files[$id]["subdefs"]['caption']["size"] = filesize($path . $file); + $files[$id]["subdefs"]['caption']['businessfields'] = $BF ? '1' : '0'; + } + if (in_array('caption-yaml', $subdefs)) { + $caption_dir = $registry->get('GV_RootPath') . 'tmp/desc_tmp/' + . time() . $session->get_usr_id() + . $session->get_ses_id() . '/'; + system_file::mkdir($caption_dir); + + $desc = $download_element->get_caption()->serialize(\caption_record::SERIALIZE_YAML, $BF); + + $file = $files[$id]["export_name"] + . $files[$id]["subdefs"]['caption-yaml']["ajout"] . '.' + . $files[$id]["subdefs"]['caption-yaml']["exportExt"]; + + $path = $caption_dir; + + file_put_contents($path . $file, $desc); + + $files[$id]["subdefs"]['caption-yaml']["path"] = $path; + $files[$id]["subdefs"]['caption-yaml']["file"] = $file; + $files[$id]["subdefs"]['caption-yaml']["size"] = filesize($path . $file); + $files[$id]["subdefs"]['caption-yaml']['businessfields'] = $BF ? '1' : '0'; } - } } - } - } - $zip->close(); - - $list['complete'] = true; - - random::updateToken($token, serialize($list)); - - foreach ($unlinks as $u) - { - @unlink($u); - } - foreach ($caption_dirs as $c) - { - @rmdir($c); - } - - $system_file = new system_file($zipFile); - $system_file->chmod(); - - return $zipFile; - } - - /** - * - * @param string $file - * @param string $exportname - * @param string $mime - * @param string $disposition - * @return Void - */ - public static function stream_file( - $file, $exportname, $mime, $disposition = 'attachment') - { - $registry = registry::get_instance(); - - $disposition = in_array($disposition, array('inline', 'attachment')) ? - $disposition : 'attachment'; - - $response = new Symfony\Component\HttpFoundation\Response(); - - if (is_file($file)) - { - $testPath = function($file, $registry) - { - return strpos($file, $registry->get('GV_RootPath') . 'tmp/download/') !== false - || strpos($file, $registry->get('GV_RootPath') . 'tmp/lazaret/') !== false - || strpos($file, $registry->get('GV_X_Accel_Redirect')) !== false; - }; - - if ($registry->get('GV_modxsendfile') && $testPath($file, $registry)) - { - $file_xaccel = str_replace( - array( - $registry->get('GV_X_Accel_Redirect'), - $registry->get('GV_RootPath') . 'tmp/download/', - $registry->get('GV_RootPath') . 'tmp/lazaret/' - ) - , array( - '/' . $registry->get('GV_X_Accel_Redirect_mount_point') . '/', - '/download/', - '/lazaret/' - ) - , $file + $this->list = array( + 'files' => $files, + 'names' => $file_names, + 'size' => $size, + 'count' => $n_files ); - $response->headers->set('X-Sendfile', $file); - $response->headers->set('X-Accel-Redirect', $file_xaccel); - $response->headers->set('Pragma', 'public', true); - $response->headers->set('Content-Type', $mime); - $response->headers->set('Content-Name', $exportname); - $response->headers->set('Content-Disposition', $disposition . "; filename=" . $exportname . ";"); - $response->headers->set('Content-Length', filesize($file)); - return $response; - } - else - { - /** - * - * Header "Pragma: public" SHOULD be present. - * In case it is not present, download on IE 8 and previous over HTTPS - * will fail. - * - * @todo : merge this shitty fix with Response object. - * - */ - if (!headers_sent()) - { - header("Pragma: public"); + + return $this->list; + } + + /** + * + * @param String $token + * @param Array $list + * @param string $zipFile + * @return string + */ + public static function build_zip($token, Array $list, $zipFile) + { + $zip = new ZipArchiveImproved(); + + if ($zip->open($zipFile, ZIPARCHIVE::CREATE) !== true) { + return false; + } + if (isset($list['complete']) && $list['complete'] === true) { + return; } - $response->headers->set('Content-Type', $mime); - $response->headers->set('Content-Name', $exportname); - $response->headers->set('Content-Disposition', $disposition . "; filename=" . $exportname . ";"); - $response->headers->set('Content-Length', filesize($file)); - $response->setContent(file_get_contents($file)); + $files = $list['files']; - return $response; - } - } - return $response; - } + $list['complete'] = false; - /** - * - * @param String $data - * @param String $exportname - * @param String $mime - * @param String $disposition - * @return Void - */ - public static function stream_data($data, $exportname, $mime, $disposition = 'attachment') - { + random::updateToken($token, serialize($list)); - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); - header("Content-Type: " . $mime); - header("Content-Length: " . strlen($data)); - header("Cache-Control: max-age=3600, must-revalidate "); - header("Content-Disposition: " . $disposition - . "; filename=" . $exportname . ";"); + $str_in = array("à", "á", "â", "ã", "ä", "å", "ç", "è", "é", "ê", + "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", + "õ", "ö", "ù", "ú", "û", "ü", "ý", "ÿ"); + $str_out = array("a", "a", "a", "a", "a", "a", "c", "e", "e", "e", + "e", "i", "i", "i", "i", "o", "n", "o", "o", "o", + "o", "o", "u", "u", "u", "u", "y", "y"); - echo $data; + $caption_dirs = $unlinks = array(); - return true; - } + foreach ($files as $record) { + if (isset($record["subdefs"])) { + foreach ($record["subdefs"] as $o => $obj) { + $path = p4string::addEndSlash($obj["path"]) . $obj["file"]; + if (is_file($path)) { + $name = $obj["folder"] + . $record["export_name"] + . $obj["ajout"] + . '.' . $obj["exportExt"]; - /** - * @todo a revoir le cas anonymous - * - * @param Array $list - * @param String> $type - * @param boolean $anonymous - * @return Void - */ - public static function log_download(Array $list, $type, $anonymous = false, $comment = '') - { - //download - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $user = false; - if ($anonymous) - { + $name = str_replace($str_in, $str_out, $name); - } - else - { - $user = User_Adapter::getInstance($session->get_usr_id(), appbox::get_instance(\bootstrap::getCore())); - } + $zip->addFile($path, $name); - $tmplog = array(); - $files = $list['files']; - - $event_names = array( - 'mail-export' => Session_Logger::EVENT_EXPORTMAIL, - 'download' => Session_Logger::EVENT_EXPORTDOWNLOAD - ); - - $event_name = isset($event_names[$type]) ? $event_names[$type] : Session_Logger::EVENT_EXPORTDOWNLOAD; - - foreach ($files as $record) - { - foreach ($record["subdefs"] as $o => $obj) - { - $sbas_id = phrasea::sbasFromBas($record['base_id']); - $record_object = new record_adapter($sbas_id, $record['record_id']); - - $session->get_logger($record_object->get_databox()) - ->log($record_object, $event_name, $o, $comment); - - if ($o != "caption") - { - $log["rid"] = $record_object->get_record_id(); - $log["subdef"] = $o; - $log["poids"] = $obj["size"]; - $log["shortXml"] = $record_object->get_caption()->serialize(caption_record::SERIALIZE_XML); - $tmplog[$record_object->get_base_id()][] = $log; - if (!$anonymous && $o == 'document') - $user->ACL()->remove_remaining($record_object->get_base_id()); + if ($o == 'caption') { + if ( ! in_array(dirname($path), $caption_dirs)) + $caption_dirs[] = dirname($path); + $unlinks[] = $path; + } + } + } + } } - unset($record_object); - } + $zip->close(); + + $list['complete'] = true; + + random::updateToken($token, serialize($list)); + + foreach ($unlinks as $u) { + @unlink($u); + } + foreach ($caption_dirs as $c) { + @rmdir($c); + } + + $system_file = new system_file($zipFile); + $system_file->chmod(); + + return $zipFile; } - $export_types = array( - 'download' => 0, - 'mail-export' => 2, - 'ftp' => 4 - ); - - $list_base = array_unique(array_keys($tmplog)); - - if (!$anonymous) + /** + * + * @param string $file + * @param string $exportname + * @param string $mime + * @param string $disposition + * @return Void + */ + public static function stream_file( + $file, $exportname, $mime, $disposition = 'attachment') { - $sql = "UPDATE basusr + $registry = registry::get_instance(); + + $disposition = in_array($disposition, array('inline', 'attachment')) ? + $disposition : 'attachment'; + + $response = new Symfony\Component\HttpFoundation\Response(); + + if (is_file($file)) { + $testPath = function($file, $registry) { + return strpos($file, $registry->get('GV_RootPath') . 'tmp/download/') !== false + || strpos($file, $registry->get('GV_RootPath') . 'tmp/lazaret/') !== false + || strpos($file, $registry->get('GV_X_Accel_Redirect')) !== false; + }; + + if ($registry->get('GV_modxsendfile') && $testPath($file, $registry)) { + $file_xaccel = str_replace( + array( + $registry->get('GV_X_Accel_Redirect'), + $registry->get('GV_RootPath') . 'tmp/download/', + $registry->get('GV_RootPath') . 'tmp/lazaret/' + ) + , array( + '/' . $registry->get('GV_X_Accel_Redirect_mount_point') . '/', + '/download/', + '/lazaret/' + ) + , $file + ); + $response->headers->set('X-Sendfile', $file); + $response->headers->set('X-Accel-Redirect', $file_xaccel); + $response->headers->set('Pragma', 'public', true); + $response->headers->set('Content-Type', $mime); + $response->headers->set('Content-Name', $exportname); + $response->headers->set('Content-Disposition', $disposition . "; filename=" . $exportname . ";"); + $response->headers->set('Content-Length', filesize($file)); + + return $response; + } else { + /** + * + * Header "Pragma: public" SHOULD be present. + * In case it is not present, download on IE 8 and previous over HTTPS + * will fail. + * + * @todo : merge this shitty fix with Response object. + * + */ + if ( ! headers_sent()) { + header("Pragma: public"); + } + + $response->headers->set('Content-Type', $mime); + $response->headers->set('Content-Name', $exportname); + $response->headers->set('Content-Disposition', $disposition . "; filename=" . $exportname . ";"); + $response->headers->set('Content-Length', filesize($file)); + $response->setContent(file_get_contents($file)); + + return $response; + } + } + + return $response; + } + + /** + * + * @param String $data + * @param String $exportname + * @param String $mime + * @param String $disposition + * @return Void + */ + public static function stream_data($data, $exportname, $mime, $disposition = 'attachment') + { + + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + header("Content-Type: " . $mime); + header("Content-Length: " . strlen($data)); + header("Cache-Control: max-age=3600, must-revalidate "); + header("Content-Disposition: " . $disposition + . "; filename=" . $exportname . ";"); + + echo $data; + + return true; + } + + /** + * @todo a revoir le cas anonymous + * + * @param Array $list + * @param String> $type + * @param boolean $anonymous + * @return Void + */ + public static function log_download(Array $list, $type, $anonymous = false, $comment = '') + { + //download + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $user = false; + if ($anonymous) { + + } else { + $user = User_Adapter::getInstance($session->get_usr_id(), appbox::get_instance(\bootstrap::getCore())); + } + + $tmplog = array(); + $files = $list['files']; + + $event_names = array( + 'mail-export' => Session_Logger::EVENT_EXPORTMAIL, + 'download' => Session_Logger::EVENT_EXPORTDOWNLOAD + ); + + $event_name = isset($event_names[$type]) ? $event_names[$type] : Session_Logger::EVENT_EXPORTDOWNLOAD; + + foreach ($files as $record) { + foreach ($record["subdefs"] as $o => $obj) { + $sbas_id = phrasea::sbasFromBas($record['base_id']); + $record_object = new record_adapter($sbas_id, $record['record_id']); + + $session->get_logger($record_object->get_databox()) + ->log($record_object, $event_name, $o, $comment); + + if ($o != "caption") { + $log["rid"] = $record_object->get_record_id(); + $log["subdef"] = $o; + $log["poids"] = $obj["size"]; + $log["shortXml"] = $record_object->get_caption()->serialize(caption_record::SERIALIZE_XML); + $tmplog[$record_object->get_base_id()][] = $log; + if ( ! $anonymous && $o == 'document') + $user->ACL()->remove_remaining($record_object->get_base_id()); + } + + unset($record_object); + } + } + + $export_types = array( + 'download' => 0, + 'mail-export' => 2, + 'ftp' => 4 + ); + + $list_base = array_unique(array_keys($tmplog)); + + if ( ! $anonymous) { + $sql = "UPDATE basusr SET remain_dwnld = :remain_dl WHERE base_id = :base_id AND usr_id = :usr_id"; - $stmt = $appbox->get_connection()->prepare($sql); + $stmt = $appbox->get_connection()->prepare($sql); - foreach ($list_base as $base_id) - { - if ($user->ACL()->is_restricted_download($base_id)) - { - $params = array( - ':remain_dl' => $user->ACL()->remaining_download($base_id) - , ':base_id' => $base_id - , ':usr_id' => $user->get_id() - ); + foreach ($list_base as $base_id) { + if ($user->ACL()->is_restricted_download($base_id)) { + $params = array( + ':remain_dl' => $user->ACL()->remaining_download($base_id) + , ':base_id' => $base_id + , ':usr_id' => $user->get_id() + ); - $stmt->execute($params); + $stmt->execute($params); + } + } + + $stmt->closeCursor(); } - } - $stmt->closeCursor(); + return; } - - return; - } - } diff --git a/lib/classes/set/exportftp.class.php b/lib/classes/set/exportftp.class.php index 347a65963c..05b2f2bd24 100644 --- a/lib/classes/set/exportftp.class.php +++ b/lib/classes/set/exportftp.class.php @@ -18,143 +18,139 @@ class set_exportftp extends set_export { - /** - * - * @param Int $usr_to - * @param String $host - * @param String $login - * @param String $password - * @param Int $ssl - * @param Int $retry - * @param Int $passif - * @param String $destfolder - * @param String $makedirectory - * @return boolean - */ - public function export_ftp($usr_to, $host, $login, $password, $ssl, $retry, $passif, $destfolder, $makedirectory, $logfile) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $user_f = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $conn = $appbox->get_connection(); - - $email_dest = ''; - if ($usr_to) + /** + * + * @param Int $usr_to + * @param String $host + * @param String $login + * @param String $password + * @param Int $ssl + * @param Int $retry + * @param Int $passif + * @param String $destfolder + * @param String $makedirectory + * @return boolean + */ + public function export_ftp($usr_to, $host, $login, $password, $ssl, $retry, $passif, $destfolder, $makedirectory, $logfile) { - $user_t = User_Adapter::getInstance($usr_to, $appbox); - $email_dest = $user_t->get_email(); - } + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $user_f = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $conn = $appbox->get_connection(); + + $email_dest = ''; + if ($usr_to) { + $user_t = User_Adapter::getInstance($usr_to, $appbox); + $email_dest = $user_t->get_email(); + } - $text_mail_receiver = "Bonjour,\n" - . "L'utilisateur " - . $user_f->get_display_name() . " (login : " . $user_f->get_login() . ") " - . "a fait un transfert FTP sur le serveur ayant comme adresse \"" - . $host . "\" avec le login \"" . $login . "\" " - . "et pour repertoire de destination \"" - . $destfolder . "\"\n"; + $text_mail_receiver = "Bonjour,\n" + . "L'utilisateur " + . $user_f->get_display_name() . " (login : " . $user_f->get_login() . ") " + . "a fait un transfert FTP sur le serveur ayant comme adresse \"" + . $host . "\" avec le login \"" . $login . "\" " + . "et pour repertoire de destination \"" + . $destfolder . "\"\n"; - $text_mail_sender = "Bonjour,\n" - . "Vous avez fait un export FTP avec les caracteristiques " - . "de connexion suivantes\n" - . "- adresse du serveur : \"" . $host . "\"\n" - . "- login utilisé \"" . $login . "\"\n" - . "- repertoire de destination \"" . $destfolder . "\"\n" - . "\n"; + $text_mail_sender = "Bonjour,\n" + . "Vous avez fait un export FTP avec les caracteristiques " + . "de connexion suivantes\n" + . "- adresse du serveur : \"" . $host . "\"\n" + . "- login utilisé \"" . $login . "\"\n" + . "- repertoire de destination \"" . $destfolder . "\"\n" + . "\n"; - $fn = "id"; - $fv = "null"; - $fn .= ",crash"; - $fv .= ",0"; - $fn .= ",nbretry"; - $fv .= ",:nbretry"; - $fn .= ",mail"; - $fv .= ",:mail"; - $fn .= ",addr"; - $fv .= ",:addr"; - $fn .= ",login"; - $fv .= ",:login"; - $fn .= ",`ssl`"; - $fv .= ",:ssl"; - $fn .= ",pwd"; - $fv .= ",:pwd"; - $fn .= ",passif"; - $fv .= ",:passif"; - $fn .= ",destfolder"; - $fv .= ",:destfolder"; - $fn .= ",sendermail"; - $fv .= ",:sendermail"; - $fn .= ",text_mail_receiver"; - $fv .= ",:text_mail_receiver"; - $fn .= ",text_mail_sender"; - $fv .= ",:text_mail_sender"; - $fn .= ",usr_id"; - $fv .= ",:usr_id"; - $fn .= ",date"; - $fv .= ", NOW()"; - $fn .= ",foldertocreate"; - $fv .= ",:foldertocreate"; - $fn .= ",logfile"; - $fv .= ",:logfile"; + $fn = "id"; + $fv = "null"; + $fn .= ",crash"; + $fv .= ",0"; + $fn .= ",nbretry"; + $fv .= ",:nbretry"; + $fn .= ",mail"; + $fv .= ",:mail"; + $fn .= ",addr"; + $fv .= ",:addr"; + $fn .= ",login"; + $fv .= ",:login"; + $fn .= ",`ssl`"; + $fv .= ",:ssl"; + $fn .= ",pwd"; + $fv .= ",:pwd"; + $fn .= ",passif"; + $fv .= ",:passif"; + $fn .= ",destfolder"; + $fv .= ",:destfolder"; + $fn .= ",sendermail"; + $fv .= ",:sendermail"; + $fn .= ",text_mail_receiver"; + $fv .= ",:text_mail_receiver"; + $fn .= ",text_mail_sender"; + $fv .= ",:text_mail_sender"; + $fn .= ",usr_id"; + $fv .= ",:usr_id"; + $fn .= ",date"; + $fv .= ", NOW()"; + $fn .= ",foldertocreate"; + $fv .= ",:foldertocreate"; + $fn .= ",logfile"; + $fv .= ",:logfile"; - $params = array( - ':nbretry' => (((int) $retry * 1) > 0 ? (int) $retry : 5) - , ':mail' => $email_dest - , ':addr' => $host - , ':login' => $login - , ':ssl' => ($ssl == '1' ? '1' : '0') - , ':pwd' => $password - , ':passif' => ($passif == "1" ? "1" : "0") - , ':destfolder' => $destfolder - , ':sendermail' => $user_f->get_email() - , ':text_mail_receiver' => $text_mail_receiver - , ':text_mail_sender' => $text_mail_sender - , ':usr_id' => $session->get_usr_id() - , ':foldertocreate' => $makedirectory - , ':logfile' => (!!$logfile ? '1' : '0') - ); + $params = array( + ':nbretry' => (((int) $retry * 1) > 0 ? (int) $retry : 5) + , ':mail' => $email_dest + , ':addr' => $host + , ':login' => $login + , ':ssl' => ($ssl == '1' ? '1' : '0') + , ':pwd' => $password + , ':passif' => ($passif == "1" ? "1" : "0") + , ':destfolder' => $destfolder + , ':sendermail' => $user_f->get_email() + , ':text_mail_receiver' => $text_mail_receiver + , ':text_mail_sender' => $text_mail_sender + , ':usr_id' => $session->get_usr_id() + , ':foldertocreate' => $makedirectory + , ':logfile' => ( ! ! $logfile ? '1' : '0') + ); - $sql = "INSERT INTO ftp_export ($fn) VALUES ($fv)"; - $stmt = $conn->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $sql = "INSERT INTO ftp_export ($fn) VALUES ($fv)"; + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $ftp_export_id = $conn->lastInsertId(); + $ftp_export_id = $conn->lastInsertId(); - $sql = 'INSERT INTO ftp_export_elements + $sql = 'INSERT INTO ftp_export_elements (id, ftp_export_id, base_id, record_id, subdef, filename, folder, businessfields) VALUES (null, :ftp_export_id, :base_id, :record_id, :subdef, :filename, :folder, :businessfields)'; - $stmt = $conn->prepare($sql); + $stmt = $conn->prepare($sql); - foreach ($this->list['files'] as $file) - { - foreach ($file['subdefs'] as $subdef => $properties) - { - $filename = $file['export_name'] - . $properties["ajout"] . '.' - . $properties['exportExt']; + foreach ($this->list['files'] as $file) { + foreach ($file['subdefs'] as $subdef => $properties) { + $filename = $file['export_name'] + . $properties["ajout"] . '.' + . $properties['exportExt']; - $bfields = isset($properties['businessfields']) ? $properties['businessfields'] : null; + $bfields = isset($properties['businessfields']) ? $properties['businessfields'] : null; - $params = array( - ':ftp_export_id' => $ftp_export_id - , ':base_id' => $file['base_id'] - , ':record_id' => $file['record_id'] - , ':subdef' => $subdef - , ':filename' => $filename - , ':folder' => $properties['folder'] - , ':businessfields' => $bfields - ); - $stmt->execute($params); - } + $params = array( + ':ftp_export_id' => $ftp_export_id + , ':base_id' => $file['base_id'] + , ':record_id' => $file['record_id'] + , ':subdef' => $subdef + , ':filename' => $filename + , ':folder' => $properties['folder'] + , ':businessfields' => $bfields + ); + $stmt->execute($params); + } + } + + $stmt->closeCursor(); + + return true; } - - $stmt->closeCursor(); - - return true; - } - } diff --git a/lib/classes/set/exportorder.class.php b/lib/classes/set/exportorder.class.php index ca7470eb42..12a980dae5 100644 --- a/lib/classes/set/exportorder.class.php +++ b/lib/classes/set/exportorder.class.php @@ -18,149 +18,136 @@ class set_exportorder extends set_export { - /** - * - * @param Int $from_usr_id - * @param String $usage - * @param String $deadline - * @return boolean - */ - public function order_available_elements($from_usr_id, $usage, $deadline) - { - $Core = bootstrap::getCore(); - - $lst = $this->get_orderable_lst(); - - $conn = connection::getPDOConnection(); - - $date = phraseadate::format_mysql(new DateTime($deadline)); - - $conn->beginTransaction(); - - $usage = p4string::cleanTags($usage); - - try + /** + * + * @param Int $from_usr_id + * @param String $usage + * @param String $deadline + * @return boolean + */ + public function order_available_elements($from_usr_id, $usage, $deadline) { + $Core = bootstrap::getCore(); - $sql = 'INSERT INTO `order` + $lst = $this->get_orderable_lst(); + + $conn = connection::getPDOConnection(); + + $date = phraseadate::format_mysql(new DateTime($deadline)); + + $conn->beginTransaction(); + + $usage = p4string::cleanTags($usage); + + try { + + $sql = 'INSERT INTO `order` (`id`, `usr_id`, `created_on`, `usage`, `deadline`) VALUES (null, :from_usr_id, NOW(), :usage, :deadline)'; - $params = array( - ':from_usr_id' => $from_usr_id - , ':usage' => $usage - , ':deadline' => $deadline - ); - $stmt = $conn->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $params = array( + ':from_usr_id' => $from_usr_id + , ':usage' => $usage + , ':deadline' => $deadline + ); + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $order_id = $conn->lastInsertId(); + $order_id = $conn->lastInsertId(); - $sql = 'INSERT INTO order_elements + $sql = 'INSERT INTO order_elements (id, order_id, base_id, record_id, order_master_id) VALUES (null, :order_id, :base_id, :record_id, null)'; - $stmt = $conn->prepare($sql); + $stmt = $conn->prepare($sql); - foreach ($lst as $basrec) - { - $basrec = explode('_', $basrec); + foreach ($lst as $basrec) { + $basrec = explode('_', $basrec); - $record = new record_adapter($basrec[0], $basrec[1]); - $base_id = $record->get_base_id(); - $record_id = $basrec[1]; + $record = new record_adapter($basrec[0], $basrec[1]); + $base_id = $record->get_base_id(); + $record_id = $basrec[1]; + + $params = array( + ':order_id' => $order_id + , ':base_id' => $base_id + , ':record_id' => $record_id + ); + $stmt->execute($params); + } + + $stmt->closeCursor(); + $conn->commit(); + } catch (Exception $e) { + $conn->rollBack(); + + return false; + } + + $evt_mngr = eventsmanager_broker::getInstance(appbox::get_instance($Core), $Core); $params = array( - ':order_id' => $order_id - , ':base_id' => $base_id - , ':record_id' => $record_id + 'order_id' => $order_id, + 'usr_id' => $from_usr_id ); - $stmt->execute($params); - } - $stmt->closeCursor(); - $conn->commit(); - } - catch (Exception $e) - { - $conn->rollBack(); + $evt_mngr->trigger('__NEW_ORDER__', $params); - return false; + return true; } - $evt_mngr = eventsmanager_broker::getInstance(appbox::get_instance($Core), $Core); - - $params = array( - 'order_id' => $order_id, - 'usr_id' => $from_usr_id - ); - - $evt_mngr->trigger('__NEW_ORDER__', $params); - - return true; - } - - /** - * - * @return Array - */ - protected function get_orderable_lst() - { - $ret = array(); - foreach ($this as $basrec => $download_element) + /** + * + * @return Array + */ + protected function get_orderable_lst() { - foreach ($download_element->get_orderable() as $name => $bool) - { - if ($bool === true) - { - $ret[] = $basrec; + $ret = array(); + foreach ($this as $basrec => $download_element) { + foreach ($download_element->get_orderable() as $name => $bool) { + if ($bool === true) { + $ret[] = $basrec; + } + } } - } + + return $ret; } - return $ret; - } - - /** - * - * @param Int $admins - * @param Int $base_id - * @return Void - */ - public static function set_order_admins($admins, $base_id) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $conn = $appbox->get_connection(); - $conn->beginTransaction(); - try + /** + * + * @param Int $admins + * @param Int $base_id + * @return Void + */ + public static function set_order_admins($admins, $base_id) { - $user_query = new User_Query($appbox); - $result = $user_query->on_base_ids(array($base_id)) - ->who_have_right(array('order_master')) - ->execute()->get_results(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $conn = $appbox->get_connection(); + $conn->beginTransaction(); + try { + $user_query = new User_Query($appbox); + $result = $user_query->on_base_ids(array($base_id)) + ->who_have_right(array('order_master')) + ->execute()->get_results(); - foreach ($result as $user) - { - $user->ACL()->update_rights_to_base($base_id, array('order_master' => false)); - } + foreach ($result as $user) { + $user->ACL()->update_rights_to_base($base_id, array('order_master' => false)); + } - foreach ($admins as $admin) - { - $user = User_Adapter::getInstance($admin, $appbox); - $user->ACL()->update_rights_to_base($base_id, array('order_master' => true)); - } + foreach ($admins as $admin) { + $user = User_Adapter::getInstance($admin, $appbox); + $user->ACL()->update_rights_to_base($base_id, array('order_master' => true)); + } - $conn->commit(); + $conn->commit(); + } catch (Exception $e) { + $conn->rollBack(); + } + + return; } - catch (Exception $e) - { - $conn->rollBack(); - } - - return; - } - } diff --git a/lib/classes/set/order.class.php b/lib/classes/set/order.class.php index 9f0926010e..b2adf5f4cb 100644 --- a/lib/classes/set/order.class.php +++ b/lib/classes/set/order.class.php @@ -17,60 +17,66 @@ */ class set_order extends set_abstract { + /** + * + * @var int + */ + protected $id; - /** - * - * @var int - */ - protected $id; - /** - * - * @var user - */ - protected $user; - /** - * - * @var int - */ - protected $todo; - /** - * - * @var DateTime - */ - protected $created_on; - /** - * - * @var string - */ - protected $usage; - /** - * - * @var DateTime - */ - protected $deadline; - /** - * - * @var int - */ - protected $total; - /** - * - * @var int - */ - protected $ssel_id; + /** + * + * @var user + */ + protected $user; - /** - * - * @param int $id - * @return set_order - */ - public function __construct($id) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $conn = $appbox->get_connection(); + /** + * + * @var int + */ + protected $todo; - $sql = 'SELECT o.id, o.usr_id, o.created_on, o.`usage`, o.deadline, + /** + * + * @var DateTime + */ + protected $created_on; + + /** + * + * @var string + */ + protected $usage; + + /** + * + * @var DateTime + */ + protected $deadline; + + /** + * + * @var int + */ + protected $total; + + /** + * + * @var int + */ + protected $ssel_id; + + /** + * + * @param int $id + * @return set_order + */ + public function __construct($id) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $conn = $appbox->get_connection(); + + $sql = 'SELECT o.id, o.usr_id, o.created_on, o.`usage`, o.deadline, COUNT(e.id) as total, o.ssel_id, COUNT(e2.id) as todo FROM (`order` o, order_elements e) LEFT JOIN order_elements e2 @@ -80,298 +86,281 @@ class set_order extends set_abstract ) WHERE o.id = e.order_id AND o.id = :order_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':order_id' => $id)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':order_id' => $id)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (!$row) - throw new Exception('unknown order ' . $id); + if ( ! $row) + throw new Exception('unknown order ' . $id); - $current_user = User_Adapter::getInstance($row['usr_id'], $appbox); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $current_user = User_Adapter::getInstance($row['usr_id'], $appbox); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $this->id = $row['id']; - $this->user = $current_user; - $this->todo = $row['todo']; - $this->created_on = new DateTime($row['created_on']); - $this->usage = $row['usage']; - $this->deadline = new DateTime($row['deadline']); - $this->total = (int) $row['total']; - $this->ssel_id = (int) $row['ssel_id']; + $this->id = $row['id']; + $this->user = $current_user; + $this->todo = $row['todo']; + $this->created_on = new DateTime($row['created_on']); + $this->usage = $row['usage']; + $this->deadline = new DateTime($row['deadline']); + $this->total = (int) $row['total']; + $this->ssel_id = (int) $row['ssel_id']; - $base_ids = array_keys($user->ACL()->get_granted_base(array('order_master'))); - $sql = 'SELECT e.base_id, e.record_id, e.order_master_id, e.id, e.deny + $base_ids = array_keys($user->ACL()->get_granted_base(array('order_master'))); + $sql = 'SELECT e.base_id, e.record_id, e.order_master_id, e.id, e.deny FROM order_elements e WHERE order_id = :order_id AND e.base_id - IN ('.implode(',', $base_ids).')'; + IN (' . implode(',', $base_ids) . ')'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':order_id' => $id)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':order_id' => $id)); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $elements = array(); + $elements = array(); - foreach ($rs as $row) - { - $order_master_id = $row['order_master_id'] ? $row['order_master_id'] : false; + foreach ($rs as $row) { + $order_master_id = $row['order_master_id'] ? $row['order_master_id'] : false; - $elements[$row['id']] = new record_orderElement( - phrasea::sbasFromBas($row['base_id']), - $row['record_id'], - $row['deny'], - $order_master_id - ); + $elements[$row['id']] = new record_orderElement( + phrasea::sbasFromBas($row['base_id']), + $row['record_id'], + $row['deny'], + $order_master_id + ); + } + + $this->elements = $elements; + + return $this; } - $this->elements = $elements; - - return $this; - } - - /** - * - * @return User_Adapter - */ - public function get_user() - { - return $this->user; - } - - /** - * - * @return DateTime - */ - public function get_created_on() - { - return $this->created_on; - } - - /** - * - * @return DateTime - */ - public function get_deadline() - { - return $this->deadline; - } - - /** - * - * @return string - */ - public function get_usage() - { - return $this->usage; - } - - /** - * - * @return int - */ - public function get_total() - { - return $this->total; - } - - /** - * - * @return int - */ - public function get_order_id() - { - return $this->id; - } - - /** - * - * @return int - */ - public function get_todo() - { - return $this->todo; - } - - /** - * - * @param Array $elements_ids - * @param boolean $force - * @return set_order - */ - public function send_elements(Array $elements_ids, $force) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $conn = $appbox->get_connection(); - $pusher = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - $basrecs = array(); - foreach ($elements_ids as $id) + /** + * + * @return User_Adapter + */ + public function get_user() { - if (isset($this->elements[$id])) - { - $basrecs[$id] = array( - 'base_id' => $this->elements[$id]->get_base_id(), - 'record_id' => $this->elements[$id]->get_record_id() - ); - } + return $this->user; } - $core = \bootstrap::getCore(); - - $em = $core->getEntityManager(); - - $Basket = null; - /* @var $repository \Repositories\BasketRepository */ - if($this->ssel_id) + /** + * + * @return DateTime + */ + public function get_created_on() { - $repository = $em->getRepository('\Entities\Basket'); + return $this->created_on; + } + + /** + * + * @return DateTime + */ + public function get_deadline() + { + return $this->deadline; + } + + /** + * + * @return string + */ + public function get_usage() + { + return $this->usage; + } + + /** + * + * @return int + */ + public function get_total() + { + return $this->total; + } + + /** + * + * @return int + */ + public function get_order_id() + { + return $this->id; + } + + /** + * + * @return int + */ + public function get_todo() + { + return $this->todo; + } + + /** + * + * @param Array $elements_ids + * @param boolean $force + * @return set_order + */ + public function send_elements(Array $elements_ids, $force) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $conn = $appbox->get_connection(); + $pusher = User_Adapter::getInstance($session->get_usr_id(), $appbox); + + $basrecs = array(); + foreach ($elements_ids as $id) { + if (isset($this->elements[$id])) { + $basrecs[$id] = array( + 'base_id' => $this->elements[$id]->get_base_id(), + 'record_id' => $this->elements[$id]->get_record_id() + ); + } + } + + $core = \bootstrap::getCore(); + + $em = $core->getEntityManager(); - try - { - $Basket = $repository->findUserBasket($this->ssel_id, $core->getAuthenticatedUser(), false); - } - catch(\Exception $e) - { $Basket = null; - } - } + /* @var $repository \Repositories\BasketRepository */ + if ($this->ssel_id) { + $repository = $em->getRepository('\Entities\Basket'); - if(!$Basket) - { - $Basket = new \Entities\Basket(); - $Basket->setName(sprintf(_('Commande du %s'), $this->created_on->format('Y-m-d'))); - $Basket->setOwner($this->user); - $Basket->setPusher($core->getAuthenticatedUser()); + try { + $Basket = $repository->findUserBasket($this->ssel_id, $core->getAuthenticatedUser(), false); + } catch (\Exception $e) { + $Basket = null; + } + } - $em->persist($Basket); - $em->flush(); + if ( ! $Basket) { + $Basket = new \Entities\Basket(); + $Basket->setName(sprintf(_('Commande du %s'), $this->created_on->format('Y-m-d'))); + $Basket->setOwner($this->user); + $Basket->setPusher($core->getAuthenticatedUser()); - $this->ssel_id = $Basket->getId(); + $em->persist($Basket); + $em->flush(); - $sql = 'UPDATE `order` SET ssel_id = :ssel_id WHERE id = :order_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':ssel_id' => $Basket->getId(), ':order_id' => $this->id)); - $stmt->closeCursor(); - } + $this->ssel_id = $Basket->getId(); - $n = 0; + $sql = 'UPDATE `order` SET ssel_id = :ssel_id WHERE id = :order_id'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':ssel_id' => $Basket->getId(), ':order_id' => $this->id)); + $stmt->closeCursor(); + } - $sql = 'UPDATE order_elements + $n = 0; + + $sql = 'UPDATE order_elements SET deny="0", order_master_id = :usr_id WHERE order_id = :order_id AND id = :order_element_id'; - if ($force == '0') - { - $sql .= ' AND ISNULL(order_master_id)'; - } - $stmt = $conn->prepare($sql); + if ($force == '0') { + $sql .= ' AND ISNULL(order_master_id)'; + } + $stmt = $conn->prepare($sql); - foreach ($basrecs as $order_element_id => $basrec) - { - try - { - $sbas_id = phrasea::sbasFromBas($basrec['base_id']); - $record = new record_adapter($sbas_id, $basrec['record_id']); + foreach ($basrecs as $order_element_id => $basrec) { + try { + $sbas_id = phrasea::sbasFromBas($basrec['base_id']); + $record = new record_adapter($sbas_id, $basrec['record_id']); - $BasketElement = new \Entities\BasketElement(); - $BasketElement->setRecord($record); - $BasketElement->setBasket($Basket); + $BasketElement = new \Entities\BasketElement(); + $BasketElement->setRecord($record); + $BasketElement->setBasket($Basket); - $Basket->addBasketElement($BasketElement); + $Basket->addBasketElement($BasketElement); - $em->persist($BasketElement); + $em->persist($BasketElement); - $params = array( - ':usr_id' => $session->get_usr_id() - , ':order_id' => $this->id - , ':order_element_id' => $order_element_id - ); + $params = array( + ':usr_id' => $session->get_usr_id() + , ':order_id' => $this->id + , ':order_element_id' => $order_element_id + ); - $stmt->execute($params); + $stmt->execute($params); - $n++; - $this->user->ACL()->grant_hd_on($record, $pusher, 'order'); + $n ++; + $this->user->ACL()->grant_hd_on($record, $pusher, 'order'); - unset($record); - } - catch (Exception $e) - { + unset($record); + } catch (Exception $e) { - } + } + } + + $em->flush(); + $stmt->closeCursor(); + + if ($n > 0) { + $evt_mngr = eventsmanager_broker::getInstance($appbox, $core); + + $params = array( + 'ssel_id' => $this->ssel_id, + 'from' => $session->get_usr_id(), + 'to' => $this->user->get_id(), + 'n' => $n + ); + + $evt_mngr->trigger('__ORDER_DELIVER__', $params); + } + + return $this; } - $em->flush(); - $stmt->closeCursor(); - - if ($n > 0) + /** + * + * @param Array $elements_ids + * @return set_order + */ + public function deny_elements(Array $elements_ids) { - $evt_mngr = eventsmanager_broker::getInstance($appbox, $core); + $Core = bootstrap::getCore(); + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $conn = $appbox->get_connection(); - $params = array( - 'ssel_id' => $this->ssel_id, - 'from' => $session->get_usr_id(), - 'to' => $this->user->get_id(), - 'n' => $n - ); + $n = 0; - $evt_mngr->trigger('__ORDER_DELIVER__', $params); - } - - return $this; - } - - /** - * - * @param Array $elements_ids - * @return set_order - */ - public function deny_elements(Array $elements_ids) - { - $Core = bootstrap::getCore(); - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $conn = $appbox->get_connection(); - - $n = 0; - - foreach ($elements_ids as $order_element_id) - { - $sql = 'UPDATE order_elements + foreach ($elements_ids as $order_element_id) { + $sql = 'UPDATE order_elements SET deny="1", order_master_id = :order_master_id WHERE order_id = :order_id AND id = :order_element_id AND ISNULL(order_master_id)'; - $params = array( - ':order_master_id' => $session->get_usr_id() - , ':order_id' => $this->id - , ':order_element_id' => $order_element_id - ); - $stmt = $conn->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); - $n++; + $params = array( + ':order_master_id' => $session->get_usr_id() + , ':order_id' => $this->id + , ':order_element_id' => $order_element_id + ); + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); + $n ++; + } + + + if ($n > 0) { + $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); + + $params = array( + 'from' => $session->get_usr_id(), + 'to' => $this->user->get_id(), + 'n' => $n + ); + + $evt_mngr->trigger('__ORDER_NOT_DELIVERED__', $params); + } + + return $this; } - - - if ($n > 0) - { - $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); - - $params = array( - 'from' => $session->get_usr_id(), - 'to' => $this->user->get_id(), - 'n' => $n - ); - - $evt_mngr->trigger('__ORDER_NOT_DELIVERED__', $params); - } - - return $this; - } - } diff --git a/lib/classes/set/ordermanager.class.php b/lib/classes/set/ordermanager.class.php index d135fcab26..adbef03889 100644 --- a/lib/classes/set/ordermanager.class.php +++ b/lib/classes/set/ordermanager.class.php @@ -17,37 +17,37 @@ */ class set_ordermanager extends set_abstract { + /** + * + * @var int + */ + protected $page; - /** - * - * @var int - */ - protected $page; - /** - * - * @var int - */ - protected $total; + /** + * + * @var int + */ + protected $total; - const PER_PAGE = 10; + const PER_PAGE = 10; - /** - * - * @return set_ordermanager - */ - public function __construct($sort = false, $page = 1) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $conn = $appbox->get_connection(); + /** + * + * @return set_ordermanager + */ + public function __construct($sort = false, $page = 1) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $conn = $appbox->get_connection(); - $page = (int) $page; + $page = (int) $page; - $debut = ($page - 1) * self::PER_PAGE; + $debut = ($page - 1) * self::PER_PAGE; - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - $base_ids = array_keys($user->ACL()->get_granted_base(array('order_master'))); - $sql = 'SELECT distinct o.id, o.usr_id, created_on, deadline, `usage` + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + $base_ids = array_keys($user->ACL()->get_granted_base(array('order_master'))); + $sql = 'SELECT distinct o.id, o.usr_id, created_on, deadline, `usage` FROM (`order_elements` e, `order` o) WHERE e.base_id IN (' . implode(', ', $base_ids) . ') AND e.order_id = o.id @@ -55,128 +55,122 @@ class set_ordermanager extends set_abstract ORDER BY o.id DESC LIMIT ' . (int) $debut . ',' . self::PER_PAGE; - $elements = array(); + $elements = array(); - $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) - { - $elements[] = new set_order($row['id']); - } + foreach ($rs as $row) { + $elements[] = new set_order($row['id']); + } - if ($sort) - { - if ($sort == 'created_on') - uasort($elements, array('ordermanager', 'date_orders_sort')); - elseif ($sort == 'user') - uasort($elements, array('ordermanager', 'user_orders_sort')); - elseif ($sort == 'usage') - uasort($elements, array('ordermanager', 'usage_orders_sort')); - } + if ($sort) { + if ($sort == 'created_on') + uasort($elements, array('ordermanager', 'date_orders_sort')); + elseif ($sort == 'user') + uasort($elements, array('ordermanager', 'user_orders_sort')); + elseif ($sort == 'usage') + uasort($elements, array('ordermanager', 'usage_orders_sort')); + } - $sql = 'SELECT distinct o.id + $sql = 'SELECT distinct o.id FROM (`order_elements` e, `order` o) WHERE e.base_id IN (' . implode(', ', $base_ids) . ') AND e.order_id = o.id GROUP BY o.id ORDER BY o.id DESC'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':usr_id' => $session->get_usr_id())); - $total = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':usr_id' => $session->get_usr_id())); + $total = $stmt->rowCount(); + $stmt->closeCursor(); - $this->elements = $elements; - $this->page = $page; - $this->total = $total; + $this->elements = $elements; + $this->page = $page; + $this->total = $total; - return $this; - } + return $this; + } - /** - * - * @return int - */ - public function get_page() - { - return $this->page; - } + /** + * + * @return int + */ + public function get_page() + { + return $this->page; + } - /** - * - * @return int - */ - public function get_previous_page() - { - $p_page = $this->page < 2 ? false : ($this->page - 1); + /** + * + * @return int + */ + public function get_previous_page() + { + $p_page = $this->page < 2 ? false : ($this->page - 1); - return $p_page; - } + return $p_page; + } - /** - * - * @return int - */ - public function get_next_page() - { - $t_page = ceil($this->total / self::PER_PAGE); - $n_page = $this->page >= $t_page ? false : $this->page + 1; + /** + * + * @return int + */ + public function get_next_page() + { + $t_page = ceil($this->total / self::PER_PAGE); + $n_page = $this->page >= $t_page ? false : $this->page + 1; - return $n_page; - } + return $n_page; + } - /** - * - * @param string $a - * @param string $b - * @return int - */ - protected static function usage_orders_sort($a, $b) - { - $comp = strcasecmp($a['usage'], $b['usage']); + /** + * + * @param string $a + * @param string $b + * @return int + */ + protected static function usage_orders_sort($a, $b) + { + $comp = strcasecmp($a['usage'], $b['usage']); - if ($comp == 0) + if ($comp == 0) + return 0; - return 0; + return $comp < 0 ? -1 : 1; + } - return $comp < 0 ? -1 : 1; - } + /** + * + * @param string $a + * @param string $b + * @return int + */ + protected static function user_orders_sort($a, $b) + { + $comp = strcasecmp($a['usr_display'], $b['usr_display']); - /** - * - * @param string $a - * @param string $b - * @return int - */ - protected static function user_orders_sort($a, $b) - { - $comp = strcasecmp($a['usr_display'], $b['usr_display']); + if ($comp == 0) + return 0; - if ($comp == 0) + return $comp < 0 ? -1 : 1; + } - return 0; + /** + * + * @param DateTime $a + * @param DateTime $b + * @return int + */ + protected static function date_orders_sort(DateTime $a, DateTime $b) + { + $comp = $b->format('U') - $a->format('U'); - return $comp < 0 ? -1 : 1; - } - - /** - * - * @param DateTime $a - * @param DateTime $b - * @return int - */ - protected static function date_orders_sort(DateTime $a, DateTime $b) - { - $comp = $b->format('U') - $a->format('U'); - - if ($comp == 0) - - return 0; - - return $comp < 0 ? -1 : 1; - } + if ($comp == 0) + return 0; + return $comp < 0 ? -1 : 1; + } } diff --git a/lib/classes/set/result.class.php b/lib/classes/set/result.class.php index 17455d9265..1ea8f043f0 100644 --- a/lib/classes/set/result.class.php +++ b/lib/classes/set/result.class.php @@ -18,13 +18,12 @@ class set_result extends set_abstract { - /** - * - * @return set_result - */ - public function __construct() - { - return $this; - } - + /** + * + * @return set_result + */ + public function __construct() + { + return $this; + } } diff --git a/lib/classes/set/selection.class.php b/lib/classes/set/selection.class.php index 77b24f04a6..bd413c7d4e 100644 --- a/lib/classes/set/selection.class.php +++ b/lib/classes/set/selection.class.php @@ -18,173 +18,145 @@ class set_selection extends set_abstract { - /** - * - * @return set_selection - */ - public function __construct() - { - $this->elements = array(); - - return $this; - } - - /** - * - * @param \Entities\Basket $basket - * @return set_selection - */ - public function load_basket(\Entities\Basket $Basket) - { - foreach ($Basket->getElements() as $basket_element) + /** + * + * @return set_selection + */ + public function __construct() { - $this->add_element($basket_element->getRecord()); + $this->elements = array(); + + return $this; } - return $this; - } - - /** - * - * @param array $rights - * @return set_selection - */ - public function grep_authorized(Array $rights = array(), Array $sbas_rights = array()) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - $to_remove = array(); - - foreach ($this->elements as $id => $record) + /** + * + * @param \Entities\Basket $basket + * @return set_selection + */ + public function load_basket(\Entities\Basket $Basket) { - $base_id = $record->get_base_id(); - $sbas_id = $record->get_sbas_id(); - $record_id = $record->get_record_id(); - if (!$rights) - { - if ($user->ACL()->has_hd_grant($record)) - { - continue; + foreach ($Basket->getElements() as $basket_element) { + $this->add_element($basket_element->getRecord()); } - if ($user->ACL()->has_preview_grant($record)) - { - continue; - } - if (!$user->ACL()->has_access_to_base($base_id)) - { - $to_remove[] = $id; - continue; - } - } - else - { - foreach ($rights as $right) - { - if (!$user->ACL()->has_right_on_base($base_id, $right)) - { - $to_remove[] = $id; - continue; - } - } - foreach ($sbas_rights as $right) - { - if (!$user->ACL()->has_right_on_sbas($sbas_id, $right)) - { - $to_remove[] = $id; - continue; - } - } - } + return $this; + } - try - { - $connsbas = $record->get_databox()->get_connection(); + /** + * + * @param array $rights + * @return set_selection + */ + public function grep_authorized(Array $rights = array(), Array $sbas_rights = array()) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); - $sql = 'SELECT record_id + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + + $to_remove = array(); + + foreach ($this->elements as $id => $record) { + $base_id = $record->get_base_id(); + $sbas_id = $record->get_sbas_id(); + $record_id = $record->get_record_id(); + if ( ! $rights) { + if ($user->ACL()->has_hd_grant($record)) { + continue; + } + + if ($user->ACL()->has_preview_grant($record)) { + continue; + } + if ( ! $user->ACL()->has_access_to_base($base_id)) { + $to_remove[] = $id; + continue; + } + } else { + foreach ($rights as $right) { + if ( ! $user->ACL()->has_right_on_base($base_id, $right)) { + $to_remove[] = $id; + continue; + } + } + foreach ($sbas_rights as $right) { + if ( ! $user->ACL()->has_right_on_sbas($sbas_id, $right)) { + $to_remove[] = $id; + continue; + } + } + } + + try { + $connsbas = $record->get_databox()->get_connection(); + + $sql = 'SELECT record_id FROM record WHERE ((status ^ ' . $user->ACL()->get_mask_xor($base_id) . ') & ' . $user->ACL()->get_mask_and($base_id) . ')=0 AND record_id = :record_id'; - $stmt = $connsbas->prepare($sql); - $stmt->execute(array(':record_id' => $record_id)); - $num_rows = $stmt->rowCount(); - $stmt->closeCursor(); + $stmt = $connsbas->prepare($sql); + $stmt->execute(array(':record_id' => $record_id)); + $num_rows = $stmt->rowCount(); + $stmt->closeCursor(); - if ($num_rows == 0) - { - $to_remove[] = $id; + if ($num_rows == 0) { + $to_remove[] = $id; + } + } catch (Exception $e) { + + } + } + foreach ($to_remove as $id) { + unset($this->elements[$id]); } - } - catch (Exception $e) - { - } + return $this; } - foreach ($to_remove as $id) + + /** + * + * @param array $lst + * @return set_selection + */ + public function load_list(Array $lst, $flatten_groupings = false) { - unset($this->elements[$id]); + foreach ($lst as $basrec) { + $basrec = explode('_', $basrec); + if (count($basrec) == 2) { + try { + $record = new record_adapter((int) $basrec[0], (int) $basrec[1], count($this->elements)); + } catch (Exception $e) { + continue; + } + if ($record->is_grouping() && $flatten_groupings === true) { + foreach ($record->get_children() as $rec) { + $this->add_element($rec); + } + } else { + $this->add_element($record); + } + } + } + + return $this; } - return $this; - } - - /** - * - * @param array $lst - * @return set_selection - */ - public function load_list(Array $lst, $flatten_groupings = false) - { - foreach ($lst as $basrec) + /** + * + * @return array + */ + public function get_distinct_sbas_ids() { - $basrec = explode('_', $basrec); - if (count($basrec) == 2) - { - try - { - $record = new record_adapter((int) $basrec[0], (int) $basrec[1], count($this->elements)); + $ret = array(); + foreach ($this->elements as $record) { + $sbas_id = phrasea::sbasFromBas($record->get_base_id()); + $ret[$sbas_id] = $sbas_id; } - catch (Exception $e) - { - continue; - } - if ($record->is_grouping() && $flatten_groupings === true) - { - foreach ($record->get_children() as $rec) - { - $this->add_element($rec); - } - } - else - { - $this->add_element($record); - } - } + + return $ret; } - - return $this; - } - - /** - * - * @return array - */ - public function get_distinct_sbas_ids() - { - $ret = array(); - foreach ($this->elements as $record) - { - $sbas_id = phrasea::sbasFromBas($record->get_base_id()); - $ret[$sbas_id] = $sbas_id; - } - - return $ret; - } - } diff --git a/lib/classes/setup.class.php b/lib/classes/setup.class.php index 691094a453..60a5923fea 100644 --- a/lib/classes/setup.class.php +++ b/lib/classes/setup.class.php @@ -21,796 +21,704 @@ */ class setup { - - protected static $PHP_EXT = array( - "dom" - , "exif" - , "fileinfo" - , "ftp" - , "curl" - , "gd" - , "gettext" - , "hash" - , "json" - , "iconv" - , "libxml" - , "mbstring" - , "mysql" - , "PDO" - , "phrasea2" - , "SimpleXML" - , "sockets" - , "xml" - , "zip" - , "zlib" - , "intl" - , "twig" - , "gmagick" - , "imagick" - ); - protected static $PHP_CONF = array( - 'output_buffering' => '4096' //INI_ALL - , 'memory_limit' => '1024M' //INI_ALL - , 'error_reporting' => '6143' //INI_ALL - , 'default_charset' => 'UTF-8' //INI_ALL - , 'session.use_cookies' => '1' //INI_ALL - , 'session.use_only_cookies' => '1' //INI_ALL - , 'session.auto_start' => '0' //INI_ALL - , 'session.hash_function' => '1' //INI_ALL - , 'session.hash_bits_per_character' => '6' //INI_ALL - , 'allow_url_fopen' => 'on' //INI_ALL - , 'display_errors' => 'off' //INI_ALL - , 'display_startup_errors' => 'off' //INI_ALL - , 'log_errors' => 'off' //INI_ALL - ); - protected static $PHP_REQ = array( - 'safe_mode' => 'off' - , 'file_uploads' => '1' - , 'magic_quotes_runtime' => 'off' //INI_ALL - , 'magic_quotes_gpc' => 'off' //INI_PER_DIR -- just for check - ); - - public static function is_installed() - { - $appConf = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification(); - - return $appConf->isSetup(); - } - - public static function needUpgradeConfigurationFile() - { - return (is_file(__DIR__ . "/../../config/connexion.inc") - && is_file(__DIR__ . "/../../config/config.inc")); - } - - function create_global_values(registryInterface &$registry, $datas = array()) - { - require(__DIR__ . "/../../lib/conf.d/_GV_template.inc"); - - - if ($registry->is_set('GV_timezone')) - date_default_timezone_set($registry->get('GV_timezone')); - else - date_default_timezone_set('Europe/Berlin'); - - $debug = $log_errors = false; - $vars = array(); - - $error = false; - $extra_conf = ''; - - foreach ($GV as $section) - { - foreach ($section['vars'] as $variable) - { - if (isset($datas[$variable['name']]) === false) - { - if (isset($variable['default'])) - { - if ($variable['type'] === 'boolean') - { - if ($variable['default'] === true) - $datas[$variable['name']] = '1'; - else - $datas[$variable['name']] = '0'; - } - else - { - $datas[$variable['name']] = $variable['default']; - } - } - } - - - $type = 'string'; - switch ($variable['type']) - { - case 'string': - case 'password': - $datas[$variable['name']] = (string) trim($datas[$variable['name']]); - break; - case 'enum': - if (!isset($variable['available'])) - { - $variable['error'] = 'avalaibility'; - } - elseif (!is_array($variable['available'])) - { - $variable['error'] = 'avalaibility'; - } - elseif (!in_array($datas[$variable['name']], $variable['available'])) - { - $variable['error'] = 'avalaibility'; - } - break; - case 'enum_multi': - if (!isset($datas[$variable['name']])) - $datas[$variable['name']] = null; - $datas[$variable['name']] = ($datas[$variable['name']]); - $type = 'array'; - break; - case 'boolean': - $datas[$variable['name']] = strtolower($datas[$variable['name']]) === 'true' ? '1' : '0'; - $type = 'boolean'; - break; - case 'integer': - $datas[$variable['name']] = (int) trim($datas[$variable['name']]); - $type = 'integer'; - break; - case 'text': - $datas[$variable['name']] = trim($datas[$variable['name']]); - break; - case 'timezone': - $datas[$variable['name']] = trim($datas[$variable['name']]); - break; - default: - $error = true; - break; - } - - if (isset($variable['required']) && $variable['required'] === true && trim($datas[$variable['name']]) === '') - $variable['error'] = 'required'; - - if (isset($variable['end_slash'])) - { - if ($variable['end_slash'] === true) - { - $datas[$variable['name']] = trim($datas[$variable['name']]) !== '' ? p4string::addEndSlash($datas[$variable['name']]) : ''; - } - if ($variable['end_slash'] === false) - { - $datas[$variable['name']] = trim($datas[$variable['name']]) !== '' ? p4string::delEndSlash($datas[$variable['name']]) : ''; - } - } - - if ($variable['name'] === 'GV_debug' && $datas[$variable['name']] === '1') - $debug = true; - if ($variable['name'] === 'GV_log_errors' && $datas[$variable['name']] === '1') - $log_errors = true; - - if ($variable['type'] !== 'integer' && $variable['type'] !== 'boolean') - $datas[$variable['name']] = $datas[$variable['name']]; - - $vars[$variable['name']] = array('value' => $datas[$variable['name']], 'type' => $type); - } - } - - if ($error === false) - { - foreach ($vars as $key => $values) - { - $registry->set($key, $values['value'], $values['type']); - } - - return true; - } - - return false; - } - - public static function check_binaries(registryInterface $registry) - { - $binaries = array( - 'PHP CLI' => $registry->get('GV_cli'), - 'ImageMagick (convert)' => $registry->get('GV_imagick'), - 'PDF 2 SWF' => $registry->get('GV_pdf2swf'), - 'Unoconv' => $registry->get('GV_unoconv'), - 'SWFextract' => $registry->get('GV_swf_extract'), - 'SWFrender' => $registry->get('GV_swf_render'), - 'MP4Box' => $registry->get('GV_mp4box'), - 'xpdf (pdf2text)' => $registry->get('GV_pdftotext'), - 'ImageMagick (composite)' => $registry->get('GV_pathcomposite'), - 'Exiftool' => $registry->get('GV_exiftool'), - 'FFmpeg' => $registry->get('GV_ffmpeg'), - 'MPlayer' => $registry->get('GV_mplayer') + protected static $PHP_EXT = array( + "dom" + , "exif" + , "fileinfo" + , "ftp" + , "curl" + , "gd" + , "gettext" + , "hash" + , "json" + , "iconv" + , "libxml" + , "mbstring" + , "mysql" + , "PDO" + , "phrasea2" + , "SimpleXML" + , "sockets" + , "xml" + , "zip" + , "zlib" + , "intl" + , "twig" + , "gmagick" + , "imagick" + ); + protected static $PHP_CONF = array( + 'output_buffering' => '4096' //INI_ALL + , 'memory_limit' => '1024M' //INI_ALL + , 'error_reporting' => '6143' //INI_ALL + , 'default_charset' => 'UTF-8' //INI_ALL + , 'session.use_cookies' => '1' //INI_ALL + , 'session.use_only_cookies' => '1' //INI_ALL + , 'session.auto_start' => '0' //INI_ALL + , 'session.hash_function' => '1' //INI_ALL + , 'session.hash_bits_per_character' => '6' //INI_ALL + , 'allow_url_fopen' => 'on' //INI_ALL + , 'display_errors' => 'off' //INI_ALL + , 'display_startup_errors' => 'off' //INI_ALL + , 'log_errors' => 'off' //INI_ALL + ); + protected static $PHP_REQ = array( + 'safe_mode' => 'off' + , 'file_uploads' => '1' + , 'magic_quotes_runtime' => 'off' //INI_ALL + , 'magic_quotes_gpc' => 'off' //INI_PER_DIR -- just for check ); - $constraints = array(); - - foreach ($binaries as $name => $binary) + public static function is_installed() { - if (trim($binary) == '' || (!is_file($binary))) - { - $constraints[] = new Setup_Constraint( + $appConf = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification(); + + return $appConf->isSetup(); + } + + public static function needUpgradeConfigurationFile() + { + return (is_file(__DIR__ . "/../../config/connexion.inc") + && is_file(__DIR__ . "/../../config/config.inc")); + } + + function create_global_values(registryInterface &$registry, $datas = array()) + { + require(__DIR__ . "/../../lib/conf.d/_GV_template.inc"); + + + if ($registry->is_set('GV_timezone')) + date_default_timezone_set($registry->get('GV_timezone')); + else + date_default_timezone_set('Europe/Berlin'); + + $debug = $log_errors = false; + $vars = array(); + + $error = false; + $extra_conf = ''; + + foreach ($GV as $section) { + foreach ($section['vars'] as $variable) { + if (isset($datas[$variable['name']]) === false) { + if (isset($variable['default'])) { + if ($variable['type'] === 'boolean') { + if ($variable['default'] === true) + $datas[$variable['name']] = '1'; + else + $datas[$variable['name']] = '0'; + } + else { + $datas[$variable['name']] = $variable['default']; + } + } + } + + + $type = 'string'; + switch ($variable['type']) { + case 'string': + case 'password': + $datas[$variable['name']] = (string) trim($datas[$variable['name']]); + break; + case 'enum': + if ( ! isset($variable['available'])) { + $variable['error'] = 'avalaibility'; + } elseif ( ! is_array($variable['available'])) { + $variable['error'] = 'avalaibility'; + } elseif ( ! in_array($datas[$variable['name']], $variable['available'])) { + $variable['error'] = 'avalaibility'; + } + break; + case 'enum_multi': + if ( ! isset($datas[$variable['name']])) + $datas[$variable['name']] = null; + $datas[$variable['name']] = ($datas[$variable['name']]); + $type = 'array'; + break; + case 'boolean': + $datas[$variable['name']] = strtolower($datas[$variable['name']]) === 'true' ? '1' : '0'; + $type = 'boolean'; + break; + case 'integer': + $datas[$variable['name']] = (int) trim($datas[$variable['name']]); + $type = 'integer'; + break; + case 'text': + $datas[$variable['name']] = trim($datas[$variable['name']]); + break; + case 'timezone': + $datas[$variable['name']] = trim($datas[$variable['name']]); + break; + default: + $error = true; + break; + } + + if (isset($variable['required']) && $variable['required'] === true && trim($datas[$variable['name']]) === '') + $variable['error'] = 'required'; + + if (isset($variable['end_slash'])) { + if ($variable['end_slash'] === true) { + $datas[$variable['name']] = trim($datas[$variable['name']]) !== '' ? p4string::addEndSlash($datas[$variable['name']]) : ''; + } + if ($variable['end_slash'] === false) { + $datas[$variable['name']] = trim($datas[$variable['name']]) !== '' ? p4string::delEndSlash($datas[$variable['name']]) : ''; + } + } + + if ($variable['name'] === 'GV_debug' && $datas[$variable['name']] === '1') + $debug = true; + if ($variable['name'] === 'GV_log_errors' && $datas[$variable['name']] === '1') + $log_errors = true; + + if ($variable['type'] !== 'integer' && $variable['type'] !== 'boolean') + $datas[$variable['name']] = $datas[$variable['name']]; + + $vars[$variable['name']] = array('value' => $datas[$variable['name']], 'type' => $type); + } + } + + if ($error === false) { + foreach ($vars as $key => $values) { + $registry->set($key, $values['value'], $values['type']); + } + + return true; + } + + return false; + } + + public static function check_binaries(registryInterface $registry) + { + $binaries = array( + 'PHP CLI' => $registry->get('GV_cli'), + 'ImageMagick (convert)' => $registry->get('GV_imagick'), + 'PDF 2 SWF' => $registry->get('GV_pdf2swf'), + 'Unoconv' => $registry->get('GV_unoconv'), + 'SWFextract' => $registry->get('GV_swf_extract'), + 'SWFrender' => $registry->get('GV_swf_render'), + 'MP4Box' => $registry->get('GV_mp4box'), + 'xpdf (pdf2text)' => $registry->get('GV_pdftotext'), + 'ImageMagick (composite)' => $registry->get('GV_pathcomposite'), + 'Exiftool' => $registry->get('GV_exiftool'), + 'FFmpeg' => $registry->get('GV_ffmpeg'), + 'MPlayer' => $registry->get('GV_mplayer') + ); + + $constraints = array(); + + foreach ($binaries as $name => $binary) { + if (trim($binary) == '' || ( ! is_file($binary))) { + $constraints[] = new Setup_Constraint( $name , false , sprintf('%s missing', $name) , false + ); + } else { + if ( ! is_executable($binary)) { + $constraints[] = new Setup_Constraint( + $name + , false + , sprintf('%s not executeable', $name) + , true + ); + } else { + $constraints[] = new Setup_Constraint( + $name + , true + , sprintf('%s OK', $name) + , true + ); + } + } + } + + return new Setup_ConstraintsIterator($constraints); + } + + public static function discover_binaries() + { + if (system_server::get_platform() == 'WINDOWS') { + $exiftool = dirname(__DIR__) . '/vendor/exiftool/exiftool.exe'; + $indexer = dirname(dirname(__DIR__)) . '/bin/phraseanet_indexer.exe'; + } else { + $exiftool = dirname(__DIR__) . '/vendor/exiftool/exiftool'; + $indexer = null; + } + + return array( + 'php' => array('name' => 'PHP CLI', 'binary' => self::discover_binary('php')), + 'exiftool' => array('name' => 'Exiftool', 'binary' => self::discover_binary('exiftool', array($exiftool))), + 'phraseanet_indexer' => array('name' => 'Indexeur Phrasea', 'binary' => self::discover_binary('phraseanet_indexer', array($indexer))), + 'convert' => array('name' => 'ImageMagick (convert)', 'binary' => self::discover_binary('convert')), + 'composite' => array('name' => 'ImageMagick (composite)', 'binary' => self::discover_binary('composite')), + 'pdf2swf' => array('name' => 'PDF 2 SWF', 'binary' => self::discover_binary('pdf2swf')), + 'unoconv' => array('name' => 'Unoconv', 'binary' => self::discover_binary('unoconv')), + 'swfextract' => array('name' => 'SWFextract', 'binary' => self::discover_binary('swfextract')), + 'swfrender' => array('name' => 'SWFrender', 'binary' => self::discover_binary('swfrender')), + 'MP4Box' => array('name' => 'MP4Box', 'binary' => self::discover_binary('MP4Box')), + 'xpdf' => array('name' => 'XPDF', 'binary' => self::discover_binary('xpdf')), + 'ffmpeg' => array('name' => 'FFmpeg', 'binary' => self::discover_binary('ffmpeg')), + 'mplayer' => array('name' => 'MPlayer', 'binary' => self::discover_binary('mplayer')) ); - } - else - { - if (!is_executable($binary)) - { - $constraints[] = new Setup_Constraint( - $name - , false - , sprintf('%s not executeable', $name) - , true - ); + } + + protected static function discover_binary($binary, array $look_here = array()) + { + if (system_server::get_platform() == 'WINDOWS') + return null; + + foreach ($look_here as $place) { + if (is_executable($place)) + return $place; } + + return exec(sprintf('which %s', $binary)); + } + + function check_mod_auth_token() + { + $registry = registry::get_instance(); + + if ($registry->get('GV_h264_streaming') !== true) + return; + ?> +

              mod_auth_token configuration

              +
                + get('GV_mod_auth_token_directory_path') . '/test_mod_auth_token.txt'; // The file to access + + touch($fileName); + + $url = $registry->get('GV_ServerName') . p4file::apache_tokenize($fileName); + + if (http_query::getHttpCodeFromUrl($url) == 200) + echo '
              • ' . _('mod_auth_token correctement configure') . '
              • '; else - { - $constraints[] = new Setup_Constraint( - $name - , true - , sprintf('%s OK', $name) - , true - ); - } - } - } - - return new Setup_ConstraintsIterator($constraints); - } - - public static function discover_binaries() - { - if (system_server::get_platform() == 'WINDOWS') - { - $exiftool = dirname(__DIR__) . '/vendor/exiftool/exiftool.exe'; - $indexer = dirname(dirname(__DIR__)) . '/bin/phraseanet_indexer.exe'; - } - else - { - $exiftool = dirname(__DIR__) . '/vendor/exiftool/exiftool'; - $indexer = null; - } - - return array( - 'php' => array('name' => 'PHP CLI', 'binary' => self::discover_binary('php')), - 'exiftool' => array('name' => 'Exiftool', 'binary' => self::discover_binary('exiftool', array($exiftool))), - 'phraseanet_indexer' => array('name' => 'Indexeur Phrasea', 'binary' => self::discover_binary('phraseanet_indexer', array($indexer))), - 'convert' => array('name' => 'ImageMagick (convert)', 'binary' => self::discover_binary('convert')), - 'composite' => array('name' => 'ImageMagick (composite)', 'binary' => self::discover_binary('composite')), - 'pdf2swf' => array('name' => 'PDF 2 SWF', 'binary' => self::discover_binary('pdf2swf')), - 'unoconv' => array('name' => 'Unoconv', 'binary' => self::discover_binary('unoconv')), - 'swfextract' => array('name' => 'SWFextract', 'binary' => self::discover_binary('swfextract')), - 'swfrender' => array('name' => 'SWFrender', 'binary' => self::discover_binary('swfrender')), - 'MP4Box' => array('name' => 'MP4Box', 'binary' => self::discover_binary('MP4Box')), - 'xpdf' => array('name' => 'XPDF', 'binary' => self::discover_binary('xpdf')), - 'ffmpeg' => array('name' => 'FFmpeg', 'binary' => self::discover_binary('ffmpeg')), - 'mplayer' => array('name' => 'MPlayer', 'binary' => self::discover_binary('mplayer')) - ); - } - - protected static function discover_binary($binary, array $look_here = array()) - { - if (system_server::get_platform() == 'WINDOWS') - - return null; - - foreach ($look_here as $place) - { - if (is_executable($place)) - - return $place; - } - - return exec(sprintf('which %s', $binary)); - } - - function check_mod_auth_token() - { - $registry = registry::get_instance(); - - if ($registry->get('GV_h264_streaming') !== true) - - return; - ?> -

                mod_auth_token configuration

                -
                  - get('GV_mod_auth_token_directory_path') . '/test_mod_auth_token.txt'; // The file to access - - touch($fileName); - - $url = $registry->get('GV_ServerName') . p4file::apache_tokenize($fileName); - - if (http_query::getHttpCodeFromUrl($url) == 200) - echo '
                • ' . _('mod_auth_token correctement configure') . '
                • '; - else - echo '
                • ' . _('mod_auth_token mal configure') . '
                • '; - ?> -
                - -

                Apache Server mods avalaibility

                -
                - -
                - - get('GV_modxsendfile')) - { - ?> -
                - - -
              • - mod_auth_token (optionnal) + } + + function check_apache() + { + $registry = registry::get_instance(); + ?> +

                Apache Server mods avalaibility

                +
                get('GV_h264_streaming')) - { - ?> -
                + echo _('Attention, seul le test de l\'activation des mods est effectue, leur bon fonctionnement ne l\'est pas ') + ?> +
                + +
                  + +
                • + mod_rewrite (required) +
                • +
                • + mod_xsendfile (optionnal) + get('GV_modxsendfile')) { + ?> +
                  + +
                • +
                • + mod_auth_token (optionnal) + get('GV_h264_streaming')) { + ?> +
                  -
                • -
                • - mod_h264_streaming (optionnal) +
                • +
                • + mod_h264_streaming (optionnal) get('GV_h264_streaming')) - { - ?> -
                  - -
                • - - + } + - '; + '; } public static function check_phrasea() { - $constraints = array(); - if (function_exists('phrasea_info')) - { - foreach (phrasea_info() as $name => $value) - { - switch ($name) - { - default: - $result = true; - $message = $name . ' = ' . $value; - break; - case 'temp_writable': - $result = $value == '1'; - if ($result) - $message = 'Directory is writeable'; - else - $message = 'Directory MUST be writable'; - break; - case 'version': - $result = version_compare($value, '1.18.0.3', '>='); - if ($result) - $message = sprintf('Phrasea version %s is ok', $value); - else - $message = sprintf('Phrasea version %s is NOT ok', $value); - break; - } - $blocker = $name == 'temp_writable' ? ($value ? '' : 'blocker') : ''; - $constraints[] = new Setup_Constraint($name, $result, $message, true); + $constraints = array(); + if (function_exists('phrasea_info')) { + foreach (phrasea_info() as $name => $value) { + switch ($name) { + default: + $result = true; + $message = $name . ' = ' . $value; + break; + case 'temp_writable': + $result = $value == '1'; + if ($result) + $message = 'Directory is writeable'; + else + $message = 'Directory MUST be writable'; + break; + case 'version': + $result = version_compare($value, '1.18.0.3', '>='); + if ($result) + $message = sprintf('Phrasea version %s is ok', $value); + else + $message = sprintf('Phrasea version %s is NOT ok', $value); + break; + } + $blocker = $name == 'temp_writable' ? ($value ? '' : 'blocker') : ''; + $constraints[] = new Setup_Constraint($name, $result, $message, true); + } } - } - return new Setup_ConstraintsIterator($constraints); + return new Setup_ConstraintsIterator($constraints); } public static function check_writability(registryInterface $registry) { - $root = p4string::addEndSlash(realpath(__DIR__ . '/../../')); + $root = p4string::addEndSlash(realpath(__DIR__ . '/../../')); - $pathes = array( - $root . 'config', - $root . 'config/stamp', - $root . 'config/status', - $root . 'config/minilogos', - $root . 'config/templates', - $root . 'config/topics', - $root . 'config/wm', - $root . 'logs', - $root . 'tmp', - $root . 'www/custom', - $root . 'tmp/locks', - $root . 'tmp/cache_twig', - $root . 'tmp/cache_minify', - $root . 'tmp/lazaret', - $root . 'tmp/desc_tmp', - $root . 'tmp/download', - $root . 'tmp/batches'); + $pathes = array( + $root . 'config', + $root . 'config/stamp', + $root . 'config/status', + $root . 'config/minilogos', + $root . 'config/templates', + $root . 'config/topics', + $root . 'config/wm', + $root . 'logs', + $root . 'tmp', + $root . 'www/custom', + $root . 'tmp/locks', + $root . 'tmp/cache_twig', + $root . 'tmp/cache_minify', + $root . 'tmp/lazaret', + $root . 'tmp/desc_tmp', + $root . 'tmp/download', + $root . 'tmp/batches'); - if ($registry->is_set('GV_base_datapath_web')) - { - $pathes[] = $registry->get('GV_base_datapath_web'); - } - if ($registry->is_set('GV_base_datapath_noweb')) - { - $pathes[] = $registry->get('GV_base_datapath_noweb'); - } - - - $constraints = array(); - - foreach ($pathes as $p) - { - if (!is_writable($p)) - { - $message = sprintf('%s not writeable', $p); + if ($registry->is_set('GV_base_datapath_web')) { + $pathes[] = $registry->get('GV_base_datapath_web'); } - else - { - $message = sprintf('%s OK', $p); + if ($registry->is_set('GV_base_datapath_noweb')) { + $pathes[] = $registry->get('GV_base_datapath_noweb'); } - $constraints[] = new Setup_Constraint( - 'Writeability test', is_writable($p), $message, true - ); - } - $php_constraints = new Setup_ConstraintsIterator($constraints); - return $php_constraints; + $constraints = array(); + + foreach ($pathes as $p) { + if ( ! is_writable($p)) { + $message = sprintf('%s not writeable', $p); + } else { + $message = sprintf('%s OK', $p); + } + + $constraints[] = new Setup_Constraint( + 'Writeability test', is_writable($p), $message, true + ); + } + $php_constraints = new Setup_ConstraintsIterator($constraints); + + return $php_constraints; } function check_mail_form() { - echo '

                  ' . _('setup::Tests d\'envois d\'emails') . '

                  '; - ?> -
                  - - -
                  + echo '

                  ' . _('setup::Tests d\'envois d\'emails') . '

                  '; + ?> +
                  + + +
                  - '); + if ( ! $version_ok) { + $message = sprintf( + 'Wrong PHP version : % ; PHP >= 5.3.4 required' + , PHP_VERSION + ); + } else { + $message = sprintf('PHP version OK : %s', PHP_VERSION); + } + $constraints = array( + new Setup_Constraint('PHP Version', $version_ok, $message) + ); + + return new Setup_ConstraintsIterator($constraints); + } + + public static function check_php_extension() + { + $constraints = array(); + foreach (self::$PHP_EXT as $ext) { + if (extension_loaded($ext) !== true) { + $blocker = true; + if (in_array($ext, array('twig', 'gmagick', 'imagick'))) { + $blocker = false; + } + + $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), false, sprintf('%s missing', $ext), $blocker); + } else { + $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), true, sprintf('%s loaded', $ext)); + } + } + + return new Setup_ConstraintsIterator($constraints); + } + + public static function check_cache_server() + { + $availables_caches = array('memcache', 'redis'); + + $constraints = array(); + foreach ($availables_caches as $ext) { + if (extension_loaded($ext) === true) { + $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), true, sprintf('%s loaded', $ext), false); + } + else + $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), false, sprintf('%s not loaded', $ext), false); + } + + return new Setup_ConstraintsIterator($constraints); + } + + function check_cache_memcache() + { + $Core = \bootstrap::getCore(); + + echo '

                  ' . _('setup:: Serveur Memcached') . '

                  '; + echo '
                    '; + + $registry = registry::get_instance(); + + if ($Core->getCache()->isServer()) { + $stats = $Core->getCache()->getStats(); + + echo '
                  • ' . sprintf(_('setup::Serveur actif sur %s'), $registry->get('GV_cache_server_host') . ':' . $registry->get('GV_cache_server_port')) . '
                  • '; + echo ""; + + foreach ($stats as $name => $stat) { + echo ""; + } + + echo "
                    " . $name . " " . $stat . "
                    "; + } else { + echo '
                  • ' . sprintf(_('setup::Aucun serveur memcached rattache.')) . '
                  • '; + } + echo '
                  '; + } + + public static function check_cache_opcode() + { + $availables = array('XCache', 'apc', 'eAccelerator', 'phpa', 'WinCache'); + $constraints = array(); + + $found = 0; + foreach ($availables as $ext) { + if (extension_loaded($ext) === true) { + $constraints[] = new Setup_Constraint($ext, true, sprintf('%s loaded', $ext), false); + $found ++; + } + } + + if ($found > 1) + $constraints[] = new Setup_Constraint('Multiple opcode caches', false, _('Many opcode cache load is forbidden'), true); + if ($found === 0) + $constraints[] = new Setup_Constraint('No opcode cache', false, _('No opcode cache were detected. Phraseanet strongly recommends the use of XCache or APC.'), false); + + return new Setup_ConstraintsIterator($constraints); + } + + public static function check_php_configuration() + { + $nonblockers = array('log_errors', 'display_startup_errors', 'display_errors'); + + $constraints = array(); + foreach (self::$PHP_REQ as $conf => $value) { + if (($tmp = self::test_php_conf($conf, $value)) === false) { + $constraints[] = new Setup_Constraint($conf, false, sprintf(_('setup::Configuration mauvaise : pour la variable %1$s, configuration donnee : %2$s ; attendue : %3$s'), $conf, $tmp, $value), true); + } else { + $constraints[] = new Setup_Constraint($conf, true, sprintf('%s = %s => OK', $conf, $value), true); + } + } + foreach (self::$PHP_CONF as $conf => $value) { + if (($tmp = self::test_php_conf($conf, $value)) === false) { + $constraints[] = new Setup_Constraint($conf, false, sprintf('Bad configuration for %1$s var ; %2$s given - %3$s supposed', $conf, $tmp, $value), ! in_array($conf, $nonblockers)); + } else { + $constraints[] = new Setup_Constraint($conf, true, sprintf('%s = %s => OK', $conf, $value), ! in_array($conf, $nonblockers)); + } + } + + return new Setup_ConstraintsIterator($constraints); + } + + public static function check_sphinx_search() + { + $registry = registry::get_instance(); + + try { + $engine = new searchEngine_adapter($registry); + $status = $engine->get_status(); + + echo '

                  ' . _('setup::Etat du moteur de recherche') . '

                  '; + echo '
                    '; + foreach ($status as $value) { + echo '
                  • ' . sprintf('%s : %s', $value[0], $value[1]) . '
                  • '; + } + echo '
                  '; + } catch (Exception $e) { + + echo '

                  ' . _('setup::Sphinx confguration') . '

                  '; + echo '
                    '; + echo '
                  • ' . $e->getMessage() . '
                  • '; + echo '
                  '; + } + } + + /** + * + * @return Setup_ConstraintsIterator + */ + public static function check_system_locales() + { + $constraints = array(); + + if ( ! extension_loaded('gettext')) + return new Setup_ConstraintsIterator($constraints); + + foreach (User_Adapter::$locales as $code => $language_name) { + phrasea::use_i18n($code, 'test'); + + if (_('test::test') == 'test') { + $constraints[] = new Setup_Constraint($language_name, true, sprintf('Locale %s (%s) ok', $language_name, $code), false); + } else { + $constraints[] = new Setup_Constraint($language_name, false, sprintf('Locale %s (%s) not installed', $language_name, $code), false); + } + } + phrasea::use_i18n(Session_Handler::get_locale()); + + return new Setup_ConstraintsIterator($constraints); + } + + private static function test_php_conf($conf, $value) + { + $is_flag = false; + $flags = array('on', 'off', '1', '0', ''); + if (in_array(strtolower($value), $flags)) + $is_flag = true; + $current = ini_get($conf); + if ($is_flag) + $current = strtolower($current); + + if (($current === '' || $current === 'off' || $current === '0') && $is_flag) + if ($value === 'off' || $value === '0' || $value === '') + return $current; + if (($current === '1' || $current === 'on') && $is_flag) + if ($value === 'on' || $value === '1') + return $current; + if ($current === $value) + return $current; + } + + public static function rollback(connection_pdo $conn, connection_pdo $connbas = null) + { + $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml"); + + if ( ! $structure) { + throw new Exception('Unable to load schema'); + } + + $appbox = $structure->appbox; + $databox = $structure->databox; + + foreach ($appbox->tables->table as $table) { + try { + $sql = 'DROP TABLE `' . $table['name'] . '`'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } catch (Exception $e) { + + } + } + if ($connbas) { + foreach ($databox->tables->table as $table) { + try { + $sql = 'DROP TABLE `' . $table['name'] . '`'; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } catch (Exception $e) { + + } + } + } + + $appConf = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification(); + + $appConf->delete(); + + return; + } } - /** - * - */ - public static function check_php_version() - { - $version_ok = version_compare(PHP_VERSION, '5.3.4', '>'); - if (!$version_ok) - { - $message = sprintf( - 'Wrong PHP version : % ; PHP >= 5.3.4 required' - , PHP_VERSION - ); - } - else - { - $message = sprintf('PHP version OK : %s', PHP_VERSION); - } - $constraints = array( - new Setup_Constraint('PHP Version', $version_ok, $message) - ); - - return new Setup_ConstraintsIterator($constraints); - } - - public static function check_php_extension() - { - $constraints = array(); - foreach (self::$PHP_EXT as $ext) - { - if (extension_loaded($ext) !== true) - { - $blocker = true; - if(in_array($ext, array('twig', 'gmagick', 'imagick'))) - { - $blocker = false; - } - - $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), false, sprintf('%s missing', $ext), $blocker); - } - else - { - $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), true, sprintf('%s loaded', $ext)); - } - } - - return new Setup_ConstraintsIterator($constraints); - } - - public static function check_cache_server() - { - $availables_caches = array('memcache', 'redis'); - - $constraints = array(); - foreach ($availables_caches as $ext) - { - if (extension_loaded($ext) === true) - { - $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), true, sprintf('%s loaded', $ext), false); - } - else - $constraints[] = new Setup_Constraint(sprintf('Extension %s', $ext), false, sprintf('%s not loaded', $ext), false); - } - - return new Setup_ConstraintsIterator($constraints); - } - - function check_cache_memcache() - { - $Core = \bootstrap::getCore(); - - echo '

                  ' . _('setup:: Serveur Memcached') . '

                  '; - echo '
                    '; - - $registry = registry::get_instance(); - - if ($Core->getCache()->isServer()) - { - $stats = $Core->getCache()->getStats(); - - echo '
                  • ' . sprintf(_('setup::Serveur actif sur %s'), $registry->get('GV_cache_server_host') . ':' . $registry->get('GV_cache_server_port')) . '
                  • '; - echo ""; - - foreach ($stats as $name => $stat) - { - echo ""; - } - - echo "
                    " . $name . " " . $stat . "
                    "; - } - else - { - echo '
                  • ' . sprintf(_('setup::Aucun serveur memcached rattache.')) . '
                  • '; - } - echo '
                  '; - } - - public static function check_cache_opcode() - { - $availables = array('XCache', 'apc', 'eAccelerator', 'phpa', 'WinCache'); - $constraints = array(); - - $found = 0; - foreach ($availables as $ext) - { - if (extension_loaded($ext) === true) - { - $constraints[] = new Setup_Constraint($ext, true, sprintf('%s loaded', $ext), false); - $found++; - } - } - - if ($found > 1) - $constraints[] = new Setup_Constraint('Multiple opcode caches', false, _('Many opcode cache load is forbidden'), true); - if ($found === 0) - $constraints[] = new Setup_Constraint('No opcode cache', false, _('No opcode cache were detected. Phraseanet strongly recommends the use of XCache or APC.'), false); - - return new Setup_ConstraintsIterator($constraints); - } - - public static function check_php_configuration() - { - $nonblockers = array('log_errors', 'display_startup_errors', 'display_errors'); - - $constraints = array(); - foreach (self::$PHP_REQ as $conf => $value) - { - if (($tmp = self::test_php_conf($conf, $value)) === false) - { - $constraints[] = new Setup_Constraint($conf, false, sprintf(_('setup::Configuration mauvaise : pour la variable %1$s, configuration donnee : %2$s ; attendue : %3$s'), $conf, $tmp, $value), true); - } - else - { - $constraints[] = new Setup_Constraint($conf, true, sprintf('%s = %s => OK', $conf, $value), true); - } - } - foreach (self::$PHP_CONF as $conf => $value) - { - if (($tmp = self::test_php_conf($conf, $value)) === false) - { - $constraints[] = new Setup_Constraint($conf, false, sprintf('Bad configuration for %1$s var ; %2$s given - %3$s supposed', $conf, $tmp, $value), !in_array($conf, $nonblockers)); - } - else - { - $constraints[] = new Setup_Constraint($conf, true, sprintf('%s = %s => OK', $conf, $value), !in_array($conf, $nonblockers)); - } - } - - return new Setup_ConstraintsIterator($constraints); - } - - public static function check_sphinx_search() - { - $registry = registry::get_instance(); - - try - { - $engine = new searchEngine_adapter($registry); - $status = $engine->get_status(); - - echo '

                  ' . _('setup::Etat du moteur de recherche') . '

                  '; - echo '
                    '; - foreach ($status as $value) - { - echo '
                  • ' . sprintf('%s : %s', $value[0], $value[1]) . '
                  • '; - } - echo '
                  '; - } - catch (Exception $e) - { - - echo '

                  ' . _('setup::Sphinx confguration') . '

                  '; - echo '
                    '; - echo '
                  • ' . $e->getMessage() . '
                  • '; - echo '
                  '; - } - } - - /** - * - * @return Setup_ConstraintsIterator - */ - public static function check_system_locales() - { - $constraints = array(); - - if (!extension_loaded('gettext')) - - return new Setup_ConstraintsIterator($constraints); - - foreach (User_Adapter::$locales as $code => $language_name) - { - phrasea::use_i18n($code, 'test'); - - if (_('test::test') == 'test') - { - $constraints[] = new Setup_Constraint($language_name, true, sprintf('Locale %s (%s) ok', $language_name, $code), false); - } - else - { - $constraints[] = new Setup_Constraint($language_name, false, sprintf('Locale %s (%s) not installed', $language_name, $code), false); - } - } - phrasea::use_i18n(Session_Handler::get_locale()); - - return new Setup_ConstraintsIterator($constraints); - } - - private static function test_php_conf($conf, $value) - { - $is_flag = false; - $flags = array('on', 'off', '1', '0', ''); - if (in_array(strtolower($value), $flags)) - $is_flag = true; - $current = ini_get($conf); - if ($is_flag) - $current = strtolower($current); - - if (($current === '' || $current === 'off' || $current === '0') && $is_flag) - if ($value === 'off' || $value === '0' || $value === '') - - return $current; - if (($current === '1' || $current === 'on') && $is_flag) - if ($value === 'on' || $value === '1') - - return $current; - if ($current === $value) - - return $current; - } - - public static function rollback(connection_pdo $conn, connection_pdo $connbas = null) - { - $structure = simplexml_load_file(__DIR__ . "/../../lib/conf.d/bases_structure.xml"); - - if (!$structure) - { - throw new Exception('Unable to load schema'); - } - - $appbox = $structure->appbox; - $databox = $structure->databox; - - foreach ($appbox->tables->table as $table) - { - try - { - $sql = 'DROP TABLE `' . $table['name'] . '`'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - catch (Exception $e) - { - - } - } - if ($connbas) - { - foreach ($databox->tables->table as $table) - { - try - { - $sql = 'DROP TABLE `' . $table['name'] . '`'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - catch (Exception $e) - { - - } - } - } - - $appConf = new \Alchemy\Phrasea\Core\Configuration\ApplicationSpecification(); - - $appConf->delete(); - - return; - } - - } - diff --git a/lib/classes/sphinx/charsetTable/CJK.class.php b/lib/classes/sphinx/charsetTable/CJK.class.php index 10856dcbc3..5fdf7e7861 100644 --- a/lib/classes/sphinx/charsetTable/CJK.class.php +++ b/lib/classes/sphinx/charsetTable/CJK.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_CJK extends sphinx_charsetTableAbstract { - - protected $name = 'Chinese, Japanese, and Korean'; - protected $table = ' + protected $name = 'Chinese, Japanese, and Korean'; + protected $table = ' ################################################# # CJK* U+F900->U+8C48, U+F901->U+66F4, U+F902->U+8ECA, U+F903->U+8CC8, U+F904->U+6ED1, diff --git a/lib/classes/sphinx/charsetTable/arabic.class.php b/lib/classes/sphinx/charsetTable/arabic.class.php index bb12ee2123..bc27fd971a 100644 --- a/lib/classes/sphinx/charsetTable/arabic.class.php +++ b/lib/classes/sphinx/charsetTable/arabic.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_arabic extends sphinx_charsetTableAbstract { - - protected $name = 'Arabic'; - protected $table = ' + protected $name = 'Arabic'; + protected $table = ' ################################################## # Arabic U+0622->U+0627, U+0623->U+0627, U+0624->U+0648, U+0625->U+0627, U+0626->U+064A, diff --git a/lib/classes/sphinx/charsetTable/armenian.class.php b/lib/classes/sphinx/charsetTable/armenian.class.php index 2e8b13a881..dca1d530bf 100644 --- a/lib/classes/sphinx/charsetTable/armenian.class.php +++ b/lib/classes/sphinx/charsetTable/armenian.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_armenian extends sphinx_charsetTableAbstract { - - protected $name = 'Armenian'; - protected $table = ' + protected $name = 'Armenian'; + protected $table = ' ################################################## # Armenian U+0531..U+0556->U+0561..U+0586, U+0561..U+0586, U+0587 diff --git a/lib/classes/sphinx/charsetTable/bengali.class.php b/lib/classes/sphinx/charsetTable/bengali.class.php index da32ee7c40..086213b849 100644 --- a/lib/classes/sphinx/charsetTable/bengali.class.php +++ b/lib/classes/sphinx/charsetTable/bengali.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_bengali extends sphinx_charsetTableAbstract { - - protected $name = 'Bengali'; - protected $table = ' + protected $name = 'Bengali'; + protected $table = ' ################################################# # Bengali U+09DC->U+09A1, U+09DD->U+09A2, U+09DF->U+09AF, U+09F0->U+09AC, U+09F1->U+09AC, diff --git a/lib/classes/sphinx/charsetTable/common.class.php b/lib/classes/sphinx/charsetTable/common.class.php index 366dc66955..dd4d1733a5 100644 --- a/lib/classes/sphinx/charsetTable/common.class.php +++ b/lib/classes/sphinx/charsetTable/common.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_common extends sphinx_charsetTableAbstract { - - protected $name = 'Default'; - protected $table = ' + protected $name = 'Default'; + protected $table = ' ################################################## # Common U+FF10..U+FF19->0..9, U+FF21..U+FF3A->a..z, U+FF41..U+FF5A->a..z, 0..9, diff --git a/lib/classes/sphinx/charsetTable/coptic.class.php b/lib/classes/sphinx/charsetTable/coptic.class.php index 8696cbbafb..18870d4baf 100644 --- a/lib/classes/sphinx/charsetTable/coptic.class.php +++ b/lib/classes/sphinx/charsetTable/coptic.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_coptic extends sphinx_charsetTableAbstract { - - protected $name = 'Coptic'; - protected $table = ' + protected $name = 'Coptic'; + protected $table = ' ################################################## # Coptic # Notes: Some shared Greek characters, may require ammendments. diff --git a/lib/classes/sphinx/charsetTable/cyrillic.class.php b/lib/classes/sphinx/charsetTable/cyrillic.class.php index a416dde647..de73912e2c 100644 --- a/lib/classes/sphinx/charsetTable/cyrillic.class.php +++ b/lib/classes/sphinx/charsetTable/cyrillic.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_cyrillic extends sphinx_charsetTableAbstract { - - protected $name = 'Cyrillic'; - protected $table = ' + protected $name = 'Cyrillic'; + protected $table = ' ################################################## # Cryllic* U+0400->U+0435, U+0401->U+0435, U+0402->U+0452, U+0452, U+0403->U+0433, diff --git a/lib/classes/sphinx/charsetTable/devanagari.class.php b/lib/classes/sphinx/charsetTable/devanagari.class.php index 1fef5b8f49..3998f12c53 100644 --- a/lib/classes/sphinx/charsetTable/devanagari.class.php +++ b/lib/classes/sphinx/charsetTable/devanagari.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_devanagari extends sphinx_charsetTableAbstract { - - protected $name = 'Devanagari'; - protected $table = ' + protected $name = 'Devanagari'; + protected $table = ' ################################################## # Devanagari U+0929->U+0928, U+0931->U+0930, U+0934->U+0933, U+0958->U+0915, U+0959->U+0916, diff --git a/lib/classes/sphinx/charsetTable/georgian.class.php b/lib/classes/sphinx/charsetTable/georgian.class.php index a62e1546f5..25131aa2bc 100644 --- a/lib/classes/sphinx/charsetTable/georgian.class.php +++ b/lib/classes/sphinx/charsetTable/georgian.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_georgian extends sphinx_charsetTableAbstract { - - protected $name = 'Georgian'; - protected $table = ' + protected $name = 'Georgian'; + protected $table = ' ################################################## # Georgian U+10FC->U+10DC, U+10D0..U+10FA, U+10A0..U+10C5->U+2D00..U+2D25, U+2D00..U+2D25 diff --git a/lib/classes/sphinx/charsetTable/greek.class.php b/lib/classes/sphinx/charsetTable/greek.class.php index efe19b974b..1f1e822fa7 100644 --- a/lib/classes/sphinx/charsetTable/greek.class.php +++ b/lib/classes/sphinx/charsetTable/greek.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_greek extends sphinx_charsetTableAbstract { - - protected $name = 'Greek'; - protected $table = ' + protected $name = 'Greek'; + protected $table = ' ################################################## # Greek U+0386->U+03B1, U+0388->U+03B5, U+0389->U+03B7, U+038A->U+03B9, U+038C->U+03BF, diff --git a/lib/classes/sphinx/charsetTable/gujarati.class.php b/lib/classes/sphinx/charsetTable/gujarati.class.php index 9ce21fb7cf..adb929307b 100644 --- a/lib/classes/sphinx/charsetTable/gujarati.class.php +++ b/lib/classes/sphinx/charsetTable/gujarati.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_gujarati extends sphinx_charsetTableAbstract { - - protected $name = 'Gujarati'; - protected $table = ' + protected $name = 'Gujarati'; + protected $table = ' ################################################## # Gujarati U+0A85..U+0A8C, U+0A8F, U+0A90, U+0A93..U+0AB0, U+0AB2, U+0AB3, U+0AB5..U+0AB9, diff --git a/lib/classes/sphinx/charsetTable/gurmukhi.class.php b/lib/classes/sphinx/charsetTable/gurmukhi.class.php index 9b4df93a42..cf6228c5e0 100644 --- a/lib/classes/sphinx/charsetTable/gurmukhi.class.php +++ b/lib/classes/sphinx/charsetTable/gurmukhi.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_gurmukhi extends sphinx_charsetTableAbstract { - - protected $name = 'Gurmukhi'; - protected $table = ' + protected $name = 'Gurmukhi'; + protected $table = ' ################################################## # Gurmukhi U+0A33->U+0A32, U+0A36->U+0A38, U+0A59->U+0A16, U+0A5A->U+0A17, U+0A5B->U+0A1C, diff --git a/lib/classes/sphinx/charsetTable/hebrew.class.php b/lib/classes/sphinx/charsetTable/hebrew.class.php index 27fdbdfcc9..b1c70f7306 100644 --- a/lib/classes/sphinx/charsetTable/hebrew.class.php +++ b/lib/classes/sphinx/charsetTable/hebrew.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_hebrew extends sphinx_charsetTableAbstract { - - protected $name = 'Hebrew'; - protected $table = ' + protected $name = 'Hebrew'; + protected $table = ' ################################################# # Hebrew* U+FB1D->U+05D9, U+FB1F->U+05F2, U+FB20->U+05E2, U+FB21->U+05D0, U+FB22->U+05D3, diff --git a/lib/classes/sphinx/charsetTable/kannada.class.php b/lib/classes/sphinx/charsetTable/kannada.class.php index 4a19c10161..f90744eeea 100644 --- a/lib/classes/sphinx/charsetTable/kannada.class.php +++ b/lib/classes/sphinx/charsetTable/kannada.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_kannada extends sphinx_charsetTableAbstract { - - protected $name = 'Kannada'; - protected $table = ' + protected $name = 'Kannada'; + protected $table = ' ################################################# # Kannada U+0C85..U+0C8C, U+0C8E..U+0C90, U+0C92..U+0CA8, U+0CAA..U+0CB3, U+0CB5..U+0CB9, diff --git a/lib/classes/sphinx/charsetTable/latin.class.php b/lib/classes/sphinx/charsetTable/latin.class.php index db1abb545b..fe3282c681 100644 --- a/lib/classes/sphinx/charsetTable/latin.class.php +++ b/lib/classes/sphinx/charsetTable/latin.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_latin extends sphinx_charsetTableAbstract { - - protected $name = 'Latin'; - protected $table = ' + protected $name = 'Latin'; + protected $table = ' ################################################## # Latin # A diff --git a/lib/classes/sphinx/charsetTable/limbu.class.php b/lib/classes/sphinx/charsetTable/limbu.class.php index 9331d58a34..ca5884b301 100644 --- a/lib/classes/sphinx/charsetTable/limbu.class.php +++ b/lib/classes/sphinx/charsetTable/limbu.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_limbu extends sphinx_charsetTableAbstract { - - protected $name = 'Limbu'; - protected $table = ' + protected $name = 'Limbu'; + protected $table = ' ################################################# # Limbu U+1900..U+191C, U+1930..U+1938, U+1946..U+194F diff --git a/lib/classes/sphinx/charsetTable/malayalam.class.php b/lib/classes/sphinx/charsetTable/malayalam.class.php index d1d87f4862..788c21c92c 100644 --- a/lib/classes/sphinx/charsetTable/malayalam.class.php +++ b/lib/classes/sphinx/charsetTable/malayalam.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_malayalam extends sphinx_charsetTableAbstract { - - protected $name = 'Malayalam'; - protected $table = ' + protected $name = 'Malayalam'; + protected $table = ' ################################################# # Malayalam U+0D05..U+0D0C, U+0D0E..U+0D10, U+0D12..U+0D28, U+0D2A..U+0D39, U+0D60, diff --git a/lib/classes/sphinx/charsetTable/tamil.class.php b/lib/classes/sphinx/charsetTable/tamil.class.php index f1926867f9..a3f0da1981 100644 --- a/lib/classes/sphinx/charsetTable/tamil.class.php +++ b/lib/classes/sphinx/charsetTable/tamil.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_tamil extends sphinx_charsetTableAbstract { - - protected $name = 'Tamil'; - protected $table = ' + protected $name = 'Tamil'; + protected $table = ' ################################################# # Tamil U+0B94->U+0B92, U+0B85..U+0B8A, U+0B8E..U+0B90, U+0B92, U+0B93, U+0B95, U+0B99, diff --git a/lib/classes/sphinx/charsetTable/thai.class.php b/lib/classes/sphinx/charsetTable/thai.class.php index cb0c3c02e9..c349b153fa 100644 --- a/lib/classes/sphinx/charsetTable/thai.class.php +++ b/lib/classes/sphinx/charsetTable/thai.class.php @@ -7,9 +7,8 @@ class sphinx_charsetTable_thai extends sphinx_charsetTableAbstract { - - protected $name = 'Thai'; - protected $table = ' + protected $name = 'Thai'; + protected $table = ' ################################################# # Thai U+0E01..U+0E30, U+0E32, U+0E33, U+0E40..U+0E46, U+0E50..U+0E5B diff --git a/lib/classes/sphinx/charsetTableAbstract.class.php b/lib/classes/sphinx/charsetTableAbstract.class.php index 4c92bed82c..891c706be4 100644 --- a/lib/classes/sphinx/charsetTableAbstract.class.php +++ b/lib/classes/sphinx/charsetTableAbstract.class.php @@ -17,22 +17,19 @@ */ abstract class sphinx_charsetTableAbstract { + protected $table; + protected $name; - protected $table; + public function get_name() + { + return $this->name; + } - protected $name; - - public function get_name() - { - return $this->name; - } - - public function get_table() - { - if (is_null($this->table)) - throw new Exception('Invalid charsetTable object'); - - return $this->table; - } + public function get_table() + { + if (is_null($this->table)) + throw new Exception('Invalid charsetTable object'); + return $this->table; + } } diff --git a/lib/classes/sphinx/configuration.class.php b/lib/classes/sphinx/configuration.class.php index 4384278696..6567c08ee0 100644 --- a/lib/classes/sphinx/configuration.class.php +++ b/lib/classes/sphinx/configuration.class.php @@ -17,108 +17,97 @@ */ class sphinx_configuration { + const OPT_ALL_SBAS = 'all'; + const OPT_LIBSTEMMER_NONE = 'none'; + const OPT_LIBSTEMMER_FR = 'fr'; + const OPT_LIBSTEMMER_EN = 'en'; + const OPT_ENABLE_STAR_ON = 'yes'; + const OPT_ENABLE_STAR_OFF = 'no'; + const OPT_MIN_PREFIX_LEN = 0; + const OPT_MIN_INFIX_LEN = 1; - const OPT_ALL_SBAS = 'all'; - const OPT_LIBSTEMMER_NONE = 'none'; - const OPT_LIBSTEMMER_FR = 'fr'; - const OPT_LIBSTEMMER_EN = 'en'; - const OPT_ENABLE_STAR_ON = 'yes'; - const OPT_ENABLE_STAR_OFF = 'no'; - const OPT_MIN_PREFIX_LEN = 0; - const OPT_MIN_INFIX_LEN = 1; - - public function __construct() - { - - } - - public function get_available_charsets() - { - $available_charsets = array(); - $dir = __DIR__ . '/charsetTable/'; - echo $dir; - $registry = registry::get_instance(); - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) + public function __construct() { - if ($file->isDir() || strpos($file->getPathname(), '/.svn/') !== false) - { - continue; - } - if ($file->isFile()) - { - $classname = str_replace(array($registry->get('GV_RootPath') . 'lib/classes/', '.class.php', '/'), array('', '', '_'), $file->getPathname()); - $available_charsets[$classname] = new $classname; - } - } - ksort($available_charsets); - return $available_charsets; - } - - public function get_available_libstemmer() - { - return array(self::OPT_LIBSTEMMER_EN, self::OPT_LIBSTEMMER_FR, self::OPT_LIBSTEMMER_NONE); - } - - public function get_configuration($options = array()) - { - - $defaults = array( - 'sbas' => self::OPT_ALL_SBAS - , 'libstemmer' => array(self::OPT_LIBSTEMMER_NONE) - , 'enable_star' => self::OPT_ENABLE_STAR_ON - , 'min_prefix_len' => self::OPT_MIN_PREFIX_LEN - , 'min_infix_len' => self::OPT_MIN_INFIX_LEN - , 'charset_tables' => array() - ); - - $options = array_merge($defaults, $options); - - $options['charset_tables'] = array_unique($options['charset_tables']); - - $lb = phrasea::sbas_params(); - - $conf = ''; - - $charsets = ''; - foreach ($options['charset_tables'] as $charset) - { - try - { - $charset_table = new $charset(); - $charsets .= $charset_table->get_table(); - } - catch (Exception $e) - { - - } } - $charsets = explode("\n", $charsets); - $last_detect = false; - - - for ($i = (count($charsets) - 1); $i >= 0; $i -- ) + public function get_available_charsets() { - if (trim($charsets[$i]) === '') - { - unset($charsets[$i]); - continue; - } - if (strpos(trim($charsets[$i]), '#') === 0) - { - unset($charsets[$i]); - continue; - } - if ($last_detect === true && substr(trim($charsets[$i]), (strlen(trim($charsets[$i])) - 1), 1) !== ',') - $charsets[$i] = rtrim($charsets[$i]) . ', '; - $charsets[$i] = " " . $charsets[$i] . " \\\n"; - $last_detect = true; + $available_charsets = array(); + $dir = __DIR__ . '/charsetTable/'; + echo $dir; + $registry = registry::get_instance(); + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if ($file->isDir() || strpos($file->getPathname(), '/.svn/') !== false) { + continue; + } + if ($file->isFile()) { + $classname = str_replace(array($registry->get('GV_RootPath') . 'lib/classes/', '.class.php', '/'), array('', '', '_'), $file->getPathname()); + $available_charsets[$classname] = new $classname; + } + } + ksort($available_charsets); + + return $available_charsets; } - $charsets = "\\\n" . implode('', $charsets); + public function get_available_libstemmer() + { + return array(self::OPT_LIBSTEMMER_EN, self::OPT_LIBSTEMMER_FR, self::OPT_LIBSTEMMER_NONE); + } - $charset_abstract = ' + public function get_configuration($options = array()) + { + + $defaults = array( + 'sbas' => self::OPT_ALL_SBAS + , 'libstemmer' => array(self::OPT_LIBSTEMMER_NONE) + , 'enable_star' => self::OPT_ENABLE_STAR_ON + , 'min_prefix_len' => self::OPT_MIN_PREFIX_LEN + , 'min_infix_len' => self::OPT_MIN_INFIX_LEN + , 'charset_tables' => array() + ); + + $options = array_merge($defaults, $options); + + $options['charset_tables'] = array_unique($options['charset_tables']); + + $lb = phrasea::sbas_params(); + + $conf = ''; + + $charsets = ''; + foreach ($options['charset_tables'] as $charset) { + try { + $charset_table = new $charset(); + $charsets .= $charset_table->get_table(); + } catch (Exception $e) { + + } + } + + $charsets = explode("\n", $charsets); + $last_detect = false; + + + for ($i = (count($charsets) - 1); $i >= 0; $i -- ) { + if (trim($charsets[$i]) === '') { + unset($charsets[$i]); + continue; + } + if (strpos(trim($charsets[$i]), '#') === 0) { + unset($charsets[$i]); + continue; + } + if ($last_detect === true && substr(trim($charsets[$i]), (strlen(trim($charsets[$i])) - 1), 1) !== ',') + $charsets[$i] = rtrim($charsets[$i]) . ', '; + $charsets[$i] = " " . $charsets[$i] . " \\\n"; + $last_detect = true; + } + + $charsets = "\\\n" . implode('', $charsets); + + $charset_abstract = ' docinfo = extern charset_type = utf-8 @@ -146,13 +135,12 @@ class sphinx_configuration min_infix_len = 1 '; - foreach ($lb as $id => $params) - { + foreach ($lb as $id => $params) { - $serialized = str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])); - $index_crc = crc32($serialized); + $serialized = str_replace(array('.', '%'), '_', sprintf('%s_%s_%s_%s', $params['host'], $params['port'], $params['user'], $params['dbname'])); + $index_crc = crc32($serialized); - $conf .= ' + $conf .= ' #------------------------------------------------------------------------------ @@ -248,9 +236,8 @@ class sphinx_configuration '; - if (in_array(self::OPT_LIBSTEMMER_NONE, $options['libstemmer'])) - { - $conf .= ' + if (in_array(self::OPT_LIBSTEMMER_NONE, $options['libstemmer'])) { + $conf .= ' #-------------------------------------- ### Metadatas Index @@ -261,11 +248,10 @@ class sphinx_configuration } '; - } + } - if (in_array(self::OPT_LIBSTEMMER_FR, $options['libstemmer'])) - { - $conf .= ' + if (in_array(self::OPT_LIBSTEMMER_FR, $options['libstemmer'])) { + $conf .= ' #-------------------------------------- ### Metadatas Index Stemmed FR @@ -290,10 +276,9 @@ class sphinx_configuration index_exact_words = 1 } '; - } - if (in_array(self::OPT_LIBSTEMMER_EN, $options['libstemmer'])) - { - $conf .= ' + } + if (in_array(self::OPT_LIBSTEMMER_EN, $options['libstemmer'])) { + $conf .= ' #-------------------------------------- ### Metadatas Index Stemmed EN @@ -318,8 +303,8 @@ class sphinx_configuration index_exact_words = 1 } '; - } - $conf .= ' + } + $conf .= ' #-------------------------------------- ### METAS_REALTIME Index @@ -474,9 +459,9 @@ class sphinx_configuration '; - } + } - $conf .=' + $conf .=' #****************************************************************************** @@ -613,7 +598,6 @@ searchd - return $conf; - } - + return $conf; + } } diff --git a/lib/classes/sphinxrt.class.php b/lib/classes/sphinxrt.class.php index c967199b23..fd6a019d20 100644 --- a/lib/classes/sphinxrt.class.php +++ b/lib/classes/sphinxrt.class.php @@ -17,122 +17,112 @@ */ class sphinxrt { + protected static $_instance; + protected static $_failure = false; + protected $connection; - protected static $_instance; - protected static $_failure = false; - protected $connection; + protected function __construct(registry $registry) + { + try { + $dsn = sprintf('mysql:host=%s;port=%s;', $registry->get('GV_sphinx_rt_host'), $registry->get('GV_sphinx_rt_port')); + $this->connection = @new PDO($dsn); + } catch (Exception $e) { + self::$_failure = true; + throw new Exception('Unable to connect to sphinx rt'); + } - protected function __construct(registry $registry) - { - try - { - $dsn = sprintf('mysql:host=%s;port=%s;', $registry->get('GV_sphinx_rt_host'), $registry->get('GV_sphinx_rt_port')); - $this->connection = @new PDO($dsn); - } - catch (Exception $e) - { - self::$_failure = true; - throw new Exception('Unable to connect to sphinx rt'); + return $this; } - return $this; - } + /** + * + * @param registry $registry + * @return sphinxrt + */ + public static function get_instance(registry $registry, $retry_on_failure = false) + { + if ( ! $retry_on_failure && self::$_failure === true) { + throw new Exception('Unable to connect to sphinx rt, try set retry_on_failure true'); + } + if ( ! self::$_instance instanceof self) { + self::$_instance = new self($registry); + } - /** - * - * @param registry $registry - * @return sphinxrt - */ - public static function get_instance(registry $registry, $retry_on_failure = false) - { - if ( ! $retry_on_failure && self::$_failure === true) - { - throw new Exception('Unable to connect to sphinx rt, try set retry_on_failure true'); - } - if ( ! self::$_instance instanceof self) - { - self::$_instance = new self($registry); + return self::$_instance; } - return self::$_instance; - } - - /** - * Delete an index - * - * @param array $index_ids - * @param $rt_id - * @param $meta_id - * @return sphinxrt - */ - public function delete(Array $index_ids, $rt_id, $id) - { - $registry = registry::get_instance(); - require_once $registry->get('GV_RootPath') . 'lib/vendor/sphinx/sphinxapi.php'; - - $cl = new SphinxClient(); - - $cl->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); - $cl->SetConnectTimeout(1); - - foreach ($index_ids as $index_id) - $cl->UpdateAttributes($index_id, array("deleted"), array($id => array(1))); - - if ($rt_id) + /** + * Delete an index + * + * @param array $index_ids + * @param $rt_id + * @param $meta_id + * @return sphinxrt + */ + public function delete(Array $index_ids, $rt_id, $id) { - $this->connection->beginTransaction(); - $sql = "DELETE FROM " . $rt_id . " WHERE id = " . (int) $id . ""; - $stmt = $this->connection->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - $this->connection->commit(); + $registry = registry::get_instance(); + require_once $registry->get('GV_RootPath') . 'lib/vendor/sphinx/sphinxapi.php'; + + $cl = new SphinxClient(); + + $cl->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); + $cl->SetConnectTimeout(1); + + foreach ($index_ids as $index_id) + $cl->UpdateAttributes($index_id, array("deleted"), array($id => array(1))); + + if ($rt_id) { + $this->connection->beginTransaction(); + $sql = "DELETE FROM " . $rt_id . " WHERE id = " . (int) $id . ""; + $stmt = $this->connection->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + $this->connection->commit(); + } + + return $this; } - return $this; - } - - public function update_status(Array $index_ids, $sbas_id, $record_id, $status) - { - $registry = registry::get_instance(); - require_once $registry->get('GV_RootPath') . 'lib/vendor/sphinx/sphinxapi.php'; - - $cl = new SphinxClient(); - - if ($cl->Status() === false) + public function update_status(Array $index_ids, $sbas_id, $record_id, $status) { - return $this; + $registry = registry::get_instance(); + require_once $registry->get('GV_RootPath') . 'lib/vendor/sphinx/sphinxapi.php'; + + $cl = new SphinxClient(); + + if ($cl->Status() === false) { + return $this; + } + + $cl->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); + $cl->SetConnectTimeout(1); + + + $status = strrev($status); + $new_stat = array(); + for ($i = 4; $i < strlen($status); $i ++ ) { + if (substr($status, $i, 1) == '1') + $new_stat[] = crc32($sbas_id . '_' . $i); + } + + foreach ($index_ids as $index_id) { + $cl->UpdateAttributes($index_id, array("status"), array($record_id => array($new_stat)), true); + } + + return $this; } - $cl->SetServer($registry->get('GV_sphinx_host'), (int) $registry->get('GV_sphinx_port')); - $cl->SetConnectTimeout(1); - - - $status = strrev($status); - $new_stat = array(); - for ($i = 4; $i < strlen($status); $i ++ ) + public function replace_in_metas($rt_id, $meta_id, $tag_id, $record_id, $sbas_id, $coll_id, $grouping, $type, $content, $business, DateTime $created) { - if (substr($status, $i, 1) == '1') - $new_stat[] = crc32($sbas_id . '_' . $i); - } + $crc_sbas_tag = crc32($sbas_id . '_' . $tag_id); + $crc_sbas_coll = crc32($sbas_id . '_' . $coll_id); + $crc_sbas_record = crc32($sbas_id . '_' . $record_id); + $crc_type = crc32($type); - foreach ($index_ids as $index_id) - { - $cl->UpdateAttributes($index_id, array("status"), array($record_id => array($new_stat)), true); - } + $this->connection->beginTransaction(); - return $this; - } - - public function replace_in_metas($rt_id, $meta_id, $tag_id, $record_id, $sbas_id, $coll_id, $grouping, $type, $content, $business, DateTime $created) - { - $crc_sbas_tag = crc32($sbas_id . '_' . $tag_id); - $crc_sbas_coll = crc32($sbas_id . '_' . $coll_id); - $crc_sbas_record = crc32($sbas_id . '_' . $record_id); - $crc_type = crc32($type); - - $this->connection->beginTransaction(); - - $sql = "REPLACE INTO " . $rt_id . " VALUES ( + $sql = "REPLACE INTO " . $rt_id . " VALUES ( '" . (int) $meta_id . "' ,'" . str_replace("'", "\'", $content) . "' ,'" . (int) $tag_id . "' @@ -148,25 +138,25 @@ class sphinxrt ," . (int) $business . " ," . (int) crc32($coll_id . '_' . $business) . " ," . (int) $created->format('U') . " )"; - $stmt = $this->connection->prepare($sql); - $stmt->execute(); + $stmt = $this->connection->prepare($sql); + $stmt->execute(); - $stmt->closeCursor(); + $stmt->closeCursor(); - $this->connection->commit(); + $this->connection->commit(); - return $this; - } + return $this; + } - public function replace_in_documents($rt_id, $record_id, $value, $sbas_id, $coll_id, $grouping, $type, DateTime $created) - { - $crc_sbas_coll = crc32($sbas_id . '_' . $coll_id); - $crc_sbas_record = crc32($sbas_id . '_' . $record_id); - $crc_type = crc32($type); + public function replace_in_documents($rt_id, $record_id, $value, $sbas_id, $coll_id, $grouping, $type, DateTime $created) + { + $crc_sbas_coll = crc32($sbas_id . '_' . $coll_id); + $crc_sbas_record = crc32($sbas_id . '_' . $record_id); + $crc_type = crc32($type); - $this->connection->beginTransaction(); + $this->connection->beginTransaction(); - $sql = "REPLACE INTO " . $rt_id . " VALUES ( + $sql = "REPLACE INTO " . $rt_id . " VALUES ( '" . (int) $record_id . "' ,'" . str_replace("'", "\'", $value) . "' ," . (int) $record_id . " @@ -179,13 +169,12 @@ class sphinxrt ,0 ," . (int) $created->format('U') . " )"; - $stmt = $this->connection->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); + $stmt = $this->connection->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); - $this->connection->commit(); - - return $this; - } + $this->connection->commit(); + return $this; + } } diff --git a/lib/classes/system/file.class.php b/lib/classes/system/file.class.php index ac83d6f2cb..07eb89571b 100644 --- a/lib/classes/system/file.class.php +++ b/lib/classes/system/file.class.php @@ -17,7 +17,6 @@ */ class system_file extends SplFileObject { - /** * * @var string @@ -30,119 +29,119 @@ class system_file extends SplFileObject * @var Array */ protected static $mimeTypes = array( - 'ai' => 'application/postscript' - , '3gp' => 'video/3gpp' - , 'aif' => 'audio/aiff' - , 'aiff' => 'audio/aiff' - , 'asf' => 'video/x-ms-asf' - , 'asx' => 'video/x-ms-asf' - , 'avi' => 'video/avi' - , 'bmp' => 'image/bmp' - , 'bz2' => 'application/x-bzip' - , '3fr' => 'image/x-tika-hasselblad' - , 'arw' => 'image/x-tika-sony' - , 'bay' => 'image/x-tika-casio' - , 'cap' => 'image/x-tika-phaseone' - , 'cr2' => 'image/x-tika-canon' - , 'crw' => 'image/x-tika-canon' - , 'dcs' => 'image/x-tika-kodak' - , 'dcr' => 'image/x-tika-kodak' - , 'dng' => 'image/x-tika-dng' - , 'drf' => 'image/x-tika-kodak' - , 'erf' => 'image/x-tika-epson' - , 'fff' => 'image/x-tika-imacon' - , 'iiq' => 'image/x-tika-phaseone' - , 'kdc' => 'image/x-tika-kodak' - , 'k25' => 'image/x-tika-kodak' - , 'mef' => 'image/x-tika-mamiya' - , 'mos' => 'image/x-tika-leaf' - , 'mrw' => 'image/x-tika-minolta' - , 'nef' => 'image/x-tika-nikon' - , 'nrw' => 'image/x-tika-nikon' - , 'orf' => 'image/x-tika-olympus' - , 'pef' => 'image/x-tika-pentax' - , 'ppm' => 'image/x-portable-pixmap' - , 'ptx' => 'image/x-tika-pentax' - , 'pxn' => 'image/x-tika-logitech' - , 'raf' => 'image/x-tika-fuji' - , 'raw' => 'image/x-tika-panasonic' - , 'r3d' => 'image/x-tika-red' - , 'rw2' => 'image/x-tika-panasonic' - , 'rwz' => 'image/x-tika-rawzor' - , 'sr2' => 'image/x-tika-sony' - , 'srf' => 'image/x-tika-sony' - , 'x3f' => 'image/x-tika-sigma' - , 'css' => 'text/css' - , 'doc' => 'application/msword' - , 'docx' => 'application/msword' - , 'eps' => 'application/postscript' - , 'exe' => 'application/x-msdownload' - , 'flv' => 'video/x-flv' - , 'gif' => 'image/gif' - , 'gz' => 'application/x-gzip' - , 'htm' => 'text/html' - , 'html' => 'text/html' - , 'jpeg' => 'image/jpeg' - , 'jpg' => 'image/jpeg' - , 'm3u' => 'audio/x-mpegurl' - , 'mid' => 'audio/mid' - , 'midi' => 'audio/mid' - , 'mkv' => 'video/matroska' - , 'mp3' => 'audio/mpeg' - , 'mp4' => 'video/mp4' - , 'vob' => 'video/mpeg' - , 'mp2p' => 'video/mpeg' - , 'mpeg' => 'video/mpeg' - , 'mpg' => 'video/mpeg' - , 'mov' => 'video/quicktime' - , 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' - , 'odt' => 'application/vnd.oasis.opendocument.text' - , 'odp' => 'application/vnd.oasis.opendocument.presentation' - , 'ogg' => 'audio/ogg' - , 'pdf' => 'application/pdf' - , 'pls' => 'audio/scpls' - , 'png' => 'image/png' - , 'pps' => 'application/vnd.ms-powerpoint' - , 'ppt' => 'application/vnd.ms-powerpoint' - , 'pptx' => 'application/vnd.ms-powerpoint' - , 'psd' => 'image/psd' - , 'ra' => 'audio/x-pn-realaudio' - , 'ram' => 'audio/x-pn-realaudio' - , 'rm' => 'application/vnd.rn-realmedia' - , 'rtf' => 'application/msword' - , 'rv' => 'video/vnd.rn-realvideo' - , 'swf' => 'application/x-shockwave-flash' - , 'tar' => 'application/x-tar' - , 'tif' => 'image/tiff' - , 'txt' => 'text/plain' - , 'wav' => 'audio/wav' - , 'wma' => 'audio/x-ms-wma' - , 'wmv' => 'video/x-ms-wmv' - , 'wmx' => 'video/x-ms-wmx' - , 'xls' => 'application/excel' - , 'xlsx' => 'application/excel' - , 'xml' => 'text/xml' - , 'xsl' => 'text/xsl' - , 'zip' => 'application/zip' + 'ai' => 'application/postscript' + , '3gp' => 'video/3gpp' + , 'aif' => 'audio/aiff' + , 'aiff' => 'audio/aiff' + , 'asf' => 'video/x-ms-asf' + , 'asx' => 'video/x-ms-asf' + , 'avi' => 'video/avi' + , 'bmp' => 'image/bmp' + , 'bz2' => 'application/x-bzip' + , '3fr' => 'image/x-tika-hasselblad' + , 'arw' => 'image/x-tika-sony' + , 'bay' => 'image/x-tika-casio' + , 'cap' => 'image/x-tika-phaseone' + , 'cr2' => 'image/x-tika-canon' + , 'crw' => 'image/x-tika-canon' + , 'dcs' => 'image/x-tika-kodak' + , 'dcr' => 'image/x-tika-kodak' + , 'dng' => 'image/x-tika-dng' + , 'drf' => 'image/x-tika-kodak' + , 'erf' => 'image/x-tika-epson' + , 'fff' => 'image/x-tika-imacon' + , 'iiq' => 'image/x-tika-phaseone' + , 'kdc' => 'image/x-tika-kodak' + , 'k25' => 'image/x-tika-kodak' + , 'mef' => 'image/x-tika-mamiya' + , 'mos' => 'image/x-tika-leaf' + , 'mrw' => 'image/x-tika-minolta' + , 'nef' => 'image/x-tika-nikon' + , 'nrw' => 'image/x-tika-nikon' + , 'orf' => 'image/x-tika-olympus' + , 'pef' => 'image/x-tika-pentax' + , 'ppm' => 'image/x-portable-pixmap' + , 'ptx' => 'image/x-tika-pentax' + , 'pxn' => 'image/x-tika-logitech' + , 'raf' => 'image/x-tika-fuji' + , 'raw' => 'image/x-tika-panasonic' + , 'r3d' => 'image/x-tika-red' + , 'rw2' => 'image/x-tika-panasonic' + , 'rwz' => 'image/x-tika-rawzor' + , 'sr2' => 'image/x-tika-sony' + , 'srf' => 'image/x-tika-sony' + , 'x3f' => 'image/x-tika-sigma' + , 'css' => 'text/css' + , 'doc' => 'application/msword' + , 'docx' => 'application/msword' + , 'eps' => 'application/postscript' + , 'exe' => 'application/x-msdownload' + , 'flv' => 'video/x-flv' + , 'gif' => 'image/gif' + , 'gz' => 'application/x-gzip' + , 'htm' => 'text/html' + , 'html' => 'text/html' + , 'jpeg' => 'image/jpeg' + , 'jpg' => 'image/jpeg' + , 'm3u' => 'audio/x-mpegurl' + , 'mid' => 'audio/mid' + , 'midi' => 'audio/mid' + , 'mkv' => 'video/matroska' + , 'mp3' => 'audio/mpeg' + , 'mp4' => 'video/mp4' + , 'vob' => 'video/mpeg' + , 'mp2p' => 'video/mpeg' + , 'mpeg' => 'video/mpeg' + , 'mpg' => 'video/mpeg' + , 'mov' => 'video/quicktime' + , 'ods' => 'application/vnd.oasis.opendocument.spreadsheet' + , 'odt' => 'application/vnd.oasis.opendocument.text' + , 'odp' => 'application/vnd.oasis.opendocument.presentation' + , 'ogg' => 'audio/ogg' + , 'pdf' => 'application/pdf' + , 'pls' => 'audio/scpls' + , 'png' => 'image/png' + , 'pps' => 'application/vnd.ms-powerpoint' + , 'ppt' => 'application/vnd.ms-powerpoint' + , 'pptx' => 'application/vnd.ms-powerpoint' + , 'psd' => 'image/psd' + , 'ra' => 'audio/x-pn-realaudio' + , 'ram' => 'audio/x-pn-realaudio' + , 'rm' => 'application/vnd.rn-realmedia' + , 'rtf' => 'application/msword' + , 'rv' => 'video/vnd.rn-realvideo' + , 'swf' => 'application/x-shockwave-flash' + , 'tar' => 'application/x-tar' + , 'tif' => 'image/tiff' + , 'txt' => 'text/plain' + , 'wav' => 'audio/wav' + , 'wma' => 'audio/x-ms-wma' + , 'wmv' => 'video/x-ms-wmv' + , 'wmx' => 'video/x-ms-wmx' + , 'xls' => 'application/excel' + , 'xlsx' => 'application/excel' + , 'xml' => 'text/xml' + , 'xsl' => 'text/xsl' + , 'zip' => 'application/zip' ); protected $sha256; protected $uuid; - const TC_DATAS_WIDTH = 'Width'; - const TC_DATAS_HEIGHT = 'Height'; - const TC_DATAS_COLORSPACE = 'ColorSpace'; - const TC_DATAS_CHANNELS = 'Channels'; - const TC_DATAS_ORIENTATION = 'Orientation'; - const TC_DATAS_COLORDEPTH = 'ColorDepth'; - const TC_DATAS_DURATION = 'Duration'; - const TC_DATAS_AUDIOCODEC = 'AudioCodec'; + const TC_DATAS_WIDTH = 'Width'; + const TC_DATAS_HEIGHT = 'Height'; + const TC_DATAS_COLORSPACE = 'ColorSpace'; + const TC_DATAS_CHANNELS = 'Channels'; + const TC_DATAS_ORIENTATION = 'Orientation'; + const TC_DATAS_COLORDEPTH = 'ColorDepth'; + const TC_DATAS_DURATION = 'Duration'; + const TC_DATAS_AUDIOCODEC = 'AudioCodec'; const TC_DATAS_AUDIOSAMPLERATE = 'AudioSamplerate'; - const TC_DATAS_AUDIOBITRATE = 'AudioBitrate'; - const TC_DATAS_VIDEOBITRATE = 'VideoBitrate'; - const TC_DATAS_VIDEOCODEC = 'VideoCodec'; - const TC_DATAS_FRAMERATE = 'FrameRate'; - const TC_DATAS_MIMETYPE = 'MimeType'; - const TC_DATAS_FILESIZE = 'FileSize'; + const TC_DATAS_AUDIOBITRATE = 'AudioBitrate'; + const TC_DATAS_VIDEOBITRATE = 'VideoBitrate'; + const TC_DATAS_VIDEOCODEC = 'VideoCodec'; + const TC_DATAS_FRAMERATE = 'FrameRate'; + const TC_DATAS_MIMETYPE = 'MimeType'; + const TC_DATAS_FILESIZE = 'FileSize'; /** * @@ -150,8 +149,7 @@ class system_file extends SplFileObject */ public function get_mime() { - if ($this->mime) - { + if ($this->mime) { return $this->mime; } @@ -159,29 +157,20 @@ class system_file extends SplFileObject $mime = ''; - if (function_exists('finfo_open')) - { + if (function_exists('finfo_open')) { $magicfile = NULL; - if (is_file('/usr/share/misc/magic')) - { + if (is_file('/usr/share/misc/magic')) { $magicfile = '/usr/share/misc/magic'; - } - elseif (is_file('/usr/share/misc/magic.mgc')) - { + } elseif (is_file('/usr/share/misc/magic.mgc')) { $magicfile = '/usr/share/misc/magic.mgc'; - } - elseif (is_file($registry->get('GV_RootPath') . 'www/include/magic')) - { + } elseif (is_file($registry->get('GV_RootPath') . 'www/include/magic')) { $magicfile = $registry->get('GV_RootPath') . 'www/include/magic'; } - if (($finfo = @finfo_open(FILEINFO_MIME, $magicfile)) !== false) - { - $mime = finfo_file($finfo, $this->getPathname()); + if (($finfo = @finfo_open(FILEINFO_MIME, $magicfile)) !== false) { + $mime = finfo_file($finfo, $this->getPathname()); finfo_close($finfo); - } - elseif (($finfo = @finfo_open(FILEINFO_MIME, NULL)) !== false) - { + } elseif (($finfo = @finfo_open(FILEINFO_MIME, NULL)) !== false) { $mime = finfo_file($finfo, $this->getPathname()); finfo_close($finfo); } @@ -189,9 +178,8 @@ class system_file extends SplFileObject $extension = $this->get_extension(true); - if (trim($mime) == '') - { - $gis = getimagesize($this->getPathname()); + if (trim($mime) == '') { + $gis = getimagesize($this->getPathname()); if ($gis['mime'] != '') $mime = $gis['mime']; } @@ -199,8 +187,7 @@ class system_file extends SplFileObject if ($mime == '' || $mime == NULL) $mime = mime_content_type($this->getPathname()); - if (( $pos = strpos($mime, '; charset=')) !== false) - { + if (( $pos = strpos($mime, '; charset=')) !== false) { $mime = substr($mime, 0, $pos); } @@ -209,12 +196,12 @@ class system_file extends SplFileObject elseif ($mime == 'text/plain' && $extension == 'mkv') $mime = 'video/matroska'; elseif (in_array($mime, array( - 'application/octet-stream', - 'image/tiff', - 'application/vnd.ms-office', - 'application/zip' - ) - ) && isset(self::$mimeTypes[$extension])) + 'application/octet-stream', + 'image/tiff', + 'application/vnd.ms-office', + 'application/zip' + ) + ) && isset(self::$mimeTypes[$extension])) $mime = self::$mimeTypes[$extension]; elseif ($mime == '' && $extension == 'm4v') $mime = 'video/x-m4v'; @@ -227,44 +214,43 @@ class system_file extends SplFileObject public function is_raw_image() { $raws = array( - '3fr' => 'image/x-tika-hasselblad' - , 'arw' => 'image/x-tika-sony' - , 'bay' => 'image/x-tika-casio' - , 'cap' => 'image/x-tika-phaseone' - , 'cr2-' => 'image/x-canon-cr2' - , 'cr2' => 'image/x-tika-canon' - , 'crw' => 'image/x-tika-canon' - , 'dcs' => 'image/x-tika-kodak' - , 'dcr' => 'image/x-tika-kodak' - , 'dng' => 'image/x-tika-dng' - , 'drf' => 'image/x-tika-kodak' - , 'erf' => 'image/x-tika-epson' - , 'fff' => 'image/x-tika-imacon' - , 'iiq' => 'image/x-tika-phaseone' - , 'kdc' => 'image/x-tika-kodak' - , 'k25' => 'image/x-tika-kodak' - , 'mef' => 'image/x-tika-mamiya' - , 'mos' => 'image/x-tika-leaf' - , 'mrw' => 'image/x-tika-minolta' - , 'nef' => 'image/x-tika-nikon' - , 'nrw' => 'image/x-tika-nikon' - , 'orf' => 'image/x-tika-olympus' - , 'pef' => 'image/x-tika-pentax' - , 'ppm' => 'image/x-portable-pixmap' - , 'ptx' => 'image/x-tika-pentax' - , 'pxn' => 'image/x-tika-logitech' - , 'raf' => 'image/x-tika-fuji' - , 'raw' => 'image/x-tika-panasonic' - , 'r3d' => 'image/x-tika-red' - , 'rw2' => 'image/x-tika-panasonic' - , 'rwz' => 'image/x-tika-rawzor' - , 'sr2' => 'image/x-tika-sony' - , 'srf' => 'image/x-tika-sony' - , 'x3f' => 'image/x-tika-sigma'); + '3fr' => 'image/x-tika-hasselblad' + , 'arw' => 'image/x-tika-sony' + , 'bay' => 'image/x-tika-casio' + , 'cap' => 'image/x-tika-phaseone' + , 'cr2-' => 'image/x-canon-cr2' + , 'cr2' => 'image/x-tika-canon' + , 'crw' => 'image/x-tika-canon' + , 'dcs' => 'image/x-tika-kodak' + , 'dcr' => 'image/x-tika-kodak' + , 'dng' => 'image/x-tika-dng' + , 'drf' => 'image/x-tika-kodak' + , 'erf' => 'image/x-tika-epson' + , 'fff' => 'image/x-tika-imacon' + , 'iiq' => 'image/x-tika-phaseone' + , 'kdc' => 'image/x-tika-kodak' + , 'k25' => 'image/x-tika-kodak' + , 'mef' => 'image/x-tika-mamiya' + , 'mos' => 'image/x-tika-leaf' + , 'mrw' => 'image/x-tika-minolta' + , 'nef' => 'image/x-tika-nikon' + , 'nrw' => 'image/x-tika-nikon' + , 'orf' => 'image/x-tika-olympus' + , 'pef' => 'image/x-tika-pentax' + , 'ppm' => 'image/x-portable-pixmap' + , 'ptx' => 'image/x-tika-pentax' + , 'pxn' => 'image/x-tika-logitech' + , 'raf' => 'image/x-tika-fuji' + , 'raw' => 'image/x-tika-panasonic' + , 'r3d' => 'image/x-tika-red' + , 'rw2' => 'image/x-tika-panasonic' + , 'rwz' => 'image/x-tika-rawzor' + , 'sr2' => 'image/x-tika-sony' + , 'srf' => 'image/x-tika-sony' + , 'x3f' => 'image/x-tika-sigma'); if (in_array($this->get_mime(), $raws)) - return true; return false; } @@ -282,21 +268,16 @@ class system_file extends SplFileObject * @see https://bugs.php.net/bug.php?id=48767 * */ - if (method_exists($this, 'getExtension')) - { + if (method_exists($this, 'getExtension')) { $extension = $this->getExtension(); - } - else - { - $pi = pathinfo($this->getFilename()); + } else { + $pi = pathinfo($this->getFilename()); $extension = isset($pi['extension']) ? $pi['extension'] : ''; } if ($lowercase) - return mb_strtolower($extension); else - return $extension; } @@ -320,15 +301,13 @@ class system_file extends SplFileObject { $this->technical_datas[self::TC_DATAS_ORIENTATION] = null; if (in_array( - $this->get_mime(), array( - 'image/tif', 'image/tiff', - 'image/jpg', 'image/pjpeg', 'image/pjpg', 'image/jpeg' + $this->get_mime(), array( + 'image/tif', 'image/tiff', + 'image/jpg', 'image/pjpeg', 'image/pjpg', 'image/jpeg' + ) ) - ) - ) - { - if ($ex = @exif_read_data($this->getPathname(), 'FILE')) - { + ) { + if ($ex = @exif_read_data($this->getPathname(), 'FILE')) { if (array_key_exists('Orientation', $ex)) $this->technical_datas[self::TC_DATAS_ORIENTATION] = $ex['Orientation']; } @@ -340,8 +319,7 @@ class system_file extends SplFileObject $domrdf->recover = true; $domrdf->preserveWhiteSpace = false; - if ($domrdf->loadXML($datas)) - { + if ($domrdf->loadXML($datas)) { $xptrdf = new DOMXPath($domrdf); $xptrdf->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); @@ -354,18 +332,14 @@ class system_file extends SplFileObject $xptrdf->registerNamespace($matches[1][$key], $value); $descriptionNode = @$xptrdf->query('/rdf:RDF/rdf:Description')->item(0); - if ($descriptionNode) - { - for ($x = $descriptionNode->firstChild; $x; $x = $x->nextSibling) - { + if ($descriptionNode) { + for ($x = $descriptionNode->firstChild; $x; $x = $x->nextSibling) { if ($x->nodeType !== XML_ELEMENT_NODE) continue; - switch ($x->nodeName) - { + switch ($x->nodeName) { case 'Composite:ImageSize': - if ((count($_t = explode('x', $x->textContent))) == 2) - { + if ((count($_t = explode('x', $x->textContent))) == 2) { $this->technical_datas[self::TC_DATAS_WIDTH] = 0 + $_t[0]; $this->technical_datas[self::TC_DATAS_HEIGHT] = 0 + $_t[1]; } @@ -393,8 +367,7 @@ class system_file extends SplFileObject if (count($_t = explode(':', $x->nodeName)) !== 2) continue; - switch ($_t[1]) - { + switch ($_t[1]) { case 'ImageWidth': if ( ! array_key_exists('width', $this->technical_datas)) $this->technical_datas[self::TC_DATAS_WIDTH] = 0 + $x->textContent; @@ -413,34 +386,29 @@ class system_file extends SplFileObject protected function read_pdf_datas() { - $system = system_server::get_platform(); + $system = system_server::get_platform(); $registry = registry::get_instance(); - $cmd = $pdf_text = ''; - $tmpfile = $registry->get('GV_RootPath') - . 'tmp/pdf-extract' . time() . mt_rand(00000, 99999); - if ($system == 'DARWIN' || $system == 'LINUX') - { + $cmd = $pdf_text = ''; + $tmpfile = $registry->get('GV_RootPath') + . 'tmp/pdf-extract' . time() . mt_rand(00000, 99999); + if ($system == 'DARWIN' || $system == 'LINUX') { $cmd = $registry->get('GV_pdftotext') . ' -f 1 -l ' - . $registry->get('GV_pdfmaxpages') - . ' -raw -enc UTF-8 -eol unix -q ' - . str_replace(' ', '\ ', addslashes($this->getPathname())) - . ' ' . $tmpfile; - } - else // WINDOWS - { + . $registry->get('GV_pdfmaxpages') + . ' -raw -enc UTF-8 -eol unix -q ' + . str_replace(' ', '\ ', addslashes($this->getPathname())) + . ' ' . $tmpfile; + } else { // WINDOWS $cmd = $registry->get('GV_pdftotext') . ' -f 1 -l ' - . $registry->get('GV_pdfmaxpages') - . ' -raw -enc UTF-8 -eol unix -q ' - . str_replace(' ', '\ ', addslashes($this->getPathname())) - . ' ' . $tmpfile; + . $registry->get('GV_pdfmaxpages') + . ' -raw -enc UTF-8 -eol unix -q ' + . str_replace(' ', '\ ', addslashes($this->getPathname())) + . ' ' . $tmpfile; } - if ($cmd) - { + if ($cmd) { $s = shell_exec($cmd); - if (file_exists($tmpfile)) - { + if (file_exists($tmpfile)) { $pdf_text = array(file_get_contents($tmpfile)); unlink($tmpfile); } @@ -458,30 +426,26 @@ class system_file extends SplFileObject $hdPath = $this->getPathname(); $datas = exiftool::get_fields( - $hdPath, array('Duration', 'Image Width', 'Image Height') + $hdPath, array('Duration', 'Image Width', 'Image Height') ); $duration = 0; - if ($datas['Duration']) - { + if ($datas['Duration']) { $data = explode('_', trim($datas['Duration'])); $data = explode(':', $data[0]); - $factor = 1; - while ($segment = array_pop($data)) - { + $factor = 1; + while ($segment = array_pop($data)) { $duration += $segment * $factor; $factor *=60; } } - $width = $height = false; - if ($datas['Image Width']) - { + $width = $height = false; + if ($datas['Image Width']) { if ((int) $datas['Image Width'] > 0) $width = $datas['Image Width']; } - if ($datas['Image Height']) - { + if ($datas['Image Height']) { if ((int) $datas['Image Height'] > 0) $height = $datas['Image Height']; } @@ -489,22 +453,21 @@ class system_file extends SplFileObject $this->technical_datas = array(); if ( ! is_executable($registry->get('GV_mplayer'))) - return $this; - $cmd = $registry->get('GV_mplayer') - . ' -identify ' - . escapeshellarg($hdPath) - . ' -ao null -vo null -frames 0 | grep ^ID_'; + $cmd = $registry->get('GV_mplayer') + . ' -identify ' + . escapeshellarg($hdPath) + . ' -ao null -vo null -frames 0 | grep ^ID_'; $docProps = array( - 'ID_VIDEO_WIDTH' => self::TC_DATAS_WIDTH, - 'ID_VIDEO_HEIGHT' => self::TC_DATAS_HEIGHT, - 'ID_VIDEO_FPS' => self::TC_DATAS_FRAMERATE, - 'ID_AUDIO_CODEC' => self::TC_DATAS_AUDIOCODEC, - 'ID_VIDEO_CODEC' => self::TC_DATAS_VIDEOCODEC, - 'ID_VIDEO_BITRATE' => self::TC_DATAS_VIDEOBITRATE, - 'ID_AUDIO_BITRATE' => self::TC_DATAS_AUDIOBITRATE, - 'ID_AUDIO_RATE' => self::TC_DATAS_AUDIOSAMPLERATE + 'ID_VIDEO_WIDTH' => self::TC_DATAS_WIDTH, + 'ID_VIDEO_HEIGHT' => self::TC_DATAS_HEIGHT, + 'ID_VIDEO_FPS' => self::TC_DATAS_FRAMERATE, + 'ID_AUDIO_CODEC' => self::TC_DATAS_AUDIOCODEC, + 'ID_VIDEO_CODEC' => self::TC_DATAS_VIDEOCODEC, + 'ID_VIDEO_BITRATE' => self::TC_DATAS_VIDEOBITRATE, + 'ID_AUDIO_BITRATE' => self::TC_DATAS_AUDIOBITRATE, + 'ID_AUDIO_RATE' => self::TC_DATAS_AUDIOSAMPLERATE ); $stdout = shell_exec($cmd); @@ -512,8 +475,7 @@ class system_file extends SplFileObject $this->technical_datas = array(); $stdout = explode("\n", $stdout); - foreach ($stdout as $property) - { + foreach ($stdout as $property) { $props = explode('=', $property); @@ -521,18 +483,16 @@ class system_file extends SplFileObject $this->technical_datas[$docProps[$props[0]]] = $props[1]; } - $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); + $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); $dom_document = new DOMDocument(); - if ($dom_document->loadXML($datas)) - { - $xq = new DOMXPath($dom_document); + if ($dom_document->loadXML($datas)) { + $xq = new DOMXPath($dom_document); $xq->registerNamespace('RIFF', 'http://ns.exiftool.ca/RIFF/RIFF/1.0/'); - $nodes_width = $xq->query('/rdf:RDF/rdf:Description/RIFF:ImageWidth'); + $nodes_width = $xq->query('/rdf:RDF/rdf:Description/RIFF:ImageWidth'); $nodes_height = $xq->query('/rdf:RDF/rdf:Description/RIFF:ImageHeight'); - if ($nodes_height->length > 0 && $nodes_width->length > 0) - { - $width = $nodes_width->item(0)->nodeValue; + if ($nodes_height->length > 0 && $nodes_width->length > 0) { + $width = $nodes_width->item(0)->nodeValue; $height = $nodes_height->item(0)->nodeValue; } } @@ -555,8 +515,7 @@ class system_file extends SplFileObject { $this->technical_datas = array(); - switch ($this->get_phrasea_type()) - { + switch ($this->get_phrasea_type()) { case 'image' : $this->read_image_datas(); break; @@ -586,8 +545,7 @@ class system_file extends SplFileObject */ public function get_phrasea_type() { - switch ($this->get_mime()) - { + switch ($this->get_mime()) { case 'image/png': case 'image/gif': case 'image/bmp': @@ -712,16 +670,14 @@ class system_file extends SplFileObject public function read_uuid() { if ($this->uuid) - return $this->uuid; - $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); + $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); $domrdf = new DOMDocument(); $domrdf->recover = true; $domrdf->preserveWhiteSpace = false; - if ($domrdf->loadXML($datas)) - { + if ($domrdf->loadXML($datas)) { $this->uuid = $this->test_rdf_fields($domrdf); } @@ -730,16 +686,11 @@ class system_file extends SplFileObject public function write_uuid($uuid = false) { - if ($uuid && uuid::is_valid($uuid)) - { + if ($uuid && uuid::is_valid($uuid)) { $this->uuid = $uuid; - } - elseif ((($uuid = $this->read_uuid()) !== false) && uuid::is_valid($uuid)) - { + } elseif ((($uuid = $this->read_uuid()) !== false) && uuid::is_valid($uuid)) { $this->uuid = $uuid; - } - else - { + } else { $this->uuid = uuid::generate_v4(); } @@ -751,12 +702,11 @@ class system_file extends SplFileObject public function is_new_in_base($sbas_id) { if ( ! $this->uuid) - return true; $connbas = connection::getPDOConnection($sbas_id); - $sql = 'SELECT record_id FROM record WHERE uuid = :uuid'; + $sql = 'SELECT record_id FROM record WHERE uuid = :uuid'; $stmt = $connbas->prepare($sql); $stmt->execute(array(':uuid' => $this->uuid)); $num_rows = $stmt->rowCount(); @@ -775,22 +725,17 @@ class system_file extends SplFileObject public function write() { - $system = system_server::get_platform(); + $system = system_server::get_platform(); $registry = registry::get_instance(); - if (in_array($system, array('DARWIN', 'LINUX'))) - { + if (in_array($system, array('DARWIN', 'LINUX'))) { $cmd = $registry->get('GV_exiftool') . ' -m -overwrite_original -XMP-exif:ImageUniqueID=\'' . $this->uuid . '\' -IPTC:UniqueDocumentID=\'' . $this->uuid . '\' ' . escapeshellarg($this->getPathname()) . ''; - } - else // WINDOWS - { - if (chdir($registry->get('GV_RootPath') . 'tmp/')) - { + } else { // WINDOWS + if (chdir($registry->get('GV_RootPath') . 'tmp/')) { $cmd = 'start /B /LOW ' . $registry->get('GV_exiftool') . ' -m -overwrite_original -XMP-exif:ImageUniqueID=\'' . $this->uuid . '\' -IPTC:UniqueDocumentID=\'' . $this->uuid . '\' ' . escapeshellarg($this->getPathname()) . ''; } } - if ($cmd) - { + if ($cmd) { $s = @shell_exec($cmd); } @@ -804,26 +749,22 @@ class system_file extends SplFileObject $xptrdf->registerNamespace('IPTC', 'http://ns.exiftool.ca/IPTC/IPTC/1.0/'); $fields = array( - '/rdf:RDF/rdf:Description/XMP-exif:ImageUniqueID', - '/rdf:RDF/rdf:Description/IPTC:UniqueDocumentID' + '/rdf:RDF/rdf:Description/XMP-exif:ImageUniqueID', + '/rdf:RDF/rdf:Description/IPTC:UniqueDocumentID' ); - foreach ($fields as $field) - { + foreach ($fields as $field) { $x = $xptrdf->query($field); - if ($x->length > 0) - { + if ($x->length > 0) { $x = $x->item(0); - $encoding = strtolower($x->getAttribute('rdf:datatype') . $x->getAttribute('et:encoding')); + $encoding = strtolower($x->getAttribute('rdf:datatype') . $x->getAttribute('et:encoding')); $base64_encoded = (strpos($encoding, 'base64') !== false); - if (($v = $x->firstChild) && $v->nodeType == XML_TEXT_NODE) - { + if (($v = $x->firstChild) && $v->nodeType == XML_TEXT_NODE) { $value = $base64_encoded ? base64_decode($v->nodeValue) : $v->nodeValue; if (uuid::is_valid($value)) - return $value; } } @@ -836,16 +777,13 @@ class system_file extends SplFileObject { clearstatcache(); $registry = registry::get_instance(); - if ( ! is_dir($path)) - { + if ( ! is_dir($path)) { $p = dirname($path); if ($p != "\\" && $p != "/" && $p != "." && $depth < 40) self::mkdir($p, $depth + 1); - if ( ! is_dir($path)) - { + if ( ! is_dir($path)) { mkdir($path); - if (is_dir($path)) - { + if (is_dir($path)) { $group = trim($registry->get('GV_filesGroup')); if ($group !== '' && function_exists('chgrp')) @@ -867,8 +805,7 @@ class system_file extends SplFileObject public function chmod() { - if (function_exists('chmod')) - { + if (function_exists('chmod')) { if (is_dir($this->getPathname())) chmod($this->getPathname(), 0755); if (is_file($this->getPathname())) @@ -882,41 +819,36 @@ class system_file extends SplFileObject { $origine = p4string::addEndSlash($this->getPathname()); - $dirs = $files = array(); + $dirs = $files = array(); - foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) - { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($origine), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $pathfile = $file->getRealPath(); - if (substr($file->getFilename(), 0, 1) == '.' || strpos($pathfile, '.svn') !== false) - { + if (substr($file->getFilename(), 0, 1) == '.' || strpos($pathfile, '.svn') !== false) { continue; } - $path = p4string::addEndSlash($file->getPath()); + $path = p4string::addEndSlash($file->getPath()); if ($path != $origine) $dirs[$path] = $path; - $files[] = $pathfile; + $files[] = $pathfile; } - foreach ($files as $file) - { + foreach ($files as $file) { unlink($file); } arsort($dirs); - foreach ($dirs as $dir) - { + foreach ($dirs as $dir) { rmdir($dir); } return $this; } - protected $phrasea_tech_field = array(); - const TECH_FIELD_SUBPATH = 'subpath'; + const TECH_FIELD_SUBPATH = 'subpath'; const TECH_FIELD_PARENTDIRECTORY = 'parentdirectory'; - const TECH_FIELD_ORIGINALNAME = 'originalname'; + const TECH_FIELD_ORIGINALNAME = 'originalname'; public function set_phrasea_tech_field($field, $value) { @@ -928,7 +860,6 @@ class system_file extends SplFileObject public function get_phrasea_tech_field($field) { if (isset($this->phrasea_tech_field[$field])) - return $this->phrasea_tech_field[$field]; return null; } @@ -942,62 +873,60 @@ class system_file extends SplFileObject $technical_datas = $this->get_technical_datas(); $tfields[metadata_description_PHRASEANET_tfmimetype::get_source()] - = array($this->get_mime()); + = array($this->get_mime()); $tfields[metadata_description_PHRASEANET_tfsize::get_source()] - = array($this->getSize()); + = array($this->getSize()); $tfields[metadata_description_PHRASEANET_tffilepath::get_source()] - = array($this->get_phrasea_tech_field(self::TECH_FIELD_SUBPATH)); + = array($this->get_phrasea_tech_field(self::TECH_FIELD_SUBPATH)); $tfields[metadata_description_PHRASEANET_tfparentdir::get_source()] - = array($this->get_phrasea_tech_field(self::TECH_FIELD_PARENTDIRECTORY)); + = array($this->get_phrasea_tech_field(self::TECH_FIELD_PARENTDIRECTORY)); $tfields[metadata_description_PHRASEANET_tffilename::get_source()] - = array($this->get_phrasea_tech_field(self::TECH_FIELD_ORIGINALNAME)); + = array($this->get_phrasea_tech_field(self::TECH_FIELD_ORIGINALNAME)); $tfields[metadata_description_PHRASEANET_tfextension::get_source()] - = array($this->get_extension()); + = array($this->get_extension()); $tfields[metadata_description_PHRASEANET_tfwidth::get_source()] - = isset($technical_datas[system_file::TC_DATAS_WIDTH]) ? array(($technical_datas[system_file::TC_DATAS_WIDTH])) : array(); + = isset($technical_datas[system_file::TC_DATAS_WIDTH]) ? array(($technical_datas[system_file::TC_DATAS_WIDTH])) : array(); $tfields[metadata_description_PHRASEANET_tfheight::get_source()] - = isset($technical_datas[system_file::TC_DATAS_HEIGHT]) ? array(($technical_datas[system_file::TC_DATAS_HEIGHT])) : array(); + = isset($technical_datas[system_file::TC_DATAS_HEIGHT]) ? array(($technical_datas[system_file::TC_DATAS_HEIGHT])) : array(); $tfields[metadata_description_PHRASEANET_tfbits::get_source()] - = isset($technical_datas[system_file::TC_DATAS_COLORDEPTH]) ? array(($technical_datas[system_file::TC_DATAS_COLORDEPTH])) : array(); + = isset($technical_datas[system_file::TC_DATAS_COLORDEPTH]) ? array(($technical_datas[system_file::TC_DATAS_COLORDEPTH])) : array(); $tfields[metadata_description_PHRASEANET_tfchannels::get_source()] - = isset($technical_datas[system_file::TC_DATAS_CHANNELS]) ? array(($technical_datas[system_file::TC_DATAS_CHANNELS])) : array(); + = isset($technical_datas[system_file::TC_DATAS_CHANNELS]) ? array(($technical_datas[system_file::TC_DATAS_CHANNELS])) : array(); $tfields[metadata_description_PHRASEANET_tfctime::get_source()] - = array(date('Y/m/d H:i:s', $this->getCTime())); + = array(date('Y/m/d H:i:s', $this->getCTime())); $tfields[metadata_description_PHRASEANET_tfmtime::get_source()] - = array(date('Y/m/d H:i:s', $this->getMTime())); + = array(date('Y/m/d H:i:s', $this->getMTime())); $tfields[metadata_description_PHRASEANET_tfatime::get_source()] - = array(date('Y/m/d H:i:s', $this->getATime())); + = array(date('Y/m/d H:i:s', $this->getATime())); $time = time(); $tfields[metadata_description_PHRASEANET_tfarchivedate::get_source()] - = array(date('Y/m/d H:i:s', $time)); + = array(date('Y/m/d H:i:s', $time)); $tfields[metadata_description_PHRASEANET_tfeditdate::get_source()] - = array(date('Y/m/d H:i:s', $time)); + = array(date('Y/m/d H:i:s', $time)); $tfields[metadata_description_PHRASEANET_tfchgdocdate::get_source()] - = array(date('Y/m/d H:i:s', $time)); + = array(date('Y/m/d H:i:s', $time)); - if ($this->get_mime() === 'application/pdf') - { + if ($this->get_mime() === 'application/pdf') { $tfields[metadata_description_PHRASEANET_pdftext::get_source()] - = $this->read_pdf_datas(); + = $this->read_pdf_datas(); } - $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); + $datas = exiftool::extract_metadatas($this, exiftool::EXTRACT_XML_RDF); $domrdf = new DOMDocument(); $domrdf->recover = true; $domrdf->preserveWhiteSpace = false; - if ($domrdf->loadXML($datas)) - { + if ($domrdf->loadXML($datas)) { $xptrdf = new DOMXPath($domrdf); $defined_namespaces = array( - 'rdf' => true - , 'XMP-exif' => true - , 'PHRASEANET' => true + 'rdf' => true + , 'XMP-exif' => true + , 'PHRASEANET' => true ); $xptrdf->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); @@ -1007,62 +936,51 @@ class system_file extends SplFileObject $xptrdf->registerNamespace('XMP-exif', 'http://ns.exiftool.ca/XMP/XMP-exif/1.0/'); $xptrdf->registerNamespace('PHRASEANET', 'http://phraseanet.com/metas/PHRASEANET/1.0/'); - foreach ($matches[2] as $key => $value) - { + foreach ($matches[2] as $key => $value) { $defined_namespaces[$matches[1][$key]] = true; $xptrdf->registerNamespace($matches[1][$key], $value); } // tous les champs de la structure - foreach ($meta_struct as $meta) - { + foreach ($meta_struct as $meta) { - if ( ! array_key_exists($meta->get_metadata_namespace(), $defined_namespaces)) - { + if ( ! array_key_exists($meta->get_metadata_namespace(), $defined_namespaces)) { $xptrdf->registerNamespace($meta->get_metadata_namespace(), 'http://ns.exiftool.ca/' . $meta->get_metadata_namespace() . '/1.0/'); $defined_namespaces[$meta->get_metadata_namespace()] = true; } - $fname = $meta->get_name(); + $fname = $meta->get_name(); $src = $meta->get_metadata_source(); if ( ! $src) continue; $x = $xptrdf->query($src); - if ( ! $x || $x->length != 1) - { + if ( ! $x || $x->length != 1) { continue; } - if ( ! isset($tfields[$src])) - { + if ( ! isset($tfields[$src])) { $tfields[$src] = array(); } $x = $x->item(0); //double check -- exiftool uses et:encoding in version prior 7.71 - $encoding = strtolower($x->getAttribute('rdf:datatype') . $x->getAttribute('et:encoding')); + $encoding = strtolower($x->getAttribute('rdf:datatype') . $x->getAttribute('et:encoding')); $base64_encoded = (strpos($encoding, 'base64') !== false); $bag = $xptrdf->query('rdf:Bag', $x); - if ($bag && $bag->length == 1) - { + if ($bag && $bag->length == 1) { $li = $xptrdf->query('rdf:li', $bag->item(0)); - if ($li->length > 0) - { - for ($ili = 0; $ili < $li->length; $ili ++ ) - { - $value = $base64_encoded ? base64_decode($li->item($ili)->nodeValue) : $li->item($ili)->nodeValue; - $utf8value = trim($this->guessCharset($value)); + if ($li->length > 0) { + for ($ili = 0; $ili < $li->length; $ili ++ ) { + $value = $base64_encoded ? base64_decode($li->item($ili)->nodeValue) : $li->item($ili)->nodeValue; + $utf8value = trim($this->guessCharset($value)); $tfields[$src][] = $utf8value; } } - } - else - { - if (($v = $x->firstChild) && $v->nodeType == XML_TEXT_NODE) - { - $value = $base64_encoded ? base64_decode($v->nodeValue) : $v->nodeValue; - $utf8value = $this->guessCharset($value); + } else { + if (($v = $x->firstChild) && $v->nodeType == XML_TEXT_NODE) { + $value = $base64_encoded ? base64_decode($v->nodeValue) : $v->nodeValue; + $utf8value = $this->guessCharset($value); $tfields[$src] = array($utf8value); } } @@ -1070,11 +988,10 @@ class system_file extends SplFileObject } - foreach ($meta_struct as $meta) - { + foreach ($meta_struct as $meta) { $fname = $meta->get_name(); - $src = $meta->get_metadata_source(); - $typ = mb_strtolower($meta->get_type()); // l'attribut 'type' du champ + $src = $meta->get_metadata_source(); + $typ = mb_strtolower($meta->get_type()); // l'attribut 'type' du champ $multi = $meta->is_multi(); // l'attribut 'multi' du champ if (trim($src) === '' || isset($tfields[$src]) === false) @@ -1085,22 +1002,19 @@ class system_file extends SplFileObject // un champ iptc peut etre multi-value, on recoit donc toujours un tableau comme valeur $tmpval = array(); - foreach ($tfields[$src] as $val) - { + foreach ($tfields[$src] as $val) { // on remplace les caracteres de controle (tous < 32 sauf 9,10,13) $val = $this->kill_ctrlchars($val); - if ($typ == 'date') - { + if ($typ == 'date') { $val = str_replace(array('-', ':', '/', '.'), array(' ', ' ', ' ', ' '), $val); $ip_date_yyyy = 0; - $ip_date_mm = 0; - $ip_date_dd = 0; - $ip_date_hh = 0; - $ip_date_nn = 0; - $ip_date_ss = 0; - switch (sscanf($val, '%d %d %d %d %d %d', $ip_date_yyyy, $ip_date_mm, $ip_date_dd, $ip_date_hh, $ip_date_nn, $ip_date_ss)) - { + $ip_date_mm = 0; + $ip_date_dd = 0; + $ip_date_hh = 0; + $ip_date_nn = 0; + $ip_date_ss = 0; + switch (sscanf($val, '%d %d %d %d %d %d', $ip_date_yyyy, $ip_date_mm, $ip_date_dd, $ip_date_hh, $ip_date_nn, $ip_date_ss)) { case 1: $val = sprintf('%04d/00/00 00:00:00', $ip_date_yyyy); break; @@ -1128,43 +1042,34 @@ class system_file extends SplFileObject $tmpval[] = $val; } - foreach ($tmpval as $val) - { + foreach ($tmpval as $val) { $ret = $this->add_meta_value($meta, $ret, $val); } } - $statBit = null; + $statBit = null; $sxcaption = null; - if ( ! is_null($caption_file)) - { + if ( ! is_null($caption_file)) { // on a une description xml en plus a lire dans un fichier externe - if ($domcaption = @DOMDocument::load($caption_file->getPathname())) - { - if ($domcaption->documentElement->tagName == 'description') // il manque 'record' (ca commence par 'description') : on repare - { + if ($domcaption = @DOMDocument::load($caption_file->getPathname())) { + if ($domcaption->documentElement->tagName == 'description') { // il manque 'record' (ca commence par 'description') : on repare $newdomcaption = new DOMDocument('1.0', 'UTF-8'); $newdomcaption->standalone = true; - $newdomrec = $newdomcaption->appendChild($newdomcaption->createElement('record')); + $newdomrec = $newdomcaption->appendChild($newdomcaption->createElement('record')); $newdomrec->appendChild($newdomcaption->importNode($domcaption->documentElement, true)); - $sxcaption = simplexml_load_string($newdomcaption->saveXML()); - } - else - { + $sxcaption = simplexml_load_string($newdomcaption->saveXML()); + } else { $sxcaption = simplexml_load_file($caption_file->getPathname()); } - if ($inStatus = $sxcaption->status) - { - if ($inStatus && $inStatus != '') - { + if ($inStatus = $sxcaption->status) { + if ($inStatus && $inStatus != '') { $statBit = $inStatus; } } } - if ($sxcaption) - { + if ($sxcaption) { $ret = $this->meta_merge($meta_struct, $ret, $sxcaption); } } @@ -1176,19 +1081,14 @@ class system_file extends SplFileObject { $found = false; - foreach ($metadatas as $key => $metadata) - { - if ($metadata['meta_struct_id'] == $databoxField->get_id()) - { - if ( ! $databoxField->is_multi()) - { + foreach ($metadatas as $key => $metadata) { + if ($metadata['meta_struct_id'] == $databoxField->get_id()) { + if ( ! $databoxField->is_multi()) { $metadatas[$key]['value'] = $value; $found = true; break; - } - elseif ($metadatas[$key]['value'] == $value) - { + } elseif ($metadatas[$key]['value'] == $value) { /** * if this is a multi valued field, we keep unique values */ @@ -1198,13 +1098,12 @@ class system_file extends SplFileObject } } - if ( ! $found) - { + if ( ! $found) { $metadatas[] = array( - 'meta_struct_id' => $databoxField->get_id(), - 'meta_id' => null, - 'value' => $value + 'meta_struct_id' => $databoxField->get_id(), + 'meta_id' => null, + 'value' => $value ); } @@ -1213,36 +1112,28 @@ class system_file extends SplFileObject protected function meta_merge(databox_descriptionStructure &$meta_struct, Array $metadatas, SimpleXMLElement $sxcaption) { - foreach ($sxcaption->description->children() as $fn => $fld) - { + foreach ($sxcaption->description->children() as $fn => $fld) { $fv = trim((string) $fld); $meta = $meta_struct->get_element_by_name($fn); - if ( ! $meta) - { + if ( ! $meta) { continue; } - if ($meta->get_type() == 'date') - { - if ($fld['format']) - { + if ($meta->get_type() == 'date') { + if ($fld['format']) { $fv = phraseadate::dateToIsodate($fv, $fld['format']); } } - if ($meta->is_multi()) - { + if ($meta->is_multi()) { $fv = caption_field::get_multi_values($fv, $meta->get_separator()); - } - else - { + } else { $fv = array($fv); } - foreach ($fv as $value) - { + foreach ($fv as $value) { $metadatas = $this->add_meta_value($meta, $metadatas, $value); } @@ -1257,24 +1148,18 @@ class system_file extends SplFileObject // (8x except 85, 8C) + (9x except 9C) + (BC, BD, BE) static $macchars = "\x81\x82\x83\x84\x86\x87\x88\x89\x8A\x8B\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9D\x9E\x9F\xBC\xBD\xBE"; - if (mb_convert_encoding(mb_convert_encoding($s, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') == $s) - { + if (mb_convert_encoding(mb_convert_encoding($s, 'UTF-32', 'UTF-8'), 'UTF-8', 'UTF-32') == $s) { $mac = mb_convert_encoding($s, 'windows-1252', 'UTF-8'); - for ($i = strlen($mac); $i;) - { + for ($i = strlen($mac); $i;) { if (strpos($macchars, $mac[ -- $i]) !== false) - return(iconv('MACINTOSH', 'UTF-8', $mac)); } return($s); } - else - { - for ($i = strlen($s); $i;) - { + else { + for ($i = strlen($s); $i;) { if (strpos($macchars, $s[ -- $i]) !== false) - return(iconv('MACINTOSH', 'UTF-8', $s)); } @@ -1284,17 +1169,14 @@ class system_file extends SplFileObject protected function kill_ctrlchars($s) // ok en utf8 ! { - static $a_in = null; + static $a_in = null; static $a_out = null; - if ($a_in === null) - { + if ($a_in === null) { $a_in = array(); $a_out = array(); - for ($cc = 0; $cc < 32; $cc ++ ) - { - if ($cc != 10 && $cc != 13 && $cc != 9) - { - $a_in[] = chr($cc); + for ($cc = 0; $cc < 32; $cc ++ ) { + if ($cc != 10 && $cc != 13 && $cc != 9) { + $a_in[] = chr($cc); $a_out[] = '_'; } } @@ -1302,11 +1184,9 @@ class system_file extends SplFileObject return(str_replace($a_in, $a_out, $s)); } - } -if ( ! function_exists('mime_content_type')) -{ +if ( ! function_exists('mime_content_type')) { /** * @@ -1316,105 +1196,104 @@ if ( ! function_exists('mime_content_type')) function mime_content_type($f) { $ext2mime = array( - 'dwg' => 'application/acad' // Fichiers AutoCAD - , 'ccad' => 'application/clariscad' // Fichiers ClarisCAD - , 'drw' => 'application/drafting' // Fichiers MATRA Prelude drafting - , 'dxf' => 'application/dxf' // Fichiers AutoCAD - , 'unv' => 'application/i-deas' // Fichiers SDRC I-deas - , 'igs' => 'application/iges' // Format d'echange CAO IGES - , 'iges' => 'application/iges' // Format d'echange CAO IGES - , 'bin' => 'application/octet-stream' // Fichiers binaires non interpretes - , 'oda' => 'application/oda' // Fichiers ODA - , 'pdf' => 'application/pdf' // Fichiers Adobe Acrobat - , 'ai' => 'application/postscript' // Fichiers PostScript - , 'eps' => 'application/postscript' // Fichiers PostScript - , 'ps' => 'application/postscript' // Fichiers PostScript - , 'prt' => 'application/pro_eng' // Fichiers ProEngineer - , 'rtf' => 'application/rtf' // Format de texte enrichi - , 'set' => 'application/set' // Fichiers CAO SET - , 'stl' => 'application/sla' // Fichiers stereolithographie - , 'dwg' => 'application/solids' // Fichiers MATRA Solids - , 'step' => 'application/step' // Fichiers de donnees STEP - , 'vda' => 'application/vda' // Fichiers de surface - , 'mif' => 'application/x-mif' // Fichiers Framemaker - , 'dwg' => 'application/x-csh' // Script C-Shell (UNIX) - , 'dvi' => 'application/x-dvi' // Fichiers texte dvi - , 'hdf' => 'application/hdf' // Fichiers de donnees - , 'latex' => 'application/x-latex' // Fichiers LaTEX - , 'nc' => 'application/x-netcdf' // Fichiers netCDF - , 'cdf' => 'application/x-netcdf' // Fichiers netCDF - , 'dwg' => 'application/x-sh' // Script Bourne Shell - , 'tcl' => 'application/x-tcl' // Script Tcl - , 'tex' => 'application/x-tex' // fichiers Tex - , 'texinfo' => 'application/x-texinfo' // Fichiers eMacs - , 'texi' => 'application/x-texinfo' // Fichiers eMacs - , 't' => 'application/x-troff' // Fichiers Troff - , 'tr' => 'application/x-troff' // Fichiers Troff - , 'troff' => 'application/x-troff' // Fichiers Troff - , 'man' => 'application/x-troff-man' // Fichiers Troff/macro man - , 'me' => 'application/x-troff-me' // Fichiers Troff/macro ME - , 'ms' => 'application/x-troff-ms' // Fichiers Troff/macro MS - , 'src' => 'application/x-wais-source' // Source Wais - , 'bcpio' => 'application/x-bcpio' // CPIO binaire - , 'cpio' => 'application/x-cpio' // CPIO Posix - , 'gtar' => 'application/x-gtar' // Tar GNU - , 'shar' => 'application/x-shar' // Archives Shell - , 'sv4cpio' => 'application/x-sv4cpio' // CPIO SVR4n - , 'sc4crc' => 'application/x-sv4crc' // CPIO SVR4 avec CRC - , 'tar' => 'application/x-tar' // Fichiers compresses tar - , 'man' => 'application/x-ustar' // Fichiers compresses tar Posix - , 'man' => 'application/zip' // Fichiers compresses ZIP - , 'au' => 'audio/basic' // Fichiers audio basiques - , 'snd' => 'audio/basic' // Fichiers audio basiques - , 'aif' => 'audio/x-aiff' // Fichiers audio AIFF - , 'aiff' => 'audio/x-aiff' // Fichiers audio AIFF - , 'aifc' => 'audio/x-aiff' // Fichiers audio AIFF - , 'wav' => 'audio/x-wav' // Fichiers audio Wave - , 'man' => 'image/gif' // Images gif - , 'ief' => 'image/ief' // Images exchange format - , 'jpg' => 'image/jpeg' // Images Jpeg - , 'jpeg' => 'image/jpeg' // Images Jpeg - , 'jpe' => 'image/jpeg' // Images Jpeg - , 'tiff' => 'image/tiff' // Images Tiff - , 'tif' => 'image/tiff' // Images Tiff - , 'cmu' => 'image/x-cmu-raster' // Raster cmu - , 'pnm' => 'image/x-portable-anymap' // Fichiers Anymap PBM - , 'pbm' => 'image/x-portable-bitmap' // Fichiers Bitmap PBM - , 'pgm' => 'image/x-portable-graymap' // Fichiers Graymap PBM - , 'ppm' => 'image/x-portable-pixmap' // Fichiers Pixmap PBM - , 'rgb' => 'image/x-rgb' // Image RGB - , 'xbm' => 'image/x-xbitmap' // Images Bitmap X - , 'xpm' => 'image/x-xpixmap' // Images Pixmap X - , 'man' => 'image/x-xwindowdump' // Images dump X Window - , 'zip' => 'multipart/x-zip' // Fichiers archive zip - , 'gz' => 'multipart/x-gzip' // Fichiers archive GNU zip - , 'gzip' => 'multipart/x-gzip' // Fichiers archive GNU zip - , 'htm' => 'text/html' // Fichiers HTML - , 'html' => 'text/html' // Fichiers HTML - , 'txt' => 'text/plain' // Fichiers texte sans mise en forme - , 'g' => 'text/plain' // Fichiers texte sans mise en forme - , 'h' => 'text/plain' // Fichiers texte sans mise en forme - , 'c' => 'text/plain' // Fichiers texte sans mise en forme - , 'cc' => 'text/plain' // Fichiers texte sans mise en forme - , 'hh' => 'text/plain' // Fichiers texte sans mise en forme - , 'm' => 'text/plain' // Fichiers texte sans mise en forme - , 'f90' => 'text/plain' // Fichiers texte sans mise en forme - , 'rtx' => 'text/richtext' // Fichiers texte enrichis - , 'tsv' => 'text/tab-separated-value' // Fichiers texte avec separation des valeurs - , 'etx' => 'text/x-setext' // Fichiers texte Struct - , 'mpeg' => 'video/mpeg' // Videos MPEG - , 'mpg' => 'video/mpeg' // Videos MPEG - , 'mpe' => 'video/mpeg' // Videos MPEG - , 'qt' => 'video/quicktime' // Videos QuickTime - , 'mov' => 'video/quicktime' // Videos QuickTime - , 'avi' => 'video/msvideo' // Videos Microsoft Windows - , 'movie' => 'video/x-sgi-movie' // Videos MoviePlayer + 'dwg' => 'application/acad' // Fichiers AutoCAD + , 'ccad' => 'application/clariscad' // Fichiers ClarisCAD + , 'drw' => 'application/drafting' // Fichiers MATRA Prelude drafting + , 'dxf' => 'application/dxf' // Fichiers AutoCAD + , 'unv' => 'application/i-deas' // Fichiers SDRC I-deas + , 'igs' => 'application/iges' // Format d'echange CAO IGES + , 'iges' => 'application/iges' // Format d'echange CAO IGES + , 'bin' => 'application/octet-stream' // Fichiers binaires non interpretes + , 'oda' => 'application/oda' // Fichiers ODA + , 'pdf' => 'application/pdf' // Fichiers Adobe Acrobat + , 'ai' => 'application/postscript' // Fichiers PostScript + , 'eps' => 'application/postscript' // Fichiers PostScript + , 'ps' => 'application/postscript' // Fichiers PostScript + , 'prt' => 'application/pro_eng' // Fichiers ProEngineer + , 'rtf' => 'application/rtf' // Format de texte enrichi + , 'set' => 'application/set' // Fichiers CAO SET + , 'stl' => 'application/sla' // Fichiers stereolithographie + , 'dwg' => 'application/solids' // Fichiers MATRA Solids + , 'step' => 'application/step' // Fichiers de donnees STEP + , 'vda' => 'application/vda' // Fichiers de surface + , 'mif' => 'application/x-mif' // Fichiers Framemaker + , 'dwg' => 'application/x-csh' // Script C-Shell (UNIX) + , 'dvi' => 'application/x-dvi' // Fichiers texte dvi + , 'hdf' => 'application/hdf' // Fichiers de donnees + , 'latex' => 'application/x-latex' // Fichiers LaTEX + , 'nc' => 'application/x-netcdf' // Fichiers netCDF + , 'cdf' => 'application/x-netcdf' // Fichiers netCDF + , 'dwg' => 'application/x-sh' // Script Bourne Shell + , 'tcl' => 'application/x-tcl' // Script Tcl + , 'tex' => 'application/x-tex' // fichiers Tex + , 'texinfo' => 'application/x-texinfo' // Fichiers eMacs + , 'texi' => 'application/x-texinfo' // Fichiers eMacs + , 't' => 'application/x-troff' // Fichiers Troff + , 'tr' => 'application/x-troff' // Fichiers Troff + , 'troff' => 'application/x-troff' // Fichiers Troff + , 'man' => 'application/x-troff-man' // Fichiers Troff/macro man + , 'me' => 'application/x-troff-me' // Fichiers Troff/macro ME + , 'ms' => 'application/x-troff-ms' // Fichiers Troff/macro MS + , 'src' => 'application/x-wais-source' // Source Wais + , 'bcpio' => 'application/x-bcpio' // CPIO binaire + , 'cpio' => 'application/x-cpio' // CPIO Posix + , 'gtar' => 'application/x-gtar' // Tar GNU + , 'shar' => 'application/x-shar' // Archives Shell + , 'sv4cpio' => 'application/x-sv4cpio' // CPIO SVR4n + , 'sc4crc' => 'application/x-sv4crc' // CPIO SVR4 avec CRC + , 'tar' => 'application/x-tar' // Fichiers compresses tar + , 'man' => 'application/x-ustar' // Fichiers compresses tar Posix + , 'man' => 'application/zip' // Fichiers compresses ZIP + , 'au' => 'audio/basic' // Fichiers audio basiques + , 'snd' => 'audio/basic' // Fichiers audio basiques + , 'aif' => 'audio/x-aiff' // Fichiers audio AIFF + , 'aiff' => 'audio/x-aiff' // Fichiers audio AIFF + , 'aifc' => 'audio/x-aiff' // Fichiers audio AIFF + , 'wav' => 'audio/x-wav' // Fichiers audio Wave + , 'man' => 'image/gif' // Images gif + , 'ief' => 'image/ief' // Images exchange format + , 'jpg' => 'image/jpeg' // Images Jpeg + , 'jpeg' => 'image/jpeg' // Images Jpeg + , 'jpe' => 'image/jpeg' // Images Jpeg + , 'tiff' => 'image/tiff' // Images Tiff + , 'tif' => 'image/tiff' // Images Tiff + , 'cmu' => 'image/x-cmu-raster' // Raster cmu + , 'pnm' => 'image/x-portable-anymap' // Fichiers Anymap PBM + , 'pbm' => 'image/x-portable-bitmap' // Fichiers Bitmap PBM + , 'pgm' => 'image/x-portable-graymap' // Fichiers Graymap PBM + , 'ppm' => 'image/x-portable-pixmap' // Fichiers Pixmap PBM + , 'rgb' => 'image/x-rgb' // Image RGB + , 'xbm' => 'image/x-xbitmap' // Images Bitmap X + , 'xpm' => 'image/x-xpixmap' // Images Pixmap X + , 'man' => 'image/x-xwindowdump' // Images dump X Window + , 'zip' => 'multipart/x-zip' // Fichiers archive zip + , 'gz' => 'multipart/x-gzip' // Fichiers archive GNU zip + , 'gzip' => 'multipart/x-gzip' // Fichiers archive GNU zip + , 'htm' => 'text/html' // Fichiers HTML + , 'html' => 'text/html' // Fichiers HTML + , 'txt' => 'text/plain' // Fichiers texte sans mise en forme + , 'g' => 'text/plain' // Fichiers texte sans mise en forme + , 'h' => 'text/plain' // Fichiers texte sans mise en forme + , 'c' => 'text/plain' // Fichiers texte sans mise en forme + , 'cc' => 'text/plain' // Fichiers texte sans mise en forme + , 'hh' => 'text/plain' // Fichiers texte sans mise en forme + , 'm' => 'text/plain' // Fichiers texte sans mise en forme + , 'f90' => 'text/plain' // Fichiers texte sans mise en forme + , 'rtx' => 'text/richtext' // Fichiers texte enrichis + , 'tsv' => 'text/tab-separated-value' // Fichiers texte avec separation des valeurs + , 'etx' => 'text/x-setext' // Fichiers texte Struct + , 'mpeg' => 'video/mpeg' // Videos MPEG + , 'mpg' => 'video/mpeg' // Videos MPEG + , 'mpe' => 'video/mpeg' // Videos MPEG + , 'qt' => 'video/quicktime' // Videos QuickTime + , 'mov' => 'video/quicktime' // Videos QuickTime + , 'avi' => 'video/msvideo' // Videos Microsoft Windows + , 'movie' => 'video/x-sgi-movie' // Videos MoviePlayer ); $fileinfo = new system_file($f); - $ext = $fileinfo->get_extension(true); + $ext = $fileinfo->get_extension(true); return array_key_exists($ext, $ext2mime) ? - $ext2mime[$ext] : 'application/octet-stream'; + $ext2mime[$ext] : 'application/octet-stream'; } - } diff --git a/lib/classes/system/server.class.php b/lib/classes/system/server.class.php index f4a5a7f8f3..3a542fafa3 100644 --- a/lib/classes/system/server.class.php +++ b/lib/classes/system/server.class.php @@ -17,81 +17,75 @@ */ class system_server { + /** + * + * @var string + */ + private $_server_software; - /** - * - * @var string - */ - private $_server_software; - - /** - * - * @return system_server - */ - function __construct() - { - $this->_server_software = isset($_SERVER['SERVER_SOFTWARE']) ? + /** + * + * @return system_server + */ + function __construct() + { + $this->_server_software = isset($_SERVER['SERVER_SOFTWARE']) ? strtolower($_SERVER['SERVER_SOFTWARE']) : ""; - return $this; - } - - /** - * Return true if server is Nginx - * - * @return boolean - */ - public function is_nginx() - { - if (strpos($this->_server_software, 'nginx') !== false) - - return true; - return false; - } - - /** - * Return true if server is lighttpd - * - * @return boolean - */ - public function is_lighttpd() - { - if (strpos($this->_server_software, 'lighttpd') !== false) - - return true; - return false; - } - - /** - * Return true if server is Apache - * - * @return boolean - */ - public function is_apache() - { - if (strpos($this->_server_software, 'apache') !== false) - - return true; - return false; - } - - /** - * Return server platform name - * - * @staticvar string $_system - * @return string - */ - public static function get_platform() - { - static $_system = NULL; - if ($_system === NULL) - { - $_system = strtoupper(php_uname('s')); - if ($_system == 'WINDOWS NT') - $_system = 'WINDOWS'; + return $this; } - return($_system); - } + /** + * Return true if server is Nginx + * + * @return boolean + */ + public function is_nginx() + { + if (strpos($this->_server_software, 'nginx') !== false) + return true; + return false; + } + /** + * Return true if server is lighttpd + * + * @return boolean + */ + public function is_lighttpd() + { + if (strpos($this->_server_software, 'lighttpd') !== false) + return true; + return false; + } + + /** + * Return true if server is Apache + * + * @return boolean + */ + public function is_apache() + { + if (strpos($this->_server_software, 'apache') !== false) + return true; + return false; + } + + /** + * Return server platform name + * + * @staticvar string $_system + * @return string + */ + public static function get_platform() + { + static $_system = NULL; + if ($_system === NULL) { + $_system = strtoupper(php_uname('s')); + if ($_system == 'WINDOWS NT') + $_system = 'WINDOWS'; + } + + return($_system); + } } diff --git a/lib/classes/system/url.class.php b/lib/classes/system/url.class.php index bbeadf1fe2..4537ff6f57 100644 --- a/lib/classes/system/url.class.php +++ b/lib/classes/system/url.class.php @@ -1,4 +1,5 @@ url = $url; - } + function __construct($url) + { + $this->url = $url; + } - function get_url() - { - return $this->url; - } + function get_url() + { + return $this->url; + } } diff --git a/lib/classes/task/Scheduler.class.php b/lib/classes/task/Scheduler.class.php index 929c1dcde0..145dece3b4 100644 --- a/lib/classes/task/Scheduler.class.php +++ b/lib/classes/task/Scheduler.class.php @@ -19,623 +19,547 @@ use Symfony\Component\Console\Output\OutputInterface; class task_Scheduler { - const TASKDELAYTOQUIT = 60; + const TASKDELAYTOQUIT = 60; - // how to schedule tasks (choose in 'run' method) - const METHOD_FORK = 'METHOD_FORK'; - const METHOD_PROC_OPEN = 'METHOD_PROC_OPEN'; + // how to schedule tasks (choose in 'run' method) + const METHOD_FORK = 'METHOD_FORK'; + const METHOD_PROC_OPEN = 'METHOD_PROC_OPEN'; - private $method; - private $input; - protected $output; + private $method; + private $input; + protected $output; - protected function log($message) - { - $registry = registry::get_instance(); - $logdir = $registry->get('GV_RootPath') . 'logs/'; - - logs::rotate($logdir . "scheduler_l.log"); - logs::rotate($logdir . "scheduler_o.log"); - logs::rotate($logdir . "scheduler_e.log"); - - $date_obj = new DateTime(); - $message = sprintf("%s\t%s", $date_obj->format(DATE_ATOM), $message); - - if($this->output instanceof OutputInterface) + protected function log($message) { + $registry = registry::get_instance(); + $logdir = $registry->get('GV_RootPath') . 'logs/'; + + logs::rotate($logdir . "scheduler_l.log"); + logs::rotate($logdir . "scheduler_o.log"); + logs::rotate($logdir . "scheduler_e.log"); + + $date_obj = new DateTime(); + $message = sprintf("%s\t%s", $date_obj->format(DATE_ATOM), $message); + + if ($this->output instanceof OutputInterface) { // $this->output->writeln($message); - } + } // $this->output->writeln($this->input->getOption('nolog')); - if($this->input && !($this->input->getOption('nolog'))) - { - file_put_contents($logdir . "scheduler_l.log", $message . "\n", FILE_APPEND); + if ($this->input && ! ($this->input->getOption('nolog'))) { + file_put_contents($logdir . "scheduler_l.log", $message . "\n", FILE_APPEND); + } + + return $this; } - return $this; - } - - protected static function get_connection() - { - return appbox::get_instance(\bootstrap::getCore())->get_connection(); - } - - public function run($input=null, OutputInterface $output = null) //, $log = true, $log_tasks = true) - { - $this->method = self::METHOD_FORK; - - require_once dirname(__FILE__) . '/../../bootstrap.php'; - $this->input = $input; - $this->output = $output; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $registry = $appbox->get_registry(); - - $nullfile = ''; - $system = system_server::get_platform(); - switch($system) + protected static function get_connection() { - case "WINDOWS": - $nullfile = 'NUL'; - break; - default: - case "DARWIN": - case "LINUX": - $nullfile = '/dev/null'; - break; + return appbox::get_instance(\bootstrap::getCore())->get_connection(); } - $lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'; - - for($try = 0; true; $try++) + public function run($input = null, OutputInterface $output = null) //, $log = true, $log_tasks = true) { - if(($schedlock = fopen(($lockfile = ($lockdir . 'scheduler.lock')), 'a+'))) - { - if(flock($schedlock, LOCK_EX | LOCK_NB) === FALSE) - { - $this->log(sprintf("failed to lock '%s' (try=%s/4)", $lockfile, $try)); - if($try == 4) - { - $this->log("scheduler already running."); - fclose($schedlock); + $this->method = self::METHOD_FORK; - return; - } - else - { - sleep(2); - } - } - else - { - // locked - ftruncate($schedlock, 0); - fwrite($schedlock, '' . getmypid()); - fflush($schedlock); - break; - } - } - } + require_once dirname(__FILE__) . '/../../bootstrap.php'; + $this->input = $input; + $this->output = $output; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $registry = $appbox->get_registry(); - $this->log(sprintf("running scheduler with method %s", $this->method)); - - if($this->method == self::METHOD_FORK) - pcntl_signal(SIGCHLD, SIG_IGN); - - $logdir = $registry->get('GV_RootPath') . 'logs/'; - - $conn = appbox::get_instance(\bootstrap::getCore())->get_connection(); - - $taskPoll = array(); // the poll of tasks - - $sleeptime = 3; - - $sql = "UPDATE sitepreff SET schedstatus='started'"; - $conn->exec($sql); - - $task_manager = new task_manager($appbox); - - // set every 'auto-start' task to start - foreach($task_manager->get_tasks() as $task) - { - if($task->is_active()) - { - $tid = $task->get_task_id(); - - if(!$task->get_pid()) - { - /* @var $task task_abstract */ - $task->reset_crash_counter(); - $task->set_status(task_abstract::STATUS_TOSTART); - } - } - } - - $tlist = array(); - - - - $schedstatus = 'started'; - $runningtask = 0; - $connwaslost = false; - - $last_log_check = array(); - - while($schedstatus == 'started' || $runningtask > 0) - { - while(1) - { - try - { - assert(is_object($conn)); - $ping = @$conn->ping(); - } - catch(ErrorException $e) - { - $ping = false; - } - if($ping) - break; - - unset($conn); - if(!$connwaslost) - { - $this->log(sprintf("Warning : abox connection lost, restarting in 10 min.")); - } - for($i = 0; $i < 60 * 10; $i++) - sleep(1); - try - { - $conn = appbox::get_instance(\bootstrap::getCore())->get_connection(); - } - catch(ErrorException $e) - { - $ping = false; - } - - $connwaslost = true; - } - if($connwaslost) - { - $this->log("abox connection restored"); - - $sql = 'UPDATE task SET crashed=0'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $connwaslost = false; - } -// printf("%d \n", __LINE__); - $schedstatus = ''; - $row = NULL; - try - { - $sql = "SELECT schedstatus FROM sitepreff"; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - } - catch(ErrorException $e) - { - continue; - } - - if($row) - { - $schedstatus = $row["schedstatus"]; - } - - if($schedstatus == 'tostop') - { - $sql = 'UPDATE sitepreff SET schedstatus = "stopping"'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - // if scheduler is stopped, stop the tasks - $sql = 'UPDATE task2 SET status="tostop" WHERE status != "stopped" and status != "manual"'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - $this->log("schedstatus == 'stopping', waiting tasks to end"); - } - - logs::rotate($logdir . "scheduler_t.log"); - logs::rotate($logdir . "scheduler_o.log"); - logs::rotate($logdir . "scheduler_e.log"); - -// printf("%d \n", __LINE__); - // initialy, all tasks are supposed to be removed from the poll - foreach($taskPoll as $tkey => $task) - $taskPoll[$tkey]["todel"] = true; - - foreach($task_manager->get_tasks(true) as $task) - { - $tkey = "t_" . $task->get_task_id(); - $status = $task->get_status(); - - logs::rotate($logdir . "task_t_" . $task->get_task_id() . ".log"); - logs::rotate($logdir . "task_o_" . $task->get_task_id() . ".log"); - logs::rotate($logdir . "task_e_" . $task->get_task_id() . ".log"); - - if(!isset($taskPoll[$tkey])) - { - // the task is not in the poll, add it - $phpcli = $registry->get('GV_cli'); - switch($system) - { + $nullfile = ''; + $system = system_server::get_platform(); + switch ($system) { case "WINDOWS": - $cmd = $phpcli; - $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); - if($this->input && ($this->input->getOption('notasklog'))) - $args[] = 'notasklog'; - break; + $nullfile = 'NUL'; + break; default: case "DARWIN": case "LINUX": - $cmd = $phpcli; - $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); - if($this->input && ($this->input->getOption('notasklog'))) - $args[] = 'notasklog'; - break; - } - - $taskPoll[$tkey] = array( - "task" => $task, - "current_status" => $status, - "cmd" => $cmd, - "args" => $args, - "killat" => null, - "sigterm_sent" => false - ); - if($this->method == self::METHOD_PROC_OPEN) - { - $taskPoll[$tkey]['process'] = NULL; - $taskPoll[$tkey]['pipes'] = NULL; - } - - $this->log( - sprintf( - "new Task %s, status=%s" - , $taskPoll[$tkey]["task"]->get_task_id() - , $status - ) - ); + $nullfile = '/dev/null'; + break; } - else - { - // the task is already in the poll, update its status - if($taskPoll[$tkey]["current_status"] != $status) - { - $this->log( - sprintf( - "Task %s, oldstatus=%s, newstatus=%s" + + $lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'; + + for ($try = 0; true; $try ++ ) { + if (($schedlock = fopen(($lockfile = ($lockdir . 'scheduler.lock')), 'a+'))) { + if (flock($schedlock, LOCK_EX | LOCK_NB) === FALSE) { + $this->log(sprintf("failed to lock '%s' (try=%s/4)", $lockfile, $try)); + if ($try == 4) { + $this->log("scheduler already running."); + fclose($schedlock); + + return; + } else { + sleep(2); + } + } else { + // locked + ftruncate($schedlock, 0); + fwrite($schedlock, '' . getmypid()); + fflush($schedlock); + break; + } + } + } + + $this->log(sprintf("running scheduler with method %s", $this->method)); + + if ($this->method == self::METHOD_FORK) + pcntl_signal(SIGCHLD, SIG_IGN); + + $logdir = $registry->get('GV_RootPath') . 'logs/'; + + $conn = appbox::get_instance(\bootstrap::getCore())->get_connection(); + + $taskPoll = array(); // the poll of tasks + + $sleeptime = 3; + + $sql = "UPDATE sitepreff SET schedstatus='started'"; + $conn->exec($sql); + + $task_manager = new task_manager($appbox); + + // set every 'auto-start' task to start + foreach ($task_manager->get_tasks() as $task) { + if ($task->is_active()) { + $tid = $task->get_task_id(); + + if ( ! $task->get_pid()) { + /* @var $task task_abstract */ + $task->reset_crash_counter(); + $task->set_status(task_abstract::STATUS_TOSTART); + } + } + } + + $tlist = array(); + + + + $schedstatus = 'started'; + $runningtask = 0; + $connwaslost = false; + + $last_log_check = array(); + + while ($schedstatus == 'started' || $runningtask > 0) { + while (1) { + try { + assert(is_object($conn)); + $ping = @$conn->ping(); + } catch (ErrorException $e) { + $ping = false; + } + if ($ping) + break; + + unset($conn); + if ( ! $connwaslost) { + $this->log(sprintf("Warning : abox connection lost, restarting in 10 min.")); + } + for ($i = 0; $i < 60 * 10; $i ++ ) + sleep(1); + try { + $conn = appbox::get_instance(\bootstrap::getCore())->get_connection(); + } catch (ErrorException $e) { + $ping = false; + } + + $connwaslost = true; + } + if ($connwaslost) { + $this->log("abox connection restored"); + + $sql = 'UPDATE task SET crashed=0'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + $connwaslost = false; + } +// printf("%d \n", __LINE__); + $schedstatus = ''; + $row = NULL; + try { + $sql = "SELECT schedstatus FROM sitepreff"; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + } catch (ErrorException $e) { + continue; + } + + if ($row) { + $schedstatus = $row["schedstatus"]; + } + + if ($schedstatus == 'tostop') { + $sql = 'UPDATE sitepreff SET schedstatus = "stopping"'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + // if scheduler is stopped, stop the tasks + $sql = 'UPDATE task2 SET status="tostop" WHERE status != "stopped" and status != "manual"'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + $this->log("schedstatus == 'stopping', waiting tasks to end"); + } + + logs::rotate($logdir . "scheduler_t.log"); + logs::rotate($logdir . "scheduler_o.log"); + logs::rotate($logdir . "scheduler_e.log"); + +// printf("%d \n", __LINE__); + // initialy, all tasks are supposed to be removed from the poll + foreach ($taskPoll as $tkey => $task) + $taskPoll[$tkey]["todel"] = true; + + foreach ($task_manager->get_tasks(true) as $task) { + $tkey = "t_" . $task->get_task_id(); + $status = $task->get_status(); + + logs::rotate($logdir . "task_t_" . $task->get_task_id() . ".log"); + logs::rotate($logdir . "task_o_" . $task->get_task_id() . ".log"); + logs::rotate($logdir . "task_e_" . $task->get_task_id() . ".log"); + + if ( ! isset($taskPoll[$tkey])) { + // the task is not in the poll, add it + $phpcli = $registry->get('GV_cli'); + switch ($system) { + case "WINDOWS": + $cmd = $phpcli; + $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); + if ($this->input && ($this->input->getOption('notasklog'))) + $args[] = 'notasklog'; + break; + default: + case "DARWIN": + case "LINUX": + $cmd = $phpcli; + $args = array('-f', $registry->get('GV_RootPath') . 'bin/console', '--', '-q', 'task:run', $task->get_task_id(), '--runner=scheduler'); + if ($this->input && ($this->input->getOption('notasklog'))) + $args[] = 'notasklog'; + break; + } + + $taskPoll[$tkey] = array( + "task" => $task, + "current_status" => $status, + "cmd" => $cmd, + "args" => $args, + "killat" => null, + "sigterm_sent" => false + ); + if ($this->method == self::METHOD_PROC_OPEN) { + $taskPoll[$tkey]['process'] = NULL; + $taskPoll[$tkey]['pipes'] = NULL; + } + + $this->log( + sprintf( + "new Task %s, status=%s" , $taskPoll[$tkey]["task"]->get_task_id() - , $taskPoll[$tkey]["current_status"] , $status - ) - ); - $taskPoll[$tkey]["current_status"] = $status; - } - // update the whole task object - unset($taskPoll[$tkey]["task"]); - $taskPoll[$tkey]["task"] = $task; + ) + ); + } else { + // the task is already in the poll, update its status + if ($taskPoll[$tkey]["current_status"] != $status) { + $this->log( + sprintf( + "Task %s, oldstatus=%s, newstatus=%s" + , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["current_status"] + , $status + ) + ); + $taskPoll[$tkey]["current_status"] = $status; + } + // update the whole task object + unset($taskPoll[$tkey]["task"]); + $taskPoll[$tkey]["task"] = $task; + } + + unset($task); + + $taskPoll[$tkey]["todel"] = false; // this task exists, do not remove from poll + } + + // remove not-existing task from poll + foreach ($taskPoll as $tkey => $task) { + if ($task["todel"]) { + $this->log(sprintf("Task %s deleted", $taskPoll[$tkey]["task"]->get_task_id())); + unset($taskPoll[$tkey]); + } + } + + // Launch task that are not yet launched + $runningtask = 0; + + foreach ($taskPoll as $tkey => $tv) { + $status = $tv['task']->get_status(); + switch ($status) { + default: + $this->log(sprintf('Unknow status `%s`', $status)); + break; + + case task_abstract::RETURNSTATUS_TORESTART: + if ( ! $taskPoll[$tkey]['task']->get_pid()) { + if ($this->method == self::METHOD_PROC_OPEN) { + @fclose($taskPoll[$tkey]["pipes"][1]); + @fclose($taskPoll[$tkey]["pipes"][2]); + @proc_close($taskPoll[$tkey]["process"]); + + $taskPoll[$tkey]["process"] = null; + } + if ($schedstatus == 'started') { + $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + } + // trick to start the task immediatly : DON'T break if ending with 'tostart' + // so it will continue with 'tostart' case ! + } else { + break; + } + + case task_abstract::STATUS_TOSTART: + // if scheduler is 'tostop', don't launch a new task ! + if ($schedstatus != 'started') + break; + + $taskPoll[$tkey]["killat"] = NULL; + + if ($this->method == self::METHOD_PROC_OPEN) { + if ( ! $taskPoll[$tkey]["process"]) { + $descriptors[1] = array('file', $logdir . "task_o_" . $task->get_task_id() . ".log", 'a+'); + $descriptors[2] = array('file', $logdir . "task_e_" . $task->get_task_id() . ".log", 'a+'); + + $taskPoll[$tkey]["process"] = proc_open( + $taskPoll[$tkey]["cmd"] . ' ' . implode(' ', $taskPoll[$tkey]["args"]) + , $descriptors + , $taskPoll[$tkey]["pipes"] + , $registry->get('GV_RootPath') . "bin/" + , null + , array('bypass_shell' => true) + ); + + if (is_resource($taskPoll[$tkey]["process"])) { + sleep(2); // let the process lock and write it's pid + } + + if (is_resource($taskPoll[$tkey]["process"]) && $taskPoll[$tkey]['task']->get_pid() !== null) { + $this->log( + sprintf( + "Task %s '%s' started (pid=%s)" + , $taskPoll[$tkey]['task']->get_task_id() + , $taskPoll[$tkey]["cmd"] + , $taskPoll[$tkey]['task']->get_pid() + ) + ); + $runningtask ++; + } else { + $taskPoll[$tkey]["task"]->increment_crash_counter(); + + @fclose($taskPoll[$tkey]["pipes"][1]); + @fclose($taskPoll[$tkey]["pipes"][2]); + @proc_close($taskPoll[$tkey]["process"]); + $taskPoll[$tkey]["process"] = null; + + $this->log( + sprintf( + "Task %s '%s' failed to start %d times" + , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["cmd"] + , $taskPoll[$tkey]["task"]->get_crash_counter() + ) + ); + + if ($taskPoll[$tkey]["task"]->get_crash_counter() > 5) + $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); + else + $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + } + } + } + elseif ($this->method == self::METHOD_FORK) { + // printf("forking pid %d\n", getmypid()); + $pid = pcntl_fork(); + if ($pid == -1) { + die("failed to fork"); + } elseif ($pid == 0) { + // child + // printf("hello i am child pid=%d\n", getmypid()); + // printf("%s %s \n", $taskPoll[$tkey]["cmd"], implode(' ', $taskPoll[$tkey]["args"])); + umask(0); + if (posix_setsid() < 0) + die("Forked process could not detach from terminal\n"); + + fclose(STDIN); + fclose(STDOUT); + fclose(STDERR); + $fdIN = fopen($nullfile, 'r'); + $fdOUT = fopen($logdir . "task_o_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); + $fdERR = fopen($logdir . "task_e_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); + + $this->log(sprintf("exec('%s %s')", $taskPoll[$tkey]["cmd"], implode(' ', $taskPoll[$tkey]["args"]))); + pcntl_exec($taskPoll[$tkey]["cmd"], $taskPoll[$tkey]["args"]); + } + else { + // parent + // sleep(2); + } + } + break; + + case task_abstract::STATUS_STARTED: + + $crashed = false; + // If no process, the task is probably manually ran + + if ($this->method == self::METHOD_PROC_OPEN) { + if ($taskPoll[$tkey]["process"]) { + $taskPoll[$tkey]["killat"] = NULL; + + if (is_resource($taskPoll[$tkey]["process"])) { + $proc_status = proc_get_status($taskPoll[$tkey]["process"]); + if ($proc_status['running']) + $runningtask ++; + else + $crashed = true; + } + else { + $crashed = true; + } + } + } + + if ( ! $crashed && ! $taskPoll[$tkey]['task']->get_pid()) + $crashed = true; + + if ( ! $crashed) { + $taskPoll[$tkey]["killat"] = NULL; + $runningtask ++; + } else { + // crashed ! + $taskPoll[$tkey]["task"]->increment_crash_counter(); + + if ($this->method == self::METHOD_PROC_OPEN) { + @fclose($taskPoll[$tkey]["pipes"][1]); + @fclose($taskPoll[$tkey]["pipes"][2]); + @proc_close($taskPoll[$tkey]["process"]); + $taskPoll[$tkey]["process"] = null; + } + $this->log( + sprintf( + "Task %s crashed %d times" + , $taskPoll[$tkey]["task"]->get_task_id() + , $taskPoll[$tkey]["task"]->get_crash_counter() + ) + ); + + if ($taskPoll[$tkey]["task"]->get_crash_counter() > 5) + $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); + else + $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); + } + break; + + case task_abstract::STATUS_TOSTOP: + + if ($taskPoll[$tkey]["killat"] === NULL) + $taskPoll[$tkey]["killat"] = time() + self::TASKDELAYTOQUIT; + + $pid = $taskPoll[$tkey]['task']->get_pid(); + if ($pid) { + if ( ! $taskPoll[$tkey]['sigterm_sent']) { + posix_kill($pid, SIGTERM); + $this->log( + sprintf( + "SIGTERM sent to task %s (pid=%s)" + , $taskPoll[$tkey]["task"]->get_task_id() + , $pid + ) + ); + } + + if (($dt = $taskPoll[$tkey]["killat"] - time()) < 0) { + posix_kill($pid, 9); + + $this->log( + sprintf( + "SIGKILL sent to task %s (pid=%s)" + , $taskPoll[$tkey]["task"]->get_task_id() + , $pid + ) + ); + + if ($this->method == self::METHOD_PROC_OPEN) { + proc_terminate($taskPoll[$tkey]["process"], 9); + @fclose($taskPoll[$tkey]["pipes"][1]); + @fclose($taskPoll[$tkey]["pipes"][2]); + proc_close($taskPoll[$tkey]["process"]); + } + unlink($lockdir . 'task_' . $taskPoll[$tkey]['task']->get_task_id() . '.lock'); + + $taskPoll[$tkey]["task"]->increment_crash_counter(); + // $taskPoll[$tkey]["task"]->set_pid(null); + $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); + } else { + $this->log( + sprintf( + "waiting task %s to quit (kill in %d seconds)" + , $taskPoll[$tkey]["task"]->get_task_id() + , $dt + ) + ); + $runningtask ++; + } + } else { + $this->log( + sprintf( + "task %s has quit" + , $taskPoll[$tkey]["task"]->get_task_id() + ) + ); + $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); + } + + break; + + case task_abstract::RETURNSTATUS_STOPPED: + case task_abstract::RETURNSTATUS_TODELETE: + if ($this->method == self::METHOD_PROC_OPEN) { + if ($taskPoll[$tkey]["process"]) { + @fclose($taskPoll[$tkey]["pipes"][1]); + @fclose($taskPoll[$tkey]["pipes"][2]); + @proc_close($taskPoll[$tkey]["process"]); + + $taskPoll[$tkey]["process"] = null; + } + } + break; + } + } + + for ($i = 0; $i < $sleeptime; $i ++ ) + sleep(1); } - unset($task); + $sql = "UPDATE sitepreff SET schedstatus='stopped', schedpid='0'"; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); - $taskPoll[$tkey]["todel"] = false; // this task exists, do not remove from poll - } + $this->log("Scheduler2 is quitting."); - // remove not-existing task from poll - foreach($taskPoll as $tkey => $task) - { - if($task["todel"]) - { - $this->log(sprintf("Task %s deleted", $taskPoll[$tkey]["task"]->get_task_id())); - unset($taskPoll[$tkey]); - } - } + ftruncate($schedlock, 0); + fclose($schedlock); - // Launch task that are not yet launched - $runningtask = 0; - - foreach($taskPoll as $tkey => $tv) - { - $status = $tv['task']->get_status(); - switch($status) - { - default: - $this->log(sprintf('Unknow status `%s`', $status)); - break; - - case task_abstract::RETURNSTATUS_TORESTART: - if(!$taskPoll[$tkey]['task']->get_pid()) - { - if($this->method == self::METHOD_PROC_OPEN) - { - @fclose($taskPoll[$tkey]["pipes"][1]); - @fclose($taskPoll[$tkey]["pipes"][2]); - @proc_close($taskPoll[$tkey]["process"]); - - $taskPoll[$tkey]["process"] = null; - } - if($schedstatus == 'started') - { - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); - } - // trick to start the task immediatly : DON'T break if ending with 'tostart' - // so it will continue with 'tostart' case ! - } - else - { - break; - } - - case task_abstract::STATUS_TOSTART: - // if scheduler is 'tostop', don't launch a new task ! - if($schedstatus != 'started') - break; - - $taskPoll[$tkey]["killat"] = NULL; - - if($this->method == self::METHOD_PROC_OPEN) - { - if(!$taskPoll[$tkey]["process"]) - { - $descriptors[1] = array('file', $logdir . "task_o_" . $task->get_task_id() . ".log", 'a+'); - $descriptors[2] = array('file', $logdir . "task_e_" . $task->get_task_id() . ".log", 'a+'); - - $taskPoll[$tkey]["process"] = proc_open( - $taskPoll[$tkey]["cmd"] . ' ' . implode(' ', $taskPoll[$tkey]["args"]) - , $descriptors - , $taskPoll[$tkey]["pipes"] - , $registry->get('GV_RootPath') . "bin/" - , null - , array('bypass_shell' => true) - ); - - if(is_resource($taskPoll[$tkey]["process"])) - { - sleep(2); // let the process lock and write it's pid - } - - if(is_resource($taskPoll[$tkey]["process"]) && $taskPoll[$tkey]['task']->get_pid() !== null) - { - $this->log( - sprintf( - "Task %s '%s' started (pid=%s)" - , $taskPoll[$tkey]['task']->get_task_id() - , $taskPoll[$tkey]["cmd"] - , $taskPoll[$tkey]['task']->get_pid() - ) - ); - $runningtask++; - } - else - { - $taskPoll[$tkey]["task"]->increment_crash_counter(); - - @fclose($taskPoll[$tkey]["pipes"][1]); - @fclose($taskPoll[$tkey]["pipes"][2]); - @proc_close($taskPoll[$tkey]["process"]); - $taskPoll[$tkey]["process"] = null; - - $this->log( - sprintf( - "Task %s '%s' failed to start %d times" - , $taskPoll[$tkey]["task"]->get_task_id() - , $taskPoll[$tkey]["cmd"] - , $taskPoll[$tkey]["task"]->get_crash_counter() - ) - ); - - if($taskPoll[$tkey]["task"]->get_crash_counter() > 5) - $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); - else - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); - } - } - } - elseif($this->method == self::METHOD_FORK) - { - // printf("forking pid %d\n", getmypid()); - $pid = pcntl_fork(); - if($pid == -1) - { - die("failed to fork"); - } - elseif($pid == 0) - { - // child - // printf("hello i am child pid=%d\n", getmypid()); - // printf("%s %s \n", $taskPoll[$tkey]["cmd"], implode(' ', $taskPoll[$tkey]["args"])); - umask(0); - if(posix_setsid() < 0) - die("Forked process could not detach from terminal\n"); - - fclose(STDIN); - fclose(STDOUT); - fclose(STDERR); - $fdIN = fopen($nullfile, 'r'); - $fdOUT = fopen($logdir . "task_o_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); - $fdERR = fopen($logdir . "task_e_" . $taskPoll[$tkey]["task"]->get_task_id() . ".log", 'a+'); - - $this->log(sprintf("exec('%s %s')", $taskPoll[$tkey]["cmd"], implode(' ', $taskPoll[$tkey]["args"]))); - pcntl_exec($taskPoll[$tkey]["cmd"], $taskPoll[$tkey]["args"]); - - } - else - { - // parent - // sleep(2); - } - } - break; - - case task_abstract::STATUS_STARTED: - - $crashed = false; - // If no process, the task is probably manually ran - - if($this->method == self::METHOD_PROC_OPEN) - { - if($taskPoll[$tkey]["process"]) - { - $taskPoll[$tkey]["killat"] = NULL; - - if(is_resource($taskPoll[$tkey]["process"])) - { - $proc_status = proc_get_status($taskPoll[$tkey]["process"]); - if($proc_status['running']) - $runningtask++; - else - $crashed = true; - } - else - { - $crashed = true; - } - } - } - - if(!$crashed && !$taskPoll[$tkey]['task']->get_pid()) - $crashed = true; - - if(!$crashed) - { - $taskPoll[$tkey]["killat"] = NULL; - $runningtask++; - } - else - { - // crashed ! - $taskPoll[$tkey]["task"]->increment_crash_counter(); - - if($this->method == self::METHOD_PROC_OPEN) - { - @fclose($taskPoll[$tkey]["pipes"][1]); - @fclose($taskPoll[$tkey]["pipes"][2]); - @proc_close($taskPoll[$tkey]["process"]); - $taskPoll[$tkey]["process"] = null; - } - $this->log( - sprintf( - "Task %s crashed %d times" - , $taskPoll[$tkey]["task"]->get_task_id() - , $taskPoll[$tkey]["task"]->get_crash_counter() - ) - ); - - if($taskPoll[$tkey]["task"]->get_crash_counter() > 5) - $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); - else - $taskPoll[$tkey]["task"]->set_status(task_abstract::STATUS_TOSTART); - } - break; - - case task_abstract::STATUS_TOSTOP: - - if($taskPoll[$tkey]["killat"] === NULL) - $taskPoll[$tkey]["killat"] = time() + self::TASKDELAYTOQUIT; - - $pid = $taskPoll[$tkey]['task']->get_pid(); - if($pid) - { - if(!$taskPoll[$tkey]['sigterm_sent']) - { - posix_kill($pid, SIGTERM); - $this->log( - sprintf( - "SIGTERM sent to task %s (pid=%s)" - , $taskPoll[$tkey]["task"]->get_task_id() - , $pid - ) - ); - } - - if(($dt = $taskPoll[$tkey]["killat"] - time()) < 0) - { - posix_kill($pid, 9); - - $this->log( - sprintf( - "SIGKILL sent to task %s (pid=%s)" - , $taskPoll[$tkey]["task"]->get_task_id() - , $pid - ) - ); - - if($this->method == self::METHOD_PROC_OPEN) - { - proc_terminate($taskPoll[$tkey]["process"], 9); - @fclose($taskPoll[$tkey]["pipes"][1]); - @fclose($taskPoll[$tkey]["pipes"][2]); - proc_close($taskPoll[$tkey]["process"]); - } - unlink($lockdir . 'task_' . $taskPoll[$tkey]['task']->get_task_id() . '.lock'); - - $taskPoll[$tkey]["task"]->increment_crash_counter(); - // $taskPoll[$tkey]["task"]->set_pid(null); - $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); - } - else - { - $this->log( - sprintf( - "waiting task %s to quit (kill in %d seconds)" - , $taskPoll[$tkey]["task"]->get_task_id() - , $dt - ) - ); - $runningtask++; - } - } - else - { - $this->log( - sprintf( - "task %s has quit" - , $taskPoll[$tkey]["task"]->get_task_id() - ) - ); - $taskPoll[$tkey]["task"]->set_status(task_abstract::RETURNSTATUS_STOPPED); - } - - break; - - case task_abstract::RETURNSTATUS_STOPPED: - case task_abstract::RETURNSTATUS_TODELETE: - if($this->method == self::METHOD_PROC_OPEN) - { - if($taskPoll[$tkey]["process"]) - { - @fclose($taskPoll[$tkey]["pipes"][1]); - @fclose($taskPoll[$tkey]["pipes"][2]); - @proc_close($taskPoll[$tkey]["process"]); - - $taskPoll[$tkey]["process"] = null; - } - } - break; - } - } - - for($i=0; $i<$sleeptime; $i++) - sleep(1); + $this->log("Scheduler2 has quit.\n"); } - - $sql = "UPDATE sitepreff SET schedstatus='stopped', schedpid='0'"; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $this->log("Scheduler2 is quitting."); - - ftruncate($schedlock, 0); - fclose($schedlock); - - $this->log("Scheduler2 has quit.\n"); - } - } diff --git a/lib/classes/task/abstract.class.php b/lib/classes/task/abstract.class.php index 3d11aaee2a..eec9d19b53 100644 --- a/lib/classes/task/abstract.class.php +++ b/lib/classes/task/abstract.class.php @@ -2,162 +2,156 @@ abstract class task_abstract { - const LAUCHED_BY_BROWSER = 1; - const LAUCHED_BY_COMMANDLINE = 2; + const LAUCHED_BY_BROWSER = 1; + const LAUCHED_BY_COMMANDLINE = 2; + const STATUS_TOSTOP = 'tostop'; + const STATUS_STARTED = 'started'; + const STATUS_TOSTART = 'tostart'; + const RETURNSTATUS_TORESTART = 'torestart'; + const RETURNSTATUS_STOPPED = 'stopped'; + const RETURNSTATUS_TODELETE = 'todelete'; + const RUNNER_MANUAL = 'manual'; + const RUNNER_SCHEDULER = 'scheduler'; + const STATE_OK = 'STATE_OK'; + const STATE_MAXMEGSREACHED = 'STATE_MAXMEGS'; + const STATE_MAXRECSDONE = 'STATE_MAXRECS'; + const STATE_FINISHED = 'STATE_FINISHED'; + const SIGNAL_SCHEDULER_DIED = 'SIGNAL_SCHEDULER_DIED'; - const STATUS_TOSTOP = 'tostop'; - const STATUS_STARTED = 'started'; - const STATUS_TOSTART = 'tostart'; + protected $suicidable = false; + protected $launched_by = 0; - const RETURNSTATUS_TORESTART = 'torestart'; - const RETURNSTATUS_STOPPED = 'stopped'; - const RETURNSTATUS_TODELETE = 'todelete'; + /** + * Number of records done + * + * @var + */ + protected $records_done = 0; - const RUNNER_MANUAL = 'manual'; - const RUNNER_SCHEDULER = 'scheduler'; + /** + * Maximum number of records before we restart the task + * + * @var + */ + protected $maxrecs; - const STATE_OK = 'STATE_OK'; - const STATE_MAXMEGSREACHED = 'STATE_MAXMEGS'; - const STATE_MAXRECSDONE = 'STATE_MAXRECS'; - const STATE_FINISHED = 'STATE_FINISHED'; + /** + * Boolean switch to stop the task + * + * @var + */ + protected $running = false; - const SIGNAL_SCHEDULER_DIED = 'SIGNAL_SCHEDULER_DIED'; + /** + * current number of loops done + * + * @var + */ + protected $loop = 0; - protected $suicidable = false; - protected $launched_by = 0; + /** + * max number of loops before the task is restarted + * + * @var + */ + protected $maxloops = 5; - /** - * Number of records done - * - * @var - */ - protected $records_done = 0; + /** + * task status, either 'tostop' or 'started' + * + * @var + */ + protected $task_status = 0; - /** - * Maximum number of records before we restart the task - * - * @var - */ - protected $maxrecs; + /** + * task state, either ok, maxmemory or maxrecords reached + * + * @var + */ + protected $current_state; - /** - * Boolean switch to stop the task - * - * @var - */ - protected $running = false; + /** + * maximum memory allowed + * + * @var + */ + protected $maxmegs; - /** - * current number of loops done - * - * @var - */ - protected $loop = 0; + /** + * the return value for the scheduler + * + * @var + */ + protected $return_value; + protected $runner; + private $input; + private $output; - /** - * max number of loops before the task is restarted - * - * @var - */ - protected $maxloops = 5; + /** + * delay between two loops + * + * @var + */ + protected $title; + protected $settings; + protected $crash_counter; + protected $status; + protected $active; + protected $debug = false; - /** - * task status, either 'tostop' or 'started' - * - * @var - */ - protected $task_status = 0; + public function get_status() + { + $conn = connection::getPDOConnection(); + $sql = 'SELECT status FROM task2 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->taskid)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + if ( ! $row) + throw new Exception('Unknown task id'); - /** - * task state, either ok, maxmemory or maxrecords reached - * - * @var - */ - protected $current_state; + return $row['status']; + } - /** - * maximum memory allowed - * - * @var - */ - protected $maxmegs; + public function printInterfaceHEAD() + { + return false; + } - /** - * the return value for the scheduler - * - * @var - */ - protected $return_value; - protected $runner; + public function printInterfaceJS() + { + return false; + } - private $input; - private $output; + public function getGraphicForm() + { + return false; + } - /** - * delay between two loops - * - * @var - */ - protected $title; - protected $settings; - protected $crash_counter; - protected $status; - protected $active; - protected $debug = false; - - public function get_status() - { - $conn = connection::getPDOConnection(); - $sql = 'SELECT status FROM task2 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->taskid)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - if(!$row) - throw new Exception('Unknown task id'); - - return $row['status']; - } - - public function printInterfaceHEAD() - { - return false; - } - - public function printInterfaceJS() - { - return false; - } - - public function getGraphicForm() - { - return false; - } - - public function set_status($status) - { - $av_status = array( - self::STATUS_STARTED - , self::STATUS_TOSTOP - , self::RETURNSTATUS_STOPPED - , self::RETURNSTATUS_TORESTART - , self::STATUS_TOSTART - ); - if(!in_array($status, $av_status)) - throw new Exception(sprintf('unknown status `%s`', $status)); + public function set_status($status) + { + $av_status = array( + self::STATUS_STARTED + , self::STATUS_TOSTOP + , self::RETURNSTATUS_STOPPED + , self::RETURNSTATUS_TORESTART + , self::STATUS_TOSTART + ); + if ( ! in_array($status, $av_status)) + throw new Exception(sprintf('unknown status `%s`', $status)); - $conn = connection::getPDOConnection(); + $conn = connection::getPDOConnection(); - $sql = 'UPDATE task2 SET status = :status WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':status' => $status, ':taskid' => $this->get_task_id())); - $stmt->closeCursor(); -$this->log(sprintf("task %d <- %s", $this->get_task_id(), $status)); - $this->task_status = $status; + $sql = 'UPDATE task2 SET status = :status WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':status' => $status, ':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + $this->log(sprintf("task %d <- %s", $this->get_task_id(), $status)); + $this->task_status = $status; - return $this->task_status; - } + return $this->task_status; + } // public function set_pid($pid) // { @@ -170,541 +164,505 @@ $this->log(sprintf("task %d <- %s", $this->get_task_id(), $status)); // // return $this; // } - // 'active' means 'auto-start when scheduler starts' - public function set_active($boolean) - { - $conn = connection::getPDOConnection(); - - $sql = 'UPDATE task2 SET active = :active WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':active' => ($boolean ? '1' : '0'), ':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - $this->active = !!$boolean; - - return $this; - } - - public function set_title($title) - { - $title = strip_tags($title); - $conn = connection::getPDOConnection(); - - $sql = 'UPDATE task2 SET name = :title WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':title' => $title, ':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - $this->title = $title; - - return $this; - } - - public function set_settings($settings) - { - $conn = connection::getPDOConnection(); - - $sql = 'UPDATE task2 SET settings = :settings WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':settings' => $settings, ':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - $this->settings = $settings; - - $this->load_settings(simplexml_load_string($settings)); - - return $this; - } - - public function reset_crash_counter() - { - $conn = connection::getPDOConnection(); - - $sql = 'UPDATE task2 SET crashed = 0 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - $this->crash_counter = 0; - - return $this; - } - - public function get_crash_counter() - { - return $this->crash_counter; - } - - public function increment_crash_counter() - { - $conn = connection::getPDOConnection(); - - $sql = 'UPDATE task2 SET crashed = crashed + 1 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - return $this->crash_counter++; - } - - public function get_settings() - { - return $this->settings; - } - - // 'active' means 'auto-start when scheduler starts' - public function is_active() - { - return $this->active; - } - - public function get_completed_percentage() - { - return $this->completed_percentage; - } - - protected $period = 10; - protected $taskid = NULL; - protected $system = ''; // "DARWIN", "WINDOWS" , "LINUX"... - protected $argt = array( - "--help" => array("set" => false, "values" => array(), "usage" => " (no help available)") - ); - - abstract public function getName(); - - abstract public function help(); - - function __construct($taskid) - { - $this->taskid = $taskid; - - phrasea::use_i18n(Session_Handler::get_locale()); - - $this->system = system_server::get_platform(); - - $this->launched_by = array_key_exists("REQUEST_URI", $_SERVER) ? self::LAUCHED_BY_BROWSER : self::LAUCHED_BY_COMMANDLINE; - if($this->system != "DARWIN" && $this->system != "WINDOWS" && $this->system != "LINUX") + // 'active' means 'auto-start when scheduler starts' + public function set_active($boolean) { - if($this->launched_by == self::LAUCHED_BY_COMMANDLINE) - { -// printf("Desole, ce programme ne fonctionne pas sous '" . $this->system . "'.\n"); - flush(); - } - exit(-1); - } - else - { - if($this->launched_by == self::LAUCHED_BY_COMMANDLINE) - { - flush(); - } + $conn = connection::getPDOConnection(); + + $sql = 'UPDATE task2 SET active = :active WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':active' => ($boolean ? '1' : '0'), ':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + + $this->active = ! ! $boolean; + + return $this; } - try + public function set_title($title) { - $conn = connection::getPDOConnection(); + $title = strip_tags($title); + $conn = connection::getPDOConnection(); + + $sql = 'UPDATE task2 SET name = :title WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':title' => $title, ':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + + $this->title = $title; + + return $this; } - catch(Exception $e) + + public function set_settings($settings) { - $this->log($e->getMessage()); - $this->log(("Warning : abox connection lost, restarting in 10 min.")); + $conn = connection::getPDOConnection(); - for($t = 60 * 10; $this->running && $t > 0; $t--) // DON'T do sleep(600) because it prevents ticks ! - sleep(1); + $sql = 'UPDATE task2 SET settings = :settings WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':settings' => $settings, ':taskid' => $this->get_task_id())); + $stmt->closeCursor(); - $this->running = false; + $this->settings = $settings; - return(''); + $this->load_settings(simplexml_load_string($settings)); + + return $this; } - $sql = 'SELECT crashed, pid, status, active, settings, name, completed, runner - FROM task2 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - if(!$row) - throw new Exception('Unknown task id'); - $this->title = $row['name']; - $this->crash_counter = (int) $row['crashed']; - $this->task_status = $row['status']; - $this->active = !!$row['active']; - $this->settings = $row['settings']; - $this->runner = $row['runner']; - $this->completed_percentage = (int) $row['completed']; - $this->load_settings(simplexml_load_string($row['settings'])); - return $this; - } + public function reset_crash_counter() + { + $conn = connection::getPDOConnection(); - public function get_runner() - { - return $this->runner; - } + $sql = 'UPDATE task2 SET crashed = 0 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->closeCursor(); - public function set_runner($runner) - { - $this->runner = $runner; + $this->crash_counter = 0; - $conn = connection::getPDOConnection(); - $sql = 'UPDATE task2 SET runner = :runner WHERE task_id = :taskid'; + return $this; + } - $params = array( - ':taskid' => $this->get_task_id() - , ':runner' => $this->runner + public function get_crash_counter() + { + return $this->crash_counter; + } + + public function increment_crash_counter() + { + $conn = connection::getPDOConnection(); + + $sql = 'UPDATE task2 SET crashed = crashed + 1 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + + return $this->crash_counter ++; + } + + public function get_settings() + { + return $this->settings; + } + + // 'active' means 'auto-start when scheduler starts' + public function is_active() + { + return $this->active; + } + + public function get_completed_percentage() + { + return $this->completed_percentage; + } + protected $period = 10; + protected $taskid = NULL; + protected $system = ''; // "DARWIN", "WINDOWS" , "LINUX"... + protected $argt = array( + "--help" => array("set" => false, "values" => array(), "usage" => " (no help available)") ); - $stmt = $conn->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + abstract public function getName(); - return $this; - } + abstract public function help(); - public function get_title() - { - return $this->title; - } - - public function delete() - { - if(!$this->get_pid()) // do not delete a running task + function __construct($taskid) { - $conn = connection::getPDOConnection(); - $registry = registry::get_instance(); - $sql = "DELETE FROM task2 WHERE task_id = :task_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $stmt->closeCursor(); + $this->taskid = $taskid; - $lock_file = $registry->get('GV_RootPath') . 'tmp/locks/task_' . $this->get_task_id() . '.lock'; - @unlink($lock_file); - } - } + phrasea::use_i18n(Session_Handler::get_locale()); - protected function check_memory_usage() - { - $current_memory = memory_get_usage(); - if($current_memory >> 20 >= $this->maxmegs) - { - $this->log(sprintf( - "Max memory (%s M) reached (current is %s M)" - , $this->maxmegs - , $current_memory - )); - $this->current_state = self::STATE_MAXMEGSREACHED; + $this->system = system_server::get_platform(); + + $this->launched_by = array_key_exists("REQUEST_URI", $_SERVER) ? self::LAUCHED_BY_BROWSER : self::LAUCHED_BY_COMMANDLINE; + if ($this->system != "DARWIN" && $this->system != "WINDOWS" && $this->system != "LINUX") { + if ($this->launched_by == self::LAUCHED_BY_COMMANDLINE) { +// printf("Desole, ce programme ne fonctionne pas sous '" . $this->system . "'.\n"); + flush(); + } + exit(-1); + } else { + if ($this->launched_by == self::LAUCHED_BY_COMMANDLINE) { + flush(); + } + } + + try { + $conn = connection::getPDOConnection(); + } catch (Exception $e) { + $this->log($e->getMessage()); + $this->log(("Warning : abox connection lost, restarting in 10 min.")); + + for ($t = 60 * 10; $this->running && $t > 0; $t -- ) // DON'T do sleep(600) because it prevents ticks ! + sleep(1); + + $this->running = false; + + return(''); + } + $sql = 'SELECT crashed, pid, status, active, settings, name, completed, runner + FROM task2 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + if ( ! $row) + throw new Exception('Unknown task id'); + $this->title = $row['name']; + $this->crash_counter = (int) $row['crashed']; + $this->task_status = $row['status']; + $this->active = ! ! $row['active']; + $this->settings = $row['settings']; + $this->runner = $row['runner']; + $this->completed_percentage = (int) $row['completed']; + $this->load_settings(simplexml_load_string($row['settings'])); + + return $this; } - return $this; - } - - protected function check_records_done() - { - if($this->records_done >= (int) ($this->maxrecs)) + public function get_runner() { - $this->current_state = self::STATE_MAXRECSDONE; + return $this->runner; } - return $this; - } - - public function set_last_exec_time() - { - $conn = connection::getPDOConnection(); - $sql = 'UPDATE task2 SET last_exec_time=NOW() WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - - return $this; - } - - public function get_pid() - { - $pid = NULL; - - $taskid = $this->get_task_id(); - - $registry = registry::get_instance(); - system_file::mkdir($lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'); - - if(($fd = fopen(($lockfile = ($lockdir . 'task_' . $taskid . '.lock')), 'a+'))) + public function set_runner($runner) { + $this->runner = $runner; + + $conn = connection::getPDOConnection(); + $sql = 'UPDATE task2 SET runner = :runner WHERE task_id = :taskid'; + + $params = array( + ':taskid' => $this->get_task_id() + , ':runner' => $this->runner + ); + + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); + + return $this; + } + + public function get_title() + { + return $this->title; + } + + public function delete() + { + if ( ! $this->get_pid()) { // do not delete a running task + $conn = connection::getPDOConnection(); + $registry = registry::get_instance(); + $sql = "DELETE FROM task2 WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $stmt->closeCursor(); + + $lock_file = $registry->get('GV_RootPath') . 'tmp/locks/task_' . $this->get_task_id() . '.lock'; + @unlink($lock_file); + } + } + + protected function check_memory_usage() + { + $current_memory = memory_get_usage(); + if ($current_memory >> 20 >= $this->maxmegs) { + $this->log(sprintf( + "Max memory (%s M) reached (current is %s M)" + , $this->maxmegs + , $current_memory + )); + $this->current_state = self::STATE_MAXMEGSREACHED; + } + + return $this; + } + + protected function check_records_done() + { + if ($this->records_done >= (int) ($this->maxrecs)) { + $this->current_state = self::STATE_MAXRECSDONE; + } + + return $this; + } + + public function set_last_exec_time() + { + $conn = connection::getPDOConnection(); + $sql = 'UPDATE task2 SET last_exec_time=NOW() WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + + return $this; + } + + public function get_pid() + { + $pid = NULL; + + $taskid = $this->get_task_id(); + + $registry = registry::get_instance(); + system_file::mkdir($lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'); + + if (($fd = fopen(($lockfile = ($lockdir . 'task_' . $taskid . '.lock')), 'a+'))) { // ************************************************ // file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : fopen(%s) \n", __FILE__, __LINE__, $lockfile), FILE_APPEND); - if(flock($fd, LOCK_EX | LOCK_NB) === FALSE) - { - // already locked ? : task running - $pid = fgets($fd); + if (flock($fd, LOCK_EX | LOCK_NB) === FALSE) { + // already locked ? : task running + $pid = fgets($fd); // ************************************************ // file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : can't flock() : pid=%s \n", __FILE__, __LINE__, $pid), FILE_APPEND); + } else { + // can lock : not running +// ************************************************ +// file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : NOT RUNNING can flock() : pid=%s \n", __FILE__, __LINE__, file_get_contents($lockfile)), FILE_APPEND); + flock($fd, LOCK_UN); + } + fclose($fd); + } + + return $pid; + } + /* + public function is_running() + { + $retval = false; + $registry = registry::get_instance(); + $lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'; + $tasklock = fopen($lockfile = ($lockdir . '/task_' . $this->get_task_id() . '.lock'), 'a+'); + + if (flock($tasklock, LOCK_SH | LOCK_NB) != true) + { + $retval = true; } else { - // can lock : not running -// ************************************************ -// file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : NOT RUNNING can flock() : pid=%s \n", __FILE__, __LINE__, file_get_contents($lockfile)), FILE_APPEND); - flock($fd, LOCK_UN); + ftruncate($tasklock, 0); + flock($tasklock, LOCK_UN | LOCK_NB); + fclose($tasklock); + unlink($lockfile); } - fclose($fd); - } - return $pid; - } - - /* - public function is_running() - { - $retval = false; - $registry = registry::get_instance(); - $lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'; - $tasklock = fopen($lockfile = ($lockdir . '/task_' . $this->get_task_id() . '.lock'), 'a+'); - - if (flock($tasklock, LOCK_SH | LOCK_NB) != true) - { - $retval = true; - } - else - { - ftruncate($tasklock, 0); - flock($tasklock, LOCK_UN | LOCK_NB); - fclose($tasklock); - unlink($lockfile); - } - - return $retval; - } - */ - - protected function check_current_state() - { - switch($this->current_state) - { - case self::STATE_MAXMEGSREACHED: - case self::STATE_MAXRECSDONE: - default: - if($this->get_runner() == self::RUNNER_SCHEDULER) - { - $this->task_status = self::STATUS_TOSTOP; - $this->return_value = self::RETURNSTATUS_TORESTART; - } - break; - case self::STATE_FINISHED: - $this->task_status = self::STATUS_TOSTOP; - if($this->suicidable === true) - { - $this->return_value = self::RETURNSTATUS_TODELETE; - $this->log('will hang myself'); - } - else - { - $this->return_value = self::RETURNSTATUS_STOPPED; - } - break; - case self::STATE_OK: - - break; - } - $this->apply_task_status(); - - return $this; - } - - protected function check_task_status() - { - try - { - $conn = connection::getPDOConnection(); - $sql = "SELECT status FROM task2 WHERE task_id = :taskid"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - if(!$row || $row['status'] == 'tostop') - { - $this->task_status = self::STATUS_TOSTOP; - $this->return_value = self::RETURNSTATUS_STOPPED; + return $retval; } - } - catch(Exception $e) + */ + + protected function check_current_state() { - $this->return_value = self::RETURNSTATUS_STOPPED; - $this->task_status = self::STATUS_TOSTOP; + switch ($this->current_state) { + case self::STATE_MAXMEGSREACHED: + case self::STATE_MAXRECSDONE: + default: + if ($this->get_runner() == self::RUNNER_SCHEDULER) { + $this->task_status = self::STATUS_TOSTOP; + $this->return_value = self::RETURNSTATUS_TORESTART; + } + break; + case self::STATE_FINISHED: + $this->task_status = self::STATUS_TOSTOP; + if ($this->suicidable === true) { + $this->return_value = self::RETURNSTATUS_TODELETE; + $this->log('will hang myself'); + } else { + $this->return_value = self::RETURNSTATUS_STOPPED; + } + break; + case self::STATE_OK: + + break; + } + $this->apply_task_status(); + + return $this; } - $this->apply_task_status(); - return $this; - } - - public function set_running($stat) - { - $this->running = $stat; - } - - protected function pause($when_started=0) - { - $this->log($this->records_done . ' records done'); - if($this->running)// && $this->records_done == 0) + protected function check_task_status() { - $when_started = time() - $when_started; - if($when_started < $this->period) - { - $conn = connection::getPDOConnection(); - $conn->close(); - unset($conn); - for($t = $this->period - $when_started; $this->running && $t > 0; $t--) // DON'T do sleep($this->period - $when_started) because it prevents ticks ! - sleep(1); - } - } - } + try { + $conn = connection::getPDOConnection(); + $sql = "SELECT status FROM task2 WHERE task_id = :taskid"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + if ( ! $row || $row['status'] == 'tostop') { + $this->task_status = self::STATUS_TOSTOP; + $this->return_value = self::RETURNSTATUS_STOPPED; + } + } catch (Exception $e) { + $this->return_value = self::RETURNSTATUS_STOPPED; + $this->task_status = self::STATUS_TOSTOP; + } + $this->apply_task_status(); - final public function run($runner, $input=null, $output = null) - { - $this->input = $input; - $this->output = $output; + return $this; + } + + public function set_running($stat) + { + $this->running = $stat; + } + + protected function pause($when_started = 0) + { + $this->log($this->records_done . ' records done'); + if ($this->running) {// && $this->records_done == 0) + $when_started = time() - $when_started; + if ($when_started < $this->period) { + $conn = connection::getPDOConnection(); + $conn->close(); + unset($conn); + for ($t = $this->period - $when_started; $this->running && $t > 0; $t -- ) // DON'T do sleep($this->period - $when_started) because it prevents ticks ! + sleep(1); + } + } + } + + final public function run($runner, $input = null, $output = null) + { + $this->input = $input; + $this->output = $output; // ************************************************ // file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : LAUNCHING : tid=%s \n", __FILE__, __LINE__, $this->get_task_id()), FILE_APPEND); - $taskid = $this->get_task_id(); - $conn = connection::getPDOConnection(); + $taskid = $this->get_task_id(); + $conn = connection::getPDOConnection(); - $registry = registry::get_instance(); - system_file::mkdir($lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'); - $locker = true; - $tasklock = fopen(($lockfile = ($lockdir . 'task_' . $taskid . '.lock')), 'a+'); - if(flock($tasklock, LOCK_EX | LOCK_NB, $locker) === FALSE) - { + $registry = registry::get_instance(); + system_file::mkdir($lockdir = $registry->get('GV_RootPath') . 'tmp/locks/'); + $locker = true; + $tasklock = fopen(($lockfile = ($lockdir . 'task_' . $taskid . '.lock')), 'a+'); + if (flock($tasklock, LOCK_EX | LOCK_NB, $locker) === FALSE) { // ************************************************ // file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : LAUNCH OPENED AND CANT LOCK : pid=%s \n", __FILE__, __LINE__, getmypid()), FILE_APPEND); - $this->log("runtask::ERROR : task already running."); - fclose($tasklock); + $this->log("runtask::ERROR : task already running."); + fclose($tasklock); - return; - } - else - { - ftruncate($tasklock, 0); - fwrite($tasklock, '' . getmypid()); - fflush($tasklock); + return; + } else { + ftruncate($tasklock, 0); + fwrite($tasklock, '' . getmypid()); + fflush($tasklock); // ************************************************ // file_put_contents("/tmp/scheduler2.log", sprintf("%s [%d] : LAUNCH OPENED AND LOCKED : pid=%s \n", __FILE__, __LINE__, getmypid()), FILE_APPEND); - } + } - $this->set_runner($runner); + $this->set_runner($runner); // $this->set_pid(getmypid()); - $this->set_status(self::STATUS_STARTED); + $this->set_status(self::STATUS_STARTED); - $this->running = true; + $this->running = true; - $this->run2(); + $this->run2(); - flock($tasklock, LOCK_UN | LOCK_NB); - ftruncate($tasklock, 0); - fclose($tasklock); - @unlink($lockfile); + flock($tasklock, LOCK_UN | LOCK_NB); + ftruncate($tasklock, 0); + fclose($tasklock); + @unlink($lockfile); - if($this->return_value == self::RETURNSTATUS_TODELETE) - $this->delete(); - else - $this->set_status($this->return_value); + if ($this->return_value == self::RETURNSTATUS_TODELETE) + $this->delete(); + else + $this->set_status($this->return_value); - return $this; - } - - abstract protected function run2(); - - protected function load_settings(SimpleXMLElement $sx_task_settings) - { - $this->period = max(10, min(3600, (int) $sx_task_settings->period)); - $this->maxrecs = max(10, min(1000, (int) $sx_task_settings->maxrecs)); - $this->maxmegs = max(16, min(512, (int) $sx_task_settings->maxmegs)); - $this->record_buffer_size = max(1, min(100, (int) $sx_task_settings->flush)); - - return $this; - } - - protected function increment_loops() - { - if($this->get_runner() == self::RUNNER_SCHEDULER && $this->loop > $this->maxloops) - { - $this->log(sprintf(('%d loops done, restarting'), $this->loop)); - $this->task_status = self::STATUS_TOSTOP; - $this->return_value = self::RETURNSTATUS_TORESTART; - } - $this->apply_task_status(); - $this->loop++; - - return $this; - } - - public function apply_task_status() - { - if($this->task_status == self::STATUS_TOSTOP) - { - $this->running = false; + return $this; } - return $this; - } + abstract protected function run2(); - function traceRam($msg='') - { - static $lastt = null; - $t = explode(' ', ($ut = microtime())); - if($lastt === null) - $lastt = $t; - $dt = ($t[0] - $lastt[0]) + ($t[1] - $lastt[1]); - - $m = memory_get_usage() >> 10; - $d = debug_backtrace(false); - - $lastt = $t; - echo "\n" . memory_get_usage() . " -- " . memory_get_usage(true) . "\n"; - // print($s); - } - - public function log($message) - { - $registry = registry::get_instance(); - $logdir = $registry->get('GV_RootPath') . 'logs/'; - - logs::rotate($logdir . 'task_l_'.$this->taskid.'.log'); - logs::rotate($logdir . 'task_o_'.$this->taskid.'.log'); - logs::rotate($logdir . 'task_e_'.$this->taskid.'.log'); - - $date_obj = new DateTime(); - $message = sprintf("%s\t%s", $date_obj->format(DATE_ATOM), $message); - - if($this->output) + protected function load_settings(SimpleXMLElement $sx_task_settings) { - $this->output->writeln($message); - } - if( $this->input && !($this->input->getOption('nolog')) ) - { - file_put_contents($logdir . 'task_l_'.$this->taskid.'.log', $message."\n", FILE_APPEND); + $this->period = max(10, min(3600, (int) $sx_task_settings->period)); + $this->maxrecs = max(10, min(1000, (int) $sx_task_settings->maxrecs)); + $this->maxmegs = max(16, min(512, (int) $sx_task_settings->maxmegs)); + $this->record_buffer_size = max(1, min(100, (int) $sx_task_settings->flush)); + + return $this; } - return $this; - } + protected function increment_loops() + { + if ($this->get_runner() == self::RUNNER_SCHEDULER && $this->loop > $this->maxloops) { + $this->log(sprintf(('%d loops done, restarting'), $this->loop)); + $this->task_status = self::STATUS_TOSTOP; + $this->return_value = self::RETURNSTATUS_TORESTART; + } + $this->apply_task_status(); + $this->loop ++; + return $this; + } - public static function interfaceAvailable() - { - return true; - } + public function apply_task_status() + { + if ($this->task_status == self::STATUS_TOSTOP) { + $this->running = false; + } - /** - * - * @param appbox $appbox - * @param type $class_name - * @param type $settings - * @return task_abstract - */ - public static function create(appbox $appbox, $class_name, $settings = null) - { - if(!class_exists($class_name)) - throw new Exception('Unknown task class'); + return $this; + } - $sql = 'INSERT INTO task2 + function traceRam($msg = '') + { + static $lastt = null; + $t = explode(' ', ($ut = microtime())); + if ($lastt === null) + $lastt = $t; + $dt = ($t[0] - $lastt[0]) + ($t[1] - $lastt[1]); + + $m = memory_get_usage() >> 10; + $d = debug_backtrace(false); + + $lastt = $t; + echo "\n" . memory_get_usage() . " -- " . memory_get_usage(true) . "\n"; + // print($s); + } + + public function log($message) + { + $registry = registry::get_instance(); + $logdir = $registry->get('GV_RootPath') . 'logs/'; + + logs::rotate($logdir . 'task_l_' . $this->taskid . '.log'); + logs::rotate($logdir . 'task_o_' . $this->taskid . '.log'); + logs::rotate($logdir . 'task_e_' . $this->taskid . '.log'); + + $date_obj = new DateTime(); + $message = sprintf("%s\t%s", $date_obj->format(DATE_ATOM), $message); + + if ($this->output) { + $this->output->writeln($message); + } + if ($this->input && ! ($this->input->getOption('nolog'))) { + file_put_contents($logdir . 'task_l_' . $this->taskid . '.log', $message . "\n", FILE_APPEND); + } + + return $this; + } + + public static function interfaceAvailable() + { + return true; + } + + /** + * + * @param appbox $appbox + * @param type $class_name + * @param type $settings + * @return task_abstract + */ + public static function create(appbox $appbox, $class_name, $settings = null) + { + if ( ! class_exists($class_name)) + throw new Exception('Unknown task class'); + + $sql = 'INSERT INTO task2 (task_id, usr_id_owner, status, crashed, active, name, last_exec_time, class, settings) VALUES @@ -712,67 +670,62 @@ $this->log(sprintf("task %d <- %s", $this->get_task_id(), $status)); :name, "0000/00/00 00:00:00", :class, :settings)'; - if($settings && !DOMDocument::loadXML($settings)) - throw new Exception('settings invalide'); - elseif(!$settings) - $settings = "\n\n"; + if ($settings && ! DOMDocument::loadXML($settings)) + throw new Exception('settings invalide'); + elseif ( ! $settings) + $settings = "\n\n"; - $params = array( - ':active' => 1 - , ':name' => $class_name::getName() - , ':class' => $class_name - , ':settings' => $settings - ); - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $params = array( + ':active' => 1 + , ':name' => $class_name::getName() + , ':class' => $class_name + , ':settings' => $settings + ); + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $tid = $appbox->get_connection()->lastInsertId(); - - return new $class_name($tid); - } - - public function getUsage() - { - global $argc, $argv; - $t = "usage: " . $argv[0] . " [options]\noptions:\n"; - foreach($this->argt as $n => $v) - $t .= "\t" . $n . $v["usage"] . "\n"; - - return($t); - } - - public function get_argt() - { - return $this->argt; - } - - public function get_task_id() - { - return $this->taskid; - } - - protected $completed_percentage; - - function setProgress($done, $todo) - { - $p = ($todo > 0) ? ((100 * $done) / $todo) : -1; - - try - { - $conn = connection::getPDOConnection(); - $sql = 'UPDATE task2 SET completed = :p WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':p' => $p, ':taskid' => $this->get_task_id())); - $stmt->closeCursor(); - $this->completed_percentage = $p; - } - catch(Exception $e) - { + $tid = $appbox->get_connection()->lastInsertId(); + return new $class_name($tid); } - return $this; - } + public function getUsage() + { + global $argc, $argv; + $t = "usage: " . $argv[0] . " [options]\noptions:\n"; + foreach ($this->argt as $n => $v) + $t .= "\t" . $n . $v["usage"] . "\n"; + return($t); + } + + public function get_argt() + { + return $this->argt; + } + + public function get_task_id() + { + return $this->taskid; + } + protected $completed_percentage; + + function setProgress($done, $todo) + { + $p = ($todo > 0) ? ((100 * $done) / $todo) : -1; + + try { + $conn = connection::getPDOConnection(); + $sql = 'UPDATE task2 SET completed = :p WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':p' => $p, ':taskid' => $this->get_task_id())); + $stmt->closeCursor(); + $this->completed_percentage = $p; + } catch (Exception $e) { + + } + + return $this; + } } diff --git a/lib/classes/task/appboxAbstract.class.php b/lib/classes/task/appboxAbstract.class.php index 0496f397ff..bf69235817 100644 --- a/lib/classes/task/appboxAbstract.class.php +++ b/lib/classes/task/appboxAbstract.class.php @@ -18,146 +18,127 @@ abstract class task_appboxAbstract extends task_abstract { - abstract protected function retrieve_content(appbox $appbox); + abstract protected function retrieve_content(appbox $appbox); - abstract protected function process_one_content(appbox $appbox, Array $row); + abstract protected function process_one_content(appbox $appbox, Array $row); - abstract protected function post_process_one_content(appbox $appbox, Array $row); + abstract protected function post_process_one_content(appbox $appbox, Array $row); - protected function run2() - { - while ($this->running) + protected function run2() { - try - { - $conn = connection::getPDOConnection(); - } - catch (Exception $e) - { - $this->log($e->getMessage()); - $this->log(("Warning : abox connection lost, restarting in 10 min.")); - sleep(60 * 10); - $this->running = false; - $this->return_value = self::RETURNSTATUS_TORESTART; + while ($this->running) { + try { + $conn = connection::getPDOConnection(); + } catch (Exception $e) { + $this->log($e->getMessage()); + $this->log(("Warning : abox connection lost, restarting in 10 min.")); + sleep(60 * 10); + $this->running = false; + $this->return_value = self::RETURNSTATUS_TORESTART; + + return; + } + + $this->set_last_exec_time(); + + try { + $sql = 'SELECT task2.* FROM task2 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + $this->records_done = 0; + $duration = time(); + } catch (Exception $e) { + $this->task_status = self::STATUS_TOSTOP; + $this->return_value = self::RETURNSTATUS_STOPPED; + $rs = array(); + } + if ($row) { + if ( ! $this->running) + break; + + $appbox = appbox::get_instance(\bootstrap::getCore()); + try { + $this->load_settings(simplexml_load_string($row['settings'])); + } catch (Exception $e) { + $this->log($e->getMessage()); + continue; + } + + $this->current_state = self::STATE_OK; + $this->process($appbox) + ->check_current_state(); + } + + $this->increment_loops(); + $this->pause($duration); + } return; - } + } - $this->set_last_exec_time(); - - try - { - $sql = 'SELECT task2.* FROM task2 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $this->records_done = 0; - $duration = time(); - } - catch (Exception $e) - { - $this->task_status = self::STATUS_TOSTOP; - $this->return_value = self::RETURNSTATUS_STOPPED; - $rs = array(); - } - if ($row) - { - if (!$this->running) - break; - - $appbox = appbox::get_instance(\bootstrap::getCore()); - try - { - $this->load_settings(simplexml_load_string($row['settings'])); - } - catch (Exception $e) - { - $this->log($e->getMessage()); - continue; + /** + * + * @return + */ + protected function process(appbox $appbox) + { + $conn = $appbox->get_connection(); + $tsub = array(); + try { + /** + * GET THE RECORDS TO PROCESS ON CURRENT SBAS + */ + $rs = $this->retrieve_content($appbox); + } catch (Exception $e) { + $this->log('Error : ' . $e->getMessage()); + $rs = array(); } - $this->current_state = self::STATE_OK; - $this->process($appbox) - ->check_current_state(); - } + $rowstodo = count($rs); + $rowsdone = 0; - $this->increment_loops(); - $this->pause($duration); - } + if ($rowstodo > 0) + $this->setProgress(0, $rowstodo); - return; - } + foreach ($rs as $row) { + try { - /** - * - * @return - */ - protected function process(appbox $appbox) - { - $conn = $appbox->get_connection(); - $tsub = array(); - try - { - /** - * GET THE RECORDS TO PROCESS ON CURRENT SBAS - */ - $rs = $this->retrieve_content($appbox); - } - catch (Exception $e) - { - $this->log('Error : ' . $e->getMessage()); - $rs = array(); - } + /** + * PROCESS ONE RECORD + */ + $this->process_one_content($appbox, $row); + } catch (Exception $e) { + $this->log("Exception : " . $e->getMessage() + . " " . basename($e->getFile()) . " " . $e->getLine()); + } - $rowstodo = count($rs); - $rowsdone = 0; + $this->records_done ++; + $this->setProgress($rowsdone, $rowstodo); - if ($rowstodo > 0) - $this->setProgress(0, $rowstodo); + /** + * POST COIT + */ + $this->post_process_one_content($appbox, $row); - foreach ($rs as $row) - { - try - { + $this->check_memory_usage() + ->check_records_done() + ->check_task_status(); - /** - * PROCESS ONE RECORD - */ - $this->process_one_content($appbox, $row); - } - catch (Exception $e) - { - $this->log("Exception : " . $e->getMessage() - . " " . basename($e->getFile()) . " " . $e->getLine()); - } - - $this->records_done++; - $this->setProgress($rowsdone, $rowstodo); - - /** - * POST COIT - */ - $this->post_process_one_content($appbox, $row); - - $this->check_memory_usage() - ->check_records_done() - ->check_task_status(); - - if (!$this->running) - break; - } + if ( ! $this->running) + break; + } - $this->check_memory_usage() + $this->check_memory_usage() ->check_records_done() ->check_task_status(); - if ($rowstodo > 0) - $this->setProgress(0, 0); - - return $this; - } + if ($rowstodo > 0) + $this->setProgress(0, 0); + return $this; + } } diff --git a/lib/classes/task/databoxAbstract.class.php b/lib/classes/task/databoxAbstract.class.php index efb99232f1..3bcb8e8779 100644 --- a/lib/classes/task/databoxAbstract.class.php +++ b/lib/classes/task/databoxAbstract.class.php @@ -21,176 +21,154 @@ abstract class task_databoxAbstract extends task_abstract // // abstract public function getName(); - protected $mono_sbas_id; + protected $mono_sbas_id; - abstract protected function retrieve_sbas_content(databox $databox); + abstract protected function retrieve_sbas_content(databox $databox); - abstract protected function process_one_content(databox $databox, Array $row); + abstract protected function process_one_content(databox $databox, Array $row); - abstract protected function flush_records_sbas(); + abstract protected function flush_records_sbas(); - abstract protected function post_process_one_content(databox $databox, Array $row); + abstract protected function post_process_one_content(databox $databox, Array $row); - protected function run2() - { - while($this->running) + protected function run2() { - try - { - $conn = connection::getPDOConnection(); - } - catch(Exception $e) - { - $this->log($e->getMessage()); - $this->log(("Warning : abox connection lost, restarting in 10 min.")); + while ($this->running) { + try { + $conn = connection::getPDOConnection(); + } catch (Exception $e) { + $this->log($e->getMessage()); + $this->log(("Warning : abox connection lost, restarting in 10 min.")); - for($t = 60 * 10; $this->running && $t; $t--) // DON'T do sleep(600) because it prevents ticks ! - sleep(1); + for ($t = 60 * 10; $this->running && $t; $t -- ) // DON'T do sleep(600) because it prevents ticks ! + sleep(1); - $this->running = false; - $this->return_value = self::RETURNSTATUS_TORESTART; + $this->running = false; + $this->return_value = self::RETURNSTATUS_TORESTART; - return; - } + return; + } - $this->set_last_exec_time(); + $this->set_last_exec_time(); - try - { - $sql = 'SELECT sbas_id, task2.* FROM sbas, task2 WHERE task_id = :taskid'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':taskid' => $this->get_task_id())); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $this->records_done = 0; - $duration = time(); - } - catch(Exception $e) - { - $this->task_status = self::STATUS_TOSTOP; - $this->return_value = self::RETURNSTATUS_STOPPED; - $rs = array(); - } - foreach($rs as $row) - { - if(!$this->running) - break; + try { + $sql = 'SELECT sbas_id, task2.* FROM sbas, task2 WHERE task_id = :taskid'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':taskid' => $this->get_task_id())); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + $this->records_done = 0; + $duration = time(); + } catch (Exception $e) { + $this->task_status = self::STATUS_TOSTOP; + $this->return_value = self::RETURNSTATUS_STOPPED; + $rs = array(); + } + foreach ($rs as $row) { + if ( ! $this->running) + break; - $this->sbas_id = (int) $row['sbas_id']; + $this->sbas_id = (int) $row['sbas_id']; - if($this->mono_sbas_id && $this->sbas_id !== $this->mono_sbas_id) - { - continue; + if ($this->mono_sbas_id && $this->sbas_id !== $this->mono_sbas_id) { + continue; + } + if ($this->mono_sbas_id) { + $this->log('This task works on ' . phrasea::sbas_names($this->mono_sbas_id)); + } + + try { + $this->load_settings(simplexml_load_string($row['settings'])); + } catch (Exception $e) { + $this->log($e->getMessage()); + continue; + } + + $this->current_state = self::STATE_OK; + $this->process_sbas()->check_current_state(); + $this->process_sbas()->flush_records_sbas(); + } + + $this->increment_loops(); + $this->pause($duration); } - if($this->mono_sbas_id) - { - $this->log('This task works on ' . phrasea::sbas_names($this->mono_sbas_id)); - } - - try - { - $this->load_settings(simplexml_load_string($row['settings'])); - } - catch(Exception $e) - { - $this->log($e->getMessage()); - continue; - } - - $this->current_state = self::STATE_OK; $this->process_sbas()->check_current_state(); $this->process_sbas()->flush_records_sbas(); - } - $this->increment_loops(); - $this->pause($duration); + $this->set_status($this->return_value); + + + return; } - $this->process_sbas()->check_current_state(); - $this->process_sbas()->flush_records_sbas(); - $this->set_status($this->return_value); - - - return; - } - - /** - * - * @return - */ - protected function process_sbas() - { - $tsub = array(); - $connbas = false; - - try + /** + * + * @return + */ + protected function process_sbas() { - $databox = databox::get_instance($this->sbas_id); - $connbas = $databox->get_connection(); - /** - * GET THE RECORDS TO PROCESS ON CURRENT SBAS - */ - $rs = $this->retrieve_sbas_content($databox); - } - catch(Exception $e) - { - $this->log('Error : ' . $e->getMessage()); - $rs = array(); - } + $tsub = array(); + $connbas = false; - $rowstodo = count($rs); - $rowsdone = 0; + try { + $databox = databox::get_instance($this->sbas_id); + $connbas = $databox->get_connection(); + /** + * GET THE RECORDS TO PROCESS ON CURRENT SBAS + */ + $rs = $this->retrieve_sbas_content($databox); + } catch (Exception $e) { + $this->log('Error : ' . $e->getMessage()); + $rs = array(); + } - if($rowstodo > 0) - $this->setProgress(0, $rowstodo); + $rowstodo = count($rs); + $rowsdone = 0; - foreach($rs as $row) - { - try - { + if ($rowstodo > 0) + $this->setProgress(0, $rowstodo); - /** - * PROCESS ONE RECORD - */ - $this->process_one_content($databox, $row); - } - catch(Exception $e) - { - $this->log("Exception : " . $e->getMessage() - . " " . basename($e->getFile()) . " " . $e->getLine()); - } + foreach ($rs as $row) { + try { - $this->records_done++; - $this->setProgress($rowsdone, $rowstodo); + /** + * PROCESS ONE RECORD + */ + $this->process_one_content($databox, $row); + } catch (Exception $e) { + $this->log("Exception : " . $e->getMessage() + . " " . basename($e->getFile()) . " " . $e->getLine()); + } - /** - * POST COIT - */ - $this->post_process_one_content($databox, $row); + $this->records_done ++; + $this->setProgress($rowsdone, $rowstodo); - $this->check_memory_usage() - ->check_records_done() - ->check_task_status(); + /** + * POST COIT + */ + $this->post_process_one_content($databox, $row); - if(!$this->running) - break; - } + $this->check_memory_usage() + ->check_records_done() + ->check_task_status(); + + if ( ! $this->running) + break; + } - $this->check_memory_usage() + $this->check_memory_usage() ->check_records_done() ->check_task_status(); - if($connbas instanceof PDO) - { - $connbas->close(); - unset($connbas); + if ($connbas instanceof PDO) { + $connbas->close(); + unset($connbas); + } + + if ($rowstodo > 0) + $this->setProgress(0, 0); + + return $this; } - - if($rowstodo > 0) - $this->setProgress(0, 0); - - return $this; - } - } diff --git a/lib/classes/task/manager.class.php b/lib/classes/task/manager.class.php index b366535e23..9208893d56 100644 --- a/lib/classes/task/manager.class.php +++ b/lib/classes/task/manager.class.php @@ -17,80 +17,72 @@ */ class task_manager { - const STATUS_SCHED_STOPPED = 'stopped'; - const STATUS_SCHED_STOPPING = 'stopping'; - const STATUS_SCHED_STARTED = 'started'; - const STATUS_SCHED_TOSTOP = 'tostop'; + const STATUS_SCHED_STOPPED = 'stopped'; + const STATUS_SCHED_STOPPING = 'stopping'; + const STATUS_SCHED_STARTED = 'started'; + const STATUS_SCHED_TOSTOP = 'tostop'; - protected $appbox; - protected $tasks; + protected $appbox; + protected $tasks; - public function __construct(appbox &$appbox) - { - $this->appbox = $appbox; - - return $this; - } - - public function old_get_tasks($refresh = false) - { - if ($this->tasks && !$refresh) - - return $this->tasks; - $sql = "SELECT task2.* FROM task2 ORDER BY task_id ASC"; - $stmt = $this->appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $tasks = array(); - - foreach ($rs as $row) + public function __construct(appbox &$appbox) { - $classname = $row['class']; - if (!class_exists($classname)) - continue; - try - { - $tasks[$row['task_id']] = new $classname($row['task_id']); - } - catch (Exception $e) - { + $this->appbox = $appbox; - } + return $this; } - $this->tasks = $tasks; - - return $this->tasks; - } - - public function get_tasks($refresh = false) - { - if ($this->tasks && !$refresh) - - return $this->tasks; - - $sql = "SELECT task2.* FROM task2 ORDER BY task_id ASC"; - $stmt = $this->appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $tasks = array(); - - $appbox = \appbox::get_instance(\bootstrap::getCore()); - $lockdir = $appbox->get_registry()->get('GV_RootPath') . 'tmp/locks/'; - - foreach ($rs as $row) + public function old_get_tasks($refresh = false) { - $row['pid'] = NULL; + if ($this->tasks && ! $refresh) + return $this->tasks; + $sql = "SELECT task2.* FROM task2 ORDER BY task_id ASC"; + $stmt = $this->appbox->get_connection()->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $classname = $row['class']; - if (!class_exists($classname)) - continue; - try - { + $tasks = array(); + + foreach ($rs as $row) { + $classname = $row['class']; + if ( ! class_exists($classname)) + continue; + try { + $tasks[$row['task_id']] = new $classname($row['task_id']); + } catch (Exception $e) { + + } + } + + $this->tasks = $tasks; + + return $this->tasks; + } + + public function get_tasks($refresh = false) + { + if ($this->tasks && ! $refresh) + return $this->tasks; + + $sql = "SELECT task2.* FROM task2 ORDER BY task_id ASC"; + $stmt = $this->appbox->get_connection()->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $tasks = array(); + + $appbox = \appbox::get_instance(\bootstrap::getCore()); + $lockdir = $appbox->get_registry()->get('GV_RootPath') . 'tmp/locks/'; + + foreach ($rs as $row) { + $row['pid'] = NULL; + + $classname = $row['class']; + if ( ! class_exists($classname)) + continue; + try { // if( ($lock = fopen( $lockdir . 'task.'.$row['task_id'].'.lock', 'a+')) ) // { // if (flock($lock, LOCK_SH | LOCK_NB) === FALSE) @@ -105,130 +97,116 @@ class task_manager // } // fclose($lock); // } - $tasks[$row['task_id']] = new $classname($row['task_id']); - } - catch (Exception $e) - { + $tasks[$row['task_id']] = new $classname($row['task_id']); + } catch (Exception $e) { - } + } + } + + $this->tasks = $tasks; + + return $this->tasks; } - $this->tasks = $tasks; - - return $this->tasks; - } - - /** - * - * @param $task_id - * @return task_abstract - */ - public function get_task($task_id) - { - $tasks = $this->get_tasks(); - - if (!isset($tasks[$task_id])) - throw new Exception('Unknown task_id'); - - return $tasks[$task_id]; - } - - public function set_sched_status($status) - { - $av_status = array( - self::STATUS_SCHED_STARTED - , self::STATUS_SCHED_STOPPED - , self::STATUS_SCHED_STOPPING - , self::STATUS_SCHED_TOSTOP - ); - - if (!in_array($status, $av_status)) - throw new Exception(sprintf('unknown status `%s` ', $status)); - - $sql = "UPDATE sitepreff SET schedstatus = :schedstatus, schedqtime=NOW()"; - $stmt = $this->appbox->get_connection()->prepare($sql); - $stmt->execute(array(':schedstatus' => $status)); - $stmt->closeCursor(); - - return $this; - } - - public function get_scheduler_state() - { - $pid = NULL; - $appbox = appbox::get_instance(\bootstrap::getCore()); - $lockdir = $appbox->get_registry()->get('GV_RootPath') . 'tmp/locks/'; - if( ($schedlock = fopen( $lockdir . 'scheduler.lock', 'a+')) ) + /** + * + * @param $task_id + * @return task_abstract + */ + public function get_task($task_id) { - if (flock($schedlock, LOCK_SH | LOCK_NB) === FALSE) - { - // already locked : running ! - $pid = trim(fgets($schedlock, 512)); - } - else - { - // can lock : not running - flock($schedlock, LOCK_UN); - } - fclose($schedlock); + $tasks = $this->get_tasks(); + + if ( ! isset($tasks[$task_id])) + throw new Exception('Unknown task_id'); + + return $tasks[$task_id]; } - $sql = "SELECT UNIX_TIMESTAMP()-UNIX_TIMESTAMP(schedqtime) AS qdelay + public function set_sched_status($status) + { + $av_status = array( + self::STATUS_SCHED_STARTED + , self::STATUS_SCHED_STOPPED + , self::STATUS_SCHED_STOPPING + , self::STATUS_SCHED_TOSTOP + ); + + if ( ! in_array($status, $av_status)) + throw new Exception(sprintf('unknown status `%s` ', $status)); + + $sql = "UPDATE sitepreff SET schedstatus = :schedstatus, schedqtime=NOW()"; + $stmt = $this->appbox->get_connection()->prepare($sql); + $stmt->execute(array(':schedstatus' => $status)); + $stmt->closeCursor(); + + return $this; + } + + public function get_scheduler_state() + { + $pid = NULL; + $appbox = appbox::get_instance(\bootstrap::getCore()); + $lockdir = $appbox->get_registry()->get('GV_RootPath') . 'tmp/locks/'; + if (($schedlock = fopen($lockdir . 'scheduler.lock', 'a+'))) { + if (flock($schedlock, LOCK_SH | LOCK_NB) === FALSE) { + // already locked : running ! + $pid = trim(fgets($schedlock, 512)); + } else { + // can lock : not running + flock($schedlock, LOCK_UN); + } + fclose($schedlock); + } + + $sql = "SELECT UNIX_TIMESTAMP()-UNIX_TIMESTAMP(schedqtime) AS qdelay , schedstatus AS status FROM sitepreff"; - $stmt = $this->appbox->get_connection()->prepare($sql); - $stmt->execute(); - $ret = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $this->appbox->get_connection()->prepare($sql); + $stmt->execute(); + $ret = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if($pid === NULL && $ret['status'] !== 'stopped') - { - // auto fix - $this->appbox->get_connection()->exec('UPDATE sitepreff SET schedstatus=\'stopped\''); - $ret['status'] = 'stopped'; - } - $ret['pid'] = $pid; - - return $ret; - } - - public static function getAvailableTasks() - { - $registry = registry::get_instance(); - $taskdir = array( $registry->get('GV_RootPath') . "lib/classes/task/period/" - , $registry->get('GV_RootPath') . "config/classes/task/period/" - ); - - $tasks = array(); - foreach($taskdir as $path) - { - if( ($hdir = @opendir($path)) ) - { - $tskin = array(); - $max = 9999; - while (($max-- > 0) && (($file = readdir($hdir)) !== false)) - { - if (!is_file($path . '/' . $file) || substr($file, 0, 1) == "." || substr($file, -10) != ".class.php") - continue; - - $classname = 'task_period_' . substr($file, 0, strlen($file) - 10); - - try - { - // $testclass = new $classname(null); - if ($classname::interfaceAvailable()) - { - $tasks[] = array("class" => $classname, "name" => $classname::getName(), "err" => null); - } + if ($pid === NULL && $ret['status'] !== 'stopped') { + // auto fix + $this->appbox->get_connection()->exec('UPDATE sitepreff SET schedstatus=\'stopped\''); + $ret['status'] = 'stopped'; } - catch (Exception $e) - { + $ret['pid'] = $pid; + return $ret; + } + + public static function getAvailableTasks() + { + $registry = registry::get_instance(); + $taskdir = array($registry->get('GV_RootPath') . "lib/classes/task/period/" + , $registry->get('GV_RootPath') . "config/classes/task/period/" + ); + + $tasks = array(); + foreach ($taskdir as $path) { + if (($hdir = @opendir($path))) { + $tskin = array(); + $max = 9999; + while (($max -- > 0) && (($file = readdir($hdir)) !== false)) { + if ( ! is_file($path . '/' . $file) || substr($file, 0, 1) == "." || substr($file, -10) != ".class.php") + continue; + + $classname = 'task_period_' . substr($file, 0, strlen($file) - 10); + + try { + // $testclass = new $classname(null); + if ($classname::interfaceAvailable()) { + $tasks[] = array("class" => $classname, "name" => $classname::getName(), "err" => null); + } + } catch (Exception $e) { + + } + } + closedir($hdir); + } } - } - closedir($hdir); - } - } - return $tasks; - } + return $tasks; + } } diff --git a/lib/classes/task/period/apibridge.class.php b/lib/classes/task/period/apibridge.class.php index 10517c335e..4422f94f57 100644 --- a/lib/classes/task/period/apibridge.class.php +++ b/lib/classes/task/period/apibridge.class.php @@ -18,179 +18,168 @@ class task_period_apibridge extends task_appboxAbstract { - /** - * Return the name of the task - * @return string - */ - public function getName() - { - return 'API bridge uploader'; - } - - /** - * Get help - * @return string - */ - public function help() - { - return ''; - } - - /** - * - * @param appbox $appbox - * @return Array - */ - protected function retrieve_content(appbox $appbox) - { - $status = array(Bridge_Element::STATUS_PENDING, Bridge_Element::STATUS_PROCESSING, Bridge_Element::STATUS_PROCESSING_SERVER); - - $params = array(); - $n = 1; - - foreach ($status as $stat) + /** + * Return the name of the task + * @return string + */ + public function getName() { - $params[':status' . $n] = $stat; - $n++; + return 'API bridge uploader'; } - $sql = 'SELECT id, account_id FROM bridge_elements + /** + * Get help + * @return string + */ + public function help() + { + return ''; + } + + /** + * + * @param appbox $appbox + * @return Array + */ + protected function retrieve_content(appbox $appbox) + { + $status = array(Bridge_Element::STATUS_PENDING, Bridge_Element::STATUS_PROCESSING, Bridge_Element::STATUS_PROCESSING_SERVER); + + $params = array(); + $n = 1; + + foreach ($status as $stat) { + $params[':status' . $n] = $stat; + $n ++; + } + + $sql = 'SELECT id, account_id FROM bridge_elements WHERE (status = ' . implode(' OR status = ', array_keys($params)) . ')'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute($params); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute($params); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $rs; - } - - /** - * - * @param appbox $appbox - * @param array $row - * @return task_period_apibridge - */ - protected function process_one_content(appbox $appbox, Array $row) - { - try - { - $account = Bridge_Account::load_account($appbox, $row['account_id']); - $element = new Bridge_Element($appbox, $account, $row['id']); - - $this->log("process " . $element->get_id() . " with status " . $element->get_status()); - - if ($element->get_status() == Bridge_Element::STATUS_PENDING) - $this->upload_element($element); - else - $this->update_element($element); - } - catch (Exception $e) - { - $sql = 'UPDATE bridge_elements SET status = :status WHERE id = :id'; - - $params = array( - ':status' => Bridge_Element::STATUS_ERROR - , ':id' => $row['id'] - ); - - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + return $rs; } - return $this; - } - - /** - * - * @param appbox $appbox - * @param array $row - * @return task_period_apibridge - */ - protected function post_process_one_content(appbox $appbox, Array $row) - { - return $this; - } - - /** - * - * @param Bridge_Element $element - * @return task_period_apibridge - */ - private function upload_element(Bridge_Element $element) - { - $account = $element->get_account(); - $element->set_status(Bridge_Element::STATUS_PROCESSING); - $dist_id = null; - try + /** + * + * @param appbox $appbox + * @param array $row + * @return task_period_apibridge + */ + protected function process_one_content(appbox $appbox, Array $row) { - $dist_id = $account->get_api()->upload($element->get_record(), $element->get_datas()); - $element->set_uploaded_on(new DateTime()); - } - catch (Exception $e) - { - $this->log('Error while uploading : '.$e->getMessage()); - $element->set_status(Bridge_Element::STATUS_ERROR); - } - $element->set_dist_id($dist_id); + try { + $account = Bridge_Account::load_account($appbox, $row['account_id']); + $element = new Bridge_Element($appbox, $account, $row['id']); - return $this; - } + $this->log("process " . $element->get_id() . " with status " . $element->get_status()); - /** - * - * @param Bridge_Element $element - * @return task_period_apibridge - */ - protected function update_element(Bridge_Element &$element) - { - $Core = bootstrap::getCore(); - $account = $element->get_account(); - $connector_status = $account->get_api()->get_element_status($element); + if ($element->get_status() == Bridge_Element::STATUS_PENDING) + $this->upload_element($element); + else + $this->update_element($element); + } catch (Exception $e) { + $sql = 'UPDATE bridge_elements SET status = :status WHERE id = :id'; - $status = $element->get_account()->get_api()->map_connector_to_element_status($connector_status); - $error_message = $element->get_account()->get_api()->get_error_message_from_status($connector_status); + $params = array( + ':status' => Bridge_Element::STATUS_ERROR + , ':id' => $row['id'] + ); - $previous_status = $element->get_status(); + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); + } - if ($status) - { - $element->set_status($status); - $this->log('updating status for : ' . $element->get_id() . " to " . $status); - } - $element->set_connector_status($connector_status); - - if ($status === $previous_status) - - return; - - - switch ($status) - { - case Bridge_Element::STATUS_ERROR: - - $params = array( - 'usr_id' => $account->get_user()->get_id() - , 'reason' => $error_message - , 'account_id' => $account->get_id() - , 'sbas_id' => $element->get_record()->get_sbas_id() - , 'record_id' => $element->get_record()->get_record_id() - ); - $events_mngr = eventsmanager_broker::getInstance(appbox::get_instance(\bootstrap::getCore()), $Core); - $events_mngr->trigger('__BRIDGE_UPLOAD_FAIL__', $params); - - break; - default: - case Bridge_Element::STATUS_DONE: - case Bridge_Element::STATUS_PENDING: - case Bridge_Element::STATUS_PROCESSING_SERVER: - case Bridge_Element::STATUS_PROCESSING: - - break; + return $this; } - return $this; - } + /** + * + * @param appbox $appbox + * @param array $row + * @return task_period_apibridge + */ + protected function post_process_one_content(appbox $appbox, Array $row) + { + return $this; + } + /** + * + * @param Bridge_Element $element + * @return task_period_apibridge + */ + private function upload_element(Bridge_Element $element) + { + $account = $element->get_account(); + $element->set_status(Bridge_Element::STATUS_PROCESSING); + $dist_id = null; + try { + $dist_id = $account->get_api()->upload($element->get_record(), $element->get_datas()); + $element->set_uploaded_on(new DateTime()); + } catch (Exception $e) { + $this->log('Error while uploading : ' . $e->getMessage()); + $element->set_status(Bridge_Element::STATUS_ERROR); + } + $element->set_dist_id($dist_id); + + return $this; + } + + /** + * + * @param Bridge_Element $element + * @return task_period_apibridge + */ + protected function update_element(Bridge_Element &$element) + { + $Core = bootstrap::getCore(); + $account = $element->get_account(); + $connector_status = $account->get_api()->get_element_status($element); + + $status = $element->get_account()->get_api()->map_connector_to_element_status($connector_status); + $error_message = $element->get_account()->get_api()->get_error_message_from_status($connector_status); + + $previous_status = $element->get_status(); + + if ($status) { + $element->set_status($status); + $this->log('updating status for : ' . $element->get_id() . " to " . $status); + } + $element->set_connector_status($connector_status); + + if ($status === $previous_status) + return; + + + switch ($status) { + case Bridge_Element::STATUS_ERROR: + + $params = array( + 'usr_id' => $account->get_user()->get_id() + , 'reason' => $error_message + , 'account_id' => $account->get_id() + , 'sbas_id' => $element->get_record()->get_sbas_id() + , 'record_id' => $element->get_record()->get_record_id() + ); + $events_mngr = eventsmanager_broker::getInstance(appbox::get_instance(\bootstrap::getCore()), $Core); + $events_mngr->trigger('__BRIDGE_UPLOAD_FAIL__', $params); + + break; + default: + case Bridge_Element::STATUS_DONE: + case Bridge_Element::STATUS_PENDING: + case Bridge_Element::STATUS_PROCESSING_SERVER: + case Bridge_Element::STATUS_PROCESSING: + + break; + } + + return $this; + } } diff --git a/lib/classes/task/period/archive.class.php b/lib/classes/task/period/archive.class.php index 108785dd03..1dde5dec27 100644 --- a/lib/classes/task/period/archive.class.php +++ b/lib/classes/task/period/archive.class.php @@ -16,73 +16,73 @@ */ class task_period_archive extends task_abstract { - /** - * command line args specifics - * - * @var string - */ - public $argt = array(); + /** + * command line args specifics + * + * @var string + */ + public $argt = array(); - /** - * - * @var - */ - protected $mimeTypes = array( - "jpg" => "image/jpeg", - "jpeg" => "image/jpeg", - "pdf" => "application/pdf" - ); + /** + * + * @var + */ + protected $mimeTypes = array( + "jpg" => "image/jpeg", + "jpeg" => "image/jpeg", + "pdf" => "application/pdf" + ); - /** - * HOT files list - * - * @var - */ - protected $hotfiles = array(); + /** + * HOT files list + * + * @var + */ + protected $hotfiles = array(); - /** - * - * @var - */ - protected $sxTaskSettings = null; + /** + * + * @var + */ + protected $sxTaskSettings = null; - /** - * - * @var - */ - protected $msg = ""; + /** + * + * @var + */ + protected $msg = ""; - /** - * - * @var - */ - protected $move_archived = true; + /** + * + * @var + */ + protected $move_archived = true; - /** - * - * @var - */ - protected $move_error = true; + /** + * + * @var + */ + protected $move_error = true; - /** - * - * @return string - */ - public function getName() - { - return(_('task::archive:Archivage')); - } + /** + * + * @return string + */ + public function getName() + { + return(_('task::archive:Archivage')); + } - /** - * - * @param string $oldxml - * @return string - */ - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); + /** + * + * @param string $oldxml + * @return string + */ + public function graphic2xml($oldxml) + { + $request = http_request::getInstance(); - $parm2 = $request->get_parms( + $parm2 = $request->get_parms( "base_id" , "hotfolder" , "period" @@ -91,1192 +91,1050 @@ class task_period_archive extends task_abstract , "copy_spe" , "delfolder" , 'cold' - ); - $dom = new DOMDocument(); - $dom->formatOutput = true; - $dom->preserveWhiteSpace = false; - if($dom->loadXML($oldxml)) - { - $xmlchanged = false; - // foreach($parm2 as $pname=>$pvalue) - foreach(array("str:base_id", "str:hotfolder", "str:period", "boo:move_archived", "boo:move_error", "boo:delfolder", 'boo:copy_spe', 'str:cold') as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while(($n = $ns->firstChild)) - $ns->removeChild($n); + ); + $dom = new DOMDocument(); + $dom->formatOutput = true; + $dom->preserveWhiteSpace = false; + if ($dom->loadXML($oldxml)) { + $xmlchanged = false; + // foreach($parm2 as $pname=>$pvalue) + foreach (array("str:base_id", "str:hotfolder", "str:period", "boo:move_archived", "boo:move_error", "boo:delfolder", 'boo:copy_spe', 'str:cold') as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; + } } - else - { - // le champ n'existait pas dans le xml, on le cree - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - } - // on fixe sa valeur - switch($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + + return($dom->saveXML()); } - return($dom->saveXML()); - } - - /** - * xml2graphic : must fill the graphic form (using js) from xml - * - * @param string $xml - * @param string $form - * @return Void - */ - public function xml2graphic($xml, $form) - { - if(($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + /** + * xml2graphic : must fill the graphic form (using js) from xml + * + * @param string $xml + * @param string $form + * @return Void + */ + public function xml2graphic($xml, $form) { - // ... but we could check for safe values (ex. 0 < period < 3600) - if((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif((int) ($sxml->period) > 300) - $sxml->period = 300; - if((int) ($sxml->cold) < 5) - $sxml->cold = 5; - elseif((int) ($sxml->cold) > 3600) - $sxml->cold = 3600; - ?> - + .hotfolder.value = "hotfolder, "js", '"') ?>"; - .period.value = "period, "js", '"') ?>"; - .cold.value = "cold, "js", '"') ?>"; - .move_archived.checked = move_archived) ? "true" : "false" ?>; - .move_error.checked = move_error) ? "true" : "false" ?>; - .delfolder.checked = delfolder) ? "true" : "false" ?>; - .copy_spe.checked = copy_spe) ? "true" : "false" ?>; - - - - -
                  - : - - -
                  -
                  - -
                  -
                  -  :  -  
                  -
                  -  :  -  
                  -
                  -   -      -  
                  -
                  -  
                  -
                  -  
                  -
                  - - */ - protected function run2() - { - $ret = ''; - $conn = connection::getPDOConnection(); - - $this->sxTaskSettings = simplexml_load_string($this->settings); - - $base_id = (int) ($this->sxTaskSettings->base_id); - $this->sbas_id = phrasea::sbasFromBas($base_id); - - if(!$this->sbas_id) - { - $this->log('base_id unknown'); - - return('tostop'); } - - $databox = databox::get_instance($this->sbas_id); - - $this->TColls = array(); - $collection = null; - foreach($databox->get_collections() as $coll) + /** + * printInterfaceJS() : generer le code js de l'interface 'graphic view' + * + * @return Void + */ + public function printInterfaceJS() { - $this->TColls['c' . $coll->get_coll_id()] = $coll->get_coll_id(); - if($base_id == $coll->get_base_id()) - $collection = $coll; - } - $server_coll_id = $collection->get_coll_id(); - - - // conn est une connexion e application server du site - // rowtask : record de la teche en cours - // connbas est une connexion e la base distante - // rowbas : record contenant les prefs de base et collection - // on a les prefs de coll directement dans la session - - $this->running = true; - $this->tmask = array(); // les masques de fichiers acceptes par cette tache - $this->tmaskgrp = array(); - $this->period = 60; - $this->cold = 60; - - - if(($this->sxBasePrefs = simplexml_load_string($collection->get_prefs()))) - { - - $this->sxBasePrefs["id"] = $base_id; // info utile - - $do_it = true; - - $this->period = (int) ($this->sxTaskSettings->period); - if($this->period <= 0 || $this->period >= 60 * 60) - $this->period = 60; - - $this->cold = (int) ($this->sxTaskSettings->cold); - if($this->cold <= 0 || $this->cold >= 60 * 60) - $this->cold = 60; - - // si on doit copier le doc dans la base, on verifie que le dossier existe - $copyhd = true; - $pathhd = (string) ($this->sxBasePrefs->path); - - if($copyhd && $pathhd) - { - system_file::mkdir($pathhd); - if(!is_dir($pathhd)) - { - $this->log(sprintf(_('task::archive:Can\'t create or go to folder \'%s\''), $pathhd)); - $this->running = false; - } - } - - // on charge les masques de fichiers - if($this->sxTaskSettings->files && $this->sxTaskSettings->files->file) - { - foreach($this->sxTaskSettings->files->file as $ft) - $this->tmask[] = array( - "mask" => (string) $ft["mask"] - , "caption" => (string) $ft["caption"] - , "accept" => (string) $ft["accept"] - ); - } - if($this->sxTaskSettings->files && $this->sxTaskSettings->files->grouping) - { - foreach($this->sxTaskSettings->files->grouping as $ft) - $this->tmaskgrp[] = array( - "mask" => (string) $ft["mask"] - , "caption" => (string) $ft["caption"] - , "representation" => (string) $ft["representation"] - , "accept" => (string) $ft["accept"] - ); - } - if(count($this->tmask) == 0) - { - // pas de masque defini : on accepte tout - $this->tmask[] = array("mask" => ".*", "caption" => "", "accept" => ""); - } - - // ici la teche tourne tant qu'elle est active - $loop = 0; - while($this->running) - { - if(!$conn->ping()) - { - $this->log(("Warning : abox connection lost, restarting in 10 min.")); - sleep(60 * 10); - $this->running = false; - - return(self::RETURNSTATUS_TORESTART); - } - - try - { - $connbas = connection::getPDOConnection($this->sbas_id); - if(!$connbas->ping()) - throw new Exception('Mysql has gone away'); - } - catch(Exception $e) - { - $this->log(("dbox connection lost, restarting in 10 min.")); - for($i = 0; $i < 60 * 10 && $this->running; $i++) - sleep(1); - $this->running = false; - - return(self::RETURNSTATUS_TORESTART); - } - - $path_in = (string) ($this->sxTaskSettings->hotfolder); - if(!@is_dir($path_in)) - { - $this->log(sprintf(('missing hotfolder \'%s\', restarting in 10 min.'), $path_in)); - for($i = 0; $i < 60 * 10 && $this->running; $i++) - sleep(1); - $this->running = false; - - return(self::RETURNSTATUS_TORESTART); - } - - - $this->set_last_exec_time(); - - $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; - - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if($row) - { - if($row['status'] == 'tostop') - { - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - } - else - { - - if($this->sxTaskSettings = simplexml_load_string($row['settings'])) + ?> + + sxTaskSettings->period); - if($period <= 0 || $period >= 60 * 60) - $period = 60; - $cold = (int) ($this->sxTaskSettings->cold); - if($cold <= 0 || $cold >= 60 * 60) + /** + * + * @return string + */ + function getGraphicForm() + { + return true; + } + + /** + * printInterfaceHTML(..) : generer l'interface 'graphic view' + * + * @return Void + */ + public function printInterfaceHTML() + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + + ob_start(); + ?> +
                  + : + + +
                  +
                  + +
                  +
                  +  :  +  
                  +
                  +  :  +  
                  +
                  +   +      +  
                  +
                  +  
                  +
                  +  
                  +
                  + + */ + protected function run2() + { + $ret = ''; + $conn = connection::getPDOConnection(); + + $this->sxTaskSettings = simplexml_load_string($this->settings); + + $base_id = (int) ($this->sxTaskSettings->base_id); + $this->sbas_id = phrasea::sbasFromBas($base_id); + + if ( ! $this->sbas_id) { + $this->log('base_id unknown'); + + return('tostop'); + } + + + $databox = databox::get_instance($this->sbas_id); + + $this->TColls = array(); + $collection = null; + foreach ($databox->get_collections() as $coll) { + $this->TColls['c' . $coll->get_coll_id()] = $coll->get_coll_id(); + if ($base_id == $coll->get_base_id()) + $collection = $coll; + } + $server_coll_id = $collection->get_coll_id(); + + + // conn est une connexion e application server du site + // rowtask : record de la teche en cours + // connbas est une connexion e la base distante + // rowbas : record contenant les prefs de base et collection + // on a les prefs de coll directement dans la session + + $this->running = true; + $this->tmask = array(); // les masques de fichiers acceptes par cette tache + $this->tmaskgrp = array(); + $this->period = 60; + $this->cold = 60; + + + if (($this->sxBasePrefs = simplexml_load_string($collection->get_prefs()))) { + + $this->sxBasePrefs["id"] = $base_id; // info utile + + $do_it = true; + + $this->period = (int) ($this->sxTaskSettings->period); + if ($this->period <= 0 || $this->period >= 60 * 60) + $this->period = 60; + + $this->cold = (int) ($this->sxTaskSettings->cold); + if ($this->cold <= 0 || $this->cold >= 60 * 60) + $this->cold = 60; + + // si on doit copier le doc dans la base, on verifie que le dossier existe + $copyhd = true; + $pathhd = (string) ($this->sxBasePrefs->path); + + if ($copyhd && $pathhd) { + system_file::mkdir($pathhd); + if ( ! is_dir($pathhd)) { + $this->log(sprintf(_('task::archive:Can\'t create or go to folder \'%s\''), $pathhd)); + $this->running = false; + } + } + + // on charge les masques de fichiers + if ($this->sxTaskSettings->files && $this->sxTaskSettings->files->file) { + foreach ($this->sxTaskSettings->files->file as $ft) + $this->tmask[] = array( + "mask" => (string) $ft["mask"] + , "caption" => (string) $ft["caption"] + , "accept" => (string) $ft["accept"] + ); + } + if ($this->sxTaskSettings->files && $this->sxTaskSettings->files->grouping) { + foreach ($this->sxTaskSettings->files->grouping as $ft) + $this->tmaskgrp[] = array( + "mask" => (string) $ft["mask"] + , "caption" => (string) $ft["caption"] + , "representation" => (string) $ft["representation"] + , "accept" => (string) $ft["accept"] + ); + } + if (count($this->tmask) == 0) { + // pas de masque defini : on accepte tout + $this->tmask[] = array("mask" => ".*", "caption" => "", "accept" => ""); + } + + // ici la teche tourne tant qu'elle est active + $loop = 0; + while ($this->running) { + if ( ! $conn->ping()) { + $this->log(("Warning : abox connection lost, restarting in 10 min.")); + sleep(60 * 10); + $this->running = false; + + return(self::RETURNSTATUS_TORESTART); + } + + try { + $connbas = connection::getPDOConnection($this->sbas_id); + if ( ! $connbas->ping()) + throw new Exception('Mysql has gone away'); + } catch (Exception $e) { + $this->log(("dbox connection lost, restarting in 10 min.")); + for ($i = 0; $i < 60 * 10 && $this->running; $i ++ ) + sleep(1); + $this->running = false; + + return(self::RETURNSTATUS_TORESTART); + } + + $path_in = (string) ($this->sxTaskSettings->hotfolder); + if ( ! @is_dir($path_in)) { + $this->log(sprintf(('missing hotfolder \'%s\', restarting in 10 min.'), $path_in)); + for ($i = 0; $i < 60 * 10 && $this->running; $i ++ ) + sleep(1); + $this->running = false; + + return(self::RETURNSTATUS_TORESTART); + } + + + $this->set_last_exec_time(); + + $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; + + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row) { + if ($row['status'] == 'tostop') { + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + } else { + + if ($this->sxTaskSettings = simplexml_load_string($row['settings'])) { + // copy settings to task, so it's easier to get later + $this->move_archived = p4field::isyes($this->sxTaskSettings->move_archived); + $this->move_error = p4field::isyes($this->sxTaskSettings->move_error); + + $period = (int) ($this->sxTaskSettings->period); + if ($period <= 0 || $period >= 60 * 60) + $period = 60; + $cold = (int) ($this->sxTaskSettings->cold); + if ($cold <= 0 || $cold >= 60 * 60) + $cold = 60; + } + else { + $period = 60; + $cold = 60; + } + + $duration = time(); + $r = $this->archiveHotFolder($server_coll_id); + + if ($loop > 10) + $r = 'MAXLOOP'; + + switch ($r) { + case 'WAIT': + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + break; + case 'BAD': + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + break; + case 'NORECSTODO': + $duration = time() - $duration; + if ($duration < ($period + $cold)) { + $conn->close(); + for ($i = 0; $i < (($period + $cold) - $duration) && $this->running; $i ++ ) + sleep(1); + unset($conn); + $conn = connection::getPDOConnection(); + } + break; + case 'MAXRECSDONE': + case 'MAXMEMORY': + case 'MAXLOOP': + if ($row['status'] == self::STATUS_STARTED && $this->get_runner() !== self::RUNNER_MANUAL) { + $ret = self::RETURNSTATUS_TORESTART; + $this->running = false; + } + break; + default: + if ($row['status'] == self::STATUS_STARTED) { + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + } + break; + } + } + } else { + $this->running = false; + } + $loop ++; + } + } + $this->return_value = $ret; + + return($ret); + } + + /** + * + * @param $server_coll_id + * @return + */ + function archiveHotFolder($server_coll_id) + { + // $this->filesToIgnore = array('.', '..', 'Thumbs.db', ''); + + clearstatcache(); + + $conn = connection::getPDOConnection(); + + $path_in = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + if ( ! @is_file($path_in . "/.phrasea.xml")) { + $this->log(sprintf(('NO .phrasea.xml AT ROOT v2 \'%s\' !'), $path_in)); + + return('WAIT'); + } + + $path_archived = $path_error = null; + if ($this->move_archived) { + $path_archived = $path_in . '_archived'; + @mkdir($path_archived, 0755, true); + if ( ! file_exists($path_archived)) { + $this->log(sprintf(('Can\'t create folder \'%s\' !'), $path_archived)); + + return('BAD'); + } + } + if ($this->move_error) { + $path_error = $path_in . '_error'; + @mkdir($path_error, 0755, true); + if ( ! file_exists($path_error)) { + $this->log(sprintf(('archive:Can\'t create folder \'%s\' !'), $path_error)); + + return('BAD'); + } + } + + $dom = new DOMDocument(); + $dom->formatOutput = true; + $root = $dom->appendChild($dom->createElement('root')); + + + $this->movedFiles = 0; + $this->archivedFiles = 0; + $this->path_in = $path_in; + + $nnew = $this->listFilesPhase1($dom, $root, $path_in, $server_coll_id); + + if ($this->debug) + $this->log("=========== listFilesPhase1 ========== (returned " . $nnew . ")\n" . $dom->saveXML()); + + $cold = (int) ($this->sxTaskSettings->cold); + if ($cold <= 0 || $cold >= 60 * 60) $cold = 60; - } - else - { - $period = 60; - $cold = 60; + + while ($cold > 0) { + $sql = "SELECT status FROM task2 WHERE task_id=" . $this->get_task_id(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row && $row['status'] == 'tostop') + return('NORECSTODO'); + sleep(2); + $cold -= 2; } - $duration = time(); - $r = $this->archiveHotFolder($server_coll_id); - if($loop > 10) - $r = 'MAXLOOP'; + $this->listFilesPhase2($dom, $root, $path_in); + if ($this->debug) + $this->log("=========== listFilesPhase2 ========== : \n" . $dom->saveXML()); - switch($r) - { - case 'WAIT': - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - break; - case 'BAD': - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - break; - case 'NORECSTODO': - $duration = time() - $duration; - if($duration < ($period + $cold)) - { - $conn->close(); - for($i = 0; $i < (($period + $cold) - $duration) && $this->running; $i++) - sleep(1); - unset($conn); - $conn = connection::getPDOConnection(); - } - break; - case 'MAXRECSDONE': - case 'MAXMEMORY': - case 'MAXLOOP': - if($row['status'] == self::STATUS_STARTED && $this->get_runner() !== self::RUNNER_MANUAL) - { - $ret = self::RETURNSTATUS_TORESTART; - $this->running = false; - } - break; - default: - if($row['status'] == self::STATUS_STARTED) - { - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - } - break; + + + $this->makePairs($dom, $root, $path_in, $path_archived, $path_error); + if ($this->debug) + $this->log("=========== makePairs ========== : \n" . $dom->saveXML()); + + + + $r = $this->removeBadGroups($dom, $root, $path_in, $path_archived, $path_error); + if ($this->debug) + $this->log("=========== removeBadGroups ========== (returned " . ($r ? 'true' : 'false') . ") : \n" . $dom->saveXML()); + + + + $this->archive($dom, $root, $path_in, $path_archived, $path_error); + if ($this->debug) + $this->log("=========== archive ========== : \n" . $dom->saveXML()); + + + + $this->bubbleResults($dom, $root, $path_in); + if ($this->debug) + $this->log("=========== bubbleResults ========== : \n" . $dom->saveXML()); + + + + $r = $this->moveFiles($dom, $root, $path_in, $path_archived, $path_error); + if ($this->debug) + $this->log("=========== moveFiles ========== (returned " . ($r ? 'true' : 'false') . ") : \n" . $dom->saveXML()); + + if ($this->movedFiles) { + // something happened : a least one file has moved + return('MAXRECSDONE'); + } elseif (memory_get_usage() >> 20 > 15) { + return('MAXMEMORY'); + } else { + return('NORECSTODO'); } - } - } - else - { - $this->running = false; - } - $loop++; - } - } - $this->return_value = $ret; - - return($ret); - } - - /** - * - * @param $server_coll_id - * @return - */ - function archiveHotFolder($server_coll_id) - { - // $this->filesToIgnore = array('.', '..', 'Thumbs.db', ''); - - clearstatcache(); - - $conn = connection::getPDOConnection(); - - $path_in = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - if(!@is_file($path_in . "/.phrasea.xml")) - { - $this->log(sprintf(('NO .phrasea.xml AT ROOT v2 \'%s\' !'), $path_in)); - - return('WAIT'); - } - - $path_archived = $path_error = null; - if($this->move_archived) - { - $path_archived = $path_in . '_archived'; - @mkdir($path_archived, 0755, true); - if(!file_exists($path_archived)) - { - $this->log(sprintf(('Can\'t create folder \'%s\' !'), $path_archived)); - - return('BAD'); - } - } - if($this->move_error) - { - $path_error = $path_in . '_error'; - @mkdir($path_error, 0755, true); - if(!file_exists($path_error)) - { - $this->log(sprintf(('archive:Can\'t create folder \'%s\' !'), $path_error)); - - return('BAD'); - } - } - - $dom = new DOMDocument(); - $dom->formatOutput = true; - $root = $dom->appendChild($dom->createElement('root')); - - - $this->movedFiles = 0; - $this->archivedFiles = 0; - $this->path_in = $path_in; - - $nnew = $this->listFilesPhase1($dom, $root, $path_in, $server_coll_id); - - if($this->debug) - $this->log("=========== listFilesPhase1 ========== (returned " . $nnew . ")\n" . $dom->saveXML()); - - $cold = (int) ($this->sxTaskSettings->cold); - if($cold <= 0 || $cold >= 60 * 60) - $cold = 60; - - while($cold > 0) - { - $sql = "SELECT status FROM task2 WHERE task_id=" . $this->get_task_id(); - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if($row && $row['status'] == 'tostop') - - return('NORECSTODO'); - sleep(2); - $cold -= 2; - } - - - $this->listFilesPhase2($dom, $root, $path_in); - if($this->debug) - $this->log("=========== listFilesPhase2 ========== : \n" . $dom->saveXML()); - - - - $this->makePairs($dom, $root, $path_in, $path_archived, $path_error); - if($this->debug) - $this->log("=========== makePairs ========== : \n" . $dom->saveXML()); - - - - $r = $this->removeBadGroups($dom, $root, $path_in, $path_archived, $path_error); - if($this->debug) - $this->log("=========== removeBadGroups ========== (returned " . ($r ? 'true' : 'false') . ") : \n" . $dom->saveXML()); - - - - $this->archive($dom, $root, $path_in, $path_archived, $path_error); - if($this->debug) - $this->log("=========== archive ========== : \n" . $dom->saveXML()); - - - - $this->bubbleResults($dom, $root, $path_in); - if($this->debug) - $this->log("=========== bubbleResults ========== : \n" . $dom->saveXML()); - - - - $r = $this->moveFiles($dom, $root, $path_in, $path_archived, $path_error); - if($this->debug) - $this->log("=========== moveFiles ========== (returned " . ($r ? 'true' : 'false') . ") : \n" . $dom->saveXML()); - - if($this->movedFiles) - { - // something happened : a least one file has moved - return('MAXRECSDONE'); - } - elseif(memory_get_usage() >> 20 > 15) - { - return('MAXMEMORY'); - } - else - { - return('NORECSTODO'); - } //print($dom->saveXML()); // unset($dom); // die(); - } - - /** - * - * @param $f - * @return - */ - function isIgnoredFile($f) - { - $f = strtolower($f); - - return(($f[0] == '.' && $f != '.phrasea.xml' && $f != '.grouping.xml') || $f == 'thumbs.db' || $f == 'par-system'); - } - - /** - * check if the file matches any mask, and flag the 'caption' file if found - * - * @param $dom - * @param $node - * @return - */ - function checkMatch($dom, $node) - { - $file = $node->getAttribute('name'); - - foreach($this->tmask as $mask) - { - $preg_mask = '/' . $mask['mask'] . '/'; - if(preg_match($preg_mask, $file)) - { - if($mask['caption']) - { - // caption in a linked file ? - $captionFileName = @preg_replace($preg_mask, $mask['caption'], $file); - $xpath = new DOMXPath($dom); - $dnl = $xpath->query('./file[@name="' . $captionFileName . '"]', $node->parentNode); - if($dnl->length == 1) - { - // the caption file exists - $node->setAttribute('match', $captionFileName); - $dnl->item(0)->setAttribute('match', '*'); - } - else - { - // the caption file is missing - $node->setAttribute('match', '?'); - } - } - else - { - // self-described - $node->setAttribute('match', '.'); } - // first match is ok - break; - } - } - - return; - } - - /** - * Phase 1 : - * list every file, all 'hot' - * read .phrasea.xml files - * - * @param $dom - * @param $node - * @param $path - * @param $server_coll_id - * @return - */ - function listFilesPhase1($dom, $node, $path, $server_coll_id) - { - // $this->traceRam(); - $nnew = 0; - - try - { - $listFolder = new CListFolder($path); - - if(($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml'))) - { - // on gere le magicfile - if(($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') + /** + * + * @param $f + * @return + */ + function isIgnoredFile($f) { - $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); - if($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) + $f = strtolower($f); - return; - elseif($magicmethod == 'UNLOCK' && !file_exists($path . '/' . $magicfile)) + return(($f[0] == '.' && $f != '.phrasea.xml' && $f != '.grouping.xml') || $f == 'thumbs.db' || $f == 'par-system'); + } + + /** + * check if the file matches any mask, and flag the 'caption' file if found + * + * @param $dom + * @param $node + * @return + */ + function checkMatch($dom, $node) + { + $file = $node->getAttribute('name'); + + foreach ($this->tmask as $mask) { + $preg_mask = '/' . $mask['mask'] . '/'; + if (preg_match($preg_mask, $file)) { + if ($mask['caption']) { + // caption in a linked file ? + $captionFileName = @preg_replace($preg_mask, $mask['caption'], $file); + $xpath = new DOMXPath($dom); + $dnl = $xpath->query('./file[@name="' . $captionFileName . '"]', $node->parentNode); + if ($dnl->length == 1) { + // the caption file exists + $node->setAttribute('match', $captionFileName); + $dnl->item(0)->setAttribute('match', '*'); + } else { + // the caption file is missing + $node->setAttribute('match', '?'); + } + } else { + // self-described + $node->setAttribute('match', '.'); + } + + // first match is ok + break; + } + } return; } - // on gere le changement de collection - if(($new_cid = $sxDotPhrasea['collection']) != '') + /** + * Phase 1 : + * list every file, all 'hot' + * read .phrasea.xml files + * + * @param $dom + * @param $node + * @param $path + * @param $server_coll_id + * @return + */ + function listFilesPhase1($dom, $node, $path, $server_coll_id) { - if(isset($this->TColls['c' . $new_cid])) - { - $server_coll_id = $new_cid; - } - else - { - $this->log(sprintf(('Unknown coll_id (%1$d) in "%2$s"'), (int) $new_cid, $path . '/.phrasea.xml')); - $server_coll_id = -1; - } + // $this->traceRam(); + $nnew = 0; + + try { + $listFolder = new CListFolder($path); + + if (($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml'))) { + // on gere le magicfile + if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') { + $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); + if ($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) + return; + elseif ($magicmethod == 'UNLOCK' && ! file_exists($path . '/' . $magicfile)) + return; + } + + // on gere le changement de collection + if (($new_cid = $sxDotPhrasea['collection']) != '') { + if (isset($this->TColls['c' . $new_cid])) { + $server_coll_id = $new_cid; + } else { + $this->log(sprintf(('Unknown coll_id (%1$d) in "%2$s"'), (int) $new_cid, $path . '/.phrasea.xml')); + $server_coll_id = -1; + } + } + $node->setAttribute('pxml', '1'); + } + + $iloop = 0; + while (($file = $listFolder->read()) !== NULL) { + if ($this->isIgnoredFile($file)) + continue; + + if (($iloop ++ % 100) == 0) + usleep(1000); + + if (is_dir($path . '/' . $file)) { + $n = $node->appendChild($dom->createElement('file')); + $n->setAttribute('isdir', '1'); + $n->setAttribute('name', $file); + + $nnew += $this->listFilesPhase1($dom, $n, $path . '/' . $file, $server_coll_id); + } else { + $n = $node->appendChild($dom->createElement('file')); + $n->setAttribute('name', $file); + $stat = stat($path . '/' . $file); + foreach (array("size", "ctime", "mtime") as $k) + $n->setAttribute($k, $stat[$k]); + $nnew ++; + } + $n->setAttribute('cid', $server_coll_id); + + $n->setAttribute('temperature', 'hot'); + } + } catch (Exception $e) { + + } + + return($nnew); } - $node->setAttribute('pxml', '1'); - } - $iloop = 0; - while(($file = $listFolder->read()) !== NULL) - { - if($this->isIgnoredFile($file)) - continue; - - if(($iloop++ % 100) == 0) - usleep(1000); - - if(is_dir($path . '/' . $file)) + /** + * Phase 2 : + * list again and flag dead files as 'cold' + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $depth + * @return + */ + function listFilesPhase2($dom, $node, $path, $depth = 0) { - $n = $node->appendChild($dom->createElement('file')); - $n->setAttribute('isdir', '1'); - $n->setAttribute('name', $file); + static $iloop = 0; + if ($depth == 0) + $iloop = 0; - $nnew += $this->listFilesPhase1($dom, $n, $path . '/' . $file, $server_coll_id); - } - else - { - $n = $node->appendChild($dom->createElement('file')); - $n->setAttribute('name', $file); - $stat = stat($path . '/' . $file); - foreach(array("size", "ctime", "mtime") as $k) - $n->setAttribute($k, $stat[$k]); - $nnew++; - } - $n->setAttribute('cid', $server_coll_id); + $nnew = 0; - $n->setAttribute('temperature', 'hot'); - } - } - catch(Exception $e) - { + try { + $listFolder = new CListFolder($path); - } + $xp = new DOMXPath($dom); - return($nnew); - } + if (($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml'))) { + // on gere le magicfile + if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') { + $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); + if ($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) + return; + elseif ($magicmethod == 'UNLOCK' && ! file_exists($path . '/' . $magicfile)) + return; + } + } - /** - * Phase 2 : - * list again and flag dead files as 'cold' - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $depth - * @return - */ - function listFilesPhase2($dom, $node, $path, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; + while (($file = $listFolder->read()) !== NULL) { + // on gere le magicfile + if (($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') { + $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); + if ($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) + return; + elseif ($magicmethod == 'UNLOCK' && ! file_exists($path . '/' . $magicfile)) + return; + } + } - $nnew = 0; + while (($file = $listFolder->read()) !== NULL) { + if ($this->isIgnoredFile($file)) + continue; - try - { - $listFolder = new CListFolder($path); + if (($iloop ++ % 100) == 0) + usleep(500); - $xp = new DOMXPath($dom); + $dnl = @$xp->query('./file[@name="' . $file . '"]', $node); + if ($dnl && $dnl->length == 0) { + if (is_dir($path . '/' . $file)) { + $n = $node->appendChild($dom->createElement('file')); + $n->setAttribute('isdir', '1'); + $n->setAttribute('name', $file); - if(($sxDotPhrasea = @simplexml_load_file($path . '/.phrasea.xml'))) - { - // on gere le magicfile - if(($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') - { - $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); - if($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) - - return; - elseif($magicmethod == 'UNLOCK' && !file_exists($path . '/' . $magicfile)) - - return; - } - } - - while(($file = $listFolder->read()) !== NULL) - { - // on gere le magicfile - if(($magicfile = trim((string) ($sxDotPhrasea->magicfile))) != '') - { - $magicmethod = strtoupper($sxDotPhrasea->magicfile['method']); - if($magicmethod == 'LOCK' && file_exists($path . '/' . $magicfile)) - - return; - elseif($magicmethod == 'UNLOCK' && !file_exists($path . '/' . $magicfile)) - - return; - } - } - - while(($file = $listFolder->read()) !== NULL) - { - if($this->isIgnoredFile($file)) - continue; - - if(($iloop++ % 100) == 0) - usleep(500); - - $dnl = @$xp->query('./file[@name="' . $file . '"]', $node); - if($dnl && $dnl->length == 0) - { - if(is_dir($path . '/' . $file)) - { - $n = $node->appendChild($dom->createElement('file')); - $n->setAttribute('isdir', '1'); - $n->setAttribute('name', $file); - - $nnew += $this->listFilesPhase2($dom, $n, $path . '/' . $file, $depth + 1); - } - else - { - $n = $node->appendChild($dom->createElement('file')); - $n->setAttribute('name', $file); + $nnew += $this->listFilesPhase2($dom, $n, $path . '/' . $file, $depth + 1); + } else { + $n = $node->appendChild($dom->createElement('file')); + $n->setAttribute('name', $file); // $stat = stat($path.'/'.$file); // foreach(array("size", "ctime", "mtime") as $k) // $n->setAttribute($k, $stat[$k]); - $nnew++; - } + $nnew ++; + } // $n->setAttribute('cid', $server_coll_id); // $n->setAttribute('temperature', 'hot'); - $this->setBranchHot($dom, $n); - } - elseif($dnl && $dnl->length == 1) - { - $dnl->item(0)->setAttribute('temperature', 'cold'); - // $dnl->item(0)->removeAttribute('hot'); - if(is_dir($path . '/' . $file)) - { - $this->listFilesPhase2($dom, $dnl->item(0), $path . '/' . $file, $depth + 1); - } - else - { - $stat = stat($path . '/' . $file); - foreach(array("size", "ctime", "mtime") as $k) - { - if($dnl->item(0)->getAttribute($k) != $stat[$k]) - { - $this->setBranchHot($dom, $dnl->item(0)); - break; - } - } - } - } - } - } - catch(Exception $e) - { - - } - - return; - } - - /** - * makePairs : - * flag files to be archived (make pairs with linked caption when needed) - * flag grp folders and their linked files (caption, representation) - * declare uncomplete grp as error - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $inGrp - * @param $depth - * @return - */ - function makePairs($dom, $node, $path, $path_archived, $path_error, $inGrp=false, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; - - if($depth == 0 && ($node->getAttribute('temperature') == 'hot' || $node->getAttribute('cid') == '-1')) - - return; - - $xpath = new DOMXPath($dom); // useful - - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(($iloop++ % 100) == 0) - usleep(1000); - - // make xml lighter (free ram) - foreach(array("size", "ctime", "mtime") as $k) - $n->removeAttribute($k); - - if($n->getAttribute('temperature') == 'hot' || $n->getAttribute('cid') == '-1') - continue; - - $name = $n->getAttribute('name'); - if($n->getAttribute('isdir') == '1') - { - if(($grpSettings = $this->getGrpSettings($name)) !== FALSE) // get 'caption', 'representation' - { - // this is a grp folder, we check it - - $dnl = $xpath->query('./file[@name=".grouping.xml"]', $n); - if($dnl->length == 1) - { - // this group is old (don't care about any linked files), just flag it - $n->setAttribute('grp', 'tocomplete'); - $dnl->item(0)->setAttribute('match', '*'); - // recurse only if group is ok - $this->makePairs($dom, $n, $path . '/' . $name, true, $depth + 1); - } - else - { - // this group in new (to be created) - // do we need one (or both) linked file ? (caption or representation) - $err = false; - $flink = array('caption' => null, 'representation' => null); - - foreach($flink as $linkName => $v) - { - if(isset($grpSettings[$linkName]) && $grpSettings[$linkName] != '') - { - // we need this linked file, calc his real name - $f = preg_replace('/' . $grpSettings['mask'] . '/i', $grpSettings[$linkName], $name); - - $dnl = $xpath->query('./file[@name="' . $f . '"]', $node); - if($dnl->length == 1) - { - $flink[$linkName] = $dnl->item(0); // it's here + $this->setBranchHot($dom, $n); + } elseif ($dnl && $dnl->length == 1) { + $dnl->item(0)->setAttribute('temperature', 'cold'); + // $dnl->item(0)->removeAttribute('hot'); + if (is_dir($path . '/' . $file)) { + $this->listFilesPhase2($dom, $dnl->item(0), $path . '/' . $file, $depth + 1); + } else { + $stat = stat($path . '/' . $file); + foreach (array("size", "ctime", "mtime") as $k) { + if ($dnl->item(0)->getAttribute($k) != $stat[$k]) { + $this->setBranchHot($dom, $dnl->item(0)); + break; + } + } + } + } } - else - { - $this->log(sprintf(('missing linked file \'%1$s\' to group \'%2$s\''), $f, $name)); - $err = true; // missing -> error - } - } + } catch (Exception $e) { + } - if(!$err) - { - // the group is ok, flag it ... - $n->setAttribute('grp', 'tocreate'); - - // ... as the existing linked file(s) ... - foreach($flink as $linkName => $v) - { - if($v) // this linked file exists - { - // $v->setAttribute('grp', '1'); - $v->setAttribute('match', '*'); - $n->setAttribute('grp_' . $linkName, $v->getAttribute('name')); - } - } - // recurse only if group is ok - $this->makePairs($dom, $n, $path . '/' . $name - , $path_archived . '/' . $name - , $path_error . '/' . $name - , true, $depth + 1); - } - else - { - // something is missing, the whole group goes error, ... - $n->setAttribute('grp', 'todelete'); - - $this->setAllChildren($dom, $n, array('error' => '1')); - - // bubble to the top - for($nn = $n; $nn && $nn->nodeType == XML_ELEMENT_NODE; $nn = $nn->parentNode) - $nn->setAttribute('error', '1'); - - // ... as the existing linked file(s) ... - foreach($flink as $linkName => $v) - { - if($v) // this linked file exists, it goes error also - $v->setAttribute('error', '1'); - } - } - } + return; } - else + + /** + * makePairs : + * flag files to be archived (make pairs with linked caption when needed) + * flag grp folders and their linked files (caption, representation) + * declare uncomplete grp as error + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $inGrp + * @param $depth + * @return + */ + function makePairs($dom, $node, $path, $path_archived, $path_error, $inGrp = false, $depth = 0) { - // not a grp folder, recurse - $this->makePairs($dom, $n, $path . '/' . $name - , $path_archived . '/' . $name - , $path_error . '/' . $name - , $inGrp, $depth + 1); + static $iloop = 0; + if ($depth == 0) + $iloop = 0; + + if ($depth == 0 && ($node->getAttribute('temperature') == 'hot' || $node->getAttribute('cid') == '-1')) + return; + + $xpath = new DOMXPath($dom); // useful + + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if (($iloop ++ % 100) == 0) + usleep(1000); + + // make xml lighter (free ram) + foreach (array("size", "ctime", "mtime") as $k) + $n->removeAttribute($k); + + if ($n->getAttribute('temperature') == 'hot' || $n->getAttribute('cid') == '-1') + continue; + + $name = $n->getAttribute('name'); + if ($n->getAttribute('isdir') == '1') { + if (($grpSettings = $this->getGrpSettings($name)) !== FALSE) { // get 'caption', 'representation' + // this is a grp folder, we check it + + $dnl = $xpath->query('./file[@name=".grouping.xml"]', $n); + if ($dnl->length == 1) { + // this group is old (don't care about any linked files), just flag it + $n->setAttribute('grp', 'tocomplete'); + $dnl->item(0)->setAttribute('match', '*'); + // recurse only if group is ok + $this->makePairs($dom, $n, $path . '/' . $name, true, $depth + 1); + } else { + // this group in new (to be created) + // do we need one (or both) linked file ? (caption or representation) + $err = false; + $flink = array('caption' => null, 'representation' => null); + + foreach ($flink as $linkName => $v) { + if (isset($grpSettings[$linkName]) && $grpSettings[$linkName] != '') { + // we need this linked file, calc his real name + $f = preg_replace('/' . $grpSettings['mask'] . '/i', $grpSettings[$linkName], $name); + + $dnl = $xpath->query('./file[@name="' . $f . '"]', $node); + if ($dnl->length == 1) { + $flink[$linkName] = $dnl->item(0); // it's here + } else { + $this->log(sprintf(('missing linked file \'%1$s\' to group \'%2$s\''), $f, $name)); + $err = true; // missing -> error + } + } + } + + if ( ! $err) { + // the group is ok, flag it ... + $n->setAttribute('grp', 'tocreate'); + + // ... as the existing linked file(s) ... + foreach ($flink as $linkName => $v) { + if ($v) { // this linked file exists + // $v->setAttribute('grp', '1'); + $v->setAttribute('match', '*'); + $n->setAttribute('grp_' . $linkName, $v->getAttribute('name')); + } + } + // recurse only if group is ok + $this->makePairs($dom, $n, $path . '/' . $name + , $path_archived . '/' . $name + , $path_error . '/' . $name + , true, $depth + 1); + } else { + // something is missing, the whole group goes error, ... + $n->setAttribute('grp', 'todelete'); + + $this->setAllChildren($dom, $n, array('error' => '1')); + + // bubble to the top + for ($nn = $n; $nn && $nn->nodeType == XML_ELEMENT_NODE; $nn = $nn->parentNode) + $nn->setAttribute('error', '1'); + + // ... as the existing linked file(s) ... + foreach ($flink as $linkName => $v) { + if ($v) // this linked file exists, it goes error also + $v->setAttribute('error', '1'); + } + } + } + } + else { + // not a grp folder, recurse + $this->makePairs($dom, $n, $path . '/' . $name + , $path_archived . '/' . $name + , $path_error . '/' . $name + , $inGrp, $depth + 1); + } + } else { + // this is a file + if ( ! $n->getAttribute('match')) { // because match can be set before + if ($name == '.phrasea.xml') + $n->setAttribute('match', '*'); // special file(s) always ok + else + $this->checkMatch($dom, $n); + } + } + } + + // scan again for unmatched files + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ( ! $n->getAttribute('isdir') == '1' && ! $n->getAttribute('match')) { + // still no match, now it's an error (bubble to the top) + for ($nn = $n; $nn && $nn->nodeType == XML_ELEMENT_NODE; $nn = $nn->parentNode) + $nn->setAttribute('error', '1'); + } + } + + return; } - } - else - { - // this is a file - if(!$n->getAttribute('match')) // because match can be set before + + /** + * removeBadGroups : + * move files to archived or error dir + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $depth + * @return + */ + function removeBadGroups($dom, $node, $path, $path_archived, $path_error, $depth = 0) { - if($name == '.phrasea.xml') - $n->setAttribute('match', '*'); // special file(s) always ok - else - $this->checkMatch($dom, $n); - } - } - } + static $iloop = 0; + if ($depth == 0) + $iloop = 0; - // scan again for unmatched files - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(!$n->getAttribute('isdir') == '1' && !$n->getAttribute('match')) - { - // still no match, now it's an error (bubble to the top) - for($nn = $n; $nn && $nn->nodeType == XML_ELEMENT_NODE; $nn = $nn->parentNode) - $nn->setAttribute('error', '1'); - } - } + $ret = false; - return; - } + if ($depth == 0 && $node->getAttribute('temperature') == 'hot') // if root of hotfolder if hot, die... + return($ret); - /** - * removeBadGroups : - * move files to archived or error dir - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $depth - * @return - */ - function removeBadGroups($dom, $node, $path, $path_archived, $path_error, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; + $nodesToDel = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if (($iloop ++ % 20) == 0) + usleep(1000); - $ret = false; + if ($n->getAttribute('temperature') == 'hot') // do not move hotfiles + continue; - if($depth == 0 && $node->getAttribute('temperature') == 'hot') // if root of hotfolder if hot, die... + $name = $n->getAttribute('name'); - return($ret); - - $nodesToDel = array(); - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(($iloop++ % 20) == 0) - usleep(1000); - - if($n->getAttribute('temperature') == 'hot') // do not move hotfiles - continue; - - $name = $n->getAttribute('name'); - - if($n->getAttribute('isdir')) - { - // a dir + if ($n->getAttribute('isdir')) { + // a dir // if($n->getAttribute('error') && $this->move_error) // { // @mkdir($path_error . '/' . $name); // } - $ret |= $this->removeBadGroups($dom, $n, $path . '/' . $name - , $path_archived . '/' . $name - , $path_error . '/' . $name - , $depth + 1); - if($n->getAttribute('grp') == 'todelete') - { - $nodesToDel[] = $n; - @unlink($path . '/' . $name); + $ret |= $this->removeBadGroups($dom, $n, $path . '/' . $name + , $path_archived . '/' . $name + , $path_error . '/' . $name + , $depth + 1); + if ($n->getAttribute('grp') == 'todelete') { + $nodesToDel[] = $n; + @unlink($path . '/' . $name); + } + } else { + // a file + if ($n->getAttribute('error')) { + if ($this->move_error) { + $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + $subpath = substr($path, strlen($rootpath)); + $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $name)); + + @mkdir($path_error, 0755, true); + @copy($path . '/' . $name, $path_error . '/' . $name); + } + + $nodesToDel[] = $n; + @unlink($path . '/' . $name); + + $this->movedFiles ++; + } + } + } + + foreach ($nodesToDel as $n) + $n->parentNode->removeChild($n); + + return; } - } - else - { - // a file - if($n->getAttribute('error')) + + /** + * archive : + * archive files + * do special work on grp folders + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $depth + * @return + */ + function archive($dom, $node, $path, $path_archived, $path_error, $depth = 0) { - if($this->move_error) - { - $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - $subpath = substr($path, strlen($rootpath)); - $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $name)); + static $iloop = 0; + if ($depth == 0) + $iloop = 0; - @mkdir($path_error, 0755, true); - @copy($path . '/' . $name, $path_error . '/' . $name); - } + if ($node->getAttribute('temperature') == 'hot') + return; - $nodesToDel[] = $n; - @unlink($path . '/' . $name); + $nodesToDel = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if (($iloop ++ % 20) == 0) + usleep(1000); - $this->movedFiles++; - } - } - } + if ($n->getAttribute('temperature') == 'hot') + continue; - foreach($nodesToDel as $n) - $n->parentNode->removeChild($n); + if ($n->getAttribute('cid') == '-1') { + $n->setAttribute('error', '1'); + continue; + } - return; - } - - /** - * archive : - * archive files - * do special work on grp folders - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $depth - * @return - */ - function archive($dom, $node, $path, $path_archived, $path_error, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; - - if($node->getAttribute('temperature') == 'hot') - - return; - - $nodesToDel = array(); - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(($iloop++ % 20) == 0) - usleep(1000); - - if($n->getAttribute('temperature') == 'hot') - continue; - - if($n->getAttribute('cid') == '-1') - { - $n->setAttribute('error', '1'); - continue; - } - - if($n->getAttribute('isdir') == '1') - { - if($n->getAttribute('grp')) - { - // a grp folder : special work - $this->ArchiveGrp($dom, $n, $path, $path_archived, $path_error, $nodesToDel); - } - else - { - // ...normal subfolder : recurse - $name = $n->getAttribute('name'); - $this->archive($dom, $n, $path . '/' . $name - , $path_archived . '/' . $name - , $path_error . '/' . $name - , $depth + 1); - } - } - else - { - // a file - $this->archiveFile($dom, $n, $path, $path_archived, $path_error, $nodesToDel, 0); // 0 = no grp - } - } + if ($n->getAttribute('isdir') == '1') { + if ($n->getAttribute('grp')) { + // a grp folder : special work + $this->ArchiveGrp($dom, $n, $path, $path_archived, $path_error, $nodesToDel); + } else { + // ...normal subfolder : recurse + $name = $n->getAttribute('name'); + $this->archive($dom, $n, $path . '/' . $name + , $path_archived . '/' . $name + , $path_error . '/' . $name + , $depth + 1); + } + } else { + // a file + $this->archiveFile($dom, $n, $path, $path_archived, $path_error, $nodesToDel, 0); // 0 = no grp + } + } // printf("========== %s === %s ====== \n", __LINE__, var_export($nodesToDel, true)); - foreach($nodesToDel as $n) - $n->parentNode->removeChild($n); + foreach ($nodesToDel as $n) + $n->parentNode->removeChild($n); - // at the end of recursion, restore the magic file (create or delete it) - if(($magicfile = $node->getAttribute('magicfile')) != '') - { - $magicmethod = $node->getAttribute('magicmethod'); - if($magicmethod == 'LOCK') - file_put_contents($path . '/' . $magicfile, ''); - elseif($magicmethod == 'UNLOCK') - unlink($path . '/' . $magicfile); - } + // at the end of recursion, restore the magic file (create or delete it) + if (($magicfile = $node->getAttribute('magicfile')) != '') { + $magicmethod = $node->getAttribute('magicmethod'); + if ($magicmethod == 'LOCK') + file_put_contents($path . '/' . $magicfile, ''); + elseif ($magicmethod == 'UNLOCK') + unlink($path . '/' . $magicfile); + } - return; - } + return; + } - /** - * bubbleResults : - * bubble result attributes ('keep', 'archived', 'error') up to top, - * to help creation of result folders and cleaning of the hotfolder - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $depth - * @return - */ - function bubbleResults($dom, $node, $path, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; + /** + * bubbleResults : + * bubble result attributes ('keep', 'archived', 'error') up to top, + * to help creation of result folders and cleaning of the hotfolder + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $depth + * @return + */ + function bubbleResults($dom, $node, $path, $depth = 0) + { + static $iloop = 0; + if ($depth == 0) + $iloop = 0; - if($node->getAttribute('temperature') == 'hot') + if ($node->getAttribute('temperature') == 'hot') + return; - return; + $ret = 0; + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if (($iloop ++ % 20) == 0) + usleep(1000); - $ret = 0; - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(($iloop++ % 20) == 0) - usleep(1000); - - if($n->getAttribute('name') == '.phrasea.xml' || $n->getAttribute('name') == '.grouping.xml') - { - // special files stay in place AND are copied into 'archived' - $n->setAttribute('keep', '1'); - if(p4field::isyes($this->sxTaskSettings->copy_spe)) - $n->setAttribute('archived', '1'); - } + if ($n->getAttribute('name') == '.phrasea.xml' || $n->getAttribute('name') == '.grouping.xml') { + // special files stay in place AND are copied into 'archived' + $n->setAttribute('keep', '1'); + if (p4field::isyes($this->sxTaskSettings->copy_spe)) + $n->setAttribute('archived', '1'); + } // else // { // if(!$n->getAttribute('isdir') && ($n->getAttribute('temperature') == 'cold' && !$n->getAttribute('archived'))) @@ -1284,69 +1142,66 @@ class task_period_archive extends task_abstract // $n->setAttribute('error', '1'); // } // } - if($n->getAttribute('keep') == '1') - $ret |= 1; - if($n->getAttribute('archived') == '1') - $ret |= 2; - if($n->getAttribute('error') == '1') - $ret |= 4; - if($n->getAttribute('isdir') == '1') - $ret |= $this->bubbleResults($dom, $n, $path . '/' . $n->getAttribute('name'), $depth + 1); - } - if($ret & 1) - $node->setAttribute('keep', '1'); - if($ret & 2) - $node->setAttribute('archived', '1'); - if($ret & 4) - $node->setAttribute('error', '1'); + if ($n->getAttribute('keep') == '1') + $ret |= 1; + if ($n->getAttribute('archived') == '1') + $ret |= 2; + if ($n->getAttribute('error') == '1') + $ret |= 4; + if ($n->getAttribute('isdir') == '1') + $ret |= $this->bubbleResults($dom, $n, $path . '/' . $n->getAttribute('name'), $depth + 1); + } + if ($ret & 1) + $node->setAttribute('keep', '1'); + if ($ret & 2) + $node->setAttribute('archived', '1'); + if ($ret & 4) + $node->setAttribute('error', '1'); - return($ret); - } + return($ret); + } - /** - * Phase 5 : - * move files to archived or error dir - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $depth - * @return - */ - function moveFiles($dom, $node, $path, $path_archived, $path_error, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; + /** + * Phase 5 : + * move files to archived or error dir + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $depth + * @return + */ + function moveFiles($dom, $node, $path, $path_archived, $path_error, $depth = 0) + { + static $iloop = 0; + if ($depth == 0) + $iloop = 0; - $ret = false; + $ret = false; - if($depth == 0 && $node->getAttribute('temperature') == 'hot') // if root of hotfolder if hot, die... - - return($ret); + if ($depth == 0 && $node->getAttribute('temperature') == 'hot') // if root of hotfolder if hot, die... + return($ret); //printf("%s : \n", __LINE__); - $nodesToDel = array(); - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if(($iloop++ % 20) == 0) - usleep(1000); + $nodesToDel = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if (($iloop ++ % 20) == 0) + usleep(1000); - if($n->getAttribute('temperature') == 'hot') // do not move hotfiles - continue; + if ($n->getAttribute('temperature') == 'hot') // do not move hotfiles + continue; //printf("%s : \n", __LINE__); - $name = $n->getAttribute('name'); + $name = $n->getAttribute('name'); //printf("----------------\n file %s : \n ", $path.'/'.$name); //$fp = fopen('php://stdin', 'r'); //fgets($fp); //fclose($fp); - if($n->getAttribute('isdir')) - { + if ($n->getAttribute('isdir')) { // printf("%s : ('%s', '%s')\n", __LINE__, $path_archived, $path_error); // $new_path_archived = $new_path_error = null; // if($n->getAttribute('archived') && $this->move_archived) @@ -1373,717 +1228,647 @@ class task_period_archive extends task_abstract // } // } - $ret |= $this->moveFiles($dom, $n, $path . '/' . $name - , $path_archived . '/' . $name - , $path_error . '/' . $name - , $depth + 1); + $ret |= $this->moveFiles($dom, $n, $path . '/' . $name + , $path_archived . '/' . $name + , $path_error . '/' . $name + , $depth + 1); - if(!$n->firstChild) - $nodesToDel[] = $n; + if ( ! $n->firstChild) + $nodesToDel[] = $n; // ----- JY 20100318 : DO NOT DELETE EMPTY FOLDERS ANYMORE, AS THEY MAY DISAPEAR TOO SOON ----- // if(!$n->getAttribute('keep')) // @rmdir($path.'/'.$name); // -------------------------------------------------------------------------------------------- - } - else - { + } + else { //printf("%s : \n", __LINE__); - $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - $subpath = substr($path, strlen($rootpath)); + $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + $subpath = substr($path, strlen($rootpath)); - if($n->getAttribute('archived') && $this->move_archived) - { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $name)); + if ($n->getAttribute('archived') && $this->move_archived) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $name)); - @mkdir($path_archived, 0755, true); - @copy($path . '/' . $name, $path_archived . '/' . $name); - if(!$n->getAttribute('keep')) // do not count copy of special files as a real event - { - $nodesToDel[] = $n; - $ret = true; - } - } + @mkdir($path_archived, 0755, true); + @copy($path . '/' . $name, $path_archived . '/' . $name); + if ( ! $n->getAttribute('keep')) { // do not count copy of special files as a real event + $nodesToDel[] = $n; + $ret = true; + } + } - if($n->getAttribute('error') && $this->move_error) - { + if ($n->getAttribute('error') && $this->move_error) { // printf("%s : \n", __LINE__); - $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $name)); + $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $name)); - @mkdir($path_error, 0755, true); - @copy($path . '/' . $name, $path_error . '/' . $name); - if(!$n->getAttribute('keep')) // do not count copy of special files as a real event - { - $nodesToDel[] = $n; - $ret = true; - } + @mkdir($path_error, 0755, true); + @copy($path . '/' . $name, $path_error . '/' . $name); + if ( ! $n->getAttribute('keep')) { // do not count copy of special files as a real event + $nodesToDel[] = $n; + $ret = true; + } //printf("-> copy to %s \n", $path_error.'/'.$name); - } + } - if(!$n->getAttribute('keep')) - { + if ( ! $n->getAttribute('keep')) { //printf("-> unlink %s \n", $path.'/'.$name); - $this->log(sprintf(('delete \'%s\''), $subpath . '/' . $name)); - if(@unlink($path . '/' . $name)) - { - // $n->parentNode->removeChild($n); - $this->movedFiles++; - } - else - { - $this->log(sprintf(("Warning : can't delete '%s' from hotfolder, task is stopped"), $subpath . '/' . $name)); - } + $this->log(sprintf(('delete \'%s\''), $subpath . '/' . $name)); + if (@unlink($path . '/' . $name)) { + // $n->parentNode->removeChild($n); + $this->movedFiles ++; + } else { + $this->log(sprintf(("Warning : can't delete '%s' from hotfolder, task is stopped"), $subpath . '/' . $name)); + } + } + } + } + + foreach ($nodesToDel as $n) + $n->parentNode->removeChild($n); + + return($ret); } - } - } - foreach($nodesToDel as $n) - $n->parentNode->removeChild($n); - - return($ret); - } - - /** - * - * @param $dom - * @param $node - * @return - */ - function setBranchHot($dom, $node) - { - for($n = $node; $n; $n = $n->parentNode) - { - if($n->nodeType == XML_ELEMENT_NODE) - { - $n->setAttribute('temperature', 'hot'); - if($n->hasAttribute('pxml')) - break; - } - } - - return; - } - - /** - * - * special work for a grp folder : - * create the grp if needed - * archive files - * - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $nodesToDel - * @return - */ - function archiveGrp($dom, $node, $path, $path_archived, $path_error, &$nodesToDel) - { - $xpath = new DOMXPath($dom); // useful - - $node->setAttribute('keep', '1'); // grp folders stay in place - $grpFolder = $node->getAttribute('name'); - - $groupingFile = $path . '/' . $grpFolder . '/.grouping.xml'; - - if($node->getAttribute('grp') == 'tocreate') - { - $representationFileName = null; - $representationFileNode = null; - $captionFileName = null; - $captionFileNode = null; - $cid = $node->getAttribute('cid'); - $genericdoc = null; - - $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - $subpath = substr($path, strlen($rootpath)); - - $this->log(sprintf(('created story \'%s\''), $subpath . '/' . $grpFolder)); - - // if the .grp does not have a representative doc, let's use a generic file - if(!($rep = $node->getAttribute('grp_representation'))) - { - - $registry = registry::get_instance(); - copy(p4string::addEndSlash($registry->get('GV_RootPath')) . 'www/skins/icons/substitution/regroup_doc.png', $genericdoc = ($path . '/group.jpg')); - $representationFileName = 'group.jpg'; - $this->log((' (no representation file)')); - } - else - { - $dnl = $xpath->query('./file[@name="' . $rep . '"]', $node->parentNode); - $representationFileNode = $dnl->item(0); - $representationFileName = $rep; - $node->removeAttribute('grp_representation'); - $this->log(sprintf(('representation from \'%s\''), $representationFileName)); - } - - if(($cap = $node->getAttribute('grp_caption'))) - { - $dnl = $xpath->query('./file[@name="' . $cap . '"]', $node->parentNode); - $captionFileNode = $dnl->item(0); - $captionFileName = $cap; - $node->removeAttribute('grp_caption'); - $this->log(sprintf(('caption from \'%s\''), $captionFileName)); - } - - $system_file = new system_file($path . '/' . $representationFileName); - - $pi = pathinfo($subpath); - - $caption_file = null; - if(file_exists($path . '/' . $captionFileName)) - { - $caption_file = new system_file($path . '/' . $captionFileName); - } - - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $representationFileName); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, $pi["basename"]); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, $subpath); - - $databox = databox::get_instance($this->sbas_id); - $meta = $system_file->extract_metadatas($databox->get_meta_structure(), $caption_file); - - $stat0 = $stat1 = "0"; - if($this->sxBasePrefs->status) - $stat0 = (string) ($this->sxBasePrefs->status); - if($this->sxTaskSettings->status) - $stat1 = (string) ($this->sxTaskSettings->status); - - if(!$stat0) - $stat0 = '0'; - if(!$stat1) - $stat1 = '0'; - - - try - { - $collection = collection::get_from_coll_id($databox, $cid); - $record = record_adapter::create($collection, $system_file, false, true); - - $record->set_metadatas($meta['metadatas'], true); - $record->set_binary_status(databox_status::operation_or($stat0, $stat1)); - $record->rebuild_subdefs(); - $record->reindex(); - $rid = $record->get_record_id(); - $this->log(sprintf((' (recordId %s)'), $rid)); - $this->archivedFiles++; - - - $rid = $record->get_record_id(); - - - - if($genericdoc) - unlink($genericdoc); - - file_put_contents($groupingFile, ''); - $n = $node->appendChild($dom->createElement('file')); - $n->setAttribute('name', '.grouping.xml'); - $n->setAttribute('temperature', 'cold'); - $n->setAttribute('grp', '1'); - // $n->setAttribute('archived', '1'); - $n->setAttribute('match', '*'); - if($this->move_archived) + /** + * + * @param $dom + * @param $node + * @return + */ + function setBranchHot($dom, $node) { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $grpFolder . '/.grouping.xml')); - @mkdir($path_archived . '/' . $grpFolder, 0755, true); - @copy($path . '/' . $grpFolder . '/.grouping.xml', $path_archived . '/' . $grpFolder . '/.grouping.xml'); - } - // + for ($n = $node; $n; $n = $n->parentNode) { + if ($n->nodeType == XML_ELEMENT_NODE) { + $n->setAttribute('temperature', 'hot'); + if ($n->hasAttribute('pxml')) + break; + } + } - if($captionFileNode) + return; + } + + /** + * + * special work for a grp folder : + * create the grp if needed + * archive files + * + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $nodesToDel + * @return + */ + function archiveGrp($dom, $node, $path, $path_archived, $path_error, &$nodesToDel) { - $captionFileNode->setAttribute('archived', '1'); - if($this->move_archived) - { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $captionFileName)); + $xpath = new DOMXPath($dom); // useful - if(!is_dir($path_archived)) - @mkdir($path_archived, 0755, true); - @copy($path . '/' . $captionFileName, $path_archived . '/' . $captionFileName); - } - @unlink($path . '/' . $captionFileName); - $nodesToDel[] = $captionFileNode; + $node->setAttribute('keep', '1'); // grp folders stay in place + $grpFolder = $node->getAttribute('name'); - $this->movedFiles++; + $groupingFile = $path . '/' . $grpFolder . '/.grouping.xml'; + + if ($node->getAttribute('grp') == 'tocreate') { + $representationFileName = null; + $representationFileNode = null; + $captionFileName = null; + $captionFileNode = null; + $cid = $node->getAttribute('cid'); + $genericdoc = null; + + $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + $subpath = substr($path, strlen($rootpath)); + + $this->log(sprintf(('created story \'%s\''), $subpath . '/' . $grpFolder)); + + // if the .grp does not have a representative doc, let's use a generic file + if ( ! ($rep = $node->getAttribute('grp_representation'))) { + + $registry = registry::get_instance(); + copy(p4string::addEndSlash($registry->get('GV_RootPath')) . 'www/skins/icons/substitution/regroup_doc.png', $genericdoc = ($path . '/group.jpg')); + $representationFileName = 'group.jpg'; + $this->log((' (no representation file)')); + } else { + $dnl = $xpath->query('./file[@name="' . $rep . '"]', $node->parentNode); + $representationFileNode = $dnl->item(0); + $representationFileName = $rep; + $node->removeAttribute('grp_representation'); + $this->log(sprintf(('representation from \'%s\''), $representationFileName)); + } + + if (($cap = $node->getAttribute('grp_caption'))) { + $dnl = $xpath->query('./file[@name="' . $cap . '"]', $node->parentNode); + $captionFileNode = $dnl->item(0); + $captionFileName = $cap; + $node->removeAttribute('grp_caption'); + $this->log(sprintf(('caption from \'%s\''), $captionFileName)); + } + + $system_file = new system_file($path . '/' . $representationFileName); + + $pi = pathinfo($subpath); + + $caption_file = null; + if (file_exists($path . '/' . $captionFileName)) { + $caption_file = new system_file($path . '/' . $captionFileName); + } + + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $representationFileName); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, $pi["basename"]); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, $subpath); + + $databox = databox::get_instance($this->sbas_id); + $meta = $system_file->extract_metadatas($databox->get_meta_structure(), $caption_file); + + $stat0 = $stat1 = "0"; + if ($this->sxBasePrefs->status) + $stat0 = (string) ($this->sxBasePrefs->status); + if ($this->sxTaskSettings->status) + $stat1 = (string) ($this->sxTaskSettings->status); + + if ( ! $stat0) + $stat0 = '0'; + if ( ! $stat1) + $stat1 = '0'; + + + try { + $collection = collection::get_from_coll_id($databox, $cid); + $record = record_adapter::create($collection, $system_file, false, true); + + $record->set_metadatas($meta['metadatas'], true); + $record->set_binary_status(databox_status::operation_or($stat0, $stat1)); + $record->rebuild_subdefs(); + $record->reindex(); + $rid = $record->get_record_id(); + $this->log(sprintf((' (recordId %s)'), $rid)); + $this->archivedFiles ++; + + + $rid = $record->get_record_id(); + + + + if ($genericdoc) + unlink($genericdoc); + + file_put_contents($groupingFile, ''); + $n = $node->appendChild($dom->createElement('file')); + $n->setAttribute('name', '.grouping.xml'); + $n->setAttribute('temperature', 'cold'); + $n->setAttribute('grp', '1'); + // $n->setAttribute('archived', '1'); + $n->setAttribute('match', '*'); + if ($this->move_archived) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $grpFolder . '/.grouping.xml')); + @mkdir($path_archived . '/' . $grpFolder, 0755, true); + @copy($path . '/' . $grpFolder . '/.grouping.xml', $path_archived . '/' . $grpFolder . '/.grouping.xml'); + } + // + + if ($captionFileNode) { + $captionFileNode->setAttribute('archived', '1'); + if ($this->move_archived) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $captionFileName)); + + if ( ! is_dir($path_archived)) + @mkdir($path_archived, 0755, true); + @copy($path . '/' . $captionFileName, $path_archived . '/' . $captionFileName); + } + @unlink($path . '/' . $captionFileName); + $nodesToDel[] = $captionFileNode; + + $this->movedFiles ++; + } + if ($representationFileNode) { + $representationFileNode->setAttribute('archived', '1'); + if ($this->move_archived) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $representationFileName)); + + if ( ! is_dir($path_archived)) + @mkdir($path_archived, 0755, true); + @copy($path . '/' . $representationFileName, $path_archived . '/' . $representationFileName); + } + @unlink($path . '/' . $representationFileName); + $nodesToDel[] = $representationFileNode; + + $this->movedFiles ++; + } + // + $node->setAttribute('grp', 'tocomplete'); + } catch (Exception $e) { + echo $e->getMessage(); + } + } + + // here the .grouping.xml should exists + if (file_exists($groupingFile)) { + // a .grouping.xml must stay in place + // -- don't do, done in phase4 + //$xpath = new DOMXPath($dom); + //$dnl = $xpath->query('./file[@name=".grouping.xml"]', $node); + //if($dnl->length == 1) + // $dnl->item(0)->setAttribute('keep', '1'); + + $sxGrouping = simplexml_load_file($groupingFile); + $grp_rid = $sxGrouping['grouping']; + + $this->archiveFilesToGrp($dom, $node, $path . '/' . $grpFolder + , $path_archived . '/' . $grpFolder + , $path_error . '/' . $grpFolder + , $grp_rid); + } + + return; } - if($representationFileNode) + + /** + * + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $grp_rid + * @return + */ + function archiveFilesToGrp($dom, $node, $path, $path_archived, $path_error, $grp_rid) { - $representationFileNode->setAttribute('archived', '1'); - if($this->move_archived) - { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $representationFileName)); - - if(!is_dir($path_archived)) - @mkdir($path_archived, 0755, true); - @copy($path . '/' . $representationFileName, $path_archived . '/' . $representationFileName); - } - @unlink($path . '/' . $representationFileName); - $nodesToDel[] = $representationFileNode; - - $this->movedFiles++; - } - // - $node->setAttribute('grp', 'tocomplete'); - } - catch(Exception $e) - { - echo $e->getMessage(); - } - } - - // here the .grouping.xml should exists - if(file_exists($groupingFile)) - { - // a .grouping.xml must stay in place - // -- don't do, done in phase4 - //$xpath = new DOMXPath($dom); - //$dnl = $xpath->query('./file[@name=".grouping.xml"]', $node); - //if($dnl->length == 1) - // $dnl->item(0)->setAttribute('keep', '1'); - - $sxGrouping = simplexml_load_file($groupingFile); - $grp_rid = $sxGrouping['grouping']; - - $this->archiveFilesToGrp($dom, $node, $path . '/' . $grpFolder - , $path_archived . '/' . $grpFolder - , $path_error . '/' . $grpFolder - , $grp_rid); - } - - return; - } - - /** - * - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $grp_rid - * @return - */ - function archiveFilesToGrp($dom, $node, $path, $path_archived, $path_error, $grp_rid) - { - //usleep(1000); - $nodesToDel = array(); - for($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if($n->getAttribute('isdir') == '1') - { - // in a grp, all levels goes in the same grp - $node->setAttribute('archived', '1'); // the main grp folder is 'keep'ed, but not subfolders - $this->archiveFilesToGrp($dom, $n, $path . '/' . $n->getAttribute('name') - , $path_archived . '/' . $n->getAttribute('name') - , $path_error . '/' . $n->getAttribute('name') - , $grp_rid); - } - else - { - // a file - $this->archiveFile($dom, $n, $path, $path_archived, $path_error, $nodesToDel, $grp_rid); - } - } + //usleep(1000); + $nodesToDel = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->getAttribute('isdir') == '1') { + // in a grp, all levels goes in the same grp + $node->setAttribute('archived', '1'); // the main grp folder is 'keep'ed, but not subfolders + $this->archiveFilesToGrp($dom, $n, $path . '/' . $n->getAttribute('name') + , $path_archived . '/' . $n->getAttribute('name') + , $path_error . '/' . $n->getAttribute('name') + , $grp_rid); + } else { + // a file + $this->archiveFile($dom, $n, $path, $path_archived, $path_error, $nodesToDel, $grp_rid); + } + } // printf("======== %s %s \n", __LINE__, var_export($nodesToDel, true)); - foreach($nodesToDel as $n) - $n->parentNode->removeChild($n); + foreach ($nodesToDel as $n) + $n->parentNode->removeChild($n); - return; - } - - /** - * Archive File - * - * @param $dom - * @param $node - * @param $path - * @param $path_archived - * @param $path_error - * @param $nodesToDel - * @param $grp_rid - * @return - */ - function archiveFile($dom, $node, $path, $path_archived, $path_error, &$nodesToDel, $grp_rid=0) - { - $match = $node->getAttribute('match'); - if($match == '*') - - return; - - $file = $node->getAttribute('name'); - $cid = $node->getAttribute('cid'); - $captionFileNode = null; - - $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - $subpath = substr($path, strlen($rootpath)); - - - if(!$match) - { - // the file does not match on any mask - $this->log(sprintf(("File '%s' does not match any mask"), $subpath . '/' . $file)); - $node->setAttribute('error', '1'); - - return; - } - elseif($match == '?') - { - // the caption file is missing - $this->log(sprintf(("Caption of file '%s' is missing"), $subpath . '/' . $file)); - $node->setAttribute('error', '1'); - - return; - } - elseif(($match != '.')) // match='.' : the file does not have a separate caption - { - $xpath = new DOMXPath($dom); - $dnl = $xpath->query('./file[@name="' . $match . '"]', $node->parentNode); - // in fact, xquery has been done in checkMatch, setting match='?' if caption does not exists... - if($dnl->length == 1) - { - // ...so we ALWAYS come here - $captionFileNode = $dnl->item(0); - } - else - { - // ...so we should NEVER come here - $node->setAttribute('error', '1'); - - return; - } - } - - $this->archiveFileAndCaption($dom, $node, $captionFileNode, $path, $path_archived, $path_error, $grp_rid, $nodesToDel); - } - - /** - * - * @param $dom - * @param $node - * @param $captionFileNode - * @param $path - * @param $path_archived - * @param $path_error - * @param $grp_rid - * @param $nodesToDel - * @return Void - */ - function archiveFileAndCaption($dom, $node, $captionFileNode, $path, $path_archived, $path_error, $grp_rid, &$nodesToDel) - { - $ret = false; - - $file = $node->getAttribute('name'); - $captionFileName = $captionFileNode ? $captionFileNode->getAttribute('name') : NULL; - - $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); - $subpath = substr($path, strlen($rootpath)); - - $this->log(sprintf(("Archiving file '%s'"), $subpath . '/' . $file)); - if($captionFileName !== NULL) - $this->log(sprintf(' ' . (" (caption in '%s')"), $captionFileName)); - if($grp_rid !== 0) - $this->log(sprintf(' ' . (" into GRP rid=%s"), $grp_rid)); - - $stat0 = $stat1 = "0"; - if($this->sxBasePrefs->status) - $stat0 = (string) ($this->sxBasePrefs->status); - if($this->sxTaskSettings->status) - $stat1 = (string) ($this->sxTaskSettings->status); - if(!$stat0) - $stat0 = '0'; - if(!$stat1) - $stat1 = '0'; - - $system_file = new system_file($path . '/' . $file); - - $caption_file = null; - - if($captionFileName != $file) - { - $caption_file = new system_file($path . '/' . $captionFileName); - } - - $pi = pathinfo($subpath); - - $databox = databox::get_instance($this->sbas_id); - - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $file); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, $pi["basename"]); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, $subpath); - - $meta = $system_file->extract_metadatas($databox->get_meta_structure(), $caption_file); - unset($databox); - - $hexstat = ''; - if($meta['status'] !== NULL) - { - $s = strrev($meta['status']) . str_repeat('0', 64); - for($a = 0; $a < 4; $a++) - $hexstat = substr('0000' . base_convert(strrev(substr($s, $a << 4, 16)), 2, 16), -4) . $hexstat; - } - else - { - $hexstat = '0'; - } - - $lazaret = false; - $uuid = false; - if($grp_rid == 0 && $captionFileName == NULL) - { - $this->log(sprintf(("Checkin for lazaret"))); - try - { - - $base_id = (int) ($this->sxTaskSettings->base_id); - $sbas_id = phrasea::sbasFromBas($base_id); - $sha256 = $system_file->get_sha256(); - - $uuid = false; - if(!$system_file->has_uuid()) - { - try - { - $connbas = connection::getPDOConnection($sbas_id); - $sql = 'SELECT uuid FROM record WHERE sha256 = :sha256'; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':sha256' => $sha256)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if($row && uuid::is_valid($row['uuid'])) - $uuid = $row['uuid']; - } - catch(Exception $e) - { - - } + return; } - $system_file->write_uuid($uuid); - - $error_file = p4file::check_file_error($system_file->getPathname(), $sbas_id, $file); - $status = databox_status::operation_or($stat0, $stat1); - - if($meta['status']) - $status = databox_status::operation_or($status, $meta['status']); - - if(!$system_file->is_new_in_base(phrasea::sbasFromBas($base_id)) || count($error_file) > 0) + /** + * Archive File + * + * @param $dom + * @param $node + * @param $path + * @param $path_archived + * @param $path_error + * @param $nodesToDel + * @param $grp_rid + * @return + */ + function archiveFile($dom, $node, $path, $path_archived, $path_error, &$nodesToDel, $grp_rid = 0) { - $this->log(sprintf(("Trying to move to lazaret"))); - if(lazaretFile::move_uploaded_to_lazaret($system_file, $base_id, $file, implode("\n", $error_file), $status)) - { - $this->log("File %s moved to lazaret"); - $lazaret = true; - $node->setAttribute('archived', '1'); - $this->archivedFiles++; - } + $match = $node->getAttribute('match'); + if ($match == '*') + return; + + $file = $node->getAttribute('name'); + $cid = $node->getAttribute('cid'); + $captionFileNode = null; + + $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + $subpath = substr($path, strlen($rootpath)); + + + if ( ! $match) { + // the file does not match on any mask + $this->log(sprintf(("File '%s' does not match any mask"), $subpath . '/' . $file)); + $node->setAttribute('error', '1'); + + return; + } elseif ($match == '?') { + // the caption file is missing + $this->log(sprintf(("Caption of file '%s' is missing"), $subpath . '/' . $file)); + $node->setAttribute('error', '1'); + + return; + } elseif (($match != '.')) { // match='.' : the file does not have a separate caption + $xpath = new DOMXPath($dom); + $dnl = $xpath->query('./file[@name="' . $match . '"]', $node->parentNode); + // in fact, xquery has been done in checkMatch, setting match='?' if caption does not exists... + if ($dnl->length == 1) { + // ...so we ALWAYS come here + $captionFileNode = $dnl->item(0); + } else { + // ...so we should NEVER come here + $node->setAttribute('error', '1'); + + return; + } + } + + $this->archiveFileAndCaption($dom, $node, $captionFileNode, $path, $path_archived, $path_error, $grp_rid, $nodesToDel); } - else + + /** + * + * @param $dom + * @param $node + * @param $captionFileNode + * @param $path + * @param $path_archived + * @param $path_error + * @param $grp_rid + * @param $nodesToDel + * @return Void + */ + function archiveFileAndCaption($dom, $node, $captionFileNode, $path, $path_archived, $path_error, $grp_rid, &$nodesToDel) { - $this->log("No need to lazaret"); - } - } - catch(Exception $e) - { - $this->log(sprintf(("Error while checking for lazaret : %s"), $e->getMessage())); - } - } + $ret = false; - if(!$lazaret) - { + $file = $node->getAttribute('name'); + $captionFileName = $captionFileNode ? $captionFileNode->getAttribute('name') : NULL; - $cid = $node->getAttribute('cid'); + $rootpath = p4string::delEndSlash(trim((string) ($this->sxTaskSettings->hotfolder))); + $subpath = substr($path, strlen($rootpath)); - $base_id = phrasea::baseFromColl($this->sbas_id, $cid); + $this->log(sprintf(("Archiving file '%s'"), $subpath . '/' . $file)); + if ($captionFileName !== NULL) + $this->log(sprintf(' ' . (" (caption in '%s')"), $captionFileName)); + if ($grp_rid !== 0) + $this->log(sprintf(' ' . (" into GRP rid=%s"), $grp_rid)); - try - { - $collection = collection::get_from_base_id($base_id); - $record = record_adapter::create($collection, $system_file, false, false); - $record->set_metadatas($meta['metadatas'], true); - $record->set_binary_status(databox_status::operation_or(databox_status::operation_or($stat0, $stat1), databox_status::hex2bin($hexstat))); - $record->rebuild_subdefs(); - $record->reindex(); + $stat0 = $stat1 = "0"; + if ($this->sxBasePrefs->status) + $stat0 = (string) ($this->sxBasePrefs->status); + if ($this->sxTaskSettings->status) + $stat1 = (string) ($this->sxTaskSettings->status); + if ( ! $stat0) + $stat0 = '0'; + if ( ! $stat1) + $stat1 = '0'; - $rid = $record->get_record_id(); - if($grp_rid !== NULL) - { - $connbas = connection::getPDOConnection($this->sbas_id); - $sql = "INSERT INTO regroup (id, rid_parent, rid_child, dateadd, ord) + $system_file = new system_file($path . '/' . $file); + + $caption_file = null; + + if ($captionFileName != $file) { + $caption_file = new system_file($path . '/' . $captionFileName); + } + + $pi = pathinfo($subpath); + + $databox = databox::get_instance($this->sbas_id); + + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $file); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, $pi["basename"]); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, $subpath); + + $meta = $system_file->extract_metadatas($databox->get_meta_structure(), $caption_file); + unset($databox); + + $hexstat = ''; + if ($meta['status'] !== NULL) { + $s = strrev($meta['status']) . str_repeat('0', 64); + for ($a = 0; $a < 4; $a ++ ) + $hexstat = substr('0000' . base_convert(strrev(substr($s, $a << 4, 16)), 2, 16), -4) . $hexstat; + } else { + $hexstat = '0'; + } + + $lazaret = false; + $uuid = false; + if ($grp_rid == 0 && $captionFileName == NULL) { + $this->log(sprintf(("Checkin for lazaret"))); + try { + + $base_id = (int) ($this->sxTaskSettings->base_id); + $sbas_id = phrasea::sbasFromBas($base_id); + $sha256 = $system_file->get_sha256(); + + $uuid = false; + if ( ! $system_file->has_uuid()) { + try { + $connbas = connection::getPDOConnection($sbas_id); + $sql = 'SELECT uuid FROM record WHERE sha256 = :sha256'; + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':sha256' => $sha256)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row && uuid::is_valid($row['uuid'])) + $uuid = $row['uuid']; + } catch (Exception $e) { + + } + } + + $system_file->write_uuid($uuid); + + $error_file = p4file::check_file_error($system_file->getPathname(), $sbas_id, $file); + $status = databox_status::operation_or($stat0, $stat1); + + if ($meta['status']) + $status = databox_status::operation_or($status, $meta['status']); + + if ( ! $system_file->is_new_in_base(phrasea::sbasFromBas($base_id)) || count($error_file) > 0) { + $this->log(sprintf(("Trying to move to lazaret"))); + if (lazaretFile::move_uploaded_to_lazaret($system_file, $base_id, $file, implode("\n", $error_file), $status)) { + $this->log("File %s moved to lazaret"); + $lazaret = true; + $node->setAttribute('archived', '1'); + $this->archivedFiles ++; + } + } else { + $this->log("No need to lazaret"); + } + } catch (Exception $e) { + $this->log(sprintf(("Error while checking for lazaret : %s"), $e->getMessage())); + } + } + + if ( ! $lazaret) { + + $cid = $node->getAttribute('cid'); + + $base_id = phrasea::baseFromColl($this->sbas_id, $cid); + + try { + $collection = collection::get_from_base_id($base_id); + $record = record_adapter::create($collection, $system_file, false, false); + $record->set_metadatas($meta['metadatas'], true); + $record->set_binary_status(databox_status::operation_or(databox_status::operation_or($stat0, $stat1), databox_status::hex2bin($hexstat))); + $record->rebuild_subdefs(); + $record->reindex(); + + $rid = $record->get_record_id(); + if ($grp_rid !== NULL) { + $connbas = connection::getPDOConnection($this->sbas_id); + $sql = "INSERT INTO regroup (id, rid_parent, rid_child, dateadd, ord) VALUES (NULL, :rid_parent, :rid_child, NOW(), 0)"; - $params = array( - ':rid_parent' => $grp_rid - , ':rid_child' => $rid - ); + $params = array( + ':rid_parent' => $grp_rid + , ':rid_child' => $rid + ); - $stmt = $connbas->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); + } + $this->archivedFiles ++; + + $node->setAttribute('archived', '1'); + if ($captionFileNode) + $captionFileNode->setAttribute('archived', '1'); + } catch (Exception $e) { + $this->log(("Error : can't insert record : " . $e->getMessage())); + $node->setAttribute('error', '1'); + if ($captionFileNode) + $captionFileNode->setAttribute('error', '1'); + } + } + + if ($node->getAttribute('archived') && $this->move_archived) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $file)); + + @mkdir($path_archived, 0755, true); + @copy($path . '/' . $file, $path_archived . '/' . $file); + if ($captionFileName != $file) { + $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $captionFileName)); + @copy($path . '/' . $captionFileName, $path_archived . '/' . $captionFileName); + } + if ( ! $node->getAttribute('keep')) // do not count copy of special files as a real event + $ret = true; + } + + if ($node->getAttribute('error') && $this->move_error) { + $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $file)); + + @mkdir($path_error, 0755, true); + @copy($path . '/' . $file, $path_error . '/' . $file); + if ($captionFileName != $file) { + $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $captionFileName)); + @copy($path . '/' . $captionFileName, $path_error . '/' . $captionFileName); + } + if ( ! $node->getAttribute('keep')) // do not count copy of special files as a real event + $ret = true; + } + + if ( ! $node->getAttribute('keep')) { + $file = $node->getAttribute('name'); + @unlink($path . '/' . $file); + $nodesToDel[] = $node; + + $this->movedFiles ++; + } + + if ($captionFileNode && ! $captionFileNode->getAttribute('keep')) { + $file = $captionFileNode->getAttribute('name'); + @unlink($path . '/' . $file); + $nodesToDel[] = $captionFileNode; + + $this->movedFiles ++; + } + + return; } - $this->archivedFiles++; - $node->setAttribute('archived', '1'); - if($captionFileNode) - $captionFileNode->setAttribute('archived', '1'); - } - catch(Exception $e) - { - $this->log(("Error : can't insert record : " . $e->getMessage())); - $node->setAttribute('error', '1'); - if($captionFileNode) - $captionFileNode->setAttribute('error', '1'); - } + /** + * xml facility : set attributes to a node and all children + * + * @staticvar int $iloop + * @param $dom + * @param $node + * @param $attributes + * @param $depth + */ + function setAllChildren($dom, $node, $attributes, $depth = 0) + { + static $iloop = 0; + if ($depth == 0) + $iloop = 0; + + foreach ($attributes as $a => $v) + $node->setAttribute($a, $v); + + if (($iloop ++ % 100) == 0) + usleep(1000); + + for ($n = $node->firstChild; $n; $n = $n->nextSibling) + $this->setAllChildren($dom, $n, $attributes, $depth + 1); + } + + /** + * + * @param string $file + * @return + */ + function getGrpSettings($file) + { + $matched = FALSE; + foreach ($this->tmaskgrp as $maskgrp) { + //$attachments = null; + //$attachments["representation"] = null; + //$attachments["caption"] = null; + + $preg_maskgrp = "/" . $maskgrp["mask"] . "/"; + if (preg_match($preg_maskgrp, $file)) { + $matched = $maskgrp; + } + if ($matched) + break; + } + + return($matched); + } } - if($node->getAttribute('archived') && $this->move_archived) + class CListFolder { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $file)); + /** + * + * @var Array + */ + protected $list; - @mkdir($path_archived, 0755, true); - @copy($path . '/' . $file, $path_archived . '/' . $file); - if($captionFileName != $file) - { - $this->log(sprintf(('copy \'%s\' to \'archived\''), $subpath . '/' . $captionFileName)); - @copy($path . '/' . $captionFileName, $path_archived . '/' . $captionFileName); - } - if(!$node->getAttribute('keep')) // do not count copy of special files as a real event - $ret = true; + /** + * + * @param string $path + * @param boolean $sorted + */ + function __construct($path, $sorted = true) + { + $this->list = array(); + if ($hdir = opendir($path)) { + while (false !== ($file = readdir($hdir))) + $this->list[] = $file; + closedir($hdir); + if ($sorted) + natcasesort($this->list); + } + } + + /** + * Destructor + * + */ + function __destruct() + { + unset($this->list); + } + + /** + * + * @return string + */ + function read() + { + return(array_shift($this->list)); + } } - if($node->getAttribute('error') && $this->move_error) - { - $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $file)); - - @mkdir($path_error, 0755, true); - @copy($path . '/' . $file, $path_error . '/' . $file); - if($captionFileName != $file) - { - $this->log(sprintf(('copy \'%s\' to \'error\''), $subpath . '/' . $captionFileName)); - @copy($path . '/' . $captionFileName, $path_error . '/' . $captionFileName); - } - if(!$node->getAttribute('keep')) // do not count copy of special files as a real event - $ret = true; - } - - if(!$node->getAttribute('keep')) - { - $file = $node->getAttribute('name'); - @unlink($path . '/' . $file); - $nodesToDel[] = $node; - - $this->movedFiles++; - } - - if($captionFileNode && !$captionFileNode->getAttribute('keep')) - { - $file = $captionFileNode->getAttribute('name'); - @unlink($path . '/' . $file); - $nodesToDel[] = $captionFileNode; - - $this->movedFiles++; - } - - return; - } - - /** - * xml facility : set attributes to a node and all children - * - * @staticvar int $iloop - * @param $dom - * @param $node - * @param $attributes - * @param $depth - */ - function setAllChildren($dom, $node, $attributes, $depth=0) - { - static $iloop = 0; - if($depth == 0) - $iloop = 0; - - foreach($attributes as $a => $v) - $node->setAttribute($a, $v); - - if(($iloop++ % 100) == 0) - usleep(1000); - - for($n = $node->firstChild; $n; $n = $n->nextSibling) - $this->setAllChildren($dom, $n, $attributes, $depth + 1); - } - - /** - * - * @param string $file - * @return - */ - function getGrpSettings($file) - { - $matched = FALSE; - foreach($this->tmaskgrp as $maskgrp) - { - //$attachments = null; - //$attachments["representation"] = null; - //$attachments["caption"] = null; - - $preg_maskgrp = "/" . $maskgrp["mask"] . "/"; - if(preg_match($preg_maskgrp, $file)) - { - $matched = $maskgrp; - } - if($matched) - break; - } - - return($matched); - } - -} - -class CListFolder -{ - /** - * - * @var Array - */ - protected $list; - - /** - * - * @param string $path - * @param boolean $sorted - */ - function __construct($path, $sorted = true) - { - $this->list = array(); - if($hdir = opendir($path)) - { - while(false !== ($file = readdir($hdir))) - $this->list[] = $file; - closedir($hdir); - if($sorted) - natcasesort($this->list); - } - } - - /** - * Destructor - * - */ - function __destruct() - { - unset($this->list); - } - - /** - * - * @return string - */ - function read() - { - return(array_shift($this->list)); - } - -} diff --git a/lib/classes/task/period/batchupload.class.php b/lib/classes/task/period/batchupload.class.php index 7b788a2427..a7900be847 100644 --- a/lib/classes/task/period/batchupload.class.php +++ b/lib/classes/task/period/batchupload.class.php @@ -18,133 +18,125 @@ class task_period_batchupload extends task_appboxAbstract { - public function getName() - { - return(("Batch upload process (XML Service)")); - } + public function getName() + { + return(("Batch upload process (XML Service)")); + } - public function help() - { - return(("Hello I'm the batch upload process.")); - } + public function help() + { + return(("Hello I'm the batch upload process.")); + } - protected function retrieve_content(appbox $appbox) - { - $conn = $appbox->get_connection(); + protected function retrieve_content(appbox $appbox) + { + $conn = $appbox->get_connection(); - $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) + $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) SET f.error="1", u.error="1" WHERE u.error=0 AND u.base_id NOT IN(SELECT base_id FROM bas)'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); - $sql = 'SELECT uplbatch_id, sbas_id, server_coll_id, usr_id + $sql = 'SELECT uplbatch_id, sbas_id, server_coll_id, usr_id FROM (uplbatch u INNER JOIN bas b USING(base_id)) WHERE complete="1" AND error="0" ORDER BY uplbatch_id'; - $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(); - return $rs; - } - - protected function process_one_content(appbox $appbox, Array $row) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $registry = $appbox->get_registry(); - $conn = $appbox->get_connection(); - $session = $appbox->get_session(); - $this->log(sprintf(('processing batch %s'), $row['uplbatch_id'])); - - $errors = ''; - - $path = NULL; - $coll_id = $row['server_coll_id']; - $sbas_id = $row['sbas_id']; - $usr_id = $row['usr_id']; - $batch_id = $row['uplbatch_id']; - - try - { - $databox = databox::get_instance($sbas_id); - $path = $registry->get('GV_RootPath') . 'tmp/batches/' . $batch_id . '/'; - if (!is_dir($path)) - throw new Exception(sprintf(('Batch directory \'%s\' does not exist'), $path)); - - $user = User_Adapter::getInstance($usr_id, $appbox); - $auth = new Session_Authentication_None($user); - $session->authenticate($auth); - - $sql = 'SELECT * FROM uplfile WHERE uplbatch_id = :batch_id ORDER BY idx'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':batch_id' => $batch_id)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row2) - { - $this->log(sprintf(('archiving file \'%s\''), $row2['filename'])); - - try - { - $system_file = new system_file($path . '/' . $row2['idx']); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $row2['filename']); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, ''); - $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, ''); - - $meta = $system_file->extract_metadatas($databox->get_meta_structure()); - $collection = collection::get_from_coll_id($databox, $coll_id); - - $record = record_adapter::create($collection, $system_file, $row2['filename'], false); - $record->set_metadatas($meta['metadatas'], true); - $record->rebuild_subdefs(); - $record->reindex(); - unset($record); - - @unlink($system_file->getPathname()); - unset($system_file); - } - catch (Exception $e) - { - - } - } - rmdir($path); - unset($databox); - $session->logout(); + return $rs; } - catch (Exception $e) - { - $this->log($e->getMessage()); - $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) + protected function process_one_content(appbox $appbox, Array $row) + { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $registry = $appbox->get_registry(); + $conn = $appbox->get_connection(); + $session = $appbox->get_session(); + $this->log(sprintf(('processing batch %s'), $row['uplbatch_id'])); + + $errors = ''; + + $path = NULL; + $coll_id = $row['server_coll_id']; + $sbas_id = $row['sbas_id']; + $usr_id = $row['usr_id']; + $batch_id = $row['uplbatch_id']; + + try { + $databox = databox::get_instance($sbas_id); + $path = $registry->get('GV_RootPath') . 'tmp/batches/' . $batch_id . '/'; + if ( ! is_dir($path)) + throw new Exception(sprintf(('Batch directory \'%s\' does not exist'), $path)); + + $user = User_Adapter::getInstance($usr_id, $appbox); + $auth = new Session_Authentication_None($user); + $session->authenticate($auth); + + $sql = 'SELECT * FROM uplfile WHERE uplbatch_id = :batch_id ORDER BY idx'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':batch_id' => $batch_id)); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $row2) { + $this->log(sprintf(('archiving file \'%s\''), $row2['filename'])); + + try { + $system_file = new system_file($path . '/' . $row2['idx']); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_ORIGINALNAME, $row2['filename']); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_PARENTDIRECTORY, ''); + $system_file->set_phrasea_tech_field(system_file::TECH_FIELD_SUBPATH, ''); + + $meta = $system_file->extract_metadatas($databox->get_meta_structure()); + $collection = collection::get_from_coll_id($databox, $coll_id); + + $record = record_adapter::create($collection, $system_file, $row2['filename'], false); + $record->set_metadatas($meta['metadatas'], true); + $record->rebuild_subdefs(); + $record->reindex(); + unset($record); + + @unlink($system_file->getPathname()); + unset($system_file); + } catch (Exception $e) { + + } + } + rmdir($path); + unset($databox); + $session->logout(); + } catch (Exception $e) { + $this->log($e->getMessage()); + + $sql = 'UPDATE uplfile AS f INNER JOIN uplbatch AS u USING(uplbatch_id) SET f.error="1", u.error="1" WHERE u.uplbatch_id = :batch_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':batch_id' => $batch_id)); - $stmt->closeCursor(); - $errors = '1'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':batch_id' => $batch_id)); + $stmt->closeCursor(); + $errors = '1'; + } + + $sql = 'UPDATE uplbatch SET complete="2", error = :error + WHERE uplbatch_id = :batch_id'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':error' => $errors, ':batch_id' => $batch_id)); + $stmt->closeCursor(); + + $this->log(sprintf(('finishing batch %s'), $row['uplbatch_id'])); + + return $this; } - $sql = 'UPDATE uplbatch SET complete="2", error = :error - WHERE uplbatch_id = :batch_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':error' => $errors, ':batch_id' => $batch_id)); - $stmt->closeCursor(); - - $this->log(sprintf(('finishing batch %s'), $row['uplbatch_id'])); - - return $this; - } - - protected function post_process_one_content(appbox $appbox, Array $row) - { - return $this; - } - + protected function post_process_one_content(appbox $appbox, Array $row) + { + return $this; + } } diff --git a/lib/classes/task/period/cindexer.class.php b/lib/classes/task/period/cindexer.class.php index 1ca70f87c8..7a7e5d658b 100644 --- a/lib/classes/task/period/cindexer.class.php +++ b/lib/classes/task/period/cindexer.class.php @@ -16,370 +16,358 @@ */ class task_period_cindexer extends task_abstract { - // how to execute indexer (choose in 'run2' method) - private $method; - const METHOD_FORK = 'METHOD_FORK'; - const METHOD_EXEC = 'METHOD_EXEC'; - const METHOD_PROC_OPEN = 'METHOD_PROC_OPEN'; + // how to execute indexer (choose in 'run2' method) + private $method; - /** - * - * @var string - */ - protected $host; + const METHOD_FORK = 'METHOD_FORK'; + const METHOD_EXEC = 'METHOD_EXEC'; + const METHOD_PROC_OPEN = 'METHOD_PROC_OPEN'; - /** - * - * @var int - */ - protected $port; + /** + * + * @var string + */ + protected $host; - /** - * - * @var string - */ - protected $base; + /** + * + * @var int + */ + protected $port; - /** - * - * @var string - */ - protected $user; + /** + * + * @var string + */ + protected $base; - /** - * - * @var string - */ - protected $password; + /** + * + * @var string + */ + protected $user; - /** - * - * @var int - */ - protected $socket; + /** + * + * @var string + */ + protected $password; - /** - * - * @var string - */ - protected $use_sbas; + /** + * + * @var int + */ + protected $socket; - /** - * - * @var string - */ - protected $charset; + /** + * + * @var string + */ + protected $use_sbas; - /** - * - * @var string - */ - protected $nolog; + /** + * + * @var string + */ + protected $charset; - /** - * - * @var string - */ - protected $winsvc_run; + /** + * + * @var string + */ + protected $nolog; - /** - * - * @var string - */ - protected $binpath; + /** + * + * @var string + */ + protected $winsvc_run; - /** - * - * @return string - */ - public function getName() - { - return(_("task::cindexer:Indexation")); - } + /** + * + * @var string + */ + protected $binpath; - /** - * - * @return string - */ - public function help() - { - return(_("task::cindexer:indexing records")); - } + /** + * + * @return string + */ + public function getName() + { + return(_("task::cindexer:Indexation")); + } - /** - * - * @param string $oldxml - * @return string - */ - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); + /** + * + * @return string + */ + public function help() + { + return(_("task::cindexer:indexing records")); + } - $parm2 = $request->get_parms( + /** + * + * @param string $oldxml + * @return string + */ + public function graphic2xml($oldxml) + { + $request = http_request::getInstance(); + + $parm2 = $request->get_parms( 'binpath', 'host', 'port', 'base', 'user', 'password', 'socket', 'use_sbas', 'nolog', 'clng', 'winsvc_run', 'charset' - ); - $dom = new DOMDocument(); - $dom->formatOutput = true; - if($dom->loadXML($oldxml)) - { - $xmlchanged = false; - foreach(array("str:binpath", "str:host", "str:port", "str:base", "str:user", "str:password", "str:socket", "boo:use_sbas", "boo:nolog", "str:clng", "boo:winsvc_run", "str:charset") as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while(($n = $ns->firstChild)) - $ns->removeChild($n); + ); + $dom = new DOMDocument(); + $dom->formatOutput = true; + if ($dom->loadXML($oldxml)) { + $xmlchanged = false; + foreach (array("str:binpath", "str:host", "str:port", "str:base", "str:user", "str:password", "str:socket", "boo:use_sbas", "boo:nolog", "str:clng", "boo:winsvc_run", "str:charset") as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cr�e + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; + } } - else - { - // le champ n'existait pas dans le xml, on le cr�e - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + + return($dom->saveXML()); + } + + /** + * + * @param string $xml + * @param string $form + * @return string + */ + public function xml2graphic($xml, $form) + { + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + ?> + + appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; + } + + /** + * + * @return void + */ + public function printInterfaceJS() + { + $appname = 'phraseanet_indexer'; + if ($this->system == 'WINDOWS') + $appname .= '.exe'; + ?> + + system == 'WINDOWS') + $appname .= '.exe'; + ob_start(); + ?> +
                  +
                  +  :  +  /  +
                  +  :  +
                  +  :  +
                  +  :  +
                  +  :  +
                  +  :  +
                  +
                  + +  :  +
                  +
                  + +
                  +   +
                  +
                  + +  :  +
                  +
                  + +   +
                  + +  :  +
                  +
                  + +
                  + +
                  +  :
                  +   +
                  + +
                  +
                  +
                  +
                  cmd
                  +
                  + saveXML()); - } - - /** - * - * @param string $xml - * @param string $form - * @return string - */ - public function xml2graphic($xml, $form) - { - if(($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... - { - ?> - - system == 'WINDOWS') - $appname .= '.exe'; - ?> - - method = self::METHOD_PROC_OPEN; + $this->method = self::METHOD_FORK; + $this->method = self::METHOD_EXEC; - /** - * - * @return string - */ - function getGraphicForm() - { - return true; - } + $cmd = $this->binpath . 'phraseanet_indexer'; + $nullfile = '/dev/null'; - /** - * - * @return return - */ - public function printInterfaceHTML() - { - $appname = 'phraseanet_indexer'; - if($this->system == 'WINDOWS') - $appname .= '.exe'; - ob_start(); - ?> -
                  -
                  -  :  -  /  -
                  -  :  -
                  -  :  -
                  -  :  -
                  -  :  -
                  -  :  -
                  -
                  + if ($this->system == 'WINDOWS') { + $cmd .= '.exe'; + $nullfile = 'NULL'; + } -  :  -
                  -
                  + if ( ! file_exists($cmd) || ! is_executable($cmd)) { + $this->log(sprintf(_('task::cindexer:file \'%s\' does not exists'), $cmd)); -
                  -   -
                  -
                  - -  :  -
                  -
                  - -   -
                  - -  :  -
                  -
                  - -
                  - -
                  -  :
                  -   -
                  - -
                  -
                  -
                  -
                  cmd
                  -
                  - host = trim($sx_task_settings->host); - $this->port = trim($sx_task_settings->port); - $this->base = trim($sx_task_settings->base); - $this->user = trim($sx_task_settings->user); - $this->password = trim($sx_task_settings->password); - $this->socket = trim($sx_task_settings->socket); - $this->use_sbas = p4field::isyes(trim($sx_task_settings->use_sbas)); - $this->charset = trim($sx_task_settings->charset); - $this->nolog = p4field::isyes(trim($sx_task_settings->nolog)); - $this->winsvc_run = p4field::isyes(trim($sx_task_settings->winsvc_run)); - $this->binpath = p4string::addEndSlash(trim($sx_task_settings->binpath)); - - parent::load_settings($sx_task_settings); - - return $this; - } - - /** - * - * @return string - */ - protected function run2() - { - $this->method = self::METHOD_PROC_OPEN; - $this->method = self::METHOD_FORK; - $this->method = self::METHOD_EXEC; - - $cmd = $this->binpath . 'phraseanet_indexer'; - $nullfile = '/dev/null'; - - if($this->system == 'WINDOWS') - { - $cmd .= '.exe'; - $nullfile = 'NULL'; - } - - if(!file_exists($cmd) || !is_executable($cmd)) - { - $this->log(sprintf(_('task::cindexer:file \'%s\' does not exists'), $cmd)); - - return; - } + return; + } // $cmd .= $this->host ? " -h=" . $this->host : ''; // $cmd .= $this->port ? " -P=" . $this->port : ''; @@ -392,245 +380,205 @@ class task_period_cindexer extends task_abstract // $cmd .= $this->nolog ? " -n" : ''; // $cmd .= $this->winsvc_run ? " --run" : ''; - $args = array(); - if($this->host) - $args[] = '-h=' . $this->host; - if($this->port) - ; - $args[] = '-P=' . $this->port; - if($this->base) - $args[] = '-b=' . $this->base; - if($this->user) - $args[] = '-u=' . $this->user; - if($this->password) - $args[] = '-p=' . $this->password; - if($this->socket) - $args[] = '--socket=' . $this->socket; - if($this->use_sbas) - $args[] = '-o'; - if($this->charset) - $args[] = '--default-character-set=' . $this->charset; - if($this->nolog) - $args[] = '-n'; - if($this->winsvc_run) - $args[] = '--run'; + $args = array(); + if ($this->host) + $args[] = '-h=' . $this->host; + if ($this->port) + ; + $args[] = '-P=' . $this->port; + if ($this->base) + $args[] = '-b=' . $this->base; + if ($this->user) + $args[] = '-u=' . $this->user; + if ($this->password) + $args[] = '-p=' . $this->password; + if ($this->socket) + $args[] = '--socket=' . $this->socket; + if ($this->use_sbas) + $args[] = '-o'; + if ($this->charset) + $args[] = '--default-character-set=' . $this->charset; + if ($this->nolog) + $args[] = '-n'; + if ($this->winsvc_run) + $args[] = '--run'; - $registry = registry::get_instance(); - $logdir = p4string::addEndSlash($registry->get('GV_RootPath') . 'logs'); + $registry = registry::get_instance(); + $logdir = p4string::addEndSlash($registry->get('GV_RootPath') . 'logs'); - $this->return_value = self::RETURNSTATUS_STOPPED; // will be normal ending + $this->return_value = self::RETURNSTATUS_STOPPED; // will be normal ending - if($this->method == self::METHOD_PROC_OPEN) - { - $descriptors = array(); + if ($this->method == self::METHOD_PROC_OPEN) { + $descriptors = array(); // $descriptors[1] = array("file", $logdir . "/phraseanet_indexer_" . $this->get_task_id() . ".log", "a+"); // $descriptors[2] = array("file", $logdir . "/phraseanet_indexer_" . $this->get_task_id() . ".error.log", "a+"); - $descriptors[1] = array("file", $nullfile, "a+"); - $descriptors[2] = array("file", $nullfile, "a+"); + $descriptors[1] = array("file", $nullfile, "a+"); + $descriptors[2] = array("file", $nullfile, "a+"); - $pipes = array(); + $pipes = array(); - $this->log(sprintf('cmd=\'%s %s\'', $cmd, implode(' ', $args))); - $process = proc_open($cmd . ' ' . implode(' ', $args), $descriptors, $pipes, $this->binpath, null, array('bypass_shell' => true)); + $this->log(sprintf('cmd=\'%s %s\'', $cmd, implode(' ', $args))); + $process = proc_open($cmd . ' ' . implode(' ', $args), $descriptors, $pipes, $this->binpath, null, array('bypass_shell' => true)); - $pid = NULL; - if(is_resource($process)) - { - $proc_status = proc_get_status($process); - if($proc_status['running']) - $pid = $proc_status['pid']; - } + $pid = NULL; + if (is_resource($process)) { + $proc_status = proc_get_status($process); + if ($proc_status['running']) + $pid = $proc_status['pid']; + } - $qsent = ''; - $timetokill = NULL; - $sock = NULL; + $qsent = ''; + $timetokill = NULL; + $sock = NULL; - $this->running = true; + $this->running = true; - while($this->running) - { - $this->check_task_status(); + while ($this->running) { + $this->check_task_status(); - if($this->task_status == self::STATUS_TOSTOP && $this->socket > 0) - { - // must quit task, so send 'Q' to port 127.0.0.1:XXXX to cindexer - if(!$qsent && (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) !== false)) - { - if(socket_connect($sock, '127.0.0.1', $this->socket) === true) - { - socket_write($sock, 'Q', 1); - socket_write($sock, "\r\n", strlen("\r\n")); - for($i=0; $this->running && $i<5; $i++) - sleep(1); - $qsent = 'Q'; - $timetokill = time() + 10; + if ($this->task_status == self::STATUS_TOSTOP && $this->socket > 0) { + // must quit task, so send 'Q' to port 127.0.0.1:XXXX to cindexer + if ( ! $qsent && (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) !== false)) { + if (socket_connect($sock, '127.0.0.1', $this->socket) === true) { + socket_write($sock, 'Q', 1); + socket_write($sock, "\r\n", strlen("\r\n")); + for ($i = 0; $this->running && $i < 5; $i ++ ) + sleep(1); + $qsent = 'Q'; + $timetokill = time() + 10; + } else { + socket_close($sock); + $sock = NULL; + } + } + } + + $proc_status = proc_get_status($process); + if ( ! $proc_status['running']) { + // the cindexer died + if ($qsent == 'Q') { + $this->log(_('task::cindexer:the cindexer clean-quit')); + } elseif ($qsent == 'K') { + $this->log(_('task::cindexer:the cindexer has been killed')); + } else { + $this->log(_('task::cindexer:the cindexer crashed')); + $this->return_value = NULL; // NOT normal ending will enforce restart from scheduler + } + $this->running = false; + } else { + if ($qsent == 'Q') { + if (time() > $timetokill) { + // must kill cindexer + $this->log(_('task::cindexer:killing the cindexer')); + $qsent = 'K'; + proc_terminate($process); // sigint + } + } + } + for ($i = 0; $this->running && $i < 5; $i ++ ) + sleep(1); + } + + if ($sock) { + socket_close($sock); + $sock = NULL; + } + + foreach (array_keys($pipes) as $offset) { + if (is_resource($pipes[$offset])) + fclose($pipes[$offset]); + } + + proc_terminate($process); // sigint + proc_close($process); } - else - { - socket_close($sock); - $sock = NULL; - } - } - } - - $proc_status = proc_get_status($process); - if(!$proc_status['running']) - { - // the cindexer died - if($qsent == 'Q') - { - $this->log(_('task::cindexer:the cindexer clean-quit')); - } - elseif($qsent == 'K') - { - $this->log(_('task::cindexer:the cindexer has been killed')); - } - else - { - $this->log(_('task::cindexer:the cindexer crashed')); - $this->return_value = NULL; // NOT normal ending will enforce restart from scheduler - } - $this->running = false; - } - else - { - if($qsent == 'Q') - { - if(time() > $timetokill) - { - // must kill cindexer - $this->log(_('task::cindexer:killing the cindexer')); - $qsent = 'K'; - proc_terminate($process); // sigint - } - } - } - for($i=0; $this->running && $i<5; $i++) - sleep(1); - } - - if($sock) - { - socket_close($sock); - $sock = NULL; - } - - foreach(array_keys($pipes) as $offset) - { - if(is_resource($pipes[$offset])) - fclose($pipes[$offset]); - } - - proc_terminate($process); // sigint - proc_close($process); - } - elseif($this->method == self::METHOD_FORK) - { - $pid = pcntl_fork(); - if($pid == -1) - { - die("failed to fork"); - } - elseif($pid == 0) - { - // child - umask(0); - // openlog('MyLog', LOG_PID | LOG_PERROR, LOG_LOCAL0); - if(posix_setsid() < 0) - die("Forked process could not detach from terminal\n"); - //chdir(dirname(__FILE__)); - fclose(STDIN); - fclose(STDOUT); - fclose(STDERR); - $fdIN = fopen($nullfile, 'r'); + elseif ($this->method == self::METHOD_FORK) { + $pid = pcntl_fork(); + if ($pid == -1) { + die("failed to fork"); + } elseif ($pid == 0) { + // child + umask(0); + // openlog('MyLog', LOG_PID | LOG_PERROR, LOG_LOCAL0); + if (posix_setsid() < 0) + die("Forked process could not detach from terminal\n"); + //chdir(dirname(__FILE__)); + fclose(STDIN); + fclose(STDOUT); + fclose(STDERR); + $fdIN = fopen($nullfile, 'r'); // $fdOUT = fopen($nullfile, 'a+'); // $fdERR = fopen($nullfile, 'a+'); - $fdOUT = fopen($logdir . "/task_o_" . $this->get_task_id() . ".log", "a+"); - $fdERR = fopen($logdir . "/task_e_" . $this->get_task_id() . ".log", "a+"); + $fdOUT = fopen($logdir . "/task_o_" . $this->get_task_id() . ".log", "a+"); + $fdERR = fopen($logdir . "/task_e_" . $this->get_task_id() . ".log", "a+"); - pcntl_exec($cmd, $args); + pcntl_exec($cmd, $args); - sleep(2); - } - else - { - // parent - $this->running = true; + sleep(2); + } + else { + // parent + $this->running = true; - $sigsent = NULL; - while($this->running) - { - // is the cindexer alive ? - if(!posix_kill($pid, 0)) - { - // dead... - if($sigsent === NULL) - { - // but it's not my fault - $this->log(_('task::cindexer:the cindexer crashed')); - $this->running = false; - // return self::RETURNSTATUS_STOPPED; - break; - } - } + $sigsent = NULL; + while ($this->running) { + // is the cindexer alive ? + if ( ! posix_kill($pid, 0)) { + // dead... + if ($sigsent === NULL) { + // but it's not my fault + $this->log(_('task::cindexer:the cindexer crashed')); + $this->running = false; + // return self::RETURNSTATUS_STOPPED; + break; + } + } - $this->check_task_status(); + $this->check_task_status(); - if($this->task_status == self::STATUS_TOSTOP) - { - posix_kill($pid, ($sigsent=SIGINT)); - sleep(2); - } + if ($this->task_status == self::STATUS_TOSTOP) { + posix_kill($pid, ($sigsent = SIGINT)); + sleep(2); + } - $status = NULL; - if(pcntl_wait($status, WNOHANG) == $pid) - { - // child (indexer) has exited - if($sigsent == SIGINT) - { - $this->log(_('task::cindexer:the cindexer clean-quit')); + $status = NULL; + if (pcntl_wait($status, WNOHANG) == $pid) { + // child (indexer) has exited + if ($sigsent == SIGINT) { + $this->log(_('task::cindexer:the cindexer clean-quit')); + } elseif ($sigsent == SIGKILL) { + $this->log(_('task::cindexer:the cindexer has been killed')); + } else { + $this->log(_('task::cindexer:the cindexer crashed')); + $this->return_value = NULL; // NOT normal ending will enforce restart from scheduler + } + $this->running = false; + } else { + if ($sigsent == SIGINT && time() > $timetokill) { + // must kill cindexer + $this->log(_('task::cindexer:killing the cindexer')); + $qsent = 'K'; + posix_kill($pid, ($sigsent = SIGKILL)); + } + sleep(2); + } + } // while running (method fork) + } + } elseif ($this->method == self::METHOD_EXEC) { + umask(0); + fclose(STDIN); + fclose(STDOUT); + fclose(STDERR); + $fdIN = fopen($nullfile, 'r'); + $fdOUT = fopen($logdir . "/task_o_" . $this->get_task_id() . ".log", "a+"); + $fdERR = fopen($logdir . "/task_e_" . $this->get_task_id() . ".log", "a+"); + + pcntl_exec($cmd, $args); + + sleep(2); } - elseif($sigsent == SIGKILL) - { - $this->log(_('task::cindexer:the cindexer has been killed')); - } - else - { - $this->log(_('task::cindexer:the cindexer crashed')); - $this->return_value = NULL; // NOT normal ending will enforce restart from scheduler - } - $this->running = false; - } - else - { - if($sigsent == SIGINT && time() > $timetokill) - { - // must kill cindexer - $this->log(_('task::cindexer:killing the cindexer')); - $qsent = 'K'; - posix_kill($pid, ($sigsent=SIGKILL)); - } - sleep(2); - } - } // while running (method fork) - } - } - elseif($this->method == self::METHOD_EXEC) - { - umask(0); - fclose(STDIN); - fclose(STDOUT); - fclose(STDERR); - $fdIN = fopen($nullfile, 'r'); - $fdOUT = fopen($logdir . "/task_o_" . $this->get_task_id() . ".log", "a+"); - $fdERR = fopen($logdir . "/task_e_" . $this->get_task_id() . ".log", "a+"); - pcntl_exec($cmd, $args); - - sleep(2); + return($this->return_value); + } } - return($this->return_value); - } - -} diff --git a/lib/classes/task/period/emptyColl.class.php b/lib/classes/task/period/emptyColl.class.php index 300a497e47..284161d42b 100644 --- a/lib/classes/task/period/emptyColl.class.php +++ b/lib/classes/task/period/emptyColl.class.php @@ -17,66 +17,61 @@ */ class task_period_emptyColl extends task_appboxAbstract { + protected $base_id; + protected $suicidable = true; - protected $base_id; - protected $suicidable = true; - - public function getName() - { - return(_("Vidage de collection")); - } - - public static function interfaceAvailable() - { - return false; - } - - public function help() - { - return("Vide une collection"); - } - - protected function load_settings(SimpleXMLElement $sx_task_settings) - { - $this->base_id = (int) $sx_task_settings->base_id; - parent::load_settings($sx_task_settings); - - return $this; - } - - protected $total_records = 0; - - protected function retrieve_content(appbox $appbox) - { - if(!$this->base_id) + public function getName() { - $this->current_state = self::STATE_FINISHED; - - return; - } - $collection = collection::get_from_base_id($this->base_id); - $this->total_records = $collection->get_record_amount(); - $collection->empty_collection(200); - $this->records_done +=$this->total_records; - $this->setProgress($this->records_done, $this->total_records); - - if ($this->total_records == 0) - { - $this->current_state = self::STATE_FINISHED; - $this->log('Job finished'); + return(_("Vidage de collection")); } - return array(); - } + public static function interfaceAvailable() + { + return false; + } - protected function process_one_content(appbox $appbox, Array $row) - { - return $this; - } + public function help() + { + return("Vide une collection"); + } - protected function post_process_one_content(appbox $appbox, Array $row) - { - return $this; - } + protected function load_settings(SimpleXMLElement $sx_task_settings) + { + $this->base_id = (int) $sx_task_settings->base_id; + parent::load_settings($sx_task_settings); + return $this; + } + protected $total_records = 0; + + protected function retrieve_content(appbox $appbox) + { + if ( ! $this->base_id) { + $this->current_state = self::STATE_FINISHED; + + return; + } + $collection = collection::get_from_base_id($this->base_id); + $this->total_records = $collection->get_record_amount(); + $collection->empty_collection(200); + $this->records_done +=$this->total_records; + $this->setProgress($this->records_done, $this->total_records); + + if ($this->total_records == 0) { + $this->current_state = self::STATE_FINISHED; + $this->log('Job finished'); + } + + return array(); + } + + protected function process_one_content(appbox $appbox, Array $row) + { + return $this; + } + + protected function post_process_one_content(appbox $appbox, Array $row) + { + return $this; + } } diff --git a/lib/classes/task/period/ftp.class.php b/lib/classes/task/period/ftp.class.php index 36da0a3b57..58d850fde0 100644 --- a/lib/classes/task/period/ftp.class.php +++ b/lib/classes/task/period/ftp.class.php @@ -17,772 +17,685 @@ class task_period_ftp extends task_appboxAbstract { - /** - * - * @return string - */ - public function getName() - { - return(_("task::ftp:FTP Push")); - } - - - /** - * - * @return string - */ - public function help() - { - return ''; - } - - /** - * - * @param string $oldxml - * @return string - */ - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - "proxy" - , "proxyport" - , "period" - ); - if ($dom = @DOMDocument::loadXML($oldxml)) + /** + * + * @return string + */ + public function getName() { - $xmlchanged = false; - foreach (array("str:proxy", "str:proxyport", "str:period") as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return(_("task::ftp:FTP Push")); } - return($dom->saveXML()); - } - - /** - * - * @param string $xml - * @param string $form - * @return string - */ - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + /** + * + * @return string + */ + public function help() { - // ... but we could check for safe values (ex. 0 < period < 3600) -?> - - - - -
                  -
                  - -
                  -
                  - -
                  -
                  - -  :  - -  
                  -
                  -get_parms("xml", "name", "active", "proxy", "proxyport", "period", "debug"); - - if ($parm["xml"] === null) - { - // pas de xml 'raw' : on accepte les champs 'graphic view' - if ($domTaskSettings = @DOMDocument::loadXML($taskrow["settings"])) - { - $xmlchanged = false; - foreach (array("proxy", "proxyport", "period") as $f) - { - if ($parm[$f] !== NULL) - { - if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); + $parm2 = $request->get_parms( + "proxy" + , "proxyport" + , "period" + ); + if ($dom = @DOMDocument::loadXML($oldxml)) { + $xmlchanged = false; + foreach (array("str:proxy", "str:proxyport", "str:period") as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $dom->documentElement->appendChild($dom->createTextNode("\t")); + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + $dom->documentElement->appendChild($dom->createTextNode("\n")); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; } - else - { - // le champ n'existait pas dans le xml, on le cree - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); - $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); - } - // on fixe sa valeur - $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); - $xmlchanged = true; - } } - if ($xmlchanged) - $parm["xml"] = $domTaskSettings->saveXML(); - } + + return($dom->saveXML()); } - // si on doit changer le xml, on verifie qu'il est valide - if ($parm["xml"] && !@DOMDocument::loadXML($parm["xml"])) - - return(false); - - $sql = ""; - $params = array(':task_id' => $taskid); - if ($parm["xml"] !== NULL) + /** + * + * @param string $xml + * @param string $form + * @return string + */ + public function xml2graphic($xml, $form) { - $sql .= ( $sql ? " ," : "") . "settings = :settings"; - $params[':settings'] = $parm['xml']; - } - if ($parm["name"] !== NULL) - { - $sql .= ( $sql ? " ," : "") . "name = :name"; - $params[':name'] = $parm['name']; - } - if ($parm["active"] !== NULL) - { - $sql .= ( $sql ? " ," : "") . "active = :active"; - $params[':active'] = $parm['active']; + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values (ex. 0 < period < 3600) + ?> + + prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + ?> + + +
                  +
                  + +
                  +
                  + +
                  +
                  - protected $proxy; - protected $proxyport; - protected $debug; +  :  + +  
                  +
                  + proxy = (string) $sx_task_settings->proxy; - $this->proxyport = (string) $sx_task_settings->proxyport; + return $out; + } - parent::load_settings($sx_task_settings); + public function saveChanges(connection_pdo $conn, $taskid, &$taskrow) + { + $request = http_request::getInstance(); - return $this; - } + $parm = $request->get_parms("xml", "name", "active", "proxy", "proxyport", "period", "debug"); - protected function retrieve_content(appbox $appbox) - { - $conn = $appbox->get_connection(); + if ($parm["xml"] === null) { + // pas de xml 'raw' : on accepte les champs 'graphic view' + if ($domTaskSettings = @DOMDocument::loadXML($taskrow["settings"])) { + $xmlchanged = false; + foreach (array("proxy", "proxyport", "period") as $f) { + if ($parm[$f] !== NULL) { + if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); + $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); + } + // on fixe sa valeur + $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); + $xmlchanged = true; + } + } + if ($xmlchanged) + $parm["xml"] = $domTaskSettings->saveXML(); + } + } - $time2sleep = null; - $ftp_exports = array(); + // si on doit changer le xml, on verifie qu'il est valide + if ($parm["xml"] && ! @DOMDocument::loadXML($parm["xml"])) + return(false); - $period = $this->period; - $time2sleep = (int) ($period); + $sql = ""; + $params = array(':task_id' => $taskid); + if ($parm["xml"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "settings = :settings"; + $params[':settings'] = $parm['xml']; + } + if ($parm["name"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "name = :name"; + $params[':name'] = $parm['name']; + } + if ($parm["active"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "active = :active"; + $params[':active'] = $parm['active']; + } - $sql = "SELECT id FROM ftp_export WHERE crash>=nbretry + if ($sql) { + try { + $sql = "UPDATE task2 SET $sql WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); + + return true; + } catch (Exception $e) { + return false; + } + } else { + return true; + } + } + protected $proxy; + protected $proxyport; + protected $debug; + + protected function load_settings(SimpleXMLElement $sx_task_settings) + { + $this->proxy = (string) $sx_task_settings->proxy; + $this->proxyport = (string) $sx_task_settings->proxyport; + + parent::load_settings($sx_task_settings); + + return $this; + } + + protected function retrieve_content(appbox $appbox) + { + $conn = $appbox->get_connection(); + + $time2sleep = null; + $ftp_exports = array(); + + $period = $this->period; + $time2sleep = (int) ($period); + + $sql = "SELECT id FROM ftp_export WHERE crash>=nbretry AND date < :date"; - $params = array(':date' => phraseadate::format_mysql(new DateTime('-30 days'))); + $params = array(':date' => phraseadate::format_mysql(new DateTime('-30 days'))); - $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 $rowtask) - { - $sql = "DELETE FROM ftp_export WHERE id = :export_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $rowtask['id'])); - $stmt->closeCursor(); + foreach ($rs as $rowtask) { + $sql = "DELETE FROM ftp_export WHERE id = :export_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $rowtask['id'])); + $stmt->closeCursor(); - $sql = "DELETE FROM ftp_export_elements WHERE ftp_export_id = :export_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $rowtask['id'])); - $stmt->closeCursor(); - } + $sql = "DELETE FROM ftp_export_elements WHERE ftp_export_id = :export_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $rowtask['id'])); + $stmt->closeCursor(); + } - $sql = "SELECT * FROM ftp_export WHERE crashprepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $sql = "SELECT * FROM ftp_export WHERE crashprepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - foreach ($rs as $row) - { - $ftp_exports[$row["id"]] = array_merge(array('files' => array()), $row); - } + foreach ($rs as $row) { + $ftp_exports[$row["id"]] = array_merge(array('files' => array()), $row); + } - $sql = "SELECT e.* from ftp_export f + $sql = "SELECT e.* from ftp_export f INNER JOIN ftp_export_elements e ON (f.id=e.ftp_export_id AND f.crashprepare($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 $rowtask) - { - if (isset($ftp_exports[$rowtask["ftp_export_id"]])) - $ftp_exports[$rowtask["ftp_export_id"]]["files"][] = $rowtask; - } + foreach ($rs as $rowtask) { + if (isset($ftp_exports[$rowtask["ftp_export_id"]])) + $ftp_exports[$rowtask["ftp_export_id"]]["files"][] = $rowtask; + } - return $ftp_exports; - } + return $ftp_exports; + } - protected function process_one_content(appbox $appbox, Array $ftp_export) - { - $conn = $appbox->get_connection(); - $registry = $appbox->get_registry(); + protected function process_one_content(appbox $appbox, Array $ftp_export) + { + $conn = $appbox->get_connection(); + $registry = $appbox->get_registry(); - $id = $ftp_export['id']; - $ftp_export[$id]["crash"] = $ftp_export["crash"]; - $ftp_export[$id]["nbretry"] = $ftp_export["nbretry"] < 1 ? 3 : (int) $ftp_export["nbretry"]; + $id = $ftp_export['id']; + $ftp_export[$id]["crash"] = $ftp_export["crash"]; + $ftp_export[$id]["nbretry"] = $ftp_export["nbretry"] < 1 ? 3 : (int) $ftp_export["nbretry"]; - $state = ""; - $ftp_server = $ftp_export["addr"]; - $ftp_user_name = $ftp_export["login"]; - $ftp_user_pass = $ftp_export["pwd"]; - $usr_id = (int) $ftp_export["usr_id"]; + $state = ""; + $ftp_server = $ftp_export["addr"]; + $ftp_user_name = $ftp_export["login"]; + $ftp_user_pass = $ftp_export["pwd"]; + $usr_id = (int) $ftp_export["usr_id"]; - $ftpLog = $ftp_user_name . "@" . p4string::addEndSlash($ftp_server) . $ftp_export["destfolder"]; + $ftpLog = $ftp_user_name . "@" . p4string::addEndSlash($ftp_server) . $ftp_export["destfolder"]; - if ($ftp_export["crash"] == 0) - { - $state .= $line = sprintf( - _('task::ftp:Etat d\'envoi FTP vers le serveur' . - ' "%1$s" avec le compte "%2$s" et pour destination le dossier : "%3$s"') . PHP_EOL - , $ftp_server - , $ftp_user_name - , $ftp_export["destfolder"] - ); + if ($ftp_export["crash"] == 0) { + $state .= $line = sprintf( + _('task::ftp:Etat d\'envoi FTP vers le serveur' . + ' "%1$s" avec le compte "%2$s" et pour destination le dossier : "%3$s"') . PHP_EOL + , $ftp_server + , $ftp_user_name + , $ftp_export["destfolder"] + ); - if ($this->debug) - echo $line; - } + if ($this->debug) + echo $line; + } - $state .= $line = sprintf( + $state .= $line = sprintf( _("task::ftp:TENTATIVE no %s, %s") , $ftp_export["crash"] + 1 , " (" . date('r') . ")" - ) . PHP_EOL; + ) . PHP_EOL; - if ($this->debug) - echo $line; + if ($this->debug) + echo $line; - if (($ses_id = phrasea_create_session($usr_id)) == null) - { - echo "Unable to create session\n"; - continue; - } - - if (!($ph_session = phrasea_open_session($ses_id, $usr_id))) - { - echo "Unable to open session\n"; - phrasea_close_session($ses_id); - continue; - } - - try - { - $ssl = ($ftp_export['ssl'] == '1'); - $ftp_client = new ftpclient($ftp_server, 21, 300, $ssl, $this->proxy, $this->proxyport); - $ftp_client->login($ftp_user_name, $ftp_user_pass); - - if ($ftp_export["passif"] == "1") - { - try - { - $ftp_client->passive(true); - } - catch (Exception $e) - { - echo $e->getMessage(); - } - } - - if (trim($ftp_export["destfolder"]) != '') - { - try - { - $ftp_client->chdir($ftp_export["destfolder"]); - $ftp_export["destfolder"] = '/' . $ftp_export["destfolder"]; - } - catch (Exception $e) - { - echo $e->getMessage(); - } - } - else - { - $ftp_export["destfolder"] = '/'; - } - - if (trim($ftp_export["foldertocreate"]) != '') - { - try - { - $ftp_client->mkdir($ftp_export["foldertocreate"]); - } - catch (Exception $e) - { - echo $e->getMessage(); - } - try - { - $new_dir = $ftp_client->add_end_slash($ftp_export["destfolder"]) - . $ftp_export["foldertocreate"]; - $ftp_client->chdir($new_dir); - } - catch (Exception $e) - { - echo $e->getMessage(); - } - } - - $obj = array(); - - $basefolder = ''; - if (!in_array(trim($ftp_export["destfolder"]), array('.', './', ''))) - $basefolder = p4string::addEndSlash($ftp_export["destfolder"]); - - $basefolder .= $ftp_export["foldertocreate"]; - - if (in_array(trim($basefolder), array('.', './', ''))) - $basefolder = '/'; - - foreach ($ftp_export['files'] as $fileid => $file) - { - $base_id = $file["base_id"]; - $record_id = $file["record_id"]; - $subdef = $file['subdef']; - - try - { - $sbas_id = phrasea::sbasFromBas($base_id); - $record = new record_adapter($sbas_id, $record_id); - - $sdcaption = $record->get_caption()->serialize(caption_record::SERIALIZE_XML, $ftp_export["businessfields"]); - - $remotefile = $file["filename"]; - - if ($subdef == 'caption') - { - $desc = $record->get_caption()->serialize(\caption_record::SERIALIZE_XML, $ftp_export["businessfields"]); - - $localfile = $registry->get('GV_RootPath') . 'tmp/' . md5($desc . time() . mt_rand()); - if (file_put_contents($localfile, $desc) === false) - { - throw new Exception('Impossible de creer un fichier temporaire'); - } - } - elseif ($subdef == 'caption-yaml') - { - $desc = $record->get_caption()->serialize(\caption_record::SERIALIZE_YAML, $ftp_export["businessfields"]); - - $localfile = $registry->get('GV_RootPath') . 'tmp/' . md5($desc . time() . mt_rand()); - if (file_put_contents($localfile, $desc) === false) - { - throw new Exception('Impossible de creer un fichier temporaire'); - } - } - else - { - $sd = $record->get_subdefs(); - - if (!$sd || !isset($sd[$subdef])) - { - continue; + if (($ses_id = phrasea_create_session($usr_id)) == null) { + echo "Unable to create session\n"; + continue; } - $localfile = $sd[$subdef]->get_pathfile(); - if (!file_exists($localfile)) - { - throw new Exception('Le fichier local n\'existe pas'); + if ( ! ($ph_session = phrasea_open_session($ses_id, $usr_id))) { + echo "Unable to open session\n"; + phrasea_close_session($ses_id); + continue; } - } - $current_folder = p4string::delEndSlash(str_replace('//', '/', $basefolder . $file['folder'])); + try { + $ssl = ($ftp_export['ssl'] == '1'); + $ftp_client = new ftpclient($ftp_server, 21, 300, $ssl, $this->proxy, $this->proxyport); + $ftp_client->login($ftp_user_name, $ftp_user_pass); - if ($ftp_client->pwd() != $current_folder) - { - try - { - $ftp_client->chdir($current_folder); - } - catch (Exception $e) - { - echo $e->getMessage(); - } - } + if ($ftp_export["passif"] == "1") { + try { + $ftp_client->passive(true); + } catch (Exception $e) { + echo $e->getMessage(); + } + } - $ftp_client->put($remotefile, $localfile); + if (trim($ftp_export["destfolder"]) != '') { + try { + $ftp_client->chdir($ftp_export["destfolder"]); + $ftp_export["destfolder"] = '/' . $ftp_export["destfolder"]; + } catch (Exception $e) { + echo $e->getMessage(); + } + } else { + $ftp_export["destfolder"] = '/'; + } + + if (trim($ftp_export["foldertocreate"]) != '') { + try { + $ftp_client->mkdir($ftp_export["foldertocreate"]); + } catch (Exception $e) { + echo $e->getMessage(); + } + try { + $new_dir = $ftp_client->add_end_slash($ftp_export["destfolder"]) + . $ftp_export["foldertocreate"]; + $ftp_client->chdir($new_dir); + } catch (Exception $e) { + echo $e->getMessage(); + } + } + + $obj = array(); + + $basefolder = ''; + if ( ! in_array(trim($ftp_export["destfolder"]), array('.', './', ''))) + $basefolder = p4string::addEndSlash($ftp_export["destfolder"]); + + $basefolder .= $ftp_export["foldertocreate"]; + + if (in_array(trim($basefolder), array('.', './', ''))) + $basefolder = '/'; + + foreach ($ftp_export['files'] as $fileid => $file) { + $base_id = $file["base_id"]; + $record_id = $file["record_id"]; + $subdef = $file['subdef']; + + try { + $sbas_id = phrasea::sbasFromBas($base_id); + $record = new record_adapter($sbas_id, $record_id); + + $sdcaption = $record->get_caption()->serialize(caption_record::SERIALIZE_XML, $ftp_export["businessfields"]); + + $remotefile = $file["filename"]; + + if ($subdef == 'caption') { + $desc = $record->get_caption()->serialize(\caption_record::SERIALIZE_XML, $ftp_export["businessfields"]); + + $localfile = $registry->get('GV_RootPath') . 'tmp/' . md5($desc . time() . mt_rand()); + if (file_put_contents($localfile, $desc) === false) { + throw new Exception('Impossible de creer un fichier temporaire'); + } + } elseif ($subdef == 'caption-yaml') { + $desc = $record->get_caption()->serialize(\caption_record::SERIALIZE_YAML, $ftp_export["businessfields"]); + + $localfile = $registry->get('GV_RootPath') . 'tmp/' . md5($desc . time() . mt_rand()); + if (file_put_contents($localfile, $desc) === false) { + throw new Exception('Impossible de creer un fichier temporaire'); + } + } else { + $sd = $record->get_subdefs(); + + if ( ! $sd || ! isset($sd[$subdef])) { + continue; + } + + $localfile = $sd[$subdef]->get_pathfile(); + if ( ! file_exists($localfile)) { + throw new Exception('Le fichier local n\'existe pas'); + } + } + + $current_folder = p4string::delEndSlash(str_replace('//', '/', $basefolder . $file['folder'])); + + if ($ftp_client->pwd() != $current_folder) { + try { + $ftp_client->chdir($current_folder); + } catch (Exception $e) { + echo $e->getMessage(); + } + } + + $ftp_client->put($remotefile, $localfile); - $obj[] = array( - "name" => $subdef, "size" => filesize($localfile), - "shortXml" => ($sdcaption ? $sdcaption : '') - ); + $obj[] = array( + "name" => $subdef, "size" => filesize($localfile), + "shortXml" => ($sdcaption ? $sdcaption : '') + ); - if ($subdef == 'caption') - { - unlink($localfile); - } + if ($subdef == 'caption') { + unlink($localfile); + } - $sql = "UPDATE ftp_export_elements + $sql = "UPDATE ftp_export_elements SET done='1', error='0' WHERE id = :file_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':file_id' => $file['id'])); - $stmt->closeCursor(); - $this->logexport($appbox->get_session(), $record, $obj, $ftpLog); - } - catch (Exception $e) - { - $state .= $line = sprintf(_('task::ftp:File "%1$s" (record %2$s) de la base "%3$s"' . - ' (Export du Document) : Transfert cancelled (le document n\'existe plus)') - , basename($localfile), $record_id - , phrasea::sbas_names(phrasea::sbasFromBas($base_id))) . "\n
                  "; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':file_id' => $file['id'])); + $stmt->closeCursor(); + $this->logexport($appbox->get_session(), $record, $obj, $ftpLog); + } catch (Exception $e) { + $state .= $line = sprintf(_('task::ftp:File "%1$s" (record %2$s) de la base "%3$s"' . + ' (Export du Document) : Transfert cancelled (le document n\'existe plus)') + , basename($localfile), $record_id + , phrasea::sbas_names(phrasea::sbasFromBas($base_id))) . "\n
                  "; - if ($this->debug) - echo $line; + if ($this->debug) + echo $line; - $done = $file['error']; + $done = $file['error']; - $sql = "UPDATE ftp_export_elements + $sql = "UPDATE ftp_export_elements SET done = :done, error='1' WHERE id = :file_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':done' => $done, ':file_id' => $file['id'])); - $stmt->closeCursor(); - } - } + $stmt = $conn->prepare($sql); + $stmt->execute(array(':done' => $done, ':file_id' => $file['id'])); + $stmt->closeCursor(); + } + } - if ($ftp_export['logfile']) - { - if($this->debug) - echo "\nlogfile \n"; + if ($ftp_export['logfile']) { + if ($this->debug) + echo "\nlogfile \n"; - $date = new DateTime(); - $remote_file = $date->format('U'); + $date = new DateTime(); + $remote_file = $date->format('U'); - $sql = 'SELECT filename, folder + $sql = 'SELECT filename, folder FROM ftp_export_elements WHERE ftp_export_id = :ftp_export_id AND error = "0" AND done="1"'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':ftp_export_id'=>$id)); - $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':ftp_export_id' => $id)); + $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $buffer = '#transfert finished '.$date->format(DATE_ATOM)."\n\n"; + $buffer = '#transfert finished ' . $date->format(DATE_ATOM) . "\n\n"; - foreach ($rs as $row) - { - $filename = $row['filename']; - $folder = $row['folder']; + foreach ($rs as $row) { + $filename = $row['filename']; + $folder = $row['folder']; - $root = $ftp_export['foldertocreate']; + $root = $ftp_export['foldertocreate']; - $buffer .= $root .'/'. $folder . $filename . "\n"; + $buffer .= $root . '/' . $folder . $filename . "\n"; + } + + $tmpfile = $registry->get('GV_RootPath') . 'tmp/tmpftpbuffer' . $date->format('U') . '.txt'; + + file_put_contents($tmpfile, $buffer); + + $remotefile = $date->format('U') . '-transfert.log'; + + $ftp_client->chdir($ftp_export["destfolder"]); + + $ftp_client->put($remotefile, $tmpfile); + + unlink($tmpfile); + } + + $ftp_client->close(); + unset($ftp_client); + } catch (Exception $e) { + $state .= $line = $e . "\n"; + + if ($this->debug) + echo $line; + + $sql = "UPDATE ftp_export SET crash=crash+1,date=now() + WHERE id = :export_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $ftp_export['id'])); + $stmt->closeCursor(); + + unset($ftp_client); + } + $this->finalize($appbox, $id); + phrasea_close_session($ses_id); } - $tmpfile = $registry->get('GV_RootPath') . 'tmp/tmpftpbuffer'.$date->format('U').'.txt'; + protected function post_process_one_content(appbox $appbox, Array $row) + { + return $this; + } - file_put_contents($tmpfile, $buffer); + function finalize(appbox $appbox, $id) + { + $conn = $appbox->get_connection(); - $remotefile = $date->format('U').'-transfert.log'; - - $ftp_client->chdir($ftp_export["destfolder"]); - - $ftp_client->put($remotefile, $tmpfile); - - unlink($tmpfile); - } - - $ftp_client->close(); - unset($ftp_client); - } - catch (Exception $e) - { - $state .= $line = $e . "\n"; - - if ($this->debug) - echo $line; - - $sql = "UPDATE ftp_export SET crash=crash+1,date=now() - WHERE id = :export_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $ftp_export['id'])); - $stmt->closeCursor(); - - unset($ftp_client); - } - $this->finalize($appbox, $id); - phrasea_close_session($ses_id); - } - - protected function post_process_one_content(appbox $appbox, Array $row) - { - return $this; - } - - function finalize(appbox $appbox, $id) - { - $conn = $appbox->get_connection(); - - $sql = 'SELECT crash, nbretry FROM ftp_export + $sql = 'SELECT crash, nbretry FROM ftp_export WHERE id = :export_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if ($row && $row['crash'] >= $row['nbretry']) - { - $this->send_mails($appbox, $id); + if ($row && $row['crash'] >= $row['nbretry']) { + $this->send_mails($appbox, $id); - return $this; - } + return $this; + } - $sql = 'SELECT count(id) as total, sum(error) as errors, sum(done) as done + $sql = 'SELECT count(id) as total, sum(error) as errors, sum(done) as done FROM ftp_export_elements WHERE ftp_export_id = :export_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if ($row && $row['done'] == (int) $row['total']) - { - $this->send_mails($appbox, $id); + if ($row && $row['done'] == (int) $row['total']) { + $this->send_mails($appbox, $id); - if ((int) $row['errors'] === 0) - { - $sql = 'DELETE FROM ftp_export WHERE id = :export_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $stmt->closeCursor(); - $sql = 'DELETE FROM ftp_export_elements WHERE ftp_export_id = :export_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $stmt->closeCursor(); - } - else - { - $sql = 'UPDATE ftp_export SET crash = nbretry'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - $sql = 'DELET FROM ftp_export_elements WHERE ftp_export_id = :export_id AND error="0"'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $stmt->closeCursor(); - } + if ((int) $row['errors'] === 0) { + $sql = 'DELETE FROM ftp_export WHERE id = :export_id'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $stmt->closeCursor(); + $sql = 'DELETE FROM ftp_export_elements WHERE ftp_export_id = :export_id'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $stmt->closeCursor(); + } else { + $sql = 'UPDATE ftp_export SET crash = nbretry'; + $stmt = $conn->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + $sql = 'DELET FROM ftp_export_elements WHERE ftp_export_id = :export_id AND error="0"'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $stmt->closeCursor(); + } - return $this; - } - } + return $this; + } + } - function send_mails(appbox $appbox, $id) - { - $conn = $appbox->get_connection(); - $registry = registry::get_instance(); + function send_mails(appbox $appbox, $id) + { + $conn = $appbox->get_connection(); + $registry = registry::get_instance(); - $sql = 'SELECT filename, base_id, record_id, subdef, error, done + $sql = 'SELECT filename, base_id, record_id, subdef, error, done FROM ftp_export_elements WHERE ftp_export_id = :export_id'; - $transferts = array(); + $transferts = array(); - $transfert_status = _('task::ftp:Tous les documents ont ete transferes avec succes'); + $transfert_status = _('task::ftp:Tous les documents ont ete transferes avec succes'); - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - foreach ($rs as $row) - { - if ($row['error'] == '0' && $row['done'] == '1') - { - $transferts[] = - '
                • ' . sprintf(_('task::ftp:Record %1$s - %2$s de la base (%3$s - %4$s) - %5$s') - , $row["record_id"], $row["filename"] - , phrasea::sbas_names(phrasea::sbasFromBas($row["base_id"])) - , phrasea::bas_names($row['base_id']), $row['subdef']) . ' : ' . _('Transfert OK') . '
                • '; - } - else - { - $transferts[] = - '
                • ' . sprintf(_('task::ftp:Record %1$s - %2$s de la base (%3$s - %4$s) - %5$s') - , $row["record_id"], $row["filename"] - , phrasea::sbas_names(phrasea::sbasFromBas($row["base_id"])), phrasea::bas_names($row['base_id']) - , $row['subdef']) . ' : ' . _('Transfert Annule') . '
                • '; - $transfert_status = _('task::ftp:Certains documents n\'ont pas pu etre tranferes'); - } - } + foreach ($rs as $row) { + if ($row['error'] == '0' && $row['done'] == '1') { + $transferts[] = + '
                • ' . sprintf(_('task::ftp:Record %1$s - %2$s de la base (%3$s - %4$s) - %5$s') + , $row["record_id"], $row["filename"] + , phrasea::sbas_names(phrasea::sbasFromBas($row["base_id"])) + , phrasea::bas_names($row['base_id']), $row['subdef']) . ' : ' . _('Transfert OK') . '
                • '; + } else { + $transferts[] = + '
                • ' . sprintf(_('task::ftp:Record %1$s - %2$s de la base (%3$s - %4$s) - %5$s') + , $row["record_id"], $row["filename"] + , phrasea::sbas_names(phrasea::sbasFromBas($row["base_id"])), phrasea::bas_names($row['base_id']) + , $row['subdef']) . ' : ' . _('Transfert Annule') . '
                • '; + $transfert_status = _('task::ftp:Certains documents n\'ont pas pu etre tranferes'); + } + } - $sql = 'SELECT addr, crash, nbretry, sendermail, mail, text_mail_sender, text_mail_receiver + $sql = 'SELECT addr, crash, nbretry, sendermail, mail, text_mail_sender, text_mail_receiver FROM ftp_export WHERE id = :export_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':export_id' => $id)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':export_id' => $id)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if ($row) - { - if ($row['crash'] >= $row['nbretry']) - $connection_status = _('Des difficultes ont ete rencontres a la connection au serveur distant'); - else - $connection_status = _('La connection vers le serveur distant est OK'); + if ($row) { + if ($row['crash'] >= $row['nbretry']) + $connection_status = _('Des difficultes ont ete rencontres a la connection au serveur distant'); + else + $connection_status = _('La connection vers le serveur distant est OK'); - $text_mail_sender = $row['text_mail_sender']; - $text_mail_receiver = $row['text_mail_receiver']; - $mail = $row['mail']; - $sendermail = $row['sendermail']; - $ftp_server = $row['addr']; + $text_mail_sender = $row['text_mail_sender']; + $text_mail_receiver = $row['text_mail_receiver']; + $mail = $row['mail']; + $sendermail = $row['sendermail']; + $ftp_server = $row['addr']; + } + + $message = "\n
                  ----------------------------------------
                  \n"; + $message = "
                  " . $connection_status . "
                  \n"; + $message .= "
                  " . $transfert_status . "
                  \n"; + $message .= "
                  " . _("task::ftp:Details des fichiers") . "
                  \n"; + + $message .= "
                    "; + $message .= implode("\n", $transferts); + $message .= "
                  "; + + $sender_message = $text_mail_sender . $message; + $receiver_message = $text_mail_receiver . $message; + + $subject = sprintf( + _('task::ftp:Status about your FTP transfert from %1$s to %2$s') + , $registry->get('GV_homeTitle'), $ftp_server + ); + + mail::ftp_sent($sendermail, $subject, $sender_message); + + mail::ftp_receive($mail, $receiver_message); + } + + function logexport(Session_Handler $session, record_adapter $record, $obj, $ftpLog) + { + foreach ($obj as $oneObj) { + $session->get_logger($record->get_databox()) + ->log($record, Session_Logger::EVENT_EXPORTFTP, $ftpLog, ''); + } + + return $this; + } } - $message = "\n
                  ----------------------------------------
                  \n"; - $message = "
                  " . $connection_status . "
                  \n"; - $message .= "
                  " . $transfert_status . "
                  \n"; - $message .= "
                  " . _("task::ftp:Details des fichiers") . "
                  \n"; - - $message .= "
                    "; - $message .= implode("\n", $transferts); - $message .= "
                  "; - - $sender_message = $text_mail_sender . $message; - $receiver_message = $text_mail_receiver . $message; - - $subject = sprintf( - _('task::ftp:Status about your FTP transfert from %1$s to %2$s') - , $registry->get('GV_homeTitle'), $ftp_server - ); - - mail::ftp_sent($sendermail, $subject, $sender_message); - - mail::ftp_receive($mail, $receiver_message); - } - - function logexport(Session_Handler $session, record_adapter $record, $obj, $ftpLog) - { - foreach ($obj as $oneObj) - { - $session->get_logger($record->get_databox()) - ->log($record, Session_Logger::EVENT_EXPORTFTP, $ftpLog, ''); - } - - return $this; - } - -} diff --git a/lib/classes/task/period/ftpPull.class.php b/lib/classes/task/period/ftpPull.class.php index 11df626fc8..5bb8678c6b 100644 --- a/lib/classes/task/period/ftpPull.class.php +++ b/lib/classes/task/period/ftpPull.class.php @@ -16,370 +16,332 @@ */ class task_period_ftpPull extends task_appboxAbstract { + protected $debug = false; + protected $proxy; + protected $proxyport; + protected $host; + protected $port; + protected $user; + protected $password; + protected $ssl; + protected $passive; + protected $ftppath; + protected $localpath; - protected $debug = false; - protected $proxy; - protected $proxyport; - protected $host; - protected $port; - protected $user; - protected $password; - protected $ssl; - protected $passive; - protected $ftppath; - protected $localpath; - - public function getName() - { - return(_("task::ftp:FTP Pull")); - } - - public function help() - { - return ''; - } - - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - "proxy", "proxyport", "host", "port", "user" - , "password", "ssl", "ftppath", "localpath" - , "passive", "period" - ); - if ($dom = @DOMDocument::loadXML($oldxml)) + public function getName() { - $xmlchanged = false; - foreach (array("str:proxy", "str:proxyport", "str:period", "boo:passive", "boo:ssl", "str:password", "str:user", "str:ftppath", "str:localpath", "str:port", "str:host") as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return(_("task::ftp:FTP Pull")); } - return($dom->saveXML()); - } - - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + public function help() { - // ... but we could check for safe values (ex. 0 < period < 3600) -?> - - - - -
                  -
                  - -
                  -
                  - -
                  -
                  - - -
                  -
                  - -
                  -
                  - -
                  -
                  - -
                  -
                  - -
                  -
                  - -
                  -
                  - - - -
                  - - -
                  - - -  
                  -
                  -get_parms( - "xml", "name", "active", "proxy", "proxyport", "period" - , "localpath", "ftppath", "port", "host", "user" - , "password", "passive", "ssl", "debug" - ); - - if ($parm["xml"] === null) - { - // pas de xml 'raw' : on accepte les champs 'graphic view' - if ($domTaskSettings = DOMDocument::loadXML($taskrow["settings"])) - { - $xmlchanged = false; - foreach (array("proxy", "proxyport", "period", "host", "port", "user", "password", "ssl", "passive", "localpath", "ftppath") as $f) - { - if ($parm[$f] !== NULL) - { - if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); + $parm2 = $request->get_parms( + "proxy", "proxyport", "host", "port", "user" + , "password", "ssl", "ftppath", "localpath" + , "passive", "period" + ); + if ($dom = @DOMDocument::loadXML($oldxml)) { + $xmlchanged = false; + foreach (array("str:proxy", "str:proxyport", "str:period", "boo:passive", "boo:ssl", "str:password", "str:user", "str:ftppath", "str:localpath", "str:port", "str:host") as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $dom->documentElement->appendChild($dom->createTextNode("\t")); + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + $dom->documentElement->appendChild($dom->createTextNode("\n")); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; } - else - { - // le champ n'existait pas dans le xml, on le cree - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); - $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); - $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); - } - // on fixe sa valeur - $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); - $xmlchanged = true; - } } - if ($xmlchanged) - $parm["xml"] = $domTaskSettings->saveXML(); - } + + return($dom->saveXML()); } - // si on doit changer le xml, on verifie qu'il est valide - if ($parm["xml"] && !DOMDocument::loadXML($parm["xml"])) + public function xml2graphic($xml, $form) + { + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values (ex. 0 < period < 3600) + ?> + + prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + global $parm; + ?> + + +
                  +
                  + +
                  +
                  + +
                  +
                  + + +
                  +
                  + +
                  +
                  + +
                  +
                  + +
                  +
                  + +
                  +
                  + +
                  +
                  + + + +
                  + + +
                  + + +  
                  +
                  + proxy = (string) $sx_task_settings->proxy; - $this->proxyport = (string) $sx_task_settings->proxyport; - $this->host = (string) ($sx_task_settings->host); - $this->port = (string) ($sx_task_settings->port); - $this->user = (string) ($sx_task_settings->user); - $this->password = (string) ($sx_task_settings->password); - $this->ssl = !!((string) ($sx_task_settings->ssl)); - $this->passive = !!((string) ($sx_task_settings->passive)); - $this->ftppath = (string) ($sx_task_settings->ftppath); - $this->localpath = (string) ($sx_task_settings->localpath); - - parent::load_settings($sx_task_settings); - - return $this; - } - - protected function retrieve_content(appbox $appbox) - { - try + public function saveChanges(connection_pdo $conn, $taskid, &$taskrow) { - if (!is_dir($this->localpath) || !system_file::mkdir($this->localpath)) - throw new Exception("$this->localpath is not writeable\n"); + $request = http_request::getInstance(); - if (!is_writeable($this->localpath)) - throw new Exception("$this->localpath is not writeable\n"); + $parm = $request->get_parms( + "xml", "name", "active", "proxy", "proxyport", "period" + , "localpath", "ftppath", "port", "host", "user" + , "password", "passive", "ssl", "debug" + ); - $ftp = new ftpclient($this->host, $port, 90, $this->ssl, $this->proxy, $this->proxyport); - $ftp->login($this->user, $this->password); - $ftp->chdir($this->ftppath); - $list_1 = $ftp->list_directory(true); - - $todo = count($list_1); - $this->setProgress($done, $todo); - - if ($this->debug) - echo "attente de 25sec pour avoir les fichiers froids...\n"; - sleep(25); - - $list_2 = $ftp->list_directory(true); - - foreach ($list_1 as $filepath => $timestamp) - { - $done++; - $this->setProgress($done, $todo); - - if (!isset($list_2[$filepath])) - { - if ($this->debug) - echo "le fichier $filepath a disparu...\n"; - continue; - } - if ($list_2[$filepath] !== $timestamp) - { - if ($this->debug) - echo "le fichier $filepath a ete modifie depuis le dernier passage...\n"; - continue; + if ($parm["xml"] === null) { + // pas de xml 'raw' : on accepte les champs 'graphic view' + if ($domTaskSettings = DOMDocument::loadXML($taskrow["settings"])) { + $xmlchanged = false; + foreach (array("proxy", "proxyport", "period", "host", "port", "user", "password", "ssl", "passive", "localpath", "ftppath") as $f) { + if ($parm[$f] !== NULL) { + if ($ns = $domTaskSettings->getElementsByTagName($f)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\t")); + $ns = $domTaskSettings->documentElement->appendChild($domTaskSettings->createElement($f)); + $domTaskSettings->documentElement->appendChild($domTaskSettings->createTextNode("\n")); + } + // on fixe sa valeur + $ns->appendChild($domTaskSettings->createTextNode($parm[$f])); + $xmlchanged = true; + } + } + if ($xmlchanged) + $parm["xml"] = $domTaskSettings->saveXML(); + } } - $finalpath = p4string::addEndSlash($this->localpath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath); - echo "Ok pour rappatriement de $filepath vers $finalpath\n"; + // si on doit changer le xml, on verifie qu'il est valide + if ($parm["xml"] && ! DOMDocument::loadXML($parm["xml"])) + return(false); - try - { - if (file_exists($finalpath)) - throw new Exception("Un fichier du meme nom ($finalpath) existe deja..."); - - system_file::mkdir(dirname($finalpath)); - - $ftp->get($finalpath, $filepath); - $ftp->delete($filepath); + $sql = ""; + $params = array(':task_id' => $taskid); + if ($parm["xml"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "settings = :settings"; + $params[':settings'] = $parm['xml']; } - catch (Exception $e) - { - if ($this->debug) - echo "Erreur lors du rappatriement de $filepath : " . $e->getMessage() . "\n"; + if ($parm["name"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "name = :name"; + $params[':name'] = $parm['name']; + } + if ($parm["active"] !== NULL) { + $sql .= ( $sql ? " ," : "") . "active = :active"; + $params[':active'] = $parm['active']; } - } - $ftp->close(); + if ($sql) { + try { + $sql = "UPDATE task2 SET $sql WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - $this->setProgress(0, 0); + return true; + } catch (Exception $e) { + return false; + } + } else { + return true; + } } - catch (Exception $e) + + protected function load_settings(SimpleXMLElement $sx_task_settings) { - if (isset($ftp) && $ftp instanceof ftpclient) - $ftp->close(); - echo $e->getMessage() . "\n"; + $this->proxy = (string) $sx_task_settings->proxy; + $this->proxyport = (string) $sx_task_settings->proxyport; + $this->host = (string) ($sx_task_settings->host); + $this->port = (string) ($sx_task_settings->port); + $this->user = (string) ($sx_task_settings->user); + $this->password = (string) ($sx_task_settings->password); + $this->ssl = ! ! ((string) ($sx_task_settings->ssl)); + $this->passive = ! ! ((string) ($sx_task_settings->passive)); + $this->ftppath = (string) ($sx_task_settings->ftppath); + $this->localpath = (string) ($sx_task_settings->localpath); + + parent::load_settings($sx_task_settings); + + return $this; } - } - protected function process_one_content(appbox $appbox, Array $row) - { + protected function retrieve_content(appbox $appbox) + { + try { + if ( ! is_dir($this->localpath) || ! system_file::mkdir($this->localpath)) + throw new Exception("$this->localpath is not writeable\n"); - } + if ( ! is_writeable($this->localpath)) + throw new Exception("$this->localpath is not writeable\n"); - protected function post_process_one_content(appbox $appbox, Array $row) - { + $ftp = new ftpclient($this->host, $port, 90, $this->ssl, $this->proxy, $this->proxyport); + $ftp->login($this->user, $this->password); + $ftp->chdir($this->ftppath); + $list_1 = $ftp->list_directory(true); - } + $todo = count($list_1); + $this->setProgress($done, $todo); + if ($this->debug) + echo "attente de 25sec pour avoir les fichiers froids...\n"; + sleep(25); + + $list_2 = $ftp->list_directory(true); + + foreach ($list_1 as $filepath => $timestamp) { + $done ++; + $this->setProgress($done, $todo); + + if ( ! isset($list_2[$filepath])) { + if ($this->debug) + echo "le fichier $filepath a disparu...\n"; + continue; + } + if ($list_2[$filepath] !== $timestamp) { + if ($this->debug) + echo "le fichier $filepath a ete modifie depuis le dernier passage...\n"; + continue; + } + + $finalpath = p4string::addEndSlash($this->localpath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath); + echo "Ok pour rappatriement de $filepath vers $finalpath\n"; + + try { + if (file_exists($finalpath)) + throw new Exception("Un fichier du meme nom ($finalpath) existe deja..."); + + system_file::mkdir(dirname($finalpath)); + + $ftp->get($finalpath, $filepath); + $ftp->delete($filepath); + } catch (Exception $e) { + if ($this->debug) + echo "Erreur lors du rappatriement de $filepath : " . $e->getMessage() . "\n"; + } + } + + $ftp->close(); + + $this->setProgress(0, 0); + } catch (Exception $e) { + if (isset($ftp) && $ftp instanceof ftpclient) + $ftp->close(); + echo $e->getMessage() . "\n"; + } + } + + protected function process_one_content(appbox $appbox, Array $row) + { + + } + + protected function post_process_one_content(appbox $appbox, Array $row) + { + + } } diff --git a/lib/classes/task/period/outofdate.class.php b/lib/classes/task/period/outofdate.class.php index 72cb2ec9d8..28f646493c 100644 --- a/lib/classes/task/period/outofdate.class.php +++ b/lib/classes/task/period/outofdate.class.php @@ -17,24 +17,24 @@ class task_period_outofdate extends task_abstract { - // ==================================================================== - // getName : must return the name for this kind of task - // MANDATORY - // ==================================================================== - public function getName() - { - return(_('Documents perimes')); - } + // ==================================================================== + // getName : must return the name for this kind of task + // MANDATORY + // ==================================================================== + public function getName() + { + return(_('Documents perimes')); + } - // ==================================================================== - // graphic2xml : must return the xml (text) version of the form - // ==================================================================== - public function graphic2xml($oldxml) - { + // ==================================================================== + // graphic2xml : must return the xml (text) version of the form + // ==================================================================== + public function graphic2xml($oldxml) + { // global $parm; - $request = http_request::getInstance(); + $request = http_request::getInstance(); - $parm2 = $request->get_parms( + $parm2 = $request->get_parms( "sbas_id" , "period" , 'field1' @@ -49,896 +49,819 @@ class task_period_outofdate extends task_abstract , 'coll1' , 'status2' , 'coll2' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if($dom->loadXML($oldxml)) - { - $xmlchanged = false; - // foreach($parm2 as $pname=>$pvalue) - foreach(array( - "str:sbas_id", - "str:period", - 'str:field1', - 'str:fieldDs1', - 'str:fieldDv1', - 'str:field2', - 'str:fieldDs2', - 'str:fieldDv2', - 'str:status0', - 'str:coll0', - 'str:status1', - 'str:coll1', - 'str:status2', - 'str:coll2' - ) as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if(($ns = $dom->getElementsByTagName($pname)->item(0))) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while(($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } - } - - return($dom->saveXML()); - } - - // ==================================================================== - // xml2graphic : must fill the graphic form (using js) from xml - // ==================================================================== - public function xml2graphic($xml, $form) - { - if(($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... - { - // ... but we could check for safe values - if((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif((int) ($sxml->period) > 1440) // 1 jour - $sxml->period = 1440; - - if((string) ($sxml->delay) == '') - $sxml->delay = 0; - ?> - - saveXML()); } - else // ... so we NEVER come here + + // ==================================================================== + // xml2graphic : must fill the graphic form (using js) from xml + // ==================================================================== + public function xml2graphic($xml, $form) { - // bad xml - return("BAD XML"); + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values + if ((int) ($sxml->period) < 10) + $sxml->period = 10; + elseif ((int) ($sxml->period) > 1440) // 1 jour + $sxml->period = 1440; + + if ((string) ($sxml->delay) == '') + $sxml->delay = 0; + ?> + + - - + + - - get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - ob_start(); - - $sbas_list = $user->ACL()->get_granted_sbas(array('bas_manage')); - ?> -
                  -  :  - - + + get_sbas_id() . "\" $selected>" . p4string::MakeString($databox->get_viewname(), "form") . "\n"); } ?> - + -   - -
                  -
                  - -  :  - -
                  -
                  - - - - - + + + + + + + + + + + + + + + + +
                    - + +
                  +
                  + +  :  + +
                  +
                  + + + + + - - - - - - - - - - - - - - - - - -
                  +   +   - - -
                  - -   -
                  -   - - -
                  - -   -
                  -   -
                  -  : - - - - - - -
                  -  :
                  -
                  - - - - - -
                  - -
                  -
                  -
                  cmd
                  -
                  - +
                  + +
                  + +   +
                  +   + + +
                  + +   +
                  +   +
                  +  : + + + + + + +
                  +  :
                  +
                  + + + + + +
                  + +
                  +
                  +
                  cmd
                  +
                  + array("set"=>false, "values"=>array(), "usage"=>" : usage du truc") - ); - - // ====================================================================================================== - // ===== help() : text displayed if --help (optional) - // ====================================================================================================== - function help() - { - return(_("task::outofdate:deplacement de docs suivant valeurs de champs 'date'")); - } - - // ====================================================================================================== - // ===== run() : le code d'execution de la tache proprement dite - // ====================================================================================================== - - protected $sxTaskSettings = null; // les settings de la tache en simplexml - private $connbas = null; // cnx a la base - private $msg = ""; - private $sbas_id; - - protected function run2() - { - $ret = ''; - $conn = connection::getPDOConnection(); - - $this->sxTaskSettings = simplexml_load_string($this->settings); - - $this->sbas_id = (int) ($this->sxTaskSettings->sbas_id); - - $this->connbas = connection::getPDOConnection($this->sbas_id); - - $this->running = true; - $this->tmask = array(); - $this->tmaskgrp = array(); - $this->period = 60; - - - // ici la tache tourne tant qu'elle est active - $last_exec = 0; - $loop = 0; - while($this->running) - { - if(!$conn->ping()) - { - $this->log(("Warning : abox connection lost, restarting in 10 min.")); - for($i=0; $i<60 * 10; $i++) - sleep(1); - $this->running = false; - - return(self::RETURNSTATUS_TORESTART); - } - - try - { - $connbas = connection::getPDOConnection($this->sbas_id); - if(!$connbas->ping()) - throw new Exception('Mysql has gone away'); - } - catch(Exception $e) - { - $this->log(("dbox connection lost, restarting in 10 min.")); - for($i=0; $i<60 * 10; $i++) - sleep(1); - $this->running = false; - - return(self::RETURNSTATUS_TORESTART); - } - - $this->set_last_exec_time(); - - $databox = databox::get_instance($this->sbas_id); - - $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if($row) - { - if($row['status'] == 'tostop') - { - $ret = self::RETURNSTATUS_STOPPED; - ; - $this->running = false; - } - else - { - if(($this->sxTaskSettings = simplexml_load_string($row['settings']))) - { - $period = (int) ($this->sxTaskSettings->period); - if($period <= 0 || $period >= 24 * 60) - $period = 60; - } - else - { - $period = 60; - } - $this->connbas = connection::getPDOConnection($this->sbas_id); - - $duration = time(); - - $r = $this->doRecords(); - - switch($r) - { - case 'WAIT': - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - break; - case 'BAD': - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - break; - case 'NORECSTODO': - $duration = time() - $duration; - if($duration < $period) - { - sleep($period - $duration); - $conn = connection::getPDOConnection(); - } - break; - case 'MAXRECSDONE': - case 'MAXMEMORY': - case 'MAXLOOP': - if($row['status'] == self::STATUS_STARTED && $this->get_runner() !== self::RUNNER_MANUAL) - { - $ret = self::RETURNSTATUS_TORESTART; - $this->running = false; - } - break; - default: - if($row['status'] == self::STATUS_STARTED) - { - $ret = self::RETURNSTATUS_STOPPED; - $this->running = false; - } - break; - } - } - } - else - { - $ret = 'stopped'; - $this->running = false; - } - $loop++; + return $out; } - - $this->return_value = $ret; - - return($ret); - } - - function doRecords() - { - $ndone = 0; - $ret = 'NORECSTODO'; - - $tsql = $this->calcSQL($this->sxTaskSettings); - - $nchanged = 0; - foreach($tsql as $xsql) - { - try - { - $stmt = $this->connbas->prepare($xsql['sql']); - if($stmt->execute($xsql['params'])) - { - $n = $stmt->rowCount(); - $stmt->closeCursor(); - - $nchanged += $n; - if($n > 0) - $this->log(sprintf("SQL='%s' ; parms=%s - %s changes", $xsql['sql'], var_export($xsql['params']), $n)); - } - else - { - $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); - } - } - catch (ErrorException $e) - { - $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); - } - } - - $ret = ($nchanged > 0 ? $nchanged : 'NORECSTODO'); - - return($ret); - } - - - private function calcSQL($sxTaskSettings) - { - $ret = array(); - - $this->sxTaskSettings = $sxTaskSettings; - - $date1 = $date2 = NULL; - $field1 = $field2 = ''; - - // test : DATE 1 - if(($field1 = trim($this->sxTaskSettings->field1)) != '') - { - $date1 = time(); - if(($delta = (int) ($this->sxTaskSettings->fieldDv1)) > 0) - { - if($this->sxTaskSettings->fieldDs1 == '-') - $date1 += 86400 * $delta; - else - $date1 -= 86400 * $delta; - } - $date1 = date("YmdHis", $date1); - } - // test : DATE 2 - if(($field2 = trim($this->sxTaskSettings->field2)) != '') - { - $date2 = time(); - if(($delta = (int) ($this->sxTaskSettings->fieldDv2)) > 0) - { - if($this->sxTaskSettings->fieldDs2 == '-') - $date2 += 86400 * $delta; - else - $date2 -= 86400 * $delta; - } - $date2 = date("YmdHis", $date2); - } - - - $sqlset = $params = $tmp_params = array(); - for($i = 0; $i <= 2; $i++) - { - $sqlwhere[$i] = ''; - $sqlset[$i] = ''; - $x = 'status' . $i; - @list($tostat, $statval) = explode('_', (string) ($this->sxTaskSettings->{$x})); - if($tostat >= 4 && $tostat <= 63) - { - if($statval == '0') - { - $sqlset[$i] = 'status=status & ~(1<<' . $tostat . ')'; - $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') = 0)'; - } - elseif($statval == '1') - { - $sqlset[$i] = 'status=status|(1<<' . $tostat . ')'; - $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') != 0)'; - } - } - $x = 'coll' . $i; - if(($tocoll = (string) ($this->sxTaskSettings->{$x})) != '') - { - $sqlset[$i] .= ( $sqlset[$i] ? ', ' : '') . ('coll_id = :coll_id_set' . $i); - $sqlwhere[$i] .= ( $sqlwhere[$i] ? ' AND ' : '') . '(coll_id = :coll_id_where' . $i . ')'; - $tmp_params[':coll_id_set' . $i] = $tocoll; - $tmp_params[':coll_id_where' . $i] = $tocoll; - } - } - - if($date1 && $sqlset[0]) - { - $params = array(); - $params[':name1'] = $field1; - $params[':date1'] = $date1; - $params[':coll_id_set0'] = $tmp_params[':coll_id_set0']; - - $w = 'p1.name = :name1 AND :date1 <= p1.value'; - if($sqlwhere[1] && $sqlwhere[2]) - { - $w .= ' AND ((' . $sqlwhere[1] . ') OR (' . $sqlwhere[2] . '))'; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - else - { - if($sqlwhere[1]) - { - $w .= ' AND ' . $sqlwhere[1]; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - elseif($sqlwhere[2]) - { - $w .= ' AND ' . $sqlwhere[2]; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - } - - $sql = "UPDATE prop AS p1 INNER JOIN record USING(record_id) - SET " . $sqlset[0] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - - if($date1 && $date2) - { - $params = array(); - $params[':name1'] = $field1; - $params[':name2'] = $field2; - $params[':date1'] = $date1; - $params[':date2'] = $date2; - $params[':coll_id_set1'] = $tmp_params[':coll_id_set1']; - - $w = 'p1.name = :name1 AND p2.name = :name2 AND :date1 > p1.value AND :date2 <= p2.value'; - if($sqlwhere[0] && $sqlwhere[2]) - { - $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[2] . '))'; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - else - { - if($sqlwhere[0]) - { - $w .= ' AND ' . $sqlwhere[0]; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - } - elseif($sqlwhere[2]) - { - $w .= ' AND ' . $sqlwhere[2]; - $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; - } - } - - $sql = "UPDATE (prop AS p1 INNER JOIN prop AS p2 USING(record_id)) - INNER JOIN record USING(record_id) - SET " . $sqlset[1] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - - if($date2 && $sqlset[2]) - { - $params = array(); - $params[':name2'] = $field2; - $params[':date2'] = $date2; - $params[':coll_id_set2'] = $tmp_params[':coll_id_set2']; - - $w = 'p2.name = :name2 AND :date2 > p2.value'; - if($sqlwhere[0] && $sqlwhere[1]) - { - $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[1] . '))'; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - else - { - if($sqlwhere[0]) - { - $w .= ' AND ' . $sqlwhere[0]; - $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; - } - elseif($sqlwhere[1]) - { - $w .= ' AND ' . $sqlwhere[1]; - $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; - } - } - - $sql = "UPDATE prop AS p2 INNER JOIN record USING(record_id) - SET " . $sqlset[2] . - " WHERE " . $w; - - $ret[] = array('sql'=>$sql, 'params'=>$params); - } - - return($ret); - } - - - - public function facility() - { - $ret = NULL; - - $request = http_request::getInstance(); - $parm2 = $request->get_parms( - 'ACT', 'bid' + // ==================================================================== + // $argt : command line args specifics to this task (optional) + // ==================================================================== + public $argt = array( + // "--truc" => array("set"=>false, "values"=>array(), "usage"=>" : usage du truc") ); - phrasea::headers(200, true, 'application/json', 'UTF-8', false); - $ret = NULL; - switch($parm2['ACT']) + // ====================================================================================================== + // ===== help() : text displayed if --help (optional) + // ====================================================================================================== + function help() { - case 'CALCSQL': - $xml = $this->graphic2xml(''); - $sxml = simplexml_load_string($xml); - $ret = $this->calcSQL($sxml); - break; - case 'GETBASE': - $ret = array('date_fields' => array(), 'status_bits' => array(), 'collections' => array()); - - if($parm2['bid'] != '') - { - $sbas_id = (int) $parm2['bid']; - try - { - $databox = databox::get_instance($sbas_id); - $meta_struct = $databox->get_meta_structure(); - - foreach($meta_struct as $meta) - { - if(mb_strtolower($meta->get_type()) == 'date') - $ret['date_fields'][] = $meta->get_name(); - } - - $status = $databox->get_statusbits(); - foreach($status as $n => $stat) - { - $labelon = $stat['labelon'] ? $stat['labelon'] : ($n . '-ON'); - $labeloff = $stat['labeloff'] ? $stat['labeloff'] : ($n . '-OFF'); - $ret['status_bits'][] = array('n' => $n, 'value' => 0, 'label' => $labeloff); - $ret['status_bits'][] = array('n' => $n, 'value' => 1, 'label' => $labelon); - } - - foreach($databox->get_collections() as $collection) - $ret['collections'][] = array('id' => $collection->get_coll_id(), 'name' => $collection->get_name()); - } - catch(Exception $e) - { - - } - } - break; + return(_("task::outofdate:deplacement de docs suivant valeurs de champs 'date'")); } - print(json_encode($ret)); - } -} + // ====================================================================================================== + // ===== run() : le code d'execution de la tache proprement dite + // ====================================================================================================== + protected $sxTaskSettings = null; // les settings de la tache en simplexml + private $connbas = null; // cnx a la base + private $msg = ""; + private $sbas_id; + + protected function run2() + { + $ret = ''; + $conn = connection::getPDOConnection(); + + $this->sxTaskSettings = simplexml_load_string($this->settings); + + $this->sbas_id = (int) ($this->sxTaskSettings->sbas_id); + + $this->connbas = connection::getPDOConnection($this->sbas_id); + + $this->running = true; + $this->tmask = array(); + $this->tmaskgrp = array(); + $this->period = 60; + + + // ici la tache tourne tant qu'elle est active + $last_exec = 0; + $loop = 0; + while ($this->running) { + if ( ! $conn->ping()) { + $this->log(("Warning : abox connection lost, restarting in 10 min.")); + for ($i = 0; $i < 60 * 10; $i ++ ) + sleep(1); + $this->running = false; + + return(self::RETURNSTATUS_TORESTART); + } + + try { + $connbas = connection::getPDOConnection($this->sbas_id); + if ( ! $connbas->ping()) + throw new Exception('Mysql has gone away'); + } catch (Exception $e) { + $this->log(("dbox connection lost, restarting in 10 min.")); + for ($i = 0; $i < 60 * 10; $i ++ ) + sleep(1); + $this->running = false; + + return(self::RETURNSTATUS_TORESTART); + } + + $this->set_last_exec_time(); + + $databox = databox::get_instance($this->sbas_id); + + $sql = "SELECT * FROM task2 WHERE task_id = :task_id"; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row) { + if ($row['status'] == 'tostop') { + $ret = self::RETURNSTATUS_STOPPED; + ; + $this->running = false; + } else { + if (($this->sxTaskSettings = simplexml_load_string($row['settings']))) { + $period = (int) ($this->sxTaskSettings->period); + if ($period <= 0 || $period >= 24 * 60) + $period = 60; + } + else { + $period = 60; + } + $this->connbas = connection::getPDOConnection($this->sbas_id); + + $duration = time(); + + $r = $this->doRecords(); + + switch ($r) { + case 'WAIT': + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + break; + case 'BAD': + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + break; + case 'NORECSTODO': + $duration = time() - $duration; + if ($duration < $period) { + sleep($period - $duration); + $conn = connection::getPDOConnection(); + } + break; + case 'MAXRECSDONE': + case 'MAXMEMORY': + case 'MAXLOOP': + if ($row['status'] == self::STATUS_STARTED && $this->get_runner() !== self::RUNNER_MANUAL) { + $ret = self::RETURNSTATUS_TORESTART; + $this->running = false; + } + break; + default: + if ($row['status'] == self::STATUS_STARTED) { + $ret = self::RETURNSTATUS_STOPPED; + $this->running = false; + } + break; + } + } + } else { + $ret = 'stopped'; + $this->running = false; + } + $loop ++; + } + + $this->return_value = $ret; + + return($ret); + } + + function doRecords() + { + $ndone = 0; + $ret = 'NORECSTODO'; + + $tsql = $this->calcSQL($this->sxTaskSettings); + + $nchanged = 0; + foreach ($tsql as $xsql) { + try { + $stmt = $this->connbas->prepare($xsql['sql']); + if ($stmt->execute($xsql['params'])) { + $n = $stmt->rowCount(); + $stmt->closeCursor(); + + $nchanged += $n; + if ($n > 0) + $this->log(sprintf("SQL='%s' ; parms=%s - %s changes", $xsql['sql'], var_export($xsql['params']), $n)); + } + else { + $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); + } + } catch (ErrorException $e) { + $this->log(sprintf("ERROR SQL='%s' ; parms=%s", $xsql['sql'], var_export($xsql['params'], true))); + } + } + + $ret = ($nchanged > 0 ? $nchanged : 'NORECSTODO'); + + return($ret); + } + + private function calcSQL($sxTaskSettings) + { + $ret = array(); + + $this->sxTaskSettings = $sxTaskSettings; + + $date1 = $date2 = NULL; + $field1 = $field2 = ''; + + // test : DATE 1 + if (($field1 = trim($this->sxTaskSettings->field1)) != '') { + $date1 = time(); + if (($delta = (int) ($this->sxTaskSettings->fieldDv1)) > 0) { + if ($this->sxTaskSettings->fieldDs1 == '-') + $date1 += 86400 * $delta; + else + $date1 -= 86400 * $delta; + } + $date1 = date("YmdHis", $date1); + } + // test : DATE 2 + if (($field2 = trim($this->sxTaskSettings->field2)) != '') { + $date2 = time(); + if (($delta = (int) ($this->sxTaskSettings->fieldDv2)) > 0) { + if ($this->sxTaskSettings->fieldDs2 == '-') + $date2 += 86400 * $delta; + else + $date2 -= 86400 * $delta; + } + $date2 = date("YmdHis", $date2); + } + + + $sqlset = $params = $tmp_params = array(); + for ($i = 0; $i <= 2; $i ++ ) { + $sqlwhere[$i] = ''; + $sqlset[$i] = ''; + $x = 'status' . $i; + @list($tostat, $statval) = explode('_', (string) ($this->sxTaskSettings->{$x})); + if ($tostat >= 4 && $tostat <= 63) { + if ($statval == '0') { + $sqlset[$i] = 'status=status & ~(1<<' . $tostat . ')'; + $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') = 0)'; + } elseif ($statval == '1') { + $sqlset[$i] = 'status=status|(1<<' . $tostat . ')'; + $sqlwhere[$i] .= '(status & (1<<' . $tostat . ') != 0)'; + } + } + $x = 'coll' . $i; + if (($tocoll = (string) ($this->sxTaskSettings->{$x})) != '') { + $sqlset[$i] .= ( $sqlset[$i] ? ', ' : '') . ('coll_id = :coll_id_set' . $i); + $sqlwhere[$i] .= ( $sqlwhere[$i] ? ' AND ' : '') . '(coll_id = :coll_id_where' . $i . ')'; + $tmp_params[':coll_id_set' . $i] = $tocoll; + $tmp_params[':coll_id_where' . $i] = $tocoll; + } + } + + if ($date1 && $sqlset[0]) { + $params = array(); + $params[':name1'] = $field1; + $params[':date1'] = $date1; + $params[':coll_id_set0'] = $tmp_params[':coll_id_set0']; + + $w = 'p1.name = :name1 AND :date1 <= p1.value'; + if ($sqlwhere[1] && $sqlwhere[2]) { + $w .= ' AND ((' . $sqlwhere[1] . ') OR (' . $sqlwhere[2] . '))'; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } else { + if ($sqlwhere[1]) { + $w .= ' AND ' . $sqlwhere[1]; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } elseif ($sqlwhere[2]) { + $w .= ' AND ' . $sqlwhere[2]; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } + } + + $sql = "UPDATE prop AS p1 INNER JOIN record USING(record_id) + SET " . $sqlset[0] . + " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + + if ($date1 && $date2) { + $params = array(); + $params[':name1'] = $field1; + $params[':name2'] = $field2; + $params[':date1'] = $date1; + $params[':date2'] = $date2; + $params[':coll_id_set1'] = $tmp_params[':coll_id_set1']; + + $w = 'p1.name = :name1 AND p2.name = :name2 AND :date1 > p1.value AND :date2 <= p2.value'; + if ($sqlwhere[0] && $sqlwhere[2]) { + $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[2] . '))'; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } else { + if ($sqlwhere[0]) { + $w .= ' AND ' . $sqlwhere[0]; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + } elseif ($sqlwhere[2]) { + $w .= ' AND ' . $sqlwhere[2]; + $params[':coll_id_where2'] = $tmp_params[':coll_id_where2']; + } + } + + $sql = "UPDATE (prop AS p1 INNER JOIN prop AS p2 USING(record_id)) + INNER JOIN record USING(record_id) + SET " . $sqlset[1] . + " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + + if ($date2 && $sqlset[2]) { + $params = array(); + $params[':name2'] = $field2; + $params[':date2'] = $date2; + $params[':coll_id_set2'] = $tmp_params[':coll_id_set2']; + + $w = 'p2.name = :name2 AND :date2 > p2.value'; + if ($sqlwhere[0] && $sqlwhere[1]) { + $w .= ' AND ((' . $sqlwhere[0] . ') OR (' . $sqlwhere[1] . '))'; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } else { + if ($sqlwhere[0]) { + $w .= ' AND ' . $sqlwhere[0]; + $params[':coll_id_where0'] = $tmp_params[':coll_id_where0']; + } elseif ($sqlwhere[1]) { + $w .= ' AND ' . $sqlwhere[1]; + $params[':coll_id_where1'] = $tmp_params[':coll_id_where1']; + } + } + + $sql = "UPDATE prop AS p2 INNER JOIN record USING(record_id) + SET " . $sqlset[2] . + " WHERE " . $w; + + $ret[] = array('sql' => $sql, 'params' => $params); + } + + return($ret); + } + + public function facility() + { + $ret = NULL; + + $request = http_request::getInstance(); + $parm2 = $request->get_parms( + 'ACT', 'bid' + ); + + phrasea::headers(200, true, 'application/json', 'UTF-8', false); + $ret = NULL; + switch ($parm2['ACT']) { + case 'CALCSQL': + $xml = $this->graphic2xml(''); + $sxml = simplexml_load_string($xml); + $ret = $this->calcSQL($sxml); + break; + case 'GETBASE': + $ret = array('date_fields' => array(), 'status_bits' => array(), 'collections' => array()); + + if ($parm2['bid'] != '') { + $sbas_id = (int) $parm2['bid']; + try { + $databox = databox::get_instance($sbas_id); + $meta_struct = $databox->get_meta_structure(); + + foreach ($meta_struct as $meta) { + if (mb_strtolower($meta->get_type()) == 'date') + $ret['date_fields'][] = $meta->get_name(); + } + + $status = $databox->get_statusbits(); + foreach ($status as $n => $stat) { + $labelon = $stat['labelon'] ? $stat['labelon'] : ($n . '-ON'); + $labeloff = $stat['labeloff'] ? $stat['labeloff'] : ($n . '-OFF'); + $ret['status_bits'][] = array('n' => $n, 'value' => 0, 'label' => $labeloff); + $ret['status_bits'][] = array('n' => $n, 'value' => 1, 'label' => $labelon); + } + + foreach ($databox->get_collections() as $collection) + $ret['collections'][] = array('id' => $collection->get_coll_id(), 'name' => $collection->get_name()); + } catch (Exception $e) { + + } + } + break; + } + print(json_encode($ret)); + } +} ?> diff --git a/lib/classes/task/period/subdef.class.php b/lib/classes/task/period/subdef.class.php index 504b7767bd..09a556f252 100644 --- a/lib/classes/task/period/subdef.class.php +++ b/lib/classes/task/period/subdef.class.php @@ -16,319 +16,303 @@ */ class task_period_subdef extends task_databoxAbstract { + /** + * Record buffer for writing meta datas after building subdefs + * + * @var array + */ + protected $recs_to_write = array(); - /** - * Record buffer for writing meta datas after building subdefs - * - * @var array - */ - protected $recs_to_write = array(); - /** - * Maximum buffer size before flushing records - * - * @var - */ - protected $record_buffer_size; + /** + * Maximum buffer size before flushing records + * + * @var + */ + protected $record_buffer_size; - /** - * Return about text - * - * @return - */ - function help() - { - return( - _("task::subdef:creation des sous definitions des documents d'origine") - ); - } - - /** - * Returns task name - * - * @return string - */ - public function getName() - { - return(_('task::subdef:creation des sous definitions')); - } - - - /** - * must return the xml (text) version of the form - * - * @param string $oldxml - * @return string - */ - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - 'period' - , 'flush' - , 'maxrecs' - , 'maxmegs' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if ($dom->loadXML($oldxml)) + /** + * Return about text + * + * @return + */ + function help() { - $xmlchanged = false; - - foreach (array("str:period", "str:flush", "str:maxrecs", "str:maxmegs") as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - } - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return( + _("task::subdef:creation des sous definitions des documents d'origine") + ); } - return($dom->saveXML()); - } - - /** - * must fill the graphic form (using js) from xml - * - * @param string $xml - * @param string $form - * @return string - */ - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) + /** + * Returns task name + * + * @return string + */ + public function getName() { - if ((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif ((int) ($sxml->period) > 300) - $sxml->period = 300; - - if ((string) ($sxml->flush) == '') - $sxml->flush = 10; - elseif ((int) ($sxml->flush) < 1) - $sxml->flush = 1; - elseif ((int) ($sxml->flush) > 100) - $sxml->flush = 100; - - if ((string) ($sxml->maxrecs) == '') - $sxml->maxrecs = 100; - if ((int) ($sxml->maxrecs) < 10) - $sxml->maxrecs = 10; - elseif ((int) ($sxml->maxrecs) > 500) - $sxml->maxrecs = 500; - - if ((string) ($sxml->maxmegs) == '') - $sxml->maxmegs = 6; - if ((int) ($sxml->maxmegs) < 3) - $sxml->maxmegs = 3; - elseif ((int) ($sxml->maxmegs) > 32) - $sxml->maxmegs = 32; -?> - -get_parms( + 'period' + , 'flush' + , 'maxrecs' + , 'maxmegs' + ); + $dom = new DOMDocument(); + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + if ($dom->loadXML($oldxml)) { + $xmlchanged = false; + + foreach (array("str:period", "str:flush", "str:maxrecs", "str:maxmegs") as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + } + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; + } + } + + return($dom->saveXML()); } - } - /** - * - * generates le code js de l'interface 'graphic view' - * - */ - public function printInterfaceJS() - { -?> - - -
                  -
                  - :  - -
                  -
                  - '); ?> -
                  -
                  -  - -   - - Mo -
                  -
                  -recs_to_write); - - if ($sql != '') + /** + * must fill the graphic form (using js) from xml + * + * @param string $xml + * @param string $form + * @return string + */ + public function xml2graphic($xml, $form) { - $this->log(sprintf( - 'setting %d record(s) to subdef meta writing' - , count($this->recs_to_write) - )); + if (($sxml = simplexml_load_string($xml))) { + if ((int) ($sxml->period) < 10) + $sxml->period = 10; + elseif ((int) ($sxml->period) > 300) + $sxml->period = 300; - try - { - $connbas = connection::getPDOConnection($this->sbas_id); - $sql = 'UPDATE record + if ((string) ($sxml->flush) == '') + $sxml->flush = 10; + elseif ((int) ($sxml->flush) < 1) + $sxml->flush = 1; + elseif ((int) ($sxml->flush) > 100) + $sxml->flush = 100; + + if ((string) ($sxml->maxrecs) == '') + $sxml->maxrecs = 100; + if ((int) ($sxml->maxrecs) < 10) + $sxml->maxrecs = 10; + elseif ((int) ($sxml->maxrecs) > 500) + $sxml->maxrecs = 500; + + if ((string) ($sxml->maxmegs) == '') + $sxml->maxmegs = 6; + if ((int) ($sxml->maxmegs) < 3) + $sxml->maxmegs = 3; + elseif ((int) ($sxml->maxmegs) > 32) + $sxml->maxmegs = 32; + ?> + + + + +
                  +
                  +  :  + +
                  +
                  + '); ?> +
                  +
                  +   + +   + + Mo +
                  +
                  + recs_to_write); + + if ($sql != '') { + $this->log(sprintf( + 'setting %d record(s) to subdef meta writing' + , count($this->recs_to_write) + )); + + try { + $connbas = connection::getPDOConnection($this->sbas_id); + $sql = 'UPDATE record SET status=(status & ~0x03), jeton=(jeton | ' . JETON_WRITE_META_SUBDEF . ') WHERE record_id IN (' . $sql . ')'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - catch (Exception $e) - { - $this->log($e->getMessage()); - } - } - $this->recs_to_write = array(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } catch (Exception $e) { + $this->log($e->getMessage()); + } + } + $this->recs_to_write = array(); - return $this; - } + return $this; + } - public function retrieve_sbas_content(databox $databox) - { - $connbas = $databox->get_connection(); + public function retrieve_sbas_content(databox $databox) + { + $connbas = $databox->get_connection(); - $sql = 'SELECT coll_id, record_id + $sql = 'SELECT coll_id, record_id FROM record WHERE jeton & ' . JETON_MAKE_SUBDEF . ' > 0 AND parent_record_id = 0 ORDER BY record_id DESC LIMIT 0, 20'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $rs; - } + return $rs; + } - public function process_one_content(databox $databox, Array $row) - { - $record_id = $row['record_id']; - $this->log(sprintf( + public function process_one_content(databox $databox, Array $row) + { + $record_id = $row['record_id']; + $this->log(sprintf( "Generate subdefs for : sbas_id %s / record %s " , $this->sbas_id, $record_id)); - $record = new record_adapter($this->sbas_id, $record_id); + $record = new record_adapter($this->sbas_id, $record_id); - $record->generate_subdefs($databox, null); + $record->generate_subdefs($databox, null); - $this->recs_to_write[] = $record->get_record_id(); + $this->recs_to_write[] = $record->get_record_id(); - if (count($this->recs_to_write) >= $this->record_buffer_size) - { - $this->flush_records_sbas(); - } - unset($record); + if (count($this->recs_to_write) >= $this->record_buffer_size) { + $this->flush_records_sbas(); + } + unset($record); - return $this; - } + return $this; + } - protected function post_process_one_content(databox $databox, Array $row) - { - $connbas = $databox->get_connection(); - $sql = 'UPDATE record + protected function post_process_one_content(databox $databox, Array $row) + { + $connbas = $databox->get_connection(); + $sql = 'UPDATE record SET jeton=(jeton & ~' . JETON_MAKE_SUBDEF . '), moddate=NOW() WHERE record_id=:record_id'; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':record_id' => $row['record_id'])); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':record_id' => $row['record_id'])); + $stmt->closeCursor(); - return $this; - } - -} + return $this; + } + } diff --git a/lib/classes/task/period/test.class.php b/lib/classes/task/period/test.class.php index 24da198055..263bc9b310 100644 --- a/lib/classes/task/period/test.class.php +++ b/lib/classes/task/period/test.class.php @@ -18,35 +18,34 @@ class task_period_test extends task_appboxAbstract { - public function getName() - { - return "Test"; - } + public function getName() + { + return "Test"; + } - public function help() - { - return "just saying what i'm doing"; - } + public function help() + { + return "just saying what i'm doing"; + } - protected function retrieve_content(appbox $appbox) - { - $this->log('test class, retrive content'); + protected function retrieve_content(appbox $appbox) + { + $this->log('test class, retrive content'); - return array('hello', 'world'); - } + return array('hello', 'world'); + } - protected function process_one_content(appbox $appbox, Array $row) - { - $this->log(sprintf("test class, process content : `%s`", implode(' ', $row))); + protected function process_one_content(appbox $appbox, Array $row) + { + $this->log(sprintf("test class, process content : `%s`", implode(' ', $row))); - return $this; - } + return $this; + } - protected function post_process_one_content(appbox $appbox, Array $row) - { - $this->log(sprintf("test class, post process content, they were %s", count($row))); - - return $this; - } + protected function post_process_one_content(appbox $appbox, Array $row) + { + $this->log(sprintf("test class, post process content, they were %s", count($row))); + return $this; + } } diff --git a/lib/classes/task/period/upgradetov31.class.php b/lib/classes/task/period/upgradetov31.class.php index 9734f1b4b5..7a2150a719 100644 --- a/lib/classes/task/period/upgradetov31.class.php +++ b/lib/classes/task/period/upgradetov31.class.php @@ -18,175 +18,159 @@ class task_period_upgradetov31 extends task_abstract { - // ========================================================================== - // ===== les interfaces de settings (task2.php) pour ce type de tache - // ========================================================================== - // ==================================================================== - // getName() : must return the name of this kind of task (utf8), MANDATORY - // ==================================================================== - public function getName() - { - return(_("upgrade to v3.1")); - } - - public static function interfaceAvailable() - { - return false; - } - - public function help() - { - return(utf8_encode("Upgrade some database values")); - } - - protected function run2() - { - printf("taskid %s starting." . PHP_EOL, $this->get_task_id()); - // task can't be stopped here - $appbox = appbox::get_instance(\bootstrap::getCore()); - $conn = $appbox->get_connection(); - $registry = $appbox->get_registry(); - $running = true; - - if (!is_executable($registry->get('GV_exiftool'))) + // ========================================================================== + // ===== les interfaces de settings (task2.php) pour ce type de tache + // ========================================================================== + // ==================================================================== + // getName() : must return the name of this kind of task (utf8), MANDATORY + // ==================================================================== + public function getName() { - printf("Exiftool is not executable, script can not process\n"); - - return 'stopped'; + return(_("upgrade to v3.1")); } - $todo = $this->how_many_left(); - $done = 0; - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $ret = 'stopped'; - - $this->setProgress($done, $todo); - - - while ($running) + public static function interfaceAvailable() { + return false; + } - foreach ($appbox->get_databoxes() as $databox) - { - $connbas = $databox->get_connection(); + public function help() + { + return(utf8_encode("Upgrade some database values")); + } - $sql = 'SELECT r.type, r.record_id, s.path, s.file, r.xml + protected function run2() + { + printf("taskid %s starting." . PHP_EOL, $this->get_task_id()); + // task can't be stopped here + $appbox = appbox::get_instance(\bootstrap::getCore()); + $conn = $appbox->get_connection(); + $registry = $appbox->get_registry(); + $running = true; + + if ( ! is_executable($registry->get('GV_exiftool'))) { + printf("Exiftool is not executable, script can not process\n"); + + return 'stopped'; + } + + $todo = $this->how_many_left(); + $done = 0; + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $ret = 'stopped'; + + $this->setProgress($done, $todo); + + + while ($running) { + + foreach ($appbox->get_databoxes() as $databox) { + $connbas = $databox->get_connection(); + + $sql = 'SELECT r.type, r.record_id, s.path, s.file, r.xml FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document" LIMIT 100'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - foreach ($rs as $row) - { - $pathfile = p4string::addEndSlash($row['path']) . $row['file']; - if (!file_exists($pathfile)) - { - printf("le fichier nexiste $pathfile pas ....\n"); - $uuid = uuid::generate_v4(); - } - else - { - $uuid_file = new system_file($pathfile); - $uuid = $uuid_file->write_uuid(); - } + foreach ($rs as $row) { + $pathfile = p4string::addEndSlash($row['path']) . $row['file']; + if ( ! file_exists($pathfile)) { + printf("le fichier nexiste $pathfile pas ....\n"); + $uuid = uuid::generate_v4(); + } else { + $uuid_file = new system_file($pathfile); + $uuid = $uuid_file->write_uuid(); + } - $sql = 'UPDATE record SET uuid = :uuid WHERE record_id = :record_id'; + $sql = 'UPDATE record SET uuid = :uuid WHERE record_id = :record_id'; - $params = array( - ':uuid' => $uuid - , ':record_id' => $row['record_id'] - ); - $stmt = $connbas->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $params = array( + ':uuid' => $uuid + , ':record_id' => $row['record_id'] + ); + $stmt = $connbas->prepare($sql); + $stmt->execute($params); + $stmt->closeCursor(); - echo "mise a jour du record " . $row['record_id'] . " avec uuid " . $uuid . "\n"; + echo "mise a jour du record " . $row['record_id'] . " avec uuid " . $uuid . "\n"; - $done++; - $this->setProgress($done, $todo); + $done ++; + $this->setProgress($done, $todo); + } + } + $todo = $this->how_many_left() + $done; + + if ($done == $todo) { + $sql = 'UPDATE task2 SET status="tostop" WHERE task_id = :task_id'; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $stmt->closeCursor(); + + $this->setProgress(0, 0); + $ret = 'todelete'; + } + + $sql = "SELECT status FROM task2 WHERE status='tostop' AND task_id=" . $this->get_task_id(); + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($row) { + $running = false; + } + + $conn->close(); + unset($conn); + sleep(1); + $conn = connection::getPDOConnection(); } - } + printf("taskid %s ending." . PHP_EOL, $this->get_task_id()); - $todo = $this->how_many_left() + $done; + sleep(1); - if ($done == $todo) - { - $sql = 'UPDATE task2 SET status="tostop" WHERE task_id = :task_id'; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $stmt->closeCursor(); + printf("good bye world I was task upgrade to version 3.1" . PHP_EOL); - $this->setProgress(0, 0); - $ret = 'todelete'; - } + flush(); - $sql = "SELECT status FROM task2 WHERE status='tostop' AND task_id=" . $this->get_task_id(); - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if ($row) - { - $running = false; - } - - $conn->close(); - unset($conn); - sleep(1); - $conn = connection::getPDOConnection(); + return $ret; } - printf("taskid %s ending." . PHP_EOL, $this->get_task_id()); - sleep(1); - - printf("good bye world I was task upgrade to version 3.1" . PHP_EOL); - - flush(); - - return $ret; - } - - private function how_many_left() - { - $todo = 0; - $appbox = appbox::get_instance(\bootstrap::getCore()); - - foreach ($appbox->get_databoxes() as $databox) + private function how_many_left() { - try - { - $connbas = $databox->get_connection(); + $todo = 0; + $appbox = appbox::get_instance(\bootstrap::getCore()); - $sql = 'SELECT count(r.record_id) as total FROM record r, subdef s + foreach ($appbox->get_databoxes() as $databox) { + try { + $connbas = $databox->get_connection(); + + $sql = 'SELECT count(r.record_id) as total FROM record r, subdef s WHERE ISNULL(uuid) AND s.record_id = r.record_id AND s.name="document"'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if ($row) - { - $todo += (int) $row['total']; + if ($row) { + $todo += (int) $row['total']; + } + } catch (Excepiton $e) { + + } } - } - catch (Excepiton $e) - { - } + return $todo; } - - return $todo; - } - } ?> diff --git a/lib/classes/task/period/upgradetov32.class.php b/lib/classes/task/period/upgradetov32.class.php index 337d39ad25..5a28c068b1 100644 --- a/lib/classes/task/period/upgradetov32.class.php +++ b/lib/classes/task/period/upgradetov32.class.php @@ -17,237 +17,208 @@ */ class task_period_upgradetov32 extends task_abstract { + protected $sbas_id; - protected $sbas_id; + // ========================================================================== + // ===== les interfaces de settings (task2.php) pour ce type de tache + // ========================================================================== + // ==================================================================== + // getName() : must return the name of this kind of task (utf8), MANDATORY + // ==================================================================== + public function getName() + { + return(_("upgrade to v3.2")); + } - // ========================================================================== - // ===== les interfaces de settings (task2.php) pour ce type de tache - // ========================================================================== - // ==================================================================== - // getName() : must return the name of this kind of task (utf8), MANDATORY - // ==================================================================== - public function getName() - { - return(_("upgrade to v3.2")); - } + public static function interfaceAvailable() + { + return false; + } - public static function interfaceAvailable() - { - return false; - } + // ========================================================================== + // help() : text displayed if --help + // ========================================================================== + public function help() + { + return(utf8_encode("Upgrade some database values")); + } - // ========================================================================== - // help() : text displayed if --help - // ========================================================================== - public function help() - { - return(utf8_encode("Upgrade some database values")); - } + // ========================================================================== + // run() : the real code executed by each task, MANDATORY + // ========================================================================== - // ========================================================================== - // run() : the real code executed by each task, MANDATORY - // ========================================================================== + protected function load_settings(SimpleXMLElement $sx_task_settings) + { + $this->sbas_id = (int) $sx_task_settings->sbas_id; + parent::load_settings($sx_task_settings); - protected function load_settings(SimpleXMLElement $sx_task_settings) - { - $this->sbas_id = (int) $sx_task_settings->sbas_id; - parent::load_settings($sx_task_settings); + return $this; + } - return $this; - } + protected function run2() + { + printf("taskid %s starting." . PHP_EOL, $this->get_task_id()); - protected function run2() - { - printf("taskid %s starting." . PHP_EOL, $this->get_task_id()); - - $registry = registry::get_instance(); + $registry = registry::get_instance(); // $registry->set('GV_cache_server_type', 'nocache', \registry::TYPE_STRING); - $registry->set('GV_sphinx', false, \registry::TYPE_BOOLEAN); + $registry->set('GV_sphinx', false, \registry::TYPE_BOOLEAN); - if (!$this->sbas_id) - { - printf("sbas_id '" . $this->sbas_id . "' invalide\n"); - $this->return_value = self::RETURNSTATUS_STOPPED; + if ( ! $this->sbas_id) { + printf("sbas_id '" . $this->sbas_id . "' invalide\n"); + $this->return_value = self::RETURNSTATUS_STOPPED; - return; - } - - try - { - $databox = databox::get_instance($this->sbas_id); - $connbas = connection::getPDOConnection($this->sbas_id); - } - catch (Exception $e) - { - $this->return_value = self::RETURNSTATUS_STOPPED; - - return; - } - - try - { - foreach ($databox->get_meta_structure()->get_elements() as $struct_el) - { - if ($struct_el instanceof databox_fieldUnknown) - { - throw new Exception('Bad field'); + return; } - } - } - catch (Exception $e) - { - printf("Please verify all your databox meta fields before migrating, It seems somes are wrong\n"); - $this->return_value = self::RETURNSTATUS_STOPPED; - return 'stopped'; - } + try { + $databox = databox::get_instance($this->sbas_id); + $connbas = connection::getPDOConnection($this->sbas_id); + } catch (Exception $e) { + $this->return_value = self::RETURNSTATUS_STOPPED; - $this->running = true; + return; + } - try - { - $sql = 'ALTER TABLE `record` ADD `migrated` TINYINT( 1 ) UNSIGNED NOT NULL , ADD INDEX ( `migrated` ) '; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - catch (Exception $e) - { + try { + foreach ($databox->get_meta_structure()->get_elements() as $struct_el) { + if ($struct_el instanceof databox_fieldUnknown) { + throw new Exception('Bad field'); + } + } + } catch (Exception $e) { + printf("Please verify all your databox meta fields before migrating, It seems somes are wrong\n"); + $this->return_value = self::RETURNSTATUS_STOPPED; - } + return 'stopped'; + } - $n_done = 0; + $this->running = true; - while ($this->running) - { - try - { + try { + $sql = 'ALTER TABLE `record` ADD `migrated` TINYINT( 1 ) UNSIGNED NOT NULL , ADD INDEX ( `migrated` ) '; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } catch (Exception $e) { - $sql = 'SELECT COUNT(record_id) as total FROM record'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + } - $total = 0; - if ($row) - $total = $row['total']; + $n_done = 0; - $sql = 'SELECT COUNT(record_id) as total FROM record WHERE migrated = 1'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + while ($this->running) { + try { - $done = 0; - if ($row) - $done = $row['total']; + $sql = 'SELECT COUNT(record_id) as total FROM record'; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $this->setProgress($done, $total); + $total = 0; + if ($row) + $total = $row['total']; - $this->running = false; - $sql = 'select record_id, coll_id, xml, BIN(status) as status + $sql = 'SELECT COUNT(record_id) as total FROM record WHERE migrated = 1'; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $done = 0; + if ($row) + $done = $row['total']; + + $this->setProgress($done, $total); + + $this->running = false; + $sql = 'select record_id, coll_id, xml, BIN(status) as status FROM record WHERE originalname IS NULL LIMIT 0, 500'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (count($rs) > 0) - { - $this->running = true; - } + if (count($rs) > 0) { + $this->running = true; + } - $sql = 'UPDATE record SET originalname = :originalname WHERE record_id = :record_id'; - $stmt_original = $connbas->prepare($sql); - $connbas->beginTransaction(); - foreach ($rs as $row) - { - $original = ''; - $sxe = simplexml_load_string($row['xml']); - if ($sxe) - { - foreach ($sxe->doc->attributes() as $key => $value) - { - $key = trim($key); - $value = trim($value); - if ($key != 'originalname') - { - continue; - } - $original = basename($value); - break; - } - } - try - { - $stmt_original->execute(array(':originalname' => $value, ':record_id' => $row['record_id'])); - } - catch (Exception $e) - { + $sql = 'UPDATE record SET originalname = :originalname WHERE record_id = :record_id'; + $stmt_original = $connbas->prepare($sql); + $connbas->beginTransaction(); + foreach ($rs as $row) { + $original = ''; + $sxe = simplexml_load_string($row['xml']); + if ($sxe) { + foreach ($sxe->doc->attributes() as $key => $value) { + $key = trim($key); + $value = trim($value); + if ($key != 'originalname') { + continue; + } + $original = basename($value); + break; + } + } + try { + $stmt_original->execute(array(':originalname' => $value, ':record_id' => $row['record_id'])); + } catch (Exception $e) { - } - } - $connbas->commit(); + } + } + $connbas->commit(); - $sql = 'select record_id, coll_id, xml, BIN(status) as status + $sql = 'select record_id, coll_id, xml, BIN(status) as status FROM record WHERE migrated="0" AND record_id NOT IN (select distinct record_id from technical_datas) LIMIT 0, 500'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - if (count($rs) > 0) - { - $this->running = true; - } + if (count($rs) > 0) { + $this->running = true; + } - $sql = 'REPLACE INTO technical_datas (id, record_id, name, value) + $sql = 'REPLACE INTO technical_datas (id, record_id, name, value) VALUES (null, :record_id, :name, :value)'; - $stmt = $connbas->prepare($sql); - $connbas->beginTransaction(); + $stmt = $connbas->prepare($sql); + $connbas->beginTransaction(); - foreach ($rs as $row) - { - try - { - $record = new record_adapter($this->sbas_id, $row['record_id']); - $system_file = $record->get_hd_file(); + foreach ($rs as $row) { + try { + $record = new record_adapter($this->sbas_id, $row['record_id']); + $system_file = $record->get_hd_file(); - if (!$system_file instanceof system_file) - continue; + if ( ! $system_file instanceof system_file) + continue; - $tc_datas = $system_file->get_technical_datas(); + $tc_datas = $system_file->get_technical_datas(); - foreach ($tc_datas as $name => $value) - { - if (is_null($value)) - continue; + foreach ($tc_datas as $name => $value) { + if (is_null($value)) + continue; - $stmt->execute(array( - ':record_id' => $record->get_record_id() - , ':name' => $name - , ':value' => $value - )); - } - } - catch (Exception $e) - { + $stmt->execute(array( + ':record_id' => $record->get_record_id() + , ':name' => $name + , ':value' => $value + )); + } + } catch (Exception $e) { - } - } + } + } - $connbas->commit(); - $stmt->closeCursor(); + $connbas->commit(); + $stmt->closeCursor(); @@ -258,166 +229,140 @@ class task_period_upgradetov32 extends task_abstract - $sql = 'select record_id, coll_id, xml, BIN(status) as status + $sql = 'select record_id, coll_id, xml, BIN(status) as status FROM record WHERE migrated=0 LIMIT 0, 500'; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + + if (count($rs) > 0) { + $this->running = true; + } + $connbas->beginTransaction(); + + $sql = 'UPDATE record SET migrated=1 WHERE record_id = :record_id'; + $stmt = $connbas->prepare($sql); + + foreach ($rs as $row) { + try { + $record = new record_adapter($this->sbas_id, $row['record_id']); + + $metas = $databox->get_meta_structure(); + + $metadatas = array(); + + if ($sxe = simplexml_load_string($row['xml'])) { + $z = $sxe->xpath('/record/description'); + if ($z && is_array($z)) { + foreach ($z[0] as $ki => $vi) { + $databox_field = $metas->get_element_by_name((string) $ki); + if ( ! $databox_field) { + continue; + } + + $value = (string) $vi; + + if (trim($value) === '') + continue; + + if ($databox_field->is_multi()) { + $new_value = caption_field::get_multi_values($value, $databox_field->get_separator()); + if (isset($metadatas[$databox_field->get_id()])) { + $value = array_unique(array_merge($metadatas[$databox_field->get_id()]['value'], $new_value)); + } else { + $value = $new_value; + } + } else { + $new_value = array($value); + if (isset($metadatas[$databox_field->get_id()])) { + $value = array(array_shift($metadatas[$databox_field->get_id()]['value']) . ' ' . array_shift($new_value)); + } else { + $value = $new_value; + } + } + + $metadatas[$databox_field->get_id()] = array( + 'meta_struct_id' => $databox_field->get_id() + , 'meta_id' => null + , 'value' => $value + ); + } + } + } + $record->set_metadatas($metadatas, true); + unset($record); + } catch (Exception $e) { + + } + try { + $record = new record_adapter($this->sbas_id, $row['record_id']); + $record->set_binary_status($row['status']); + unset($record); + } catch (Exception $e) { + + } + $stmt->execute(array(':record_id' => $row['record_id'])); + } + + $stmt->closeCursor(); + unset($stmt); + $connbas->commit(); + + $n_done += 500; + + $memory = memory_get_usage() >> 20; + + if ($n_done >= 5000) { + $this->return_value = task_abstract::RETURNSTATUS_TORESTART; + + return; + } + if ($memory > 100) { + $this->return_value = task_abstract::RETURNSTATUS_TORESTART; + + return; + } + } catch (Exception $e) { + + } + usleep(500000); + } + + $sql = 'ALTER TABLE `record` DROP `migrated`'; $stmt = $connbas->prepare($sql); $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - if (count($rs) > 0) - { - $this->running = true; - } - $connbas->beginTransaction(); - - $sql = 'UPDATE record SET migrated=1 WHERE record_id = :record_id'; + $sql = "DELETE from technical_datas WHERE name='DONE'"; $stmt = $connbas->prepare($sql); - - foreach ($rs as $row) - { - try - { - $record = new record_adapter($this->sbas_id, $row['record_id']); - - $metas = $databox->get_meta_structure(); - - $metadatas = array(); - - if ($sxe = simplexml_load_string($row['xml'])) - { - $z = $sxe->xpath('/record/description'); - if ($z && is_array($z)) - { - foreach ($z[0] as $ki => $vi) - { - $databox_field = $metas->get_element_by_name((string) $ki); - if (!$databox_field) - { - continue; - } - - $value = (string) $vi; - - if (trim($value) === '') - continue; - - if ($databox_field->is_multi()) - { - $new_value = caption_field::get_multi_values($value, $databox_field->get_separator()); - if (isset($metadatas[$databox_field->get_id()])) - { - $value = array_unique(array_merge($metadatas[$databox_field->get_id()]['value'], $new_value)); - } - else - { - $value = $new_value; - } - } - else - { - $new_value = array($value); - if (isset($metadatas[$databox_field->get_id()])) - { - $value = array(array_shift($metadatas[$databox_field->get_id()]['value']) . ' ' . array_shift($new_value)); - } - else - { - $value = $new_value; - } - } - - $metadatas[$databox_field->get_id()] = array( - 'meta_struct_id' => $databox_field->get_id() - , 'meta_id' => null - , 'value' => $value - ); - } - } - } - $record->set_metadatas($metadatas, true); - unset($record); - } - catch (Exception $e) - { - - } - try - { - $record = new record_adapter($this->sbas_id, $row['record_id']); - $record->set_binary_status($row['status']); - unset($record); - } - catch (Exception $e) - { - - } - $stmt->execute(array(':record_id' => $row['record_id'])); - } - + $stmt->execute(); $stmt->closeCursor(); - unset($stmt); - $connbas->commit(); - $n_done += 500; + $conn = connection::getPDOConnection(); - $memory = memory_get_usage() >> 20; + printf("taskid %s ending." . PHP_EOL, $this->get_task_id()); + sleep(1); + printf("good bye world I was task upgrade to version 3.2" . PHP_EOL); - if ($n_done >= 5000) - { - $this->return_value = task_abstract::RETURNSTATUS_TORESTART; + $sql = 'UPDATE task2 SET status="tostop" WHERE task_id = :task_id'; - return; - } - if ($memory > 100) - { - $this->return_value = task_abstract::RETURNSTATUS_TORESTART; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':task_id' => $this->get_task_id())); + $stmt->closeCursor(); - return; - } - } - catch (Exception $e) - { + $this->setProgress(0, 0); - } - usleep(500000); + $this->return_value = self::RETURNSTATUS_TODELETE; + + flush(); + + return; } - - $sql = 'ALTER TABLE `record` DROP `migrated`'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - - $sql = "DELETE from technical_datas WHERE name='DONE'"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $conn = connection::getPDOConnection(); - - printf("taskid %s ending." . PHP_EOL, $this->get_task_id()); - sleep(1); - printf("good bye world I was task upgrade to version 3.2" . PHP_EOL); - - $sql = 'UPDATE task2 SET status="tostop" WHERE task_id = :task_id'; - - $stmt = $conn->prepare($sql); - $stmt->execute(array(':task_id' => $this->get_task_id())); - $stmt->closeCursor(); - - $this->setProgress(0, 0); - - $this->return_value = self::RETURNSTATUS_TODELETE; - - flush(); - - return; - } - } diff --git a/lib/classes/task/period/workflow01.class.php b/lib/classes/task/period/workflow01.class.php index a48d8083de..d9b0e0212d 100644 --- a/lib/classes/task/period/workflow01.class.php +++ b/lib/classes/task/period/workflow01.class.php @@ -17,528 +17,510 @@ class task_period_workflow01 extends task_databoxAbstract { - public function getName() - { - return(_('task::workflow01')); - } - - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - "sbas_id" - , "period" - , 'status0' - , 'coll0' - , 'status1' - , 'coll1' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if ($dom->loadXML($oldxml)) + public function getName() { - $xmlchanged = false; - // foreach($parm2 as $pname=>$pvalue) - foreach (array( - "str:sbas_id", - "str:period", - 'str:status0', - 'str:coll0', - 'str:status1', - 'str:coll1', - ) as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); + return(_('task::workflow01')); + } + + public function graphic2xml($oldxml) + { + $request = http_request::getInstance(); + + $parm2 = $request->get_parms( + "sbas_id" + , "period" + , 'status0' + , 'coll0' + , 'status1' + , 'coll1' + ); + $dom = new DOMDocument(); + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + if ($dom->loadXML($oldxml)) { + $xmlchanged = false; + // foreach($parm2 as $pname=>$pvalue) + foreach (array( + "str:sbas_id", + "str:period", + 'str:status0', + 'str:coll0', + 'str:status1', + 'str:coll1', + ) as $pname) { + $ptype = substr($pname, 0, 3); + $pname = substr($pname, 4); + $pvalue = $parm2[$pname]; + if ($ns = $dom->getElementsByTagName($pname)->item(0)) { + // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) + while (($n = $ns->firstChild)) + $ns->removeChild($n); + } else { + // le champ n'existait pas dans le xml, on le cree + $dom->documentElement->appendChild($dom->createTextNode("\t")); + $ns = $dom->documentElement->appendChild($dom->createElement($pname)); + $dom->documentElement->appendChild($dom->createTextNode("\n")); + } + // on fixe sa valeur + switch ($ptype) { + case "str": + $ns->appendChild($dom->createTextNode($pvalue)); + break; + case "boo": + $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); + break; + } + $xmlchanged = true; + } } + + return($dom->saveXML()); + } + + public function xml2graphic($xml, $form) + { + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values + if ((int) ($sxml->period) < 10) + $sxml->period = 10; + elseif ((int) ($sxml->period) > 1440) // 1 jour + $sxml->period = 1440; + + if ((string) ($sxml->delay) == '') + $sxml->delay = 0; + ?> + + + + + + get_session(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + ob_start(); + ?> +
                  +  :  + + + +   + +
                  +
                  + +  :  + +
                  +
                  + + + + + + + + + + + + + +
                  + Collection : + + + +   ====>   + + +
                  + Status : + + + + +
                  +
                  +
                  +
                  +
                  cmd
                  +
                  + status_origine = (string) $sx_task_settings->status0; + $this->status_destination = (string) $sx_task_settings->status1; + + $this->coll_origine = (int) $sx_task_settings->coll0; + $this->coll_destination = (int) $sx_task_settings->coll1; + + parent::load_settings($sx_task_settings); + + $this->mono_sbas_id = (int) $sx_task_settings->sbas_id; + // in minutes + $this->period = (int) $sx_task_settings->period * 60; + + if ($this->period <= 0 || $this->period >= 24 * 60) + $this->period = 60; + + return $this; + } + + protected function retrieve_sbas_content(databox $databox) + { + + $connbas = $databox->get_connection(); + + $status_origine = explode('_', $this->status_origine); + if (count($status_origine) !== 2) + throw new Exception('Error in settings for status origine'); + + $status_destination = explode('_', $this->status_destination); + if (count($status_destination) !== 2) + throw new Exception('Error in settings for status destination'); + + $collection_origine = collection::get_from_base_id($this->coll_origine); + $collection_destination = collection::get_from_base_id($this->coll_destination); + + unset($collection_destination); + unset($collection_origine); + + $status_orgine_number = (int) $status_origine[0]; + $status_orgine_state = (int) $status_origine[1]; + + $status_destination_number = (int) $status_destination[0]; + $status_destination_state = (int) $status_destination[1]; + + + $u = 'coll_id = :coll_dest'; + if ($status_destination_state === 0) + $u .= ', status = status &~(1 << ' . $status_destination_number . ')'; else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } - } - - return($dom->saveXML()); - } - - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... - { - // ... but we could check for safe values - if ((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif ((int) ($sxml->period) > 1440) // 1 jour - $sxml->period = 1440; - - if ((string) ($sxml->delay) == '') - $sxml->delay = 0; -?> - - - - - -get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - ob_start(); -?> -
                  -  :  - - - -   - -
                  -
                  - -  :  - -
                  -
                  - - - - - - - - - - - - - -
                  - Collection : - - - -   ====>   - - -
                  - Status : - - - - -
                  -
                  -
                  -
                  -
                  cmd
                  -
                  -status_origine = (string) $sx_task_settings->status0; - $this->status_destination = (string) $sx_task_settings->status1; - - $this->coll_origine = (int) $sx_task_settings->coll0; - $this->coll_destination = (int) $sx_task_settings->coll1; - - parent::load_settings($sx_task_settings); - - $this->mono_sbas_id = (int) $sx_task_settings->sbas_id; - // in minutes - $this->period = (int) $sx_task_settings->period * 60; - - if ($this->period <= 0 || $this->period >= 24 * 60) - $this->period = 60; - - return $this; - } - - protected function retrieve_sbas_content(databox $databox) - { - - $connbas = $databox->get_connection(); - - $status_origine = explode('_', $this->status_origine); - if (count($status_origine) !== 2) - throw new Exception('Error in settings for status origine'); - - $status_destination = explode('_', $this->status_destination); - if (count($status_destination) !== 2) - throw new Exception('Error in settings for status destination'); - - $collection_origine = collection::get_from_base_id($this->coll_origine); - $collection_destination = collection::get_from_base_id($this->coll_destination); - - unset($collection_destination); - unset($collection_origine); - - $status_orgine_number = (int) $status_origine[0]; - $status_orgine_state = (int) $status_origine[1]; - - $status_destination_number = (int) $status_destination[0]; - $status_destination_state = (int) $status_destination[1]; + $u .= ', status = status |(1 << ' . $status_destination_number . ')'; - $u = 'coll_id = :coll_dest'; - if ($status_destination_state === 0) - $u .= ', status = status &~(1 << ' . $status_destination_number . ')'; - else - $u .= ', status = status |(1 << ' . $status_destination_number . ')'; - - - $sql = 'UPDATE record + $sql = 'UPDATE record SET ' . $u . ' WHERE coll_id = :coll_id AND (status >> ' . $status_orgine_number . ') & 1 = ' . $status_orgine_state; - $params = array( - ':coll_id' => $this->coll_origine, - ':coll_dest' => $this->coll_destination - ); + $params = array( + ':coll_id' => $this->coll_origine, + ':coll_dest' => $this->coll_destination + ); - $stmt = $connbas->prepare($sql); - $stmt->execute($params); - $this->log(sprintf(("SQL=%s - %s changes"), str_replace(array("\r\n","\n","\r"), " ", $sql), $stmt->rowCount())); - $stmt->closeCursor(); - - return array(); - } - - protected function process_one_content(databox $databox, Array $row) - { - return $this; - } - - protected function flush_records_sbas() - { - return $this; - } - - protected function post_process_one_content(databox $databox, Array $row) - { - return $this; - } - - public function facility() - { - $request = http_request::getInstance(); - - $appbox = appbox::get_instance(\bootstrap::getCore()); - $session = $appbox->get_session(); - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - - $parm = $request->get_parms("bid"); - - phrasea::headers(200, true, 'text/xml', 'UTF-8', false); - - $ret = new DOMDocument("1.0", "UTF-8"); - $ret->standalone = true; - $ret->preserveWhiteSpace = false; - - $element = $ret->createElement('result'); - - $root = $ret->appendChild($element); - $root->appendChild($ret->createCDATASection(var_export($parm, true))); - $dfields = $root->appendChild($ret->createElement("date_fields")); - $statbits = $root->appendChild($ret->createElement("status_bits")); - $coll = $root->appendChild($ret->createElement("collections")); - - $sbas_id = (int)$parm['bid']; - try - { - $databox = databox::get_instance($sbas_id); - - foreach ($databox->get_meta_structure() as $meta) - { - if ($meta->get_type() !== 'date') - continue; - $dfields->appendChild($ret->createElement("field")) - ->appendChild($ret->createTextNode($meta->get_name())); - } - - $status = $databox->get_statusbits(); - - foreach ($status as $n => $s) - { - $node = $statbits->appendChild($ret->createElement("bit")); - $node->setAttribute('n', $n); - $node->setAttribute('value', '0'); - $node->setAttribute('label', $s['labeloff']); - $node->appendChild($ret->createTextNode($s['labeloff'])); - $node = $statbits->appendChild($ret->createElement("bit")); - $node->setAttribute('n', $n); - $node->setAttribute('value', '1'); - $node->setAttribute('label', $s['labelon']); - $node->appendChild($ret->createTextNode($s['labelon'])); - } - - $base_ids = $user->ACL()->get_granted_base(array(), array($sbas_id)); - - foreach ($base_ids as $base_id=>$collection) - { - $node = $coll->appendChild($ret->createElement("collection")); - $node->setAttribute('id', $collection->get_coll_id()); - $node->appendChild($ret->createTextNode($collection->get_name())); - } - } - catch (Exception $e) - { + $stmt = $connbas->prepare($sql); + $stmt->execute($params); + $this->log(sprintf(("SQL=%s - %s changes"), str_replace(array("\r\n", "\n", "\r"), " ", $sql), $stmt->rowCount())); + $stmt->closeCursor(); + return array(); } - return $ret->saveXML(); - } + protected function process_one_content(databox $databox, Array $row) + { + return $this; + } + protected function flush_records_sbas() + { + return $this; + } + + protected function post_process_one_content(databox $databox, Array $row) + { + return $this; + } + + public function facility() + { + $request = http_request::getInstance(); + + $appbox = appbox::get_instance(\bootstrap::getCore()); + $session = $appbox->get_session(); + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + + $parm = $request->get_parms("bid"); + + phrasea::headers(200, true, 'text/xml', 'UTF-8', false); + + $ret = new DOMDocument("1.0", "UTF-8"); + $ret->standalone = true; + $ret->preserveWhiteSpace = false; + + $element = $ret->createElement('result'); + + $root = $ret->appendChild($element); + $root->appendChild($ret->createCDATASection(var_export($parm, true))); + $dfields = $root->appendChild($ret->createElement("date_fields")); + $statbits = $root->appendChild($ret->createElement("status_bits")); + $coll = $root->appendChild($ret->createElement("collections")); + + $sbas_id = (int) $parm['bid']; + try { + $databox = databox::get_instance($sbas_id); + + foreach ($databox->get_meta_structure() as $meta) { + if ($meta->get_type() !== 'date') + continue; + $dfields->appendChild($ret->createElement("field")) + ->appendChild($ret->createTextNode($meta->get_name())); + } + + $status = $databox->get_statusbits(); + + foreach ($status as $n => $s) { + $node = $statbits->appendChild($ret->createElement("bit")); + $node->setAttribute('n', $n); + $node->setAttribute('value', '0'); + $node->setAttribute('label', $s['labeloff']); + $node->appendChild($ret->createTextNode($s['labeloff'])); + $node = $statbits->appendChild($ret->createElement("bit")); + $node->setAttribute('n', $n); + $node->setAttribute('value', '1'); + $node->setAttribute('label', $s['labelon']); + $node->appendChild($ret->createTextNode($s['labelon'])); + } + + $base_ids = $user->ACL()->get_granted_base(array(), array($sbas_id)); + + foreach ($base_ids as $base_id => $collection) { + $node = $coll->appendChild($ret->createElement("collection")); + $node->setAttribute('id', $collection->get_coll_id()); + $node->appendChild($ret->createTextNode($collection->get_name())); + } + } catch (Exception $e) { + + } + + return $ret->saveXML(); + } } diff --git a/lib/classes/task/period/writemeta.class.php b/lib/classes/task/period/writemeta.class.php index b9909c9515..b4765c327a 100644 --- a/lib/classes/task/period/writemeta.class.php +++ b/lib/classes/task/period/writemeta.class.php @@ -16,380 +16,355 @@ */ class task_period_writemeta extends task_databoxAbstract { + protected $clear_doc; + protected $metasubdefs = array(); - protected $clear_doc; - protected $metasubdefs = array(); - - function help() - { - return(_("task::writemeta:(re)ecriture des metadatas dans les documents (et subdefs concernees)")); - } - - protected function load_settings(SimpleXMLElement $sx_task_settings) - { - $this->clear_doc = p4field::isyes($sx_task_settings->cleardoc); - parent::load_settings($sx_task_settings); - - return $this; - } - - public function getName() - { - return(_('task::writemeta:ecriture des metadatas')); - } - - public function graphic2xml($oldxml) - { - $request = http_request::getInstance(); - - $parm2 = $request->get_parms( - "period" - , 'cleardoc' - , 'maxrecs' - , 'maxmegs' - ); - $dom = new DOMDocument(); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - if ($dom->loadXML($oldxml)) + function help() { - $xmlchanged = false; - foreach (array("str:period", 'str:maxrecs', 'str:maxmegs', 'boo:cleardoc') as $pname) - { - $ptype = substr($pname, 0, 3); - $pname = substr($pname, 4); - $pvalue = $parm2[$pname]; - if ($ns = $dom->getElementsByTagName($pname)->item(0)) - { - // le champ existait dans le xml, on supprime son ancienne valeur (tout le contenu) - while (($n = $ns->firstChild)) - $ns->removeChild($n); - } - else - { - // le champ n'existait pas dans le xml, on le cree - $dom->documentElement->appendChild($dom->createTextNode("\t")); - $ns = $dom->documentElement->appendChild($dom->createElement($pname)); - $dom->documentElement->appendChild($dom->createTextNode("\n")); - } - // on fixe sa valeur - switch ($ptype) - { - case "str": - $ns->appendChild($dom->createTextNode($pvalue)); - break; - case "boo": - $ns->appendChild($dom->createTextNode($pvalue ? '1' : '0')); - break; - } - $xmlchanged = true; - } + return(_("task::writemeta:(re)ecriture des metadatas dans les documents (et subdefs concernees)")); } - return($dom->saveXML()); - } - - public function xml2graphic($xml, $form) - { - if (($sxml = simplexml_load_string($xml))) // in fact XML IS always valid here... + protected function load_settings(SimpleXMLElement $sx_task_settings) { - // ... but we could check for safe values (ex. 0 < period < 3600) - if ((int) ($sxml->period) < 10) - $sxml->period = 10; - elseif ((int) ($sxml->period) > 300) - $sxml->period = 300; + $this->clear_doc = p4field::isyes($sx_task_settings->cleardoc); + parent::load_settings($sx_task_settings); - if ((string) ($sxml->maxrecs) == '') - $sxml->maxrecs = 100; - if ((int) ($sxml->maxrecs) < 10) - $sxml->maxrecs = 10; - elseif ((int) ($sxml->maxrecs) > 500) - $sxml->maxrecs = 500; - - if ((string) ($sxml->maxmegs) == '') - $sxml->maxmegs = 6; - if ((int) ($sxml->maxmegs) < 3) - $sxml->maxmegs = 3; - elseif ((int) ($sxml->maxmegs) > 32) - $sxml->maxmegs = 32; -?> - - - -get_session(); - $sbas_ids = User_Adapter::getInstance($session->get_usr_id(), $appbox) - ->ACL()->get_granted_sbas(array('bas_manage')); - - ob_start(); - if (count($sbas_ids) > 0) - { -?> -
                  -
                  - :  - -
                  -
                  - - -
                  -
                  -  - -   - - Mo -
                  -
                  -get_connection(); - $subdefgroups = $databox->get_subdef_structure(); - $metasubdefs = array(); - - foreach ($subdefgroups as $type => $subdefs) - { - foreach ($subdefs as $sub) - { - $name = $sub->get_name(); - if ($sub->meta_writeable()) - $metasubdefs[$name . '_' . $type] = true; - } + return($dom->saveXML()); } - $this->metasubdefs = $metasubdefs; + public function xml2graphic($xml, $form) + { + if (($sxml = simplexml_load_string($xml))) { // in fact XML IS always valid here... + // ... but we could check for safe values (ex. 0 < period < 3600) + if ((int) ($sxml->period) < 10) + $sxml->period = 10; + elseif ((int) ($sxml->period) > 300) + $sxml->period = 300; - $sql = 'SELECT record_id, coll_id, jeton + if ((string) ($sxml->maxrecs) == '') + $sxml->maxrecs = 100; + if ((int) ($sxml->maxrecs) < 10) + $sxml->maxrecs = 10; + elseif ((int) ($sxml->maxrecs) > 500) + $sxml->maxrecs = 500; + + if ((string) ($sxml->maxmegs) == '') + $sxml->maxmegs = 6; + if ((int) ($sxml->maxmegs) < 3) + $sxml->maxmegs = 3; + elseif ((int) ($sxml->maxmegs) > 32) + $sxml->maxmegs = 32; + ?> + + + + get_session(); + $sbas_ids = User_Adapter::getInstance($session->get_usr_id(), $appbox) + ->ACL()->get_granted_sbas(array('bas_manage')); + + ob_start(); + if (count($sbas_ids) > 0) { + ?> +
                  +
                  +  :  + +
                  +
                  + + +
                  +
                  +   + +   + + Mo +
                  +
                  + get_connection(); + $subdefgroups = $databox->get_subdef_structure(); + $metasubdefs = array(); + + foreach ($subdefgroups as $type => $subdefs) { + foreach ($subdefs as $sub) { + $name = $sub->get_name(); + if ($sub->meta_writeable()) + $metasubdefs[$name . '_' . $type] = true; + } + } + + $this->metasubdefs = $metasubdefs; + + $sql = 'SELECT record_id, coll_id, jeton FROM record WHERE (jeton & ' . JETON_WRITE_META . ' > 0)'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); - return $rs; - } - - protected function format_value($type, $value) - { - if ($type == 'date') - { - $value = str_replace(array("-", ":", "/", "."), array(" ", " ", " ", " "), $value); - $ip_date_yyyy = 0; - $ip_date_mm = 0; - $ip_date_dd = 0; - $ip_date_hh = 0; - $ip_date_nn = 0; - $ip_date_ss = 0; - switch (sscanf($value, "%d %d %d %d %d %d", $ip_date_yyyy, $ip_date_mm, $ip_date_dd, $ip_date_hh, $ip_date_nn, $ip_date_ss)) - { - case 1: - $value = sprintf("%04d:00:00", $ip_date_yyyy); - break; - case 2: - $value = sprintf("%04d:%02d:00", $ip_date_yyyy, $ip_date_mm); - break; - case 3: - case 4: - case 5: - case 6: - $value = sprintf("%04d:%02d:%02d", $ip_date_yyyy, $ip_date_mm, $ip_date_dd); - break; - default: - $value = '0000:00:00'; - } - } - - return $value; - } - - protected function process_one_content(databox $databox, Array $row) - { - $coll_id = $row['coll_id']; - $record_id = $row['record_id']; - $jeton = $row['jeton']; - - $record = new record_adapter($this->sbas_id, $record_id); - - $type = $record->get_type(); - $subdefs = $record->get_subdefs(); - - $tsub = array(); - - foreach ($subdefs as $name => $subdef) - { - $write_document = (($jeton & JETON_WRITE_META_DOC) && $name == 'document'); - $write_subdef = (($jeton & JETON_WRITE_META_SUBDEF) && isset($this->metasubdefs[$name . '_' . $type])); - - if ($write_document || $write_subdef) - { - $tsub[$name] = $subdef->get_pathfile(); - } - } - - $registry = $databox->get_registry(); - - $fields = $record->get_caption()->get_fields(); - - $subCMD = ''; - - if ($record->get_uuid()) - { - $subCMD .= ' -XMP-exif:ImageUniqueID='; - $subCMD .= escapeshellarg($record->get_uuid()); - $subCMD .= ' -IPTC:UniqueDocumentID='; - $subCMD .= escapeshellarg($record->get_uuid()); - } - - foreach ($fields as $field) - { - $meta = $field->get_databox_field(); - - /* @var $meta \databox_field */ - - if (trim($meta->get_metadata_source()) === '') - { - continue; - } - - $multi = $meta->is_multi(); - $type = $meta->get_type(); - $datas = $field->get_values(); - - if ($multi) - { - foreach ($datas as $value) - { - $value = $this->format_value($type, $value->getValue()); - - $subCMD .= ' -'.$meta->get_metadata_namespace().':'.$meta->get_metadata_tagname().'='; - $subCMD .= escapeshellarg($value).' '; + return $rs; } - } - else - { - $value = array_pop($datas); - $datas = $this->format_value($type, $value->getValue()); - $subCMD .= ' -'.$meta->get_metadata_namespace().':'.$meta->get_metadata_tagname().'='; - $subCMD .= escapeshellarg($datas).' '; - } - } + protected function format_value($type, $value) + { + if ($type == 'date') { + $value = str_replace(array("-", ":", "/", "."), array(" ", " ", " ", " "), $value); + $ip_date_yyyy = 0; + $ip_date_mm = 0; + $ip_date_dd = 0; + $ip_date_hh = 0; + $ip_date_nn = 0; + $ip_date_ss = 0; + switch (sscanf($value, "%d %d %d %d %d %d", $ip_date_yyyy, $ip_date_mm, $ip_date_dd, $ip_date_hh, $ip_date_nn, $ip_date_ss)) { + case 1: + $value = sprintf("%04d:00:00", $ip_date_yyyy); + break; + case 2: + $value = sprintf("%04d:%02d:00", $ip_date_yyyy, $ip_date_mm); + break; + case 3: + case 4: + case 5: + case 6: + $value = sprintf("%04d:%02d:%02d", $ip_date_yyyy, $ip_date_mm, $ip_date_dd); + break; + default: + $value = '0000:00:00'; + } + } - foreach ($tsub as $name => $file) - { - $cmd = ''; - if ($this->system == 'WINDOWS') - $cmd = 'start /B /LOW '; - $cmd .= ( $registry->get('GV_exiftool') . ' -m -overwrite_original '); - if ($name != 'document' || $this->clear_doc) - $cmd .= ' -all:all= '; + return $value; + } - $cmd .= ' -codedcharacterset=utf8 '; + protected function process_one_content(databox $databox, Array $row) + { + $coll_id = $row['coll_id']; + $record_id = $row['record_id']; + $jeton = $row['jeton']; - $cmd .= $subCMD.' '.escapeshellarg($file); + $record = new record_adapter($this->sbas_id, $record_id); - $this->log(sprintf(('writing meta for sbas_id=%1$d - record_id=%2$d (%3$s)'), $this->sbas_id, $record_id, $name)); + $type = $record->get_type(); + $subdefs = $record->get_subdefs(); - $s = trim(shell_exec($cmd)); + $tsub = array(); - $this->log("\t" . $s); - } + foreach ($subdefs as $name => $subdef) { + $write_document = (($jeton & JETON_WRITE_META_DOC) && $name == 'document'); + $write_subdef = (($jeton & JETON_WRITE_META_SUBDEF) && isset($this->metasubdefs[$name . '_' . $type])); - return $this; - } + if ($write_document || $write_subdef) { + $tsub[$name] = $subdef->get_pathfile(); + } + } - protected function flush_records_sbas() - { - return $this; - } + $registry = $databox->get_registry(); - protected function post_process_one_content(databox $databox, Array $row) - { - $connbas = $databox->get_connection(); + $fields = $record->get_caption()->get_fields(); - $sql = 'UPDATE record SET jeton=jeton & ~' . JETON_WRITE_META . ' + $subCMD = ''; + + if ($record->get_uuid()) { + $subCMD .= ' -XMP-exif:ImageUniqueID='; + $subCMD .= escapeshellarg($record->get_uuid()); + $subCMD .= ' -IPTC:UniqueDocumentID='; + $subCMD .= escapeshellarg($record->get_uuid()); + } + + foreach ($fields as $field) { + $meta = $field->get_databox_field(); + + /* @var $meta \databox_field */ + + if (trim($meta->get_metadata_source()) === '') { + continue; + } + + $multi = $meta->is_multi(); + $type = $meta->get_type(); + $datas = $field->get_values(); + + if ($multi) { + foreach ($datas as $value) { + $value = $this->format_value($type, $value->getValue()); + + $subCMD .= ' -' . $meta->get_metadata_namespace() . ':' . $meta->get_metadata_tagname() . '='; + $subCMD .= escapeshellarg($value) . ' '; + } + } else { + $value = array_pop($datas); + $datas = $this->format_value($type, $value->getValue()); + + $subCMD .= ' -' . $meta->get_metadata_namespace() . ':' . $meta->get_metadata_tagname() . '='; + $subCMD .= escapeshellarg($datas) . ' '; + } + } + + foreach ($tsub as $name => $file) { + $cmd = ''; + if ($this->system == 'WINDOWS') + $cmd = 'start /B /LOW '; + $cmd .= ( $registry->get('GV_exiftool') . ' -m -overwrite_original '); + if ($name != 'document' || $this->clear_doc) + $cmd .= ' -all:all= '; + + $cmd .= ' -codedcharacterset=utf8 '; + + $cmd .= $subCMD . ' ' . escapeshellarg($file); + + $this->log(sprintf(('writing meta for sbas_id=%1$d - record_id=%2$d (%3$s)'), $this->sbas_id, $record_id, $name)); + + $s = trim(shell_exec($cmd)); + + $this->log("\t" . $s); + } + + return $this; + } + + protected function flush_records_sbas() + { + return $this; + } + + protected function post_process_one_content(databox $databox, Array $row) + { + $connbas = $databox->get_connection(); + + $sql = 'UPDATE record SET jeton=jeton & ~' . JETON_WRITE_META . ' WHERE record_id = :record_id'; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':record_id' => $row['record_id'])); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':record_id' => $row['record_id'])); + $stmt->closeCursor(); - return $this; - } + return $this; + } + } -} diff --git a/lib/classes/thesaurus.class.php b/lib/classes/thesaurus.class.php index e4d070b5e8..5e1992017f 100644 --- a/lib/classes/thesaurus.class.php +++ b/lib/classes/thesaurus.class.php @@ -3,9 +3,8 @@ class thesaurus { - public static function xquery_escape($s) - { - return(str_replace(array("&", "\"", "'"), array("&", """, "'"), $s)); - } - + public static function xquery_escape($s) + { + return(str_replace(array("&", "\"", "'"), array("&", """, "'"), $s)); + } } diff --git a/lib/classes/thesaurus/xpath.class.php b/lib/classes/thesaurus/xpath.class.php index 4c83a88fa4..2ca37b925f 100644 --- a/lib/classes/thesaurus/xpath.class.php +++ b/lib/classes/thesaurus/xpath.class.php @@ -17,32 +17,29 @@ */ class thesaurus_xpath extends DOMXPath { + /** + * + * @var array + */ + protected static $r = array(); - /** - * - * @var array - */ - protected static $r = array(); - - /** - * - * @param string $xquery - * @param DOMNode $context_node - * @param string $context_path - * @return DOMNodeList - */ - public function cache_query($xquery, DOMNode $context_node=NULL, $context_path='') - { - $context_path .= $xquery; - - if (!array_key_exists($context_path, self::$r)) + /** + * + * @param string $xquery + * @param DOMNode $context_node + * @param string $context_path + * @return DOMNodeList + */ + public function cache_query($xquery, DOMNode $context_node = NULL, $context_path = '') { - self::$r[$context_path] = $context_node ? - parent::query($xquery, $context_node) : parent::query($xquery); + $context_path .= $xquery; + + if ( ! array_key_exists($context_path, self::$r)) { + self::$r[$context_path] = $context_node ? + parent::query($xquery, $context_node) : parent::query($xquery); + } + + return(self::$r[$context_path]); } - - return(self::$r[$context_path]); - } - } diff --git a/lib/classes/unicode.class.php b/lib/classes/unicode.class.php index 274d7f5b9d..39a799cd30 100644 --- a/lib/classes/unicode.class.php +++ b/lib/classes/unicode.class.php @@ -17,1428 +17,1416 @@ */ class unicode { + protected $map = array( + //------ U+0000..U+007F : Basic Latin + /* U+0041 */ "\x41" => "\x61", + /* U+0042 */ "\x42" => "\x62", + /* U+0043 */ "\x43" => "\x63", + /* U+0044 */ "\x44" => "\x64", + /* U+0045 */ "\x45" => "\x65", + /* U+0046 */ "\x46" => "\x66", + /* U+0047 */ "\x47" => "\x67", + /* U+0048 */ "\x48" => "\x68", + /* U+0049 */ "\x49" => "\x69", + /* U+004A */ "\x4A" => "\x6A", + /* U+004B */ "\x4B" => "\x6B", + /* U+004C */ "\x4C" => "\x6C", + /* U+004D */ "\x4D" => "\x6D", + /* U+004E */ "\x4E" => "\x6E", + /* U+004F */ "\x4F" => "\x6F", + /* U+0050 */ "\x50" => "\x70", + /* U+0051 */ "\x51" => "\x71", + /* U+0052 */ "\x52" => "\x72", + /* U+0053 */ "\x53" => "\x73", + /* U+0054 */ "\x54" => "\x74", + /* U+0055 */ "\x55" => "\x75", + /* U+0056 */ "\x56" => "\x76", + /* U+0057 */ "\x57" => "\x77", + /* U+0058 */ "\x58" => "\x78", + /* U+0059 */ "\x59" => "\x79", + /* U+005A */ "\x5A" => "\x7A", + //------ U+0080..U+00FF : Latin-1 Supplement + /* U+00C0 */ "\xC3\x80" => "\x61", + /* U+00C1 */ "\xC3\x81" => "\x61", + /* U+00C2 */ "\xC3\x82" => "\x61", + /* U+00C3 */ "\xC3\x83" => "\x61", + /* U+00C4 */ "\xC3\x84" => "\x61", + /* U+00C5 */ "\xC3\x85" => "\x61", + /* U+00C6 */ "\xC3\x86" => "\xC3\xA6", + /* U+00C7 */ "\xC3\x87" => "\x63", + /* U+00C8 */ "\xC3\x88" => "\x65", + /* U+00C9 */ "\xC3\x89" => "\x65", + /* U+00CA */ "\xC3\x8A" => "\x65", + /* U+00CB */ "\xC3\x8B" => "\x65", + /* U+00CC */ "\xC3\x8C" => "\x69", + /* U+00CD */ "\xC3\x8D" => "\x69", + /* U+00CE */ "\xC3\x8E" => "\x69", + /* U+00CF */ "\xC3\x8F" => "\x69", + /* U+00D0 */ "\xC3\x90" => "\xC3\xB0", + /* U+00D1 */ "\xC3\x91" => "\x6E", + /* U+00D2 */ "\xC3\x92" => "\x6F", + /* U+00D3 */ "\xC3\x93" => "\x6F", + /* U+00D4 */ "\xC3\x94" => "\x6F", + /* U+00D5 */ "\xC3\x95" => "\x6F", + /* U+00D6 */ "\xC3\x96" => "\x6F", + /* U+00D8 */ "\xC3\x98" => "\x6F", + /* U+00D9 */ "\xC3\x99" => "\x75", + /* U+00DA */ "\xC3\x9A" => "\x75", + /* U+00DB */ "\xC3\x9B" => "\x75", + /* U+00DC */ "\xC3\x9C" => "\x75", + /* U+00DD */ "\xC3\x9D" => "\x79", + /* U+00DE */ "\xC3\x9E" => "\xC3\xBE", + /* U+00E0 */ "\xC3\xA0" => "\x61", + /* U+00E1 */ "\xC3\xA1" => "\x61", + /* U+00E2 */ "\xC3\xA2" => "\x61", + /* U+00E3 */ "\xC3\xA3" => "\x61", + /* U+00E4 */ "\xC3\xA4" => "\x61", + /* U+00E5 */ "\xC3\xA5" => "\x61", + /* U+00E7 */ "\xC3\xA7" => "\x63", + /* U+00E8 */ "\xC3\xA8" => "\x65", + /* U+00E9 */ "\xC3\xA9" => "\x65", + /* U+00EA */ "\xC3\xAA" => "\x65", + /* U+00EB */ "\xC3\xAB" => "\x65", + /* U+00EC */ "\xC3\xAC" => "\x69", + /* U+00ED */ "\xC3\xAD" => "\x69", + /* U+00EE */ "\xC3\xAE" => "\x69", + /* U+00EF */ "\xC3\xAF" => "\x69", + /* U+00F1 */ "\xC3\xB1" => "\x6E", + /* U+00F2 */ "\xC3\xB2" => "\x6F", + /* U+00F3 */ "\xC3\xB3" => "\x6F", + /* U+00F4 */ "\xC3\xB4" => "\x6F", + /* U+00F5 */ "\xC3\xB5" => "\x6F", + /* U+00F6 */ "\xC3\xB6" => "\x6F", + /* U+00F8 */ "\xC3\xB8" => "\x6F", + /* U+00F9 */ "\xC3\xB9" => "\x75", + /* U+00FA */ "\xC3\xBA" => "\x75", + /* U+00FB */ "\xC3\xBB" => "\x75", + /* U+00FC */ "\xC3\xBC" => "\x75", + /* U+00FD */ "\xC3\xBD" => "\x79", + /* U+00FF */ "\xC3\xBF" => "\x79", + //------ U+0100..U+017F : Latin Extended-A + /* U+0100 */ "\xC4\x80" => "\x61", + /* U+0101 */ "\xC4\x81" => "\x61", + /* U+0102 */ "\xC4\x82" => "\x61", + /* U+0103 */ "\xC4\x83" => "\x61", + /* U+0104 */ "\xC4\x84" => "\x61", + /* U+0105 */ "\xC4\x85" => "\x61", + /* U+0106 */ "\xC4\x86" => "\x63", + /* U+0107 */ "\xC4\x87" => "\x63", + /* U+0108 */ "\xC4\x88" => "\x63", + /* U+0109 */ "\xC4\x89" => "\x63", + /* U+010A */ "\xC4\x8A" => "\x63", + /* U+010B */ "\xC4\x8B" => "\x63", + /* U+010C */ "\xC4\x8C" => "\x63", + /* U+010D */ "\xC4\x8D" => "\x63", + /* U+010E */ "\xC4\x8E" => "\x64", + /* U+010F */ "\xC4\x8F" => "\x64", + /* U+0110 */ "\xC4\x90" => "\x64", + /* U+0111 */ "\xC4\x91" => "\x64", + /* U+0112 */ "\xC4\x92" => "\x65", + /* U+0113 */ "\xC4\x93" => "\x65", + /* U+0114 */ "\xC4\x94" => "\x65", + /* U+0115 */ "\xC4\x95" => "\x65", + /* U+0116 */ "\xC4\x96" => "\x65", + /* U+0117 */ "\xC4\x97" => "\x65", + /* U+0118 */ "\xC4\x98" => "\x65", + /* U+0119 */ "\xC4\x99" => "\x65", + /* U+011A */ "\xC4\x9A" => "\x65", + /* U+011B */ "\xC4\x9B" => "\x65", + /* U+011C */ "\xC4\x9C" => "\x67", + /* U+011D */ "\xC4\x9D" => "\x67", + /* U+011E */ "\xC4\x9E" => "\x67", + /* U+011F */ "\xC4\x9F" => "\x67", + /* U+0120 */ "\xC4\xA0" => "\x67", + /* U+0121 */ "\xC4\xA1" => "\x67", + /* U+0122 */ "\xC4\xA2" => "\x67", + /* U+0123 */ "\xC4\xA3" => "\x67", + /* U+0124 */ "\xC4\xA4" => "\x68", + /* U+0125 */ "\xC4\xA5" => "\x68", + /* U+0126 */ "\xC4\xA6" => "\x68", + /* U+0127 */ "\xC4\xA7" => "\x68", + /* U+0128 */ "\xC4\xA8" => "\x69", + /* U+0129 */ "\xC4\xA9" => "\x69", + /* U+012A */ "\xC4\xAA" => "\x69", + /* U+012B */ "\xC4\xAB" => "\x69", + /* U+012C */ "\xC4\xAC" => "\x69", + /* U+012D */ "\xC4\xAD" => "\x69", + /* U+012E */ "\xC4\xAE" => "\x69", + /* U+012F */ "\xC4\xAF" => "\x69", + /* U+0130 */ "\xC4\xB0" => "\x69", + /* U+0132 */ "\xC4\xB2" => "\xC4\xB3", + /* U+0134 */ "\xC4\xB4" => "\x6A", + /* U+0135 */ "\xC4\xB5" => "\x6A", + /* U+0136 */ "\xC4\xB6" => "\x6B", + /* U+0137 */ "\xC4\xB7" => "\x6B", + /* U+0139 */ "\xC4\xB9" => "\x6C", + /* U+013A */ "\xC4\xBA" => "\x6C", + /* U+013B */ "\xC4\xBB" => "\x6C", + /* U+013C */ "\xC4\xBC" => "\x6C", + /* U+013D */ "\xC4\xBD" => "\x6C", + /* U+013E */ "\xC4\xBE" => "\x6C", + /* U+013F */ "\xC4\xBF" => "\x6C", + /* U+0140 */ "\xC5\x80" => "\x6C", + /* U+0141 */ "\xC5\x81" => "\x6C", + /* U+0142 */ "\xC5\x82" => "\x6C", + /* U+0143 */ "\xC5\x83" => "\x6E", + /* U+0144 */ "\xC5\x84" => "\x6E", + /* U+0145 */ "\xC5\x85" => "\x6E", + /* U+0146 */ "\xC5\x86" => "\x6E", + /* U+0147 */ "\xC5\x87" => "\x6E", + /* U+0148 */ "\xC5\x88" => "\x6E", + /* U+014A */ "\xC5\x8A" => "\xC5\x8B", + /* U+014C */ "\xC5\x8C" => "\x6F", + /* U+014D */ "\xC5\x8D" => "\x6F", + /* U+014E */ "\xC5\x8E" => "\x6F", + /* U+014F */ "\xC5\x8F" => "\x6F", + /* U+0150 */ "\xC5\x90" => "\x6F", + /* U+0151 */ "\xC5\x91" => "\x6F", + /* U+0152 */ "\xC5\x92" => "\xC5\x93", + /* U+0154 */ "\xC5\x94" => "\x72", + /* U+0155 */ "\xC5\x95" => "\x72", + /* U+0156 */ "\xC5\x96" => "\x72", + /* U+0157 */ "\xC5\x97" => "\x72", + /* U+0158 */ "\xC5\x98" => "\x72", + /* U+0159 */ "\xC5\x99" => "\x72", + /* U+015A */ "\xC5\x9A" => "\x73", + /* U+015B */ "\xC5\x9B" => "\x73", + /* U+015C */ "\xC5\x9C" => "\x73", + /* U+015D */ "\xC5\x9D" => "\x73", + /* U+015E */ "\xC5\x9E" => "\x73", + /* U+015F */ "\xC5\x9F" => "\x73", + /* U+0160 */ "\xC5\xA0" => "\x73", + /* U+0161 */ "\xC5\xA1" => "\x73", + /* U+0162 */ "\xC5\xA2" => "\x74", + /* U+0163 */ "\xC5\xA3" => "\x74", + /* U+0164 */ "\xC5\xA4" => "\x74", + /* U+0165 */ "\xC5\xA5" => "\x74", + /* U+0166 */ "\xC5\xA6" => "\x74", + /* U+0167 */ "\xC5\xA7" => "\x74", + /* U+0168 */ "\xC5\xA8" => "\x75", + /* U+0169 */ "\xC5\xA9" => "\x75", + /* U+016A */ "\xC5\xAA" => "\x75", + /* U+016B */ "\xC5\xAB" => "\x75", + /* U+016C */ "\xC5\xAC" => "\x75", + /* U+016D */ "\xC5\xAD" => "\x75", + /* U+016E */ "\xC5\xAE" => "\x75", + /* U+016F */ "\xC5\xAF" => "\x75", + /* U+0170 */ "\xC5\xB0" => "\x75", + /* U+0171 */ "\xC5\xB1" => "\x75", + /* U+0172 */ "\xC5\xB2" => "\x75", + /* U+0173 */ "\xC5\xB3" => "\x75", + /* U+0174 */ "\xC5\xB4" => "\x77", + /* U+0175 */ "\xC5\xB5" => "\x77", + /* U+0176 */ "\xC5\xB6" => "\x79", + /* U+0177 */ "\xC5\xB7" => "\x79", + /* U+0178 */ "\xC5\xB8" => "\x79", + /* U+0179 */ "\xC5\xB9" => "\x7A", + /* U+017A */ "\xC5\xBA" => "\x7A", + /* U+017B */ "\xC5\xBB" => "\x7A", + /* U+017C */ "\xC5\xBC" => "\x7A", + /* U+017D */ "\xC5\xBD" => "\x7A", + /* U+017E */ "\xC5\xBE" => "\x7A", + //------ U+0180..U+024F : Latin Extended-B + /* U+0180 */ "\xC6\x80" => "\x62", + /* U+0181 */ "\xC6\x81" => "\x62", + /* U+0182 */ "\xC6\x82" => "\x62", + /* U+0183 */ "\xC6\x83" => "\x62", + /* U+0184 */ "\xC6\x84" => "\xC6\x85", + /* U+0186 */ "\xC6\x86" => "\xC9\x94", + /* U+0187 */ "\xC6\x87" => "\x63", + /* U+0188 */ "\xC6\x88" => "\x63", + /* U+0189 */ "\xC6\x89" => "\x64", + /* U+018A */ "\xC6\x8A" => "\x64", + /* U+018B */ "\xC6\x8B" => "\x64", + /* U+018C */ "\xC6\x8C" => "\x64", + /* U+018E */ "\xC6\x8E" => "\xC7\x9D", + /* U+018F */ "\xC6\x8F" => "\xC9\x99", + /* U+0190 */ "\xC6\x90" => "\xC9\x9B", + /* U+0191 */ "\xC6\x91" => "\x66", + /* U+0192 */ "\xC6\x92" => "\x66", + /* U+0193 */ "\xC6\x93" => "\x67", + /* U+0194 */ "\xC6\x94" => "\xC9\xA3", + /* U+0196 */ "\xC6\x96" => "\xC9\xA9", + /* U+0197 */ "\xC6\x97" => "\x69", + /* U+0198 */ "\xC6\x98" => "\x6B", + /* U+0199 */ "\xC6\x99" => "\x6B", + /* U+019A */ "\xC6\x9A" => "\x6C", + /* U+019C */ "\xC6\x9C" => "\xC9\xAF", + /* U+019D */ "\xC6\x9D" => "\x6E", + /* U+019E */ "\xC6\x9E" => "\x6E", + /* U+019F */ "\xC6\x9F" => "\xC9\xB5", + /* U+01A0 */ "\xC6\xA0" => "\x6F", + /* U+01A1 */ "\xC6\xA1" => "\x6F", + /* U+01A2 */ "\xC6\xA2" => "\xC6\xA3", + /* U+01A4 */ "\xC6\xA4" => "\x70", + /* U+01A5 */ "\xC6\xA5" => "\x70", + /* U+01A6 */ "\xC6\xA6" => "\xCA\x80", + /* U+01A7 */ "\xC6\xA7" => "\xC6\xA8", + /* U+01A9 */ "\xC6\xA9" => "\xCA\x83", + /* U+01AB */ "\xC6\xAB" => "\x74", + /* U+01AC */ "\xC6\xAC" => "\x74", + /* U+01AD */ "\xC6\xAD" => "\x74", + /* U+01AE */ "\xC6\xAE" => "\x74", + /* U+01AF */ "\xC6\xAF" => "\x75", + /* U+01B0 */ "\xC6\xB0" => "\x75", + /* U+01B1 */ "\xC6\xB1" => "\xCA\x8A", + /* U+01B2 */ "\xC6\xB2" => "\x76", + /* U+01B3 */ "\xC6\xB3" => "\x79", + /* U+01B4 */ "\xC6\xB4" => "\x79", + /* U+01B5 */ "\xC6\xB5" => "\x7A", + /* U+01B6 */ "\xC6\xB6" => "\x7A", + /* U+01B7 */ "\xC6\xB7" => "\xCA\x92", + /* U+01B8 */ "\xC6\xB8" => "\xC6\xB9", + /* U+01BA */ "\xC6\xBA" => "\xCA\x92", + /* U+01BC */ "\xC6\xBC" => "\xC6\xBD", + /* U+01C4 */ "\xC7\x84" => "\xC7\x86", + /* U+01C5 */ "\xC7\x85" => "\xC7\x86", + /* U+01C7 */ "\xC7\x87" => "\xC7\x89", + /* U+01C8 */ "\xC7\x88" => "\xC7\x89", + /* U+01CA */ "\xC7\x8A" => "\xC7\x8C", + /* U+01CB */ "\xC7\x8B" => "\xC7\x8C", + /* U+01CD */ "\xC7\x8D" => "\x61", + /* U+01CE */ "\xC7\x8E" => "\x61", + /* U+01CF */ "\xC7\x8F" => "\x69", + /* U+01D0 */ "\xC7\x90" => "\x69", + /* U+01D1 */ "\xC7\x91" => "\x6F", + /* U+01D2 */ "\xC7\x92" => "\x6F", + /* U+01D3 */ "\xC7\x93" => "\x75", + /* U+01D4 */ "\xC7\x94" => "\x75", + /* U+01D5 */ "\xC7\x95" => "\x75", + /* U+01D6 */ "\xC7\x96" => "\x75", + /* U+01D7 */ "\xC7\x97" => "\x75", + /* U+01D8 */ "\xC7\x98" => "\x75", + /* U+01D9 */ "\xC7\x99" => "\x75", + /* U+01DA */ "\xC7\x9A" => "\x75", + /* U+01DB */ "\xC7\x9B" => "\x75", + /* U+01DC */ "\xC7\x9C" => "\x75", + /* U+01DE */ "\xC7\x9E" => "\x61", + /* U+01DF */ "\xC7\x9F" => "\x61", + /* U+01E0 */ "\xC7\xA0" => "\x61", + /* U+01E1 */ "\xC7\xA1" => "\x61", + /* U+01E2 */ "\xC7\xA2" => "\xC3\xA6", + /* U+01E3 */ "\xC7\xA3" => "\xC3\xA6", + /* U+01E4 */ "\xC7\xA4" => "\x67", + /* U+01E5 */ "\xC7\xA5" => "\x67", + /* U+01E6 */ "\xC7\xA6" => "\x67", + /* U+01E7 */ "\xC7\xA7" => "\x67", + /* U+01E8 */ "\xC7\xA8" => "\x6B", + /* U+01E9 */ "\xC7\xA9" => "\x6B", + /* U+01EA */ "\xC7\xAA" => "\x6F", + /* U+01EB */ "\xC7\xAB" => "\x6F", + /* U+01EC */ "\xC7\xAC" => "\x6F", + /* U+01ED */ "\xC7\xAD" => "\x6F", + /* U+01EE */ "\xC7\xAE" => "\xCA\x92", + /* U+01EF */ "\xC7\xAF" => "\xCA\x92", + /* U+01F0 */ "\xC7\xB0" => "\x6A", + /* U+01F1 */ "\xC7\xB1" => "\xC7\xB3", + /* U+01F2 */ "\xC7\xB2" => "\xC7\xB3", + /* U+01F4 */ "\xC7\xB4" => "\x67", + /* U+01F5 */ "\xC7\xB5" => "\x67", + /* U+01F6 */ "\xC7\xB6" => "\xC6\x95", + /* U+01F7 */ "\xC7\xB7" => "\xC6\xBF", + /* U+01F8 */ "\xC7\xB8" => "\x6E", + /* U+01F9 */ "\xC7\xB9" => "\x6E", + /* U+01FA */ "\xC7\xBA" => "\x61", + /* U+01FB */ "\xC7\xBB" => "\x61", + /* U+01FC */ "\xC7\xBC" => "\xC3\xA6", + /* U+01FD */ "\xC7\xBD" => "\xC3\xA6", + /* U+01FE */ "\xC7\xBE" => "\x6F", + /* U+01FF */ "\xC7\xBF" => "\x6F", + /* U+0200 */ "\xC8\x80" => "\x61", + /* U+0201 */ "\xC8\x81" => "\x61", + /* U+0202 */ "\xC8\x82" => "\x61", + /* U+0203 */ "\xC8\x83" => "\x61", + /* U+0204 */ "\xC8\x84" => "\x65", + /* U+0205 */ "\xC8\x85" => "\x65", + /* U+0206 */ "\xC8\x86" => "\x65", + /* U+0207 */ "\xC8\x87" => "\x65", + /* U+0208 */ "\xC8\x88" => "\x69", + /* U+0209 */ "\xC8\x89" => "\x69", + /* U+020A */ "\xC8\x8A" => "\x69", + /* U+020B */ "\xC8\x8B" => "\x69", + /* U+020C */ "\xC8\x8C" => "\x6F", + /* U+020D */ "\xC8\x8D" => "\x6F", + /* U+020E */ "\xC8\x8E" => "\x6F", + /* U+020F */ "\xC8\x8F" => "\x6F", + /* U+0210 */ "\xC8\x90" => "\x72", + /* U+0211 */ "\xC8\x91" => "\x72", + /* U+0212 */ "\xC8\x92" => "\x72", + /* U+0213 */ "\xC8\x93" => "\x72", + /* U+0214 */ "\xC8\x94" => "\x75", + /* U+0215 */ "\xC8\x95" => "\x75", + /* U+0216 */ "\xC8\x96" => "\x75", + /* U+0217 */ "\xC8\x97" => "\x75", + /* U+0218 */ "\xC8\x98" => "\x73", + /* U+0219 */ "\xC8\x99" => "\x73", + /* U+021A */ "\xC8\x9A" => "\x74", + /* U+021B */ "\xC8\x9B" => "\x74", + /* U+021C */ "\xC8\x9C" => "\xC8\x9D", + /* U+021E */ "\xC8\x9E" => "\x68", + /* U+021F */ "\xC8\x9F" => "\x68", + /* U+0220 */ "\xC8\xA0" => "\x6E", + /* U+0221 */ "\xC8\xA1" => "\x64", + /* U+0222 */ "\xC8\xA2" => "\xC8\xA3", + /* U+0224 */ "\xC8\xA4" => "\x7A", + /* U+0225 */ "\xC8\xA5" => "\x7A", + /* U+0226 */ "\xC8\xA6" => "\x61", + /* U+0227 */ "\xC8\xA7" => "\x61", + /* U+0228 */ "\xC8\xA8" => "\x65", + /* U+0229 */ "\xC8\xA9" => "\x65", + /* U+022A */ "\xC8\xAA" => "\x6F", + /* U+022B */ "\xC8\xAB" => "\x6F", + /* U+022C */ "\xC8\xAC" => "\x6F", + /* U+022D */ "\xC8\xAD" => "\x6F", + /* U+022E */ "\xC8\xAE" => "\x6F", + /* U+022F */ "\xC8\xAF" => "\x6F", + /* U+0230 */ "\xC8\xB0" => "\x6F", + /* U+0231 */ "\xC8\xB1" => "\x6F", + /* U+0232 */ "\xC8\xB2" => "\x79", + /* U+0233 */ "\xC8\xB3" => "\x79", + /* U+0234 */ "\xC8\xB4" => "\x6C", + /* U+0235 */ "\xC8\xB5" => "\x6E", + /* U+0236 */ "\xC8\xB6" => "\x74", + /* U+023B */ "\xC8\xBB" => "\xC8\xBC", + /* U+023D */ "\xC8\xBD" => "\x6C", + /* U+0241 */ "\xC9\x81" => "\xCA\x94", + //------ U+0370..U+03FF : Greek and Coptic + /* U+0386 */ "\xCE\x86" => "\xCE\xB1", + /* U+0388 */ "\xCE\x88" => "\xCE\xB5", + /* U+0389 */ "\xCE\x89" => "\xCE\xB7", + /* U+038A */ "\xCE\x8A" => "\xCE\xB9", + /* U+038C */ "\xCE\x8C" => "\xCE\xBF", + /* U+038E */ "\xCE\x8E" => "\xCF\x85", + /* U+038F */ "\xCE\x8F" => "\xCF\x89", + /* U+0390 */ "\xCE\x90" => "\xCE\xB9", + /* U+0391 */ "\xCE\x91" => "\xCE\xB1", + /* U+0392 */ "\xCE\x92" => "\xCE\xB2", + /* U+0393 */ "\xCE\x93" => "\xCE\xB3", + /* U+0394 */ "\xCE\x94" => "\xCE\xB4", + /* U+0395 */ "\xCE\x95" => "\xCE\xB5", + /* U+0396 */ "\xCE\x96" => "\xCE\xB6", + /* U+0397 */ "\xCE\x97" => "\xCE\xB7", + /* U+0398 */ "\xCE\x98" => "\xCE\xB8", + /* U+0399 */ "\xCE\x99" => "\xCE\xB9", + /* U+039A */ "\xCE\x9A" => "\xCE\xBA", + /* U+039B */ "\xCE\x9B" => "\xCE\xBB", + /* U+039C */ "\xCE\x9C" => "\xCE\xBC", + /* U+039D */ "\xCE\x9D" => "\xCE\xBD", + /* U+039E */ "\xCE\x9E" => "\xCE\xBE", + /* U+039F */ "\xCE\x9F" => "\xCE\xBF", + /* U+03A0 */ "\xCE\xA0" => "\xCF\x80", + /* U+03A1 */ "\xCE\xA1" => "\xCF\x81", + /* U+03A3 */ "\xCE\xA3" => "\xCF\x83", + /* U+03A4 */ "\xCE\xA4" => "\xCF\x84", + /* U+03A5 */ "\xCE\xA5" => "\xCF\x85", + /* U+03A6 */ "\xCE\xA6" => "\xCF\x86", + /* U+03A7 */ "\xCE\xA7" => "\xCF\x87", + /* U+03A8 */ "\xCE\xA8" => "\xCF\x88", + /* U+03A9 */ "\xCE\xA9" => "\xCF\x89", + /* U+03AA */ "\xCE\xAA" => "\xCE\xB9", + /* U+03AB */ "\xCE\xAB" => "\xCF\x85", + /* U+03AC */ "\xCE\xAC" => "\xCE\xB1", + /* U+03AD */ "\xCE\xAD" => "\xCE\xB5", + /* U+03AE */ "\xCE\xAE" => "\xCE\xB7", + /* U+03AF */ "\xCE\xAF" => "\xCE\xB9", + /* U+03B0 */ "\xCE\xB0" => "\xCF\x85", + /* U+03CA */ "\xCF\x8A" => "\xCE\xB9", + /* U+03CB */ "\xCF\x8B" => "\xCF\x85", + /* U+03CC */ "\xCF\x8C" => "\xCE\xBF", + /* U+03CD */ "\xCF\x8D" => "\xCF\x85", + /* U+03CE */ "\xCF\x8E" => "\xCF\x89", + /* U+03D8 */ "\xCF\x98" => "\xCF\x99", + /* U+03DA */ "\xCF\x9A" => "\xCF\x9B", + /* U+03DC */ "\xCF\x9C" => "\xCF\x9D", + /* U+03DE */ "\xCF\x9E" => "\xCF\x9F", + /* U+03E0 */ "\xCF\xA0" => "\xCF\xA1", + /* U+03E2 */ "\xCF\xA2" => "\xCF\xA3", + /* U+03E4 */ "\xCF\xA4" => "\xCF\xA5", + /* U+03E6 */ "\xCF\xA6" => "\xCF\xA7", + /* U+03E8 */ "\xCF\xA8" => "\xCF\xA9", + /* U+03EA */ "\xCF\xAA" => "\xCF\xAB", + /* U+03EC */ "\xCF\xAC" => "\xCF\xAD", + /* U+03EE */ "\xCF\xAE" => "\xCF\xAF", + /* U+03F4 */ "\xCF\xB4" => "\xCE\xB8", + /* U+03F7 */ "\xCF\xB7" => "\xCF\xB8", + /* U+03F9 */ "\xCF\xB9" => "\xCF\xB2", + /* U+03FA */ "\xCF\xBA" => "\xCF\xBB", + //------ U+0400..U+04FF : Cyrillic + /* U+0400 */ "\xD0\x80" => "\xD0\xB5", + /* U+0401 */ "\xD0\x81" => "\xD1\x91", + /* U+0402 */ "\xD0\x82" => "\xD1\x92", + /* U+0403 */ "\xD0\x83" => "\xD1\x93", + /* U+0404 */ "\xD0\x84" => "\xD1\x94", + /* U+0405 */ "\xD0\x85" => "\xD1\x95", + /* U+0406 */ "\xD0\x86" => "\xD1\x96", + /* U+0407 */ "\xD0\x87" => "\xD1\x97", + /* U+0408 */ "\xD0\x88" => "\xD1\x98", + /* U+0409 */ "\xD0\x89" => "\xD1\x99", + /* U+040A */ "\xD0\x8A" => "\xD1\x9A", + /* U+040B */ "\xD0\x8B" => "\xD1\x9B", + /* U+040C */ "\xD0\x8C" => "\xD1\x9C", + /* U+040D */ "\xD0\x8D" => "\xD0\xB8", + /* U+040E */ "\xD0\x8E" => "\xD1\x9E", + /* U+040F */ "\xD0\x8F" => "\xD1\x9F", + /* U+0410 */ "\xD0\x90" => "\xD0\xB0", + /* U+0411 */ "\xD0\x91" => "\xD0\xB1", + /* U+0412 */ "\xD0\x92" => "\xD0\xB2", + /* U+0413 */ "\xD0\x93" => "\xD0\xB3", + /* U+0414 */ "\xD0\x94" => "\xD0\xB4", + /* U+0415 */ "\xD0\x95" => "\xD0\xB5", + /* U+0416 */ "\xD0\x96" => "\xD0\xB6", + /* U+0417 */ "\xD0\x97" => "\xD0\xB7", + /* U+0418 */ "\xD0\x98" => "\xD0\xB8", + /* U+0419 */ "\xD0\x99" => "\xD0\xB9", + /* U+041A */ "\xD0\x9A" => "\xD0\xBA", + /* U+041B */ "\xD0\x9B" => "\xD0\xBB", + /* U+041C */ "\xD0\x9C" => "\xD0\xBC", + /* U+041D */ "\xD0\x9D" => "\xD0\xBD", + /* U+041E */ "\xD0\x9E" => "\xD0\xBE", + /* U+041F */ "\xD0\x9F" => "\xD0\xBF", + /* U+0420 */ "\xD0\xA0" => "\xD1\x80", + /* U+0421 */ "\xD0\xA1" => "\xD1\x81", + /* U+0422 */ "\xD0\xA2" => "\xD1\x82", + /* U+0423 */ "\xD0\xA3" => "\xD1\x83", + /* U+0424 */ "\xD0\xA4" => "\xD1\x84", + /* U+0425 */ "\xD0\xA5" => "\xD1\x85", + /* U+0426 */ "\xD0\xA6" => "\xD1\x86", + /* U+0427 */ "\xD0\xA7" => "\xD1\x87", + /* U+0428 */ "\xD0\xA8" => "\xD1\x88", + /* U+0429 */ "\xD0\xA9" => "\xD1\x89", + /* U+042A */ "\xD0\xAA" => "\xD1\x8A", + /* U+042B */ "\xD0\xAB" => "\xD1\x8B", + /* U+042C */ "\xD0\xAC" => "\xD1\x8C", + /* U+042D */ "\xD0\xAD" => "\xD1\x8D", + /* U+042E */ "\xD0\xAE" => "\xD1\x8E", + /* U+042F */ "\xD0\xAF" => "\xD1\x8F", + /* U+0450 */ "\xD1\x90" => "\xD0\xB5", + /* U+045D */ "\xD1\x9D" => "\xD0\xB8", + /* U+0460 */ "\xD1\xA0" => "\xD1\xA1", + /* U+0462 */ "\xD1\xA2" => "\xD1\xA3", + /* U+0464 */ "\xD1\xA4" => "\xD1\xA5", + /* U+0466 */ "\xD1\xA6" => "\xD1\xA7", + /* U+0468 */ "\xD1\xA8" => "\xD1\xA9", + /* U+046A */ "\xD1\xAA" => "\xD1\xAB", + /* U+046C */ "\xD1\xAC" => "\xD1\xAD", + /* U+046E */ "\xD1\xAE" => "\xD1\xAF", + /* U+0470 */ "\xD1\xB0" => "\xD1\xB1", + /* U+0472 */ "\xD1\xB2" => "\xD1\xB3", + /* U+0474 */ "\xD1\xB4" => "\xD1\xB5", + /* U+0476 */ "\xD1\xB6" => "\xD1\xB5", + /* U+0477 */ "\xD1\xB7" => "\xD1\xB5", + /* U+0478 */ "\xD1\xB8" => "\xD1\xB9", + /* U+047A */ "\xD1\xBA" => "\xD1\xBB", + /* U+047C */ "\xD1\xBC" => "\xD1\xA1", + /* U+047D */ "\xD1\xBD" => "\xD1\xA1", + /* U+047E */ "\xD1\xBE" => "\xD1\xBF", + /* U+0480 */ "\xD2\x80" => "\xD2\x81", + /* U+048A */ "\xD2\x8A" => "\xD0\xB9", + /* U+048B */ "\xD2\x8B" => "\xD0\xB9", + /* U+048C */ "\xD2\x8C" => "\xD2\x8D", + /* U+048E */ "\xD2\x8E" => "\xD1\x80", + /* U+048F */ "\xD2\x8F" => "\xD1\x80", + /* U+0490 */ "\xD2\x90" => "\xD0\xB3", + /* U+0491 */ "\xD2\x91" => "\xD0\xB3", + /* U+0492 */ "\xD2\x92" => "\xD0\xB3", + /* U+0493 */ "\xD2\x93" => "\xD0\xB3", + /* U+0494 */ "\xD2\x94" => "\xD0\xB3", + /* U+0495 */ "\xD2\x95" => "\xD0\xB3", + /* U+0496 */ "\xD2\x96" => "\xD0\xB6", + /* U+0497 */ "\xD2\x97" => "\xD0\xB6", + /* U+0498 */ "\xD2\x98" => "\xD0\xB7", + /* U+0499 */ "\xD2\x99" => "\xD0\xB7", + /* U+049A */ "\xD2\x9A" => "\xD0\xBA", + /* U+049B */ "\xD2\x9B" => "\xD0\xBA", + /* U+049C */ "\xD2\x9C" => "\xD0\xBA", + /* U+049D */ "\xD2\x9D" => "\xD0\xBA", + /* U+049E */ "\xD2\x9E" => "\xD0\xBA", + /* U+049F */ "\xD2\x9F" => "\xD0\xBA", + /* U+04A0 */ "\xD2\xA0" => "\xD2\xA1", + /* U+04A2 */ "\xD2\xA2" => "\xD0\xBD", + /* U+04A3 */ "\xD2\xA3" => "\xD0\xBD", + /* U+04A4 */ "\xD2\xA4" => "\xD2\xA5", + /* U+04A6 */ "\xD2\xA6" => "\xD0\xBF", + /* U+04A7 */ "\xD2\xA7" => "\xD0\xBF", + /* U+04A8 */ "\xD2\xA8" => "\xD2\xA9", + /* U+04AA */ "\xD2\xAA" => "\xD1\x81", + /* U+04AB */ "\xD2\xAB" => "\xD1\x81", + /* U+04AC */ "\xD2\xAC" => "\xD1\x82", + /* U+04AD */ "\xD2\xAD" => "\xD1\x82", + /* U+04AE */ "\xD2\xAE" => "\xD2\xAF", + /* U+04B0 */ "\xD2\xB0" => "\xD2\xAF", + /* U+04B1 */ "\xD2\xB1" => "\xD2\xAF", + /* U+04B2 */ "\xD2\xB2" => "\xD0\xA5", + /* U+04B3 */ "\xD2\xB3" => "\xD0\xA5", + /* U+04B4 */ "\xD2\xB4" => "\xD2\xB5", + /* U+04B6 */ "\xD2\xB6" => "\xD2\xBC", + /* U+04B7 */ "\xD2\xB7" => "\xD2\xBC", + /* U+04B8 */ "\xD2\xB8" => "\xD1\x87", + /* U+04B9 */ "\xD2\xB9" => "\xD1\x87", + /* U+04BA */ "\xD2\xBA" => "\xD2\xBB", + /* U+04BC */ "\xD2\xBC" => "\xD2\xBD", + /* U+04BE */ "\xD2\xBE" => "\xD2\xBC", + /* U+04BF */ "\xD2\xBF" => "\xD2\xBC", + /* U+04C1 */ "\xD3\x81" => "\xD0\xB6", + /* U+04C2 */ "\xD3\x82" => "\xD0\xB6", + /* U+04C3 */ "\xD3\x83" => "\xD0\xBA", + /* U+04C4 */ "\xD3\x84" => "\xD0\xBA", + /* U+04C5 */ "\xD3\x85" => "\xD0\xBB", + /* U+04C6 */ "\xD3\x86" => "\xD0\xBB", + /* U+04C7 */ "\xD3\x87" => "\xD0\xBD", + /* U+04C8 */ "\xD3\x88" => "\xD0\xBD", + /* U+04C9 */ "\xD3\x89" => "\xD0\xBD", + /* U+04CA */ "\xD3\x8A" => "\xD0\xBD", + /* U+04CB */ "\xD3\x8B" => "\xD2\xBC", + /* U+04CC */ "\xD3\x8C" => "\xD2\xBC", + /* U+04CD */ "\xD3\x8D" => "\xD0\xBC", + /* U+04CE */ "\xD3\x8E" => "\xD0\xBC", + /* U+04D0 */ "\xD3\x90" => "\xD0\xB0", + /* U+04D1 */ "\xD3\x91" => "\xD0\xB0", + /* U+04D2 */ "\xD3\x92" => "\xD0\xB0", + /* U+04D3 */ "\xD3\x93" => "\xD0\xB0", + /* U+04D4 */ "\xD3\x94" => "\xD3\x95", + /* U+04D6 */ "\xD3\x96" => "\xD0\xB5", + /* U+04D7 */ "\xD3\x97" => "\xD0\xB5", + /* U+04D8 */ "\xD3\x98" => "\xD3\x99", + /* U+04DA */ "\xD3\x9A" => "\xD3\x99", + /* U+04DB */ "\xD3\x9B" => "\xD3\x99", + /* U+04DC */ "\xD3\x9C" => "\xD0\xB6", + /* U+04DD */ "\xD3\x9D" => "\xD0\xB6", + /* U+04DE */ "\xD3\x9E" => "\xD0\xB7", + /* U+04DF */ "\xD3\x9F" => "\xD0\xB7", + /* U+04E0 */ "\xD3\xA0" => "\xD3\xA1", + /* U+04E2 */ "\xD3\xA2" => "\xD0\xB8", + /* U+04E3 */ "\xD3\xA3" => "\xD0\xB8", + /* U+04E4 */ "\xD3\xA4" => "\xD0\xB8", + /* U+04E5 */ "\xD3\xA5" => "\xD0\xB8", + /* U+04E6 */ "\xD3\xA6" => "\xD0\xBE", + /* U+04E7 */ "\xD3\xA7" => "\xD0\xBE", + /* U+04E8 */ "\xD3\xA8" => "\xD3\xA9", + /* U+04EA */ "\xD3\xAA" => "\xD3\xA9", + /* U+04EB */ "\xD3\xAB" => "\xD3\xA9", + /* U+04EC */ "\xD3\xAC" => "\xD1\x8D", + /* U+04ED */ "\xD3\xAD" => "\xD1\x8D", + /* U+04EE */ "\xD3\xAE" => "\xD1\x83", + /* U+04EF */ "\xD3\xAF" => "\xD1\x83", + /* U+04F0 */ "\xD3\xB0" => "\xD1\x83", + /* U+04F1 */ "\xD3\xB1" => "\xD1\x83", + /* U+04F2 */ "\xD3\xB2" => "\xD1\x83", + /* U+04F3 */ "\xD3\xB3" => "\xD1\x83", + /* U+04F4 */ "\xD3\xB4" => "\xD1\x87", + /* U+04F5 */ "\xD3\xB5" => "\xD1\x87", + /* U+04F6 */ "\xD3\xB6" => "\xD3\xB7", + /* U+04F8 */ "\xD3\xB8" => "\xD1\x8B", + /* U+04F9 */ "\xD3\xB9" => "\xD1\x8B", + //------ U+0500..U+052F : Cyrillic Supplement + /* U+0500 */ "\xD4\x80" => "\xD4\x81", + /* U+0502 */ "\xD4\x82" => "\xD4\x83", + /* U+0504 */ "\xD4\x84" => "\xD4\x85", + /* U+0506 */ "\xD4\x86" => "\xD4\x87", + /* U+0508 */ "\xD4\x88" => "\xD4\x89", + /* U+050A */ "\xD4\x8A" => "\xD4\x8B", + /* U+050C */ "\xD4\x8C" => "\xD4\x8D", + /* U+050E */ "\xD4\x8E" => "\xD4\x8F", + //------ U+0530..U+058F : Armenian + /* U+0531 */ "\xD4\xB1" => "\xD5\xA1", + /* U+0532 */ "\xD4\xB2" => "\xD5\xA2", + /* U+0533 */ "\xD4\xB3" => "\xD5\xA3", + /* U+0534 */ "\xD4\xB4" => "\xD5\xA4", + /* U+0535 */ "\xD4\xB5" => "\xD5\xA5", + /* U+0536 */ "\xD4\xB6" => "\xD5\xA6", + /* U+0537 */ "\xD4\xB7" => "\xD5\xA7", + /* U+0538 */ "\xD4\xB8" => "\xD5\xA8", + /* U+0539 */ "\xD4\xB9" => "\xD5\xA9", + /* U+053A */ "\xD4\xBA" => "\xD5\xAA", + /* U+053B */ "\xD4\xBB" => "\xD5\xAB", + /* U+053C */ "\xD4\xBC" => "\xD5\xAC", + /* U+053D */ "\xD4\xBD" => "\xD5\xAD", + /* U+053E */ "\xD4\xBE" => "\xD5\xAE", + /* U+053F */ "\xD4\xBF" => "\xD5\xAF", + /* U+0540 */ "\xD5\x80" => "\xD5\xB0", + /* U+0541 */ "\xD5\x81" => "\xD5\xB1", + /* U+0542 */ "\xD5\x82" => "\xD5\xB2", + /* U+0543 */ "\xD5\x83" => "\xD5\xB3", + /* U+0544 */ "\xD5\x84" => "\xD5\xB4", + /* U+0545 */ "\xD5\x85" => "\xD5\xB5", + /* U+0546 */ "\xD5\x86" => "\xD5\xB6", + /* U+0547 */ "\xD5\x87" => "\xD5\xB7", + /* U+0548 */ "\xD5\x88" => "\xD5\xB8", + /* U+0549 */ "\xD5\x89" => "\xD5\xB9", + /* U+054A */ "\xD5\x8A" => "\xD5\xBA", + /* U+054B */ "\xD5\x8B" => "\xD5\xBB", + /* U+054C */ "\xD5\x8C" => "\xD5\xBC", + /* U+054D */ "\xD5\x8D" => "\xD5\xBD", + /* U+054E */ "\xD5\x8E" => "\xD5\xBE", + /* U+054F */ "\xD5\x8F" => "\xD5\xBF", + /* U+0550 */ "\xD5\x90" => "\xD6\x80", + /* U+0551 */ "\xD5\x91" => "\xD6\x81", + /* U+0552 */ "\xD5\x92" => "\xD6\x82", + /* U+0553 */ "\xD5\x93" => "\xD6\x83", + /* U+0554 */ "\xD5\x94" => "\xD6\x84", + /* U+0555 */ "\xD5\x95" => "\xD6\x85", + /* U+0556 */ "\xD5\x96" => "\xD6\x86", + //------ U+1E00..U+1EFF : Latin Extended Additional + /* U+1E00 */ "\xE1\xB8\x80" => "\x61", + /* U+1E01 */ "\xE1\xB8\x81" => "\x61", + /* U+1E02 */ "\xE1\xB8\x82" => "\x62", + /* U+1E03 */ "\xE1\xB8\x83" => "\x62", + /* U+1E04 */ "\xE1\xB8\x84" => "\x62", + /* U+1E05 */ "\xE1\xB8\x85" => "\x62", + /* U+1E06 */ "\xE1\xB8\x86" => "\x62", + /* U+1E07 */ "\xE1\xB8\x87" => "\x62", + /* U+1E08 */ "\xE1\xB8\x88" => "\x63", + /* U+1E09 */ "\xE1\xB8\x89" => "\x63", + /* U+1E0A */ "\xE1\xB8\x8A" => "\x64", + /* U+1E0B */ "\xE1\xB8\x8B" => "\x64", + /* U+1E0C */ "\xE1\xB8\x8C" => "\x64", + /* U+1E0D */ "\xE1\xB8\x8D" => "\x64", + /* U+1E0E */ "\xE1\xB8\x8E" => "\x64", + /* U+1E0F */ "\xE1\xB8\x8F" => "\x64", + /* U+1E10 */ "\xE1\xB8\x90" => "\x64", + /* U+1E11 */ "\xE1\xB8\x91" => "\x64", + /* U+1E12 */ "\xE1\xB8\x92" => "\x64", + /* U+1E13 */ "\xE1\xB8\x93" => "\x64", + /* U+1E14 */ "\xE1\xB8\x94" => "\x65", + /* U+1E15 */ "\xE1\xB8\x95" => "\x65", + /* U+1E16 */ "\xE1\xB8\x96" => "\x65", + /* U+1E17 */ "\xE1\xB8\x97" => "\x65", + /* U+1E18 */ "\xE1\xB8\x98" => "\x65", + /* U+1E19 */ "\xE1\xB8\x99" => "\x65", + /* U+1E1A */ "\xE1\xB8\x9A" => "\x65", + /* U+1E1B */ "\xE1\xB8\x9B" => "\x65", + /* U+1E1C */ "\xE1\xB8\x9C" => "\x65", + /* U+1E1D */ "\xE1\xB8\x9D" => "\x65", + /* U+1E1E */ "\xE1\xB8\x9E" => "\x66", + /* U+1E1F */ "\xE1\xB8\x9F" => "\x66", + /* U+1E20 */ "\xE1\xB8\xA0" => "\x67", + /* U+1E21 */ "\xE1\xB8\xA1" => "\x67", + /* U+1E22 */ "\xE1\xB8\xA2" => "\x68", + /* U+1E23 */ "\xE1\xB8\xA3" => "\x68", + /* U+1E24 */ "\xE1\xB8\xA4" => "\x68", + /* U+1E25 */ "\xE1\xB8\xA5" => "\x68", + /* U+1E26 */ "\xE1\xB8\xA6" => "\x68", + /* U+1E27 */ "\xE1\xB8\xA7" => "\x68", + /* U+1E28 */ "\xE1\xB8\xA8" => "\x68", + /* U+1E29 */ "\xE1\xB8\xA9" => "\x68", + /* U+1E2A */ "\xE1\xB8\xAA" => "\x68", + /* U+1E2B */ "\xE1\xB8\xAB" => "\x68", + /* U+1E2C */ "\xE1\xB8\xAC" => "\x69", + /* U+1E2D */ "\xE1\xB8\xAD" => "\x69", + /* U+1E2E */ "\xE1\xB8\xAE" => "\x69", + /* U+1E2F */ "\xE1\xB8\xAF" => "\x69", + /* U+1E30 */ "\xE1\xB8\xB0" => "\x6B", + /* U+1E31 */ "\xE1\xB8\xB1" => "\x6B", + /* U+1E32 */ "\xE1\xB8\xB2" => "\x6B", + /* U+1E33 */ "\xE1\xB8\xB3" => "\x6B", + /* U+1E34 */ "\xE1\xB8\xB4" => "\x6B", + /* U+1E35 */ "\xE1\xB8\xB5" => "\x6B", + /* U+1E36 */ "\xE1\xB8\xB6" => "\x6C", + /* U+1E37 */ "\xE1\xB8\xB7" => "\x6C", + /* U+1E38 */ "\xE1\xB8\xB8" => "\x6C", + /* U+1E39 */ "\xE1\xB8\xB9" => "\x6C", + /* U+1E3A */ "\xE1\xB8\xBA" => "\x6C", + /* U+1E3B */ "\xE1\xB8\xBB" => "\x6C", + /* U+1E3C */ "\xE1\xB8\xBC" => "\x6C", + /* U+1E3D */ "\xE1\xB8\xBD" => "\x6C", + /* U+1E3E */ "\xE1\xB8\xBE" => "\x6D", + /* U+1E3F */ "\xE1\xB8\xBF" => "\x6D", + /* U+1E40 */ "\xE1\xB9\x80" => "\x6D", + /* U+1E41 */ "\xE1\xB9\x81" => "\x6D", + /* U+1E42 */ "\xE1\xB9\x82" => "\x6D", + /* U+1E43 */ "\xE1\xB9\x83" => "\x6D", + /* U+1E44 */ "\xE1\xB9\x84" => "\x6E", + /* U+1E45 */ "\xE1\xB9\x85" => "\x6E", + /* U+1E46 */ "\xE1\xB9\x86" => "\x6E", + /* U+1E47 */ "\xE1\xB9\x87" => "\x6E", + /* U+1E48 */ "\xE1\xB9\x88" => "\x6E", + /* U+1E49 */ "\xE1\xB9\x89" => "\x6E", + /* U+1E4A */ "\xE1\xB9\x8A" => "\x6E", + /* U+1E4B */ "\xE1\xB9\x8B" => "\x6E", + /* U+1E4C */ "\xE1\xB9\x8C" => "\x6F", + /* U+1E4D */ "\xE1\xB9\x8D" => "\x6F", + /* U+1E4E */ "\xE1\xB9\x8E" => "\x6F", + /* U+1E4F */ "\xE1\xB9\x8F" => "\x6F", + /* U+1E50 */ "\xE1\xB9\x90" => "\x6F", + /* U+1E51 */ "\xE1\xB9\x91" => "\x6F", + /* U+1E52 */ "\xE1\xB9\x92" => "\x6F", + /* U+1E53 */ "\xE1\xB9\x93" => "\x6F", + /* U+1E54 */ "\xE1\xB9\x94" => "\x70", + /* U+1E55 */ "\xE1\xB9\x95" => "\x70", + /* U+1E56 */ "\xE1\xB9\x96" => "\x70", + /* U+1E57 */ "\xE1\xB9\x97" => "\x70", + /* U+1E58 */ "\xE1\xB9\x98" => "\x72", + /* U+1E59 */ "\xE1\xB9\x99" => "\x72", + /* U+1E5A */ "\xE1\xB9\x9A" => "\x72", + /* U+1E5B */ "\xE1\xB9\x9B" => "\x72", + /* U+1E5C */ "\xE1\xB9\x9C" => "\x72", + /* U+1E5D */ "\xE1\xB9\x9D" => "\x72", + /* U+1E5E */ "\xE1\xB9\x9E" => "\x72", + /* U+1E5F */ "\xE1\xB9\x9F" => "\x72", + /* U+1E60 */ "\xE1\xB9\xA0" => "\x73", + /* U+1E61 */ "\xE1\xB9\xA1" => "\x73", + /* U+1E62 */ "\xE1\xB9\xA2" => "\x73", + /* U+1E63 */ "\xE1\xB9\xA3" => "\x73", + /* U+1E64 */ "\xE1\xB9\xA4" => "\x73", + /* U+1E65 */ "\xE1\xB9\xA5" => "\x73", + /* U+1E66 */ "\xE1\xB9\xA6" => "\x73", + /* U+1E67 */ "\xE1\xB9\xA7" => "\x73", + /* U+1E68 */ "\xE1\xB9\xA8" => "\x73", + /* U+1E69 */ "\xE1\xB9\xA9" => "\x73", + /* U+1E6A */ "\xE1\xB9\xAA" => "\x74", + /* U+1E6B */ "\xE1\xB9\xAB" => "\x74", + /* U+1E6C */ "\xE1\xB9\xAC" => "\x74", + /* U+1E6D */ "\xE1\xB9\xAD" => "\x74", + /* U+1E6E */ "\xE1\xB9\xAE" => "\x74", + /* U+1E6F */ "\xE1\xB9\xAF" => "\x74", + /* U+1E70 */ "\xE1\xB9\xB0" => "\x74", + /* U+1E71 */ "\xE1\xB9\xB1" => "\x74", + /* U+1E72 */ "\xE1\xB9\xB2" => "\x75", + /* U+1E73 */ "\xE1\xB9\xB3" => "\x75", + /* U+1E74 */ "\xE1\xB9\xB4" => "\x75", + /* U+1E75 */ "\xE1\xB9\xB5" => "\x75", + /* U+1E76 */ "\xE1\xB9\xB6" => "\x75", + /* U+1E77 */ "\xE1\xB9\xB7" => "\x75", + /* U+1E78 */ "\xE1\xB9\xB8" => "\x75", + /* U+1E79 */ "\xE1\xB9\xB9" => "\x75", + /* U+1E7A */ "\xE1\xB9\xBA" => "\x75", + /* U+1E7B */ "\xE1\xB9\xBB" => "\x75", + /* U+1E7C */ "\xE1\xB9\xBC" => "\x76", + /* U+1E7D */ "\xE1\xB9\xBD" => "\x76", + /* U+1E7E */ "\xE1\xB9\xBE" => "\x76", + /* U+1E7F */ "\xE1\xB9\xBF" => "\x76", + /* U+1E80 */ "\xE1\xBA\x80" => "\x77", + /* U+1E81 */ "\xE1\xBA\x81" => "\x77", + /* U+1E82 */ "\xE1\xBA\x82" => "\x77", + /* U+1E83 */ "\xE1\xBA\x83" => "\x77", + /* U+1E84 */ "\xE1\xBA\x84" => "\x77", + /* U+1E85 */ "\xE1\xBA\x85" => "\x77", + /* U+1E86 */ "\xE1\xBA\x86" => "\x77", + /* U+1E87 */ "\xE1\xBA\x87" => "\x77", + /* U+1E88 */ "\xE1\xBA\x88" => "\x77", + /* U+1E89 */ "\xE1\xBA\x89" => "\x77", + /* U+1E8A */ "\xE1\xBA\x8A" => "\x78", + /* U+1E8B */ "\xE1\xBA\x8B" => "\x78", + /* U+1E8C */ "\xE1\xBA\x8C" => "\x78", + /* U+1E8D */ "\xE1\xBA\x8D" => "\x78", + /* U+1E8E */ "\xE1\xBA\x8E" => "\x79", + /* U+1E8F */ "\xE1\xBA\x8F" => "\x79", + /* U+1E90 */ "\xE1\xBA\x90" => "\x7A", + /* U+1E91 */ "\xE1\xBA\x91" => "\x7A", + /* U+1E92 */ "\xE1\xBA\x92" => "\x7A", + /* U+1E93 */ "\xE1\xBA\x93" => "\x7A", + /* U+1E94 */ "\xE1\xBA\x94" => "\x7A", + /* U+1E95 */ "\xE1\xBA\x95" => "\x7A", + /* U+1E96 */ "\xE1\xBA\x96" => "\x68", + /* U+1E97 */ "\xE1\xBA\x97" => "\x74", + /* U+1E98 */ "\xE1\xBA\x98" => "\x77", + /* U+1E99 */ "\xE1\xBA\x99" => "\x79", + /* U+1E9A */ "\xE1\xBA\x9A" => "\x61", + /* U+1E9B */ "\xE1\xBA\x9B" => "\xC5\xBF", + /* U+1EA0 */ "\xE1\xBA\xA0" => "\x61", + /* U+1EA1 */ "\xE1\xBA\xA1" => "\x61", + /* U+1EA2 */ "\xE1\xBA\xA2" => "\x61", + /* U+1EA3 */ "\xE1\xBA\xA3" => "\x61", + /* U+1EA4 */ "\xE1\xBA\xA4" => "\x61", + /* U+1EA5 */ "\xE1\xBA\xA5" => "\x61", + /* U+1EA6 */ "\xE1\xBA\xA6" => "\x61", + /* U+1EA7 */ "\xE1\xBA\xA7" => "\x61", + /* U+1EA8 */ "\xE1\xBA\xA8" => "\x61", + /* U+1EA9 */ "\xE1\xBA\xA9" => "\x61", + /* U+1EAA */ "\xE1\xBA\xAA" => "\x61", + /* U+1EAB */ "\xE1\xBA\xAB" => "\x61", + /* U+1EAC */ "\xE1\xBA\xAC" => "\x61", + /* U+1EAD */ "\xE1\xBA\xAD" => "\x61", + /* U+1EAE */ "\xE1\xBA\xAE" => "\x61", + /* U+1EAF */ "\xE1\xBA\xAF" => "\x61", + /* U+1EB0 */ "\xE1\xBA\xB0" => "\x61", + /* U+1EB1 */ "\xE1\xBA\xB1" => "\x61", + /* U+1EB2 */ "\xE1\xBA\xB2" => "\x61", + /* U+1EB3 */ "\xE1\xBA\xB3" => "\x61", + /* U+1EB4 */ "\xE1\xBA\xB4" => "\x61", + /* U+1EB5 */ "\xE1\xBA\xB5" => "\x61", + /* U+1EB6 */ "\xE1\xBA\xB6" => "\x61", + /* U+1EB7 */ "\xE1\xBA\xB7" => "\x61", + /* U+1EB8 */ "\xE1\xBA\xB8" => "\x65", + /* U+1EB9 */ "\xE1\xBA\xB9" => "\x65", + /* U+1EBA */ "\xE1\xBA\xBA" => "\x65", + /* U+1EBB */ "\xE1\xBA\xBB" => "\x65", + /* U+1EBC */ "\xE1\xBA\xBC" => "\x65", + /* U+1EBD */ "\xE1\xBA\xBD" => "\x65", + /* U+1EBE */ "\xE1\xBA\xBE" => "\x65", + /* U+1EBF */ "\xE1\xBA\xBF" => "\x65", + /* U+1EC0 */ "\xE1\xBB\x80" => "\x65", + /* U+1EC1 */ "\xE1\xBB\x81" => "\x65", + /* U+1EC2 */ "\xE1\xBB\x82" => "\x65", + /* U+1EC3 */ "\xE1\xBB\x83" => "\x65", + /* U+1EC4 */ "\xE1\xBB\x84" => "\x65", + /* U+1EC5 */ "\xE1\xBB\x85" => "\x65", + /* U+1EC6 */ "\xE1\xBB\x86" => "\x65", + /* U+1EC7 */ "\xE1\xBB\x87" => "\x65", + /* U+1EC8 */ "\xE1\xBB\x88" => "\x69", + /* U+1EC9 */ "\xE1\xBB\x89" => "\x69", + /* U+1ECA */ "\xE1\xBB\x8A" => "\x69", + /* U+1ECB */ "\xE1\xBB\x8B" => "\x69", + /* U+1ECC */ "\xE1\xBB\x8C" => "\x6F", + /* U+1ECD */ "\xE1\xBB\x8D" => "\x6F", + /* U+1ECE */ "\xE1\xBB\x8E" => "\x6F", + /* U+1ECF */ "\xE1\xBB\x8F" => "\x6F", + /* U+1ED0 */ "\xE1\xBB\x90" => "\x6F", + /* U+1ED1 */ "\xE1\xBB\x91" => "\x6F", + /* U+1ED2 */ "\xE1\xBB\x92" => "\x6F", + /* U+1ED3 */ "\xE1\xBB\x93" => "\x6F", + /* U+1ED4 */ "\xE1\xBB\x94" => "\x6F", + /* U+1ED5 */ "\xE1\xBB\x95" => "\x6F", + /* U+1ED6 */ "\xE1\xBB\x96" => "\x6F", + /* U+1ED7 */ "\xE1\xBB\x97" => "\x6F", + /* U+1ED8 */ "\xE1\xBB\x98" => "\x6F", + /* U+1ED9 */ "\xE1\xBB\x99" => "\x6F", + /* U+1EDA */ "\xE1\xBB\x9A" => "\x6F", + /* U+1EDB */ "\xE1\xBB\x9B" => "\x6F", + /* U+1EDC */ "\xE1\xBB\x9C" => "\x6F", + /* U+1EDD */ "\xE1\xBB\x9D" => "\x6F", + /* U+1EDE */ "\xE1\xBB\x9E" => "\x6F", + /* U+1EDF */ "\xE1\xBB\x9F" => "\x6F", + /* U+1EE0 */ "\xE1\xBB\xA0" => "\x6F", + /* U+1EE1 */ "\xE1\xBB\xA1" => "\x6F", + /* U+1EE2 */ "\xE1\xBB\xA2" => "\x6F", + /* U+1EE3 */ "\xE1\xBB\xA3" => "\x6F", + /* U+1EE4 */ "\xE1\xBB\xA4" => "\x75", + /* U+1EE5 */ "\xE1\xBB\xA5" => "\x75", + /* U+1EE6 */ "\xE1\xBB\xA6" => "\x75", + /* U+1EE7 */ "\xE1\xBB\xA7" => "\x75", + /* U+1EE8 */ "\xE1\xBB\xA8" => "\x75", + /* U+1EE9 */ "\xE1\xBB\xA9" => "\x75", + /* U+1EEA */ "\xE1\xBB\xAA" => "\x75", + /* U+1EEB */ "\xE1\xBB\xAB" => "\x75", + /* U+1EEC */ "\xE1\xBB\xAC" => "\x75", + /* U+1EED */ "\xE1\xBB\xAD" => "\x75", + /* U+1EEE */ "\xE1\xBB\xAE" => "\x75", + /* U+1EEF */ "\xE1\xBB\xAF" => "\x75", + /* U+1EF0 */ "\xE1\xBB\xB0" => "\x75", + /* U+1EF1 */ "\xE1\xBB\xB1" => "\x75", + /* U+1EF2 */ "\xE1\xBB\xB2" => "\x79", + /* U+1EF3 */ "\xE1\xBB\xB3" => "\x79", + /* U+1EF4 */ "\xE1\xBB\xB4" => "\x79", + /* U+1EF5 */ "\xE1\xBB\xB5" => "\x79", + /* U+1EF6 */ "\xE1\xBB\xB6" => "\x79", + /* U+1EF7 */ "\xE1\xBB\xB7" => "\x79", + /* U+1EF8 */ "\xE1\xBB\xB8" => "\x79", + /* U+1EF9 */ "\xE1\xBB\xB9" => "\x79", + //------ U+1F00..U+1FFF : Greek Extended + /* U+1F00 */ "\xE1\xBC\x80" => "\xCE\xB1", + /* U+1F01 */ "\xE1\xBC\x81" => "\xCE\xB1", + /* U+1F02 */ "\xE1\xBC\x82" => "\xCE\xB1", + /* U+1F03 */ "\xE1\xBC\x83" => "\xCE\xB1", + /* U+1F04 */ "\xE1\xBC\x84" => "\xCE\xB1", + /* U+1F05 */ "\xE1\xBC\x85" => "\xCE\xB1", + /* U+1F06 */ "\xE1\xBC\x86" => "\xCE\xB1", + /* U+1F07 */ "\xE1\xBC\x87" => "\xCE\xB1", + /* U+1F08 */ "\xE1\xBC\x88" => "\xCE\xB1", + /* U+1F09 */ "\xE1\xBC\x89" => "\xCE\xB1", + /* U+1F0A */ "\xE1\xBC\x8A" => "\xCE\xB1", + /* U+1F0B */ "\xE1\xBC\x8B" => "\xCE\xB1", + /* U+1F0C */ "\xE1\xBC\x8C" => "\xCE\xB1", + /* U+1F0D */ "\xE1\xBC\x8D" => "\xCE\xB1", + /* U+1F0E */ "\xE1\xBC\x8E" => "\xCE\xB1", + /* U+1F0F */ "\xE1\xBC\x8F" => "\xCE\xB1", + /* U+1F10 */ "\xE1\xBC\x90" => "\xCE\xB5", + /* U+1F11 */ "\xE1\xBC\x91" => "\xCE\xB5", + /* U+1F12 */ "\xE1\xBC\x92" => "\xCE\xB5", + /* U+1F13 */ "\xE1\xBC\x93" => "\xCE\xB5", + /* U+1F14 */ "\xE1\xBC\x94" => "\xCE\xB5", + /* U+1F15 */ "\xE1\xBC\x95" => "\xCE\xB5", + /* U+1F18 */ "\xE1\xBC\x98" => "\xCE\xB5", + /* U+1F19 */ "\xE1\xBC\x99" => "\xCE\xB5", + /* U+1F1A */ "\xE1\xBC\x9A" => "\xCE\xB5", + /* U+1F1B */ "\xE1\xBC\x9B" => "\xCE\xB5", + /* U+1F1C */ "\xE1\xBC\x9C" => "\xCE\xB5", + /* U+1F1D */ "\xE1\xBC\x9D" => "\xCE\xB5", + /* U+1F20 */ "\xE1\xBC\xA0" => "\xCE\xB7", + /* U+1F21 */ "\xE1\xBC\xA1" => "\xCE\xB7", + /* U+1F22 */ "\xE1\xBC\xA2" => "\xCE\xB7", + /* U+1F23 */ "\xE1\xBC\xA3" => "\xCE\xB7", + /* U+1F24 */ "\xE1\xBC\xA4" => "\xCE\xB7", + /* U+1F25 */ "\xE1\xBC\xA5" => "\xCE\xB7", + /* U+1F26 */ "\xE1\xBC\xA6" => "\xCE\xB7", + /* U+1F27 */ "\xE1\xBC\xA7" => "\xCE\xB7", + /* U+1F28 */ "\xE1\xBC\xA8" => "\xCE\xB7", + /* U+1F29 */ "\xE1\xBC\xA9" => "\xCE\xB7", + /* U+1F2A */ "\xE1\xBC\xAA" => "\xCE\xB7", + /* U+1F2B */ "\xE1\xBC\xAB" => "\xCE\xB7", + /* U+1F2C */ "\xE1\xBC\xAC" => "\xCE\xB7", + /* U+1F2D */ "\xE1\xBC\xAD" => "\xCE\xB7", + /* U+1F2E */ "\xE1\xBC\xAE" => "\xCE\xB7", + /* U+1F2F */ "\xE1\xBC\xAF" => "\xCE\xB7", + /* U+1F30 */ "\xE1\xBC\xB0" => "\xCE\xB9", + /* U+1F31 */ "\xE1\xBC\xB1" => "\xCE\xB9", + /* U+1F32 */ "\xE1\xBC\xB2" => "\xCE\xB9", + /* U+1F33 */ "\xE1\xBC\xB3" => "\xCE\xB9", + /* U+1F34 */ "\xE1\xBC\xB4" => "\xCE\xB9", + /* U+1F35 */ "\xE1\xBC\xB5" => "\xCE\xB9", + /* U+1F36 */ "\xE1\xBC\xB6" => "\xCE\xB9", + /* U+1F37 */ "\xE1\xBC\xB7" => "\xCE\xB9", + /* U+1F38 */ "\xE1\xBC\xB8" => "\xCE\xB9", + /* U+1F39 */ "\xE1\xBC\xB9" => "\xCE\xB9", + /* U+1F3A */ "\xE1\xBC\xBA" => "\xCE\xB9", + /* U+1F3B */ "\xE1\xBC\xBB" => "\xCE\xB9", + /* U+1F3C */ "\xE1\xBC\xBC" => "\xCE\xB9", + /* U+1F3D */ "\xE1\xBC\xBD" => "\xCE\xB9", + /* U+1F3E */ "\xE1\xBC\xBE" => "\xCE\xB9", + /* U+1F3F */ "\xE1\xBC\xBF" => "\xCE\xB9", + /* U+1F40 */ "\xE1\xBD\x80" => "\xCE\xBF", + /* U+1F41 */ "\xE1\xBD\x81" => "\xCE\xBF", + /* U+1F42 */ "\xE1\xBD\x82" => "\xCE\xBF", + /* U+1F43 */ "\xE1\xBD\x83" => "\xCE\xBF", + /* U+1F44 */ "\xE1\xBD\x84" => "\xCE\xBF", + /* U+1F45 */ "\xE1\xBD\x85" => "\xCE\xBF", + /* U+1F48 */ "\xE1\xBD\x88" => "\xCE\xBF", + /* U+1F49 */ "\xE1\xBD\x89" => "\xCE\xBF", + /* U+1F4A */ "\xE1\xBD\x8A" => "\xCE\xBF", + /* U+1F4B */ "\xE1\xBD\x8B" => "\xCE\xBF", + /* U+1F4C */ "\xE1\xBD\x8C" => "\xCE\xBF", + /* U+1F4D */ "\xE1\xBD\x8D" => "\xCE\xBF", + /* U+1F50 */ "\xE1\xBD\x90" => "\xCF\x85", + /* U+1F51 */ "\xE1\xBD\x91" => "\xCF\x85", + /* U+1F52 */ "\xE1\xBD\x92" => "\xCF\x85", + /* U+1F53 */ "\xE1\xBD\x93" => "\xCF\x85", + /* U+1F54 */ "\xE1\xBD\x94" => "\xCF\x85", + /* U+1F55 */ "\xE1\xBD\x95" => "\xCF\x85", + /* U+1F56 */ "\xE1\xBD\x96" => "\xCF\x85", + /* U+1F57 */ "\xE1\xBD\x97" => "\xCF\x85", + /* U+1F59 */ "\xE1\xBD\x99" => "\xCF\x85", + /* U+1F5B */ "\xE1\xBD\x9B" => "\xCF\x85", + /* U+1F5D */ "\xE1\xBD\x9D" => "\xCF\x85", + /* U+1F5F */ "\xE1\xBD\x9F" => "\xCF\x85", + /* U+1F60 */ "\xE1\xBD\xA0" => "\xCF\x89", + /* U+1F61 */ "\xE1\xBD\xA1" => "\xCF\x89", + /* U+1F62 */ "\xE1\xBD\xA2" => "\xCF\x89", + /* U+1F63 */ "\xE1\xBD\xA3" => "\xCF\x89", + /* U+1F64 */ "\xE1\xBD\xA4" => "\xCF\x89", + /* U+1F65 */ "\xE1\xBD\xA5" => "\xCF\x89", + /* U+1F66 */ "\xE1\xBD\xA6" => "\xCF\x89", + /* U+1F67 */ "\xE1\xBD\xA7" => "\xCF\x89", + /* U+1F68 */ "\xE1\xBD\xA8" => "\xCF\x89", + /* U+1F69 */ "\xE1\xBD\xA9" => "\xCF\x89", + /* U+1F6A */ "\xE1\xBD\xAA" => "\xCF\x89", + /* U+1F6B */ "\xE1\xBD\xAB" => "\xCF\x89", + /* U+1F6C */ "\xE1\xBD\xAC" => "\xCF\x89", + /* U+1F6D */ "\xE1\xBD\xAD" => "\xCF\x89", + /* U+1F6E */ "\xE1\xBD\xAE" => "\xCF\x89", + /* U+1F6F */ "\xE1\xBD\xAF" => "\xCF\x89", + /* U+1F70 */ "\xE1\xBD\xB0" => "\xCE\xB1", + /* U+1F71 */ "\xE1\xBD\xB1" => "\xCE\xB1", + /* U+1F72 */ "\xE1\xBD\xB2" => "\xCE\xB5", + /* U+1F73 */ "\xE1\xBD\xB3" => "\xCE\xB5", + /* U+1F74 */ "\xE1\xBD\xB4" => "\xCE\xB7", + /* U+1F75 */ "\xE1\xBD\xB5" => "\xCE\xB7", + /* U+1F76 */ "\xE1\xBD\xB6" => "\xCE\xB9", + /* U+1F77 */ "\xE1\xBD\xB7" => "\xCE\xB9", + /* U+1F78 */ "\xE1\xBD\xB8" => "\xCE\xBF", + /* U+1F79 */ "\xE1\xBD\xB9" => "\xCE\xBF", + /* U+1F7A */ "\xE1\xBD\xBA" => "\xCF\x85", + /* U+1F7B */ "\xE1\xBD\xBB" => "\xCF\x85", + /* U+1F7C */ "\xE1\xBD\xBC" => "\xCF\x89", + /* U+1F7D */ "\xE1\xBD\xBD" => "\xCF\x89", + /* U+1F80 */ "\xE1\xBE\x80" => "\xCE\xB1", + /* U+1F81 */ "\xE1\xBE\x81" => "\xCE\xB1", + /* U+1F82 */ "\xE1\xBE\x82" => "\xCE\xB1", + /* U+1F83 */ "\xE1\xBE\x83" => "\xCE\xB1", + /* U+1F84 */ "\xE1\xBE\x84" => "\xCE\xB1", + /* U+1F85 */ "\xE1\xBE\x85" => "\xCE\xB1", + /* U+1F86 */ "\xE1\xBE\x86" => "\xCE\xB1", + /* U+1F87 */ "\xE1\xBE\x87" => "\xCE\xB1", + /* U+1F88 */ "\xE1\xBE\x88" => "\xCE\xB1", + /* U+1F89 */ "\xE1\xBE\x89" => "\xCE\xB1", + /* U+1F8A */ "\xE1\xBE\x8A" => "\xCE\xB1", + /* U+1F8B */ "\xE1\xBE\x8B" => "\xCE\xB1", + /* U+1F8C */ "\xE1\xBE\x8C" => "\xCE\xB1", + /* U+1F8D */ "\xE1\xBE\x8D" => "\xCE\xB1", + /* U+1F8E */ "\xE1\xBE\x8E" => "\xCE\xB1", + /* U+1F8F */ "\xE1\xBE\x8F" => "\xCE\xB1", + /* U+1F90 */ "\xE1\xBE\x90" => "\xCE\xB7", + /* U+1F91 */ "\xE1\xBE\x91" => "\xCE\xB7", + /* U+1F92 */ "\xE1\xBE\x92" => "\xCE\xB7", + /* U+1F93 */ "\xE1\xBE\x93" => "\xCE\xB7", + /* U+1F94 */ "\xE1\xBE\x94" => "\xCE\xB7", + /* U+1F95 */ "\xE1\xBE\x95" => "\xCE\xB7", + /* U+1F96 */ "\xE1\xBE\x96" => "\xCE\xB7", + /* U+1F97 */ "\xE1\xBE\x97" => "\xCE\xB7", + /* U+1F98 */ "\xE1\xBE\x98" => "\xCE\xB7", + /* U+1F99 */ "\xE1\xBE\x99" => "\xCE\xB7", + /* U+1F9A */ "\xE1\xBE\x9A" => "\xCE\xB7", + /* U+1F9B */ "\xE1\xBE\x9B" => "\xCE\xB7", + /* U+1F9C */ "\xE1\xBE\x9C" => "\xCE\xB7", + /* U+1F9D */ "\xE1\xBE\x9D" => "\xCE\xB7", + /* U+1F9E */ "\xE1\xBE\x9E" => "\xCE\xB7", + /* U+1F9F */ "\xE1\xBE\x9F" => "\xCE\xB7", + /* U+1FA0 */ "\xE1\xBE\xA0" => "\xCF\x89", + /* U+1FA1 */ "\xE1\xBE\xA1" => "\xCF\x89", + /* U+1FA2 */ "\xE1\xBE\xA2" => "\xCF\x89", + /* U+1FA3 */ "\xE1\xBE\xA3" => "\xCF\x89", + /* U+1FA4 */ "\xE1\xBE\xA4" => "\xCF\x89", + /* U+1FA5 */ "\xE1\xBE\xA5" => "\xCF\x89", + /* U+1FA6 */ "\xE1\xBE\xA6" => "\xCF\x89", + /* U+1FA7 */ "\xE1\xBE\xA7" => "\xCF\x89", + /* U+1FA8 */ "\xE1\xBE\xA8" => "\xCF\x89", + /* U+1FA9 */ "\xE1\xBE\xA9" => "\xCF\x89", + /* U+1FAA */ "\xE1\xBE\xAA" => "\xCF\x89", + /* U+1FAB */ "\xE1\xBE\xAB" => "\xCF\x89", + /* U+1FAC */ "\xE1\xBE\xAC" => "\xCF\x89", + /* U+1FAD */ "\xE1\xBE\xAD" => "\xCF\x89", + /* U+1FAE */ "\xE1\xBE\xAE" => "\xCF\x89", + /* U+1FAF */ "\xE1\xBE\xAF" => "\xCF\x89", + /* U+1FB0 */ "\xE1\xBE\xB0" => "\xCE\xB1", + /* U+1FB1 */ "\xE1\xBE\xB1" => "\xCE\xB1", + /* U+1FB2 */ "\xE1\xBE\xB2" => "\xCE\xB1", + /* U+1FB3 */ "\xE1\xBE\xB3" => "\xCE\xB1", + /* U+1FB4 */ "\xE1\xBE\xB4" => "\xCE\xB1", + /* U+1FB6 */ "\xE1\xBE\xB6" => "\xCE\xB1", + /* U+1FB7 */ "\xE1\xBE\xB7" => "\xCE\xB1", + /* U+1FB8 */ "\xE1\xBE\xB8" => "\xCE\xB1", + /* U+1FB9 */ "\xE1\xBE\xB9" => "\xCE\xB1", + /* U+1FBA */ "\xE1\xBE\xBA" => "\xCE\xB1", + /* U+1FBB */ "\xE1\xBE\xBB" => "\xCE\xB1", + /* U+1FBC */ "\xE1\xBE\xBC" => "\xCE\xB1", + /* U+1FC2 */ "\xE1\xBF\x82" => "\xCE\xB7", + /* U+1FC3 */ "\xE1\xBF\x83" => "\xCE\xB7", + /* U+1FC4 */ "\xE1\xBF\x84" => "\xCE\xB7", + /* U+1FC6 */ "\xE1\xBF\x86" => "\xCE\xB7", + /* U+1FC7 */ "\xE1\xBF\x87" => "\xCE\xB7", + /* U+1FC8 */ "\xE1\xBF\x88" => "\xCE\xB5", + /* U+1FC9 */ "\xE1\xBF\x89" => "\xCE\xB5", + /* U+1FCA */ "\xE1\xBF\x8A" => "\xCE\xB7", + /* U+1FCB */ "\xE1\xBF\x8B" => "\xCE\xB7", + /* U+1FCC */ "\xE1\xBF\x8C" => "\xCE\xB7", + /* U+1FD0 */ "\xE1\xBF\x90" => "\xCE\xB9", + /* U+1FD1 */ "\xE1\xBF\x91" => "\xCE\xB9", + /* U+1FD2 */ "\xE1\xBF\x92" => "\xCE\xB9", + /* U+1FD3 */ "\xE1\xBF\x93" => "\xCE\xB9", + /* U+1FD6 */ "\xE1\xBF\x96" => "\xCE\xB9", + /* U+1FD7 */ "\xE1\xBF\x97" => "\xCE\xB9", + /* U+1FD8 */ "\xE1\xBF\x98" => "\xCE\xB9", + /* U+1FD9 */ "\xE1\xBF\x99" => "\xCE\xB9", + /* U+1FDA */ "\xE1\xBF\x9A" => "\xCE\xB9", + /* U+1FDB */ "\xE1\xBF\x9B" => "\xCE\xB9", + /* U+1FE0 */ "\xE1\xBF\xA0" => "\xCF\x85", + /* U+1FE1 */ "\xE1\xBF\xA1" => "\xCF\x85", + /* U+1FE2 */ "\xE1\xBF\xA2" => "\xCF\x85", + /* U+1FE3 */ "\xE1\xBF\xA3" => "\xCF\x85", + /* U+1FE4 */ "\xE1\xBF\xA4" => "\xCF\x81", + /* U+1FE5 */ "\xE1\xBF\xA5" => "\xCF\x81", + /* U+1FE6 */ "\xE1\xBF\xA6" => "\xCF\x85", + /* U+1FE7 */ "\xE1\xBF\xA7" => "\xCF\x85", + /* U+1FE8 */ "\xE1\xBF\xA8" => "\xCF\x85", + /* U+1FE9 */ "\xE1\xBF\xA9" => "\xCF\x85", + /* U+1FEA */ "\xE1\xBF\xAA" => "\xCF\x85", + /* U+1FEB */ "\xE1\xBF\xAB" => "\xCF\x85", + /* U+1FEC */ "\xE1\xBF\xAC" => "\xCF\x81", + /* U+1FF2 */ "\xE1\xBF\xB2" => "\xCF\x89", + /* U+1FF3 */ "\xE1\xBF\xB3" => "\xCF\x89", + /* U+1FF4 */ "\xE1\xBF\xB4" => "\xCF\x89", + /* U+1FF6 */ "\xE1\xBF\xB6" => "\xCF\x89", + /* U+1FF7 */ "\xE1\xBF\xB7" => "\xCF\x89", + /* U+1FF8 */ "\xE1\xBF\xB8" => "\xCE\xBF", + /* U+1FF9 */ "\xE1\xBF\xB9" => "\xCE\xBF", + /* U+1FFA */ "\xE1\xBF\xBA" => "\xCF\x89", + /* U+1FFB */ "\xE1\xBF\xBB" => "\xCF\x89", + /* U+1FFC */ "\xE1\xBF\xBC" => "\xCF\x89", + //------ U+2C00..U+2C5F : Glagolitic + /* U+2C00 */ "\xE2\xB0\x80" => "\xE2\xB0\xB0", + /* U+2C01 */ "\xE2\xB0\x81" => "\xE2\xB0\xB1", + /* U+2C02 */ "\xE2\xB0\x82" => "\xE2\xB0\xB2", + /* U+2C03 */ "\xE2\xB0\x83" => "\xE2\xB0\xB3", + /* U+2C04 */ "\xE2\xB0\x84" => "\xE2\xB0\xB4", + /* U+2C05 */ "\xE2\xB0\x85" => "\xE2\xB0\xB5", + /* U+2C06 */ "\xE2\xB0\x86" => "\xE2\xB0\xB6", + /* U+2C07 */ "\xE2\xB0\x87" => "\xE2\xB0\xB7", + /* U+2C08 */ "\xE2\xB0\x88" => "\xE2\xB0\xB8", + /* U+2C09 */ "\xE2\xB0\x89" => "\xE2\xB0\xB9", + /* U+2C0A */ "\xE2\xB0\x8A" => "\xE2\xB0\xBA", + /* U+2C0B */ "\xE2\xB0\x8B" => "\xE2\xB0\xBB", + /* U+2C0C */ "\xE2\xB0\x8C" => "\xE2\xB0\xBC", + /* U+2C0D */ "\xE2\xB0\x8D" => "\xE2\xB0\xBD", + /* U+2C0E */ "\xE2\xB0\x8E" => "\xE2\xB0\xBE", + /* U+2C0F */ "\xE2\xB0\x8F" => "\xE2\xB0\xBF", + /* U+2C10 */ "\xE2\xB0\x90" => "\xE2\xB1\x80", + /* U+2C11 */ "\xE2\xB0\x91" => "\xE2\xB1\x81", + /* U+2C12 */ "\xE2\xB0\x92" => "\xE2\xB1\x82", + /* U+2C13 */ "\xE2\xB0\x93" => "\xE2\xB1\x83", + /* U+2C14 */ "\xE2\xB0\x94" => "\xE2\xB1\x84", + /* U+2C15 */ "\xE2\xB0\x95" => "\xE2\xB1\x85", + /* U+2C16 */ "\xE2\xB0\x96" => "\xE2\xB1\x86", + /* U+2C17 */ "\xE2\xB0\x97" => "\xE2\xB1\x87", + /* U+2C18 */ "\xE2\xB0\x98" => "\xE2\xB1\x88", + /* U+2C19 */ "\xE2\xB0\x99" => "\xE2\xB1\x89", + /* U+2C1A */ "\xE2\xB0\x9A" => "\xE2\xB1\x8A", + /* U+2C1B */ "\xE2\xB0\x9B" => "\xE2\xB1\x8B", + /* U+2C1C */ "\xE2\xB0\x9C" => "\xE2\xB1\x8C", + /* U+2C1D */ "\xE2\xB0\x9D" => "\xE2\xB1\x8D", + /* U+2C1E */ "\xE2\xB0\x9E" => "\xE2\xB1\x8E", + /* U+2C1F */ "\xE2\xB0\x9F" => "\xE2\xB1\x8F", + /* U+2C20 */ "\xE2\xB0\xA0" => "\xE2\xB1\x90", + /* U+2C21 */ "\xE2\xB0\xA1" => "\xE2\xB1\x91", + /* U+2C22 */ "\xE2\xB0\xA2" => "\xE2\xB1\x92", + /* U+2C23 */ "\xE2\xB0\xA3" => "\xE2\xB1\x93", + /* U+2C24 */ "\xE2\xB0\xA4" => "\xE2\xB1\x94", + /* U+2C25 */ "\xE2\xB0\xA5" => "\xE2\xB1\x95", + /* U+2C26 */ "\xE2\xB0\xA6" => "\xE2\xB1\x96", + /* U+2C27 */ "\xE2\xB0\xA7" => "\xE2\xB1\x97", + /* U+2C28 */ "\xE2\xB0\xA8" => "\xE2\xB1\x98", + /* U+2C29 */ "\xE2\xB0\xA9" => "\xE2\xB1\x99", + /* U+2C2A */ "\xE2\xB0\xAA" => "\xE2\xB1\x9A", + /* U+2C2B */ "\xE2\xB0\xAB" => "\xE2\xB1\x9B", + /* U+2C2C */ "\xE2\xB0\xAC" => "\xE2\xB1\x9C", + /* U+2C2D */ "\xE2\xB0\xAD" => "\xE2\xB1\x9D", + /* U+2C2E */ "\xE2\xB0\xAE" => "\xE2\xB1\x9E", + //------ U+2C80..U+2CFF : Coptic + /* U+2C80 */ "\xE2\xB2\x80" => "\xE2\xB2\x81", + /* U+2C82 */ "\xE2\xB2\x82" => "\xE2\xB2\x83", + /* U+2C84 */ "\xE2\xB2\x84" => "\xE2\xB2\x85", + /* U+2C86 */ "\xE2\xB2\x86" => "\xE2\xB2\x87", + /* U+2C88 */ "\xE2\xB2\x88" => "\xE2\xB2\x89", + /* U+2C8A */ "\xE2\xB2\x8A" => "\xE2\xB2\x8B", + /* U+2C8C */ "\xE2\xB2\x8C" => "\xE2\xB2\x8D", + /* U+2C8E */ "\xE2\xB2\x8E" => "\xE2\xB2\x8F", + /* U+2C90 */ "\xE2\xB2\x90" => "\xE2\xB2\x91", + /* U+2C92 */ "\xE2\xB2\x92" => "\xE2\xB2\x93", + /* U+2C94 */ "\xE2\xB2\x94" => "\xE2\xB2\x95", + /* U+2C96 */ "\xE2\xB2\x96" => "\xE2\xB2\x97", + /* U+2C98 */ "\xE2\xB2\x98" => "\xE2\xB2\x99", + /* U+2C9A */ "\xE2\xB2\x9A" => "\xE2\xB2\x9B", + /* U+2C9C */ "\xE2\xB2\x9C" => "\xE2\xB2\x9D", + /* U+2C9E */ "\xE2\xB2\x9E" => "\xE2\xB2\x9F", + /* U+2CA0 */ "\xE2\xB2\xA0" => "\xE2\xB2\xA1", + /* U+2CA2 */ "\xE2\xB2\xA2" => "\xE2\xB2\xA3", + /* U+2CA4 */ "\xE2\xB2\xA4" => "\xE2\xB2\xA5", + /* U+2CA6 */ "\xE2\xB2\xA6" => "\xE2\xB2\xA7", + /* U+2CA8 */ "\xE2\xB2\xA8" => "\xE2\xB2\xA9", + /* U+2CAA */ "\xE2\xB2\xAA" => "\xE2\xB2\xAB", + /* U+2CAC */ "\xE2\xB2\xAC" => "\xE2\xB2\xAD", + /* U+2CAE */ "\xE2\xB2\xAE" => "\xE2\xB2\xAF", + /* U+2CB0 */ "\xE2\xB2\xB0" => "\xE2\xB2\xB1", + /* U+2CB2 */ "\xE2\xB2\xB2" => "\xE2\xB2\xB3", + /* U+2CB4 */ "\xE2\xB2\xB4" => "\xE2\xB2\xB5", + /* U+2CB6 */ "\xE2\xB2\xB6" => "\xE2\xB2\xB7", + /* U+2CB8 */ "\xE2\xB2\xB8" => "\xE2\xB2\xB9", + /* U+2CBA */ "\xE2\xB2\xBA" => "\xE2\xB2\xBB", + /* U+2CBC */ "\xE2\xB2\xBC" => "\xE2\xB2\xBD", + /* U+2CBE */ "\xE2\xB2\xBE" => "\xE2\xB2\xBF", + /* U+2CC0 */ "\xE2\xB3\x80" => "\xE2\xB3\x81", + /* U+2CC2 */ "\xE2\xB3\x82" => "\xE2\xB3\x83", + /* U+2CC4 */ "\xE2\xB3\x84" => "\xE2\xB3\x85", + /* U+2CC6 */ "\xE2\xB3\x86" => "\xE2\xB3\x87", + /* U+2CC8 */ "\xE2\xB3\x88" => "\xE2\xB3\x89", + /* U+2CCA */ "\xE2\xB3\x8A" => "\xE2\xB3\x8B", + /* U+2CCC */ "\xE2\xB3\x8C" => "\xE2\xB3\x8D", + /* U+2CCE */ "\xE2\xB3\x8E" => "\xE2\xB3\x8F", + /* U+2CD0 */ "\xE2\xB3\x90" => "\xE2\xB3\x91", + /* U+2CD2 */ "\xE2\xB3\x92" => "\xE2\xB3\x93", + /* U+2CD4 */ "\xE2\xB3\x94" => "\xE2\xB3\x95", + /* U+2CD6 */ "\xE2\xB3\x96" => "\xE2\xB3\x97", + /* U+2CD8 */ "\xE2\xB3\x98" => "\xE2\xB3\x99", + /* U+2CDA */ "\xE2\xB3\x9A" => "\xE2\xB3\x9B", + /* U+2CDC */ "\xE2\xB3\x9C" => "\xE2\xB3\x9D", + /* U+2CDE */ "\xE2\xB3\x9E" => "\xE2\xB3\x9F", + /* U+2CE0 */ "\xE2\xB3\xA0" => "\xE2\xB3\xA1", + /* U+2CE2 */ "\xE2\xB3\xA2" => "\xE2\xB3\xA3", + //------ U+FB00..U+FB4F : Alphabetic Presentation Forms + /* U+FB1D */ "\xEF\xAC\x9D" => "\xD7\x99", + /* U+FB2A */ "\xEF\xAC\xAA" => "\xD7\xA9", + /* U+FB2B */ "\xEF\xAC\xAB" => "\xD7\xA9", + /* U+FB2C */ "\xEF\xAC\xAC" => "\xD7\xA9", + /* U+FB2D */ "\xEF\xAC\xAD" => "\xD7\xA9", + /* U+FB2E */ "\xEF\xAC\xAE" => "\xD7\x90", + /* U+FB2F */ "\xEF\xAC\xAF" => "\xD7\x90", + /* U+FB30 */ "\xEF\xAC\xB0" => "\xD7\x90", + /* U+FB31 */ "\xEF\xAC\xB1" => "\xD7\x91", + /* U+FB32 */ "\xEF\xAC\xB2" => "\xD7\x92", + /* U+FB33 */ "\xEF\xAC\xB3" => "\xD7\x93", + /* U+FB34 */ "\xEF\xAC\xB4" => "\xD7\x94", + /* U+FB35 */ "\xEF\xAC\xB5" => "\xD7\x95", + /* U+FB36 */ "\xEF\xAC\xB6" => "\xD7\x96", + /* U+FB38 */ "\xEF\xAC\xB8" => "\xD7\x98", + /* U+FB39 */ "\xEF\xAC\xB9" => "\xD7\x99", + /* U+FB3A */ "\xEF\xAC\xBA" => "\xD7\x9A", + /* U+FB3B */ "\xEF\xAC\xBB" => "\xD7\x9B", + /* U+FB3C */ "\xEF\xAC\xBC" => "\xD7\x9C", + /* U+FB3E */ "\xEF\xAC\xBE" => "\xD7\x9E", + /* U+FB40 */ "\xEF\xAD\x80" => "\xD7\xA0", + /* U+FB41 */ "\xEF\xAD\x81" => "\xD7\xA1", + /* U+FB43 */ "\xEF\xAD\x83" => "\xD7\xA3", + /* U+FB44 */ "\xEF\xAD\x84" => "\xD7\xA4", + /* U+FB46 */ "\xEF\xAD\x86" => "\xD7\xA6", + /* U+FB47 */ "\xEF\xAD\x87" => "\xD7\xA7", + /* U+FB48 */ "\xEF\xAD\x88" => "\xD7\xA8", + /* U+FB49 */ "\xEF\xAD\x89" => "\xD7\xA9", + /* U+FB4A */ "\xEF\xAD\x8A" => "\xD7\xAA", + /* U+FB4B */ "\xEF\xAD\x8B" => "\xD7\x95", + /* U+FB4C */ "\xEF\xAD\x8C" => "\xD7\x91", + /* U+FB4D */ "\xEF\xAD\x8D" => "\xD7\x9B", + /* U+FB4E */ "\xEF\xAD\x8E" => "\xD7\xA4", + //------ U+FF00..U+FFEF : Halfwidth and Fullwidth Forms + /* U+FF21 */ "\xEF\xBC\xA1" => "\xEF\xBD\x81", + /* U+FF22 */ "\xEF\xBC\xA2" => "\xEF\xBD\x82", + /* U+FF23 */ "\xEF\xBC\xA3" => "\xEF\xBD\x83", + /* U+FF24 */ "\xEF\xBC\xA4" => "\xEF\xBD\x84", + /* U+FF25 */ "\xEF\xBC\xA5" => "\xEF\xBD\x85", + /* U+FF26 */ "\xEF\xBC\xA6" => "\xEF\xBD\x86", + /* U+FF27 */ "\xEF\xBC\xA7" => "\xEF\xBD\x87", + /* U+FF28 */ "\xEF\xBC\xA8" => "\xEF\xBD\x88", + /* U+FF29 */ "\xEF\xBC\xA9" => "\xEF\xBD\x89", + /* U+FF2A */ "\xEF\xBC\xAA" => "\xEF\xBD\x8A", + /* U+FF2B */ "\xEF\xBC\xAB" => "\xEF\xBD\x8B", + /* U+FF2C */ "\xEF\xBC\xAC" => "\xEF\xBD\x8C", + /* U+FF2D */ "\xEF\xBC\xAD" => "\xEF\xBD\x8D", + /* U+FF2E */ "\xEF\xBC\xAE" => "\xEF\xBD\x8E", + /* U+FF2F */ "\xEF\xBC\xAF" => "\xEF\xBD\x8F", + /* U+FF30 */ "\xEF\xBC\xB0" => "\xEF\xBD\x90", + /* U+FF31 */ "\xEF\xBC\xB1" => "\xEF\xBD\x91", + /* U+FF32 */ "\xEF\xBC\xB2" => "\xEF\xBD\x92", + /* U+FF33 */ "\xEF\xBC\xB3" => "\xEF\xBD\x93", + /* U+FF34 */ "\xEF\xBC\xB4" => "\xEF\xBD\x94", + /* U+FF35 */ "\xEF\xBC\xB5" => "\xEF\xBD\x95", + /* U+FF36 */ "\xEF\xBC\xB6" => "\xEF\xBD\x96", + /* U+FF37 */ "\xEF\xBC\xB7" => "\xEF\xBD\x97", + /* U+FF38 */ "\xEF\xBC\xB8" => "\xEF\xBD\x98", + /* U+FF39 */ "\xEF\xBC\xB9" => "\xEF\xBD\x99", + /* U+FF3A */ "\xEF\xBC\xBA" => "\xEF\xBD\x9A", + //------ U+10400..U+1044F : Deseret + /* U+10400 */ "\xF0\x90\x90\x80" => "\xF0\x90\x90\xA8", + /* U+10401 */ "\xF0\x90\x90\x81" => "\xF0\x90\x90\xA9", + /* U+10402 */ "\xF0\x90\x90\x82" => "\xF0\x90\x90\xAA", + /* U+10403 */ "\xF0\x90\x90\x83" => "\xF0\x90\x90\xAB", + /* U+10404 */ "\xF0\x90\x90\x84" => "\xF0\x90\x90\xAC", + /* U+10405 */ "\xF0\x90\x90\x85" => "\xF0\x90\x90\xAD", + /* U+10406 */ "\xF0\x90\x90\x86" => "\xF0\x90\x90\xAE", + /* U+10407 */ "\xF0\x90\x90\x87" => "\xF0\x90\x90\xAF", + /* U+10408 */ "\xF0\x90\x90\x88" => "\xF0\x90\x90\xB0", + /* U+10409 */ "\xF0\x90\x90\x89" => "\xF0\x90\x90\xB1", + /* U+1040A */ "\xF0\x90\x90\x8A" => "\xF0\x90\x90\xB2", + /* U+1040B */ "\xF0\x90\x90\x8B" => "\xF0\x90\x90\xB3", + /* U+1040C */ "\xF0\x90\x90\x8C" => "\xF0\x90\x90\xB4", + /* U+1040D */ "\xF0\x90\x90\x8D" => "\xF0\x90\x90\xB5", + /* U+1040E */ "\xF0\x90\x90\x8E" => "\xF0\x90\x90\xB6", + /* U+1040F */ "\xF0\x90\x90\x8F" => "\xF0\x90\x90\xB7", + /* U+10410 */ "\xF0\x90\x90\x90" => "\xF0\x90\x90\xB8", + /* U+10411 */ "\xF0\x90\x90\x91" => "\xF0\x90\x90\xB9", + /* U+10412 */ "\xF0\x90\x90\x92" => "\xF0\x90\x90\xBA", + /* U+10413 */ "\xF0\x90\x90\x93" => "\xF0\x90\x90\xBB", + /* U+10414 */ "\xF0\x90\x90\x94" => "\xF0\x90\x90\xBC", + /* U+10415 */ "\xF0\x90\x90\x95" => "\xF0\x90\x90\xBD", + /* U+10416 */ "\xF0\x90\x90\x96" => "\xF0\x90\x90\xBE", + /* U+10417 */ "\xF0\x90\x90\x97" => "\xF0\x90\x90\xBF", + /* U+10418 */ "\xF0\x90\x90\x98" => "\xF0\x90\x91\x80", + /* U+10419 */ "\xF0\x90\x90\x99" => "\xF0\x90\x91\x81", + /* U+1041A */ "\xF0\x90\x90\x9A" => "\xF0\x90\x91\x82", + /* U+1041B */ "\xF0\x90\x90\x9B" => "\xF0\x90\x91\x83", + /* U+1041C */ "\xF0\x90\x90\x9C" => "\xF0\x90\x91\x84", + /* U+1041D */ "\xF0\x90\x90\x9D" => "\xF0\x90\x91\x85", + /* U+1041E */ "\xF0\x90\x90\x9E" => "\xF0\x90\x91\x86", + /* U+1041F */ "\xF0\x90\x90\x9F" => "\xF0\x90\x91\x87", + /* U+10420 */ "\xF0\x90\x90\xA0" => "\xF0\x90\x91\x88", + /* U+10421 */ "\xF0\x90\x90\xA1" => "\xF0\x90\x91\x89", + /* U+10422 */ "\xF0\x90\x90\xA2" => "\xF0\x90\x91\x8A", + /* U+10423 */ "\xF0\x90\x90\xA3" => "\xF0\x90\x91\x8B", + /* U+10424 */ "\xF0\x90\x90\xA4" => "\xF0\x90\x91\x8C", + /* U+10425 */ "\xF0\x90\x90\xA5" => "\xF0\x90\x91\x8D", + /* U+10426 */ "\xF0\x90\x90\xA6" => "\xF0\x90\x91\x8E", + /* U+10427 */ "\xF0\x90\x90\xA7" => "\xF0\x90\x91\x8F" + ); + protected $endCharacters_utf8 = "\t\r\n !\"#\$%&'()+,-./:;<=>@[\]^_`{|}~£§¨°"; - protected $map = array( - //------ U+0000..U+007F : Basic Latin - /* U+0041 */ "\x41" => "\x61", - /* U+0042 */ "\x42" => "\x62", - /* U+0043 */ "\x43" => "\x63", - /* U+0044 */ "\x44" => "\x64", - /* U+0045 */ "\x45" => "\x65", - /* U+0046 */ "\x46" => "\x66", - /* U+0047 */ "\x47" => "\x67", - /* U+0048 */ "\x48" => "\x68", - /* U+0049 */ "\x49" => "\x69", - /* U+004A */ "\x4A" => "\x6A", - /* U+004B */ "\x4B" => "\x6B", - /* U+004C */ "\x4C" => "\x6C", - /* U+004D */ "\x4D" => "\x6D", - /* U+004E */ "\x4E" => "\x6E", - /* U+004F */ "\x4F" => "\x6F", - /* U+0050 */ "\x50" => "\x70", - /* U+0051 */ "\x51" => "\x71", - /* U+0052 */ "\x52" => "\x72", - /* U+0053 */ "\x53" => "\x73", - /* U+0054 */ "\x54" => "\x74", - /* U+0055 */ "\x55" => "\x75", - /* U+0056 */ "\x56" => "\x76", - /* U+0057 */ "\x57" => "\x77", - /* U+0058 */ "\x58" => "\x78", - /* U+0059 */ "\x59" => "\x79", - /* U+005A */ "\x5A" => "\x7A", - //------ U+0080..U+00FF : Latin-1 Supplement - /* U+00C0 */ "\xC3\x80" => "\x61", - /* U+00C1 */ "\xC3\x81" => "\x61", - /* U+00C2 */ "\xC3\x82" => "\x61", - /* U+00C3 */ "\xC3\x83" => "\x61", - /* U+00C4 */ "\xC3\x84" => "\x61", - /* U+00C5 */ "\xC3\x85" => "\x61", - /* U+00C6 */ "\xC3\x86" => "\xC3\xA6", - /* U+00C7 */ "\xC3\x87" => "\x63", - /* U+00C8 */ "\xC3\x88" => "\x65", - /* U+00C9 */ "\xC3\x89" => "\x65", - /* U+00CA */ "\xC3\x8A" => "\x65", - /* U+00CB */ "\xC3\x8B" => "\x65", - /* U+00CC */ "\xC3\x8C" => "\x69", - /* U+00CD */ "\xC3\x8D" => "\x69", - /* U+00CE */ "\xC3\x8E" => "\x69", - /* U+00CF */ "\xC3\x8F" => "\x69", - /* U+00D0 */ "\xC3\x90" => "\xC3\xB0", - /* U+00D1 */ "\xC3\x91" => "\x6E", - /* U+00D2 */ "\xC3\x92" => "\x6F", - /* U+00D3 */ "\xC3\x93" => "\x6F", - /* U+00D4 */ "\xC3\x94" => "\x6F", - /* U+00D5 */ "\xC3\x95" => "\x6F", - /* U+00D6 */ "\xC3\x96" => "\x6F", - /* U+00D8 */ "\xC3\x98" => "\x6F", - /* U+00D9 */ "\xC3\x99" => "\x75", - /* U+00DA */ "\xC3\x9A" => "\x75", - /* U+00DB */ "\xC3\x9B" => "\x75", - /* U+00DC */ "\xC3\x9C" => "\x75", - /* U+00DD */ "\xC3\x9D" => "\x79", - /* U+00DE */ "\xC3\x9E" => "\xC3\xBE", - /* U+00E0 */ "\xC3\xA0" => "\x61", - /* U+00E1 */ "\xC3\xA1" => "\x61", - /* U+00E2 */ "\xC3\xA2" => "\x61", - /* U+00E3 */ "\xC3\xA3" => "\x61", - /* U+00E4 */ "\xC3\xA4" => "\x61", - /* U+00E5 */ "\xC3\xA5" => "\x61", - /* U+00E7 */ "\xC3\xA7" => "\x63", - /* U+00E8 */ "\xC3\xA8" => "\x65", - /* U+00E9 */ "\xC3\xA9" => "\x65", - /* U+00EA */ "\xC3\xAA" => "\x65", - /* U+00EB */ "\xC3\xAB" => "\x65", - /* U+00EC */ "\xC3\xAC" => "\x69", - /* U+00ED */ "\xC3\xAD" => "\x69", - /* U+00EE */ "\xC3\xAE" => "\x69", - /* U+00EF */ "\xC3\xAF" => "\x69", - /* U+00F1 */ "\xC3\xB1" => "\x6E", - /* U+00F2 */ "\xC3\xB2" => "\x6F", - /* U+00F3 */ "\xC3\xB3" => "\x6F", - /* U+00F4 */ "\xC3\xB4" => "\x6F", - /* U+00F5 */ "\xC3\xB5" => "\x6F", - /* U+00F6 */ "\xC3\xB6" => "\x6F", - /* U+00F8 */ "\xC3\xB8" => "\x6F", - /* U+00F9 */ "\xC3\xB9" => "\x75", - /* U+00FA */ "\xC3\xBA" => "\x75", - /* U+00FB */ "\xC3\xBB" => "\x75", - /* U+00FC */ "\xC3\xBC" => "\x75", - /* U+00FD */ "\xC3\xBD" => "\x79", - /* U+00FF */ "\xC3\xBF" => "\x79", - //------ U+0100..U+017F : Latin Extended-A - /* U+0100 */ "\xC4\x80" => "\x61", - /* U+0101 */ "\xC4\x81" => "\x61", - /* U+0102 */ "\xC4\x82" => "\x61", - /* U+0103 */ "\xC4\x83" => "\x61", - /* U+0104 */ "\xC4\x84" => "\x61", - /* U+0105 */ "\xC4\x85" => "\x61", - /* U+0106 */ "\xC4\x86" => "\x63", - /* U+0107 */ "\xC4\x87" => "\x63", - /* U+0108 */ "\xC4\x88" => "\x63", - /* U+0109 */ "\xC4\x89" => "\x63", - /* U+010A */ "\xC4\x8A" => "\x63", - /* U+010B */ "\xC4\x8B" => "\x63", - /* U+010C */ "\xC4\x8C" => "\x63", - /* U+010D */ "\xC4\x8D" => "\x63", - /* U+010E */ "\xC4\x8E" => "\x64", - /* U+010F */ "\xC4\x8F" => "\x64", - /* U+0110 */ "\xC4\x90" => "\x64", - /* U+0111 */ "\xC4\x91" => "\x64", - /* U+0112 */ "\xC4\x92" => "\x65", - /* U+0113 */ "\xC4\x93" => "\x65", - /* U+0114 */ "\xC4\x94" => "\x65", - /* U+0115 */ "\xC4\x95" => "\x65", - /* U+0116 */ "\xC4\x96" => "\x65", - /* U+0117 */ "\xC4\x97" => "\x65", - /* U+0118 */ "\xC4\x98" => "\x65", - /* U+0119 */ "\xC4\x99" => "\x65", - /* U+011A */ "\xC4\x9A" => "\x65", - /* U+011B */ "\xC4\x9B" => "\x65", - /* U+011C */ "\xC4\x9C" => "\x67", - /* U+011D */ "\xC4\x9D" => "\x67", - /* U+011E */ "\xC4\x9E" => "\x67", - /* U+011F */ "\xC4\x9F" => "\x67", - /* U+0120 */ "\xC4\xA0" => "\x67", - /* U+0121 */ "\xC4\xA1" => "\x67", - /* U+0122 */ "\xC4\xA2" => "\x67", - /* U+0123 */ "\xC4\xA3" => "\x67", - /* U+0124 */ "\xC4\xA4" => "\x68", - /* U+0125 */ "\xC4\xA5" => "\x68", - /* U+0126 */ "\xC4\xA6" => "\x68", - /* U+0127 */ "\xC4\xA7" => "\x68", - /* U+0128 */ "\xC4\xA8" => "\x69", - /* U+0129 */ "\xC4\xA9" => "\x69", - /* U+012A */ "\xC4\xAA" => "\x69", - /* U+012B */ "\xC4\xAB" => "\x69", - /* U+012C */ "\xC4\xAC" => "\x69", - /* U+012D */ "\xC4\xAD" => "\x69", - /* U+012E */ "\xC4\xAE" => "\x69", - /* U+012F */ "\xC4\xAF" => "\x69", - /* U+0130 */ "\xC4\xB0" => "\x69", - /* U+0132 */ "\xC4\xB2" => "\xC4\xB3", - /* U+0134 */ "\xC4\xB4" => "\x6A", - /* U+0135 */ "\xC4\xB5" => "\x6A", - /* U+0136 */ "\xC4\xB6" => "\x6B", - /* U+0137 */ "\xC4\xB7" => "\x6B", - /* U+0139 */ "\xC4\xB9" => "\x6C", - /* U+013A */ "\xC4\xBA" => "\x6C", - /* U+013B */ "\xC4\xBB" => "\x6C", - /* U+013C */ "\xC4\xBC" => "\x6C", - /* U+013D */ "\xC4\xBD" => "\x6C", - /* U+013E */ "\xC4\xBE" => "\x6C", - /* U+013F */ "\xC4\xBF" => "\x6C", - /* U+0140 */ "\xC5\x80" => "\x6C", - /* U+0141 */ "\xC5\x81" => "\x6C", - /* U+0142 */ "\xC5\x82" => "\x6C", - /* U+0143 */ "\xC5\x83" => "\x6E", - /* U+0144 */ "\xC5\x84" => "\x6E", - /* U+0145 */ "\xC5\x85" => "\x6E", - /* U+0146 */ "\xC5\x86" => "\x6E", - /* U+0147 */ "\xC5\x87" => "\x6E", - /* U+0148 */ "\xC5\x88" => "\x6E", - /* U+014A */ "\xC5\x8A" => "\xC5\x8B", - /* U+014C */ "\xC5\x8C" => "\x6F", - /* U+014D */ "\xC5\x8D" => "\x6F", - /* U+014E */ "\xC5\x8E" => "\x6F", - /* U+014F */ "\xC5\x8F" => "\x6F", - /* U+0150 */ "\xC5\x90" => "\x6F", - /* U+0151 */ "\xC5\x91" => "\x6F", - /* U+0152 */ "\xC5\x92" => "\xC5\x93", - /* U+0154 */ "\xC5\x94" => "\x72", - /* U+0155 */ "\xC5\x95" => "\x72", - /* U+0156 */ "\xC5\x96" => "\x72", - /* U+0157 */ "\xC5\x97" => "\x72", - /* U+0158 */ "\xC5\x98" => "\x72", - /* U+0159 */ "\xC5\x99" => "\x72", - /* U+015A */ "\xC5\x9A" => "\x73", - /* U+015B */ "\xC5\x9B" => "\x73", - /* U+015C */ "\xC5\x9C" => "\x73", - /* U+015D */ "\xC5\x9D" => "\x73", - /* U+015E */ "\xC5\x9E" => "\x73", - /* U+015F */ "\xC5\x9F" => "\x73", - /* U+0160 */ "\xC5\xA0" => "\x73", - /* U+0161 */ "\xC5\xA1" => "\x73", - /* U+0162 */ "\xC5\xA2" => "\x74", - /* U+0163 */ "\xC5\xA3" => "\x74", - /* U+0164 */ "\xC5\xA4" => "\x74", - /* U+0165 */ "\xC5\xA5" => "\x74", - /* U+0166 */ "\xC5\xA6" => "\x74", - /* U+0167 */ "\xC5\xA7" => "\x74", - /* U+0168 */ "\xC5\xA8" => "\x75", - /* U+0169 */ "\xC5\xA9" => "\x75", - /* U+016A */ "\xC5\xAA" => "\x75", - /* U+016B */ "\xC5\xAB" => "\x75", - /* U+016C */ "\xC5\xAC" => "\x75", - /* U+016D */ "\xC5\xAD" => "\x75", - /* U+016E */ "\xC5\xAE" => "\x75", - /* U+016F */ "\xC5\xAF" => "\x75", - /* U+0170 */ "\xC5\xB0" => "\x75", - /* U+0171 */ "\xC5\xB1" => "\x75", - /* U+0172 */ "\xC5\xB2" => "\x75", - /* U+0173 */ "\xC5\xB3" => "\x75", - /* U+0174 */ "\xC5\xB4" => "\x77", - /* U+0175 */ "\xC5\xB5" => "\x77", - /* U+0176 */ "\xC5\xB6" => "\x79", - /* U+0177 */ "\xC5\xB7" => "\x79", - /* U+0178 */ "\xC5\xB8" => "\x79", - /* U+0179 */ "\xC5\xB9" => "\x7A", - /* U+017A */ "\xC5\xBA" => "\x7A", - /* U+017B */ "\xC5\xBB" => "\x7A", - /* U+017C */ "\xC5\xBC" => "\x7A", - /* U+017D */ "\xC5\xBD" => "\x7A", - /* U+017E */ "\xC5\xBE" => "\x7A", - //------ U+0180..U+024F : Latin Extended-B - /* U+0180 */ "\xC6\x80" => "\x62", - /* U+0181 */ "\xC6\x81" => "\x62", - /* U+0182 */ "\xC6\x82" => "\x62", - /* U+0183 */ "\xC6\x83" => "\x62", - /* U+0184 */ "\xC6\x84" => "\xC6\x85", - /* U+0186 */ "\xC6\x86" => "\xC9\x94", - /* U+0187 */ "\xC6\x87" => "\x63", - /* U+0188 */ "\xC6\x88" => "\x63", - /* U+0189 */ "\xC6\x89" => "\x64", - /* U+018A */ "\xC6\x8A" => "\x64", - /* U+018B */ "\xC6\x8B" => "\x64", - /* U+018C */ "\xC6\x8C" => "\x64", - /* U+018E */ "\xC6\x8E" => "\xC7\x9D", - /* U+018F */ "\xC6\x8F" => "\xC9\x99", - /* U+0190 */ "\xC6\x90" => "\xC9\x9B", - /* U+0191 */ "\xC6\x91" => "\x66", - /* U+0192 */ "\xC6\x92" => "\x66", - /* U+0193 */ "\xC6\x93" => "\x67", - /* U+0194 */ "\xC6\x94" => "\xC9\xA3", - /* U+0196 */ "\xC6\x96" => "\xC9\xA9", - /* U+0197 */ "\xC6\x97" => "\x69", - /* U+0198 */ "\xC6\x98" => "\x6B", - /* U+0199 */ "\xC6\x99" => "\x6B", - /* U+019A */ "\xC6\x9A" => "\x6C", - /* U+019C */ "\xC6\x9C" => "\xC9\xAF", - /* U+019D */ "\xC6\x9D" => "\x6E", - /* U+019E */ "\xC6\x9E" => "\x6E", - /* U+019F */ "\xC6\x9F" => "\xC9\xB5", - /* U+01A0 */ "\xC6\xA0" => "\x6F", - /* U+01A1 */ "\xC6\xA1" => "\x6F", - /* U+01A2 */ "\xC6\xA2" => "\xC6\xA3", - /* U+01A4 */ "\xC6\xA4" => "\x70", - /* U+01A5 */ "\xC6\xA5" => "\x70", - /* U+01A6 */ "\xC6\xA6" => "\xCA\x80", - /* U+01A7 */ "\xC6\xA7" => "\xC6\xA8", - /* U+01A9 */ "\xC6\xA9" => "\xCA\x83", - /* U+01AB */ "\xC6\xAB" => "\x74", - /* U+01AC */ "\xC6\xAC" => "\x74", - /* U+01AD */ "\xC6\xAD" => "\x74", - /* U+01AE */ "\xC6\xAE" => "\x74", - /* U+01AF */ "\xC6\xAF" => "\x75", - /* U+01B0 */ "\xC6\xB0" => "\x75", - /* U+01B1 */ "\xC6\xB1" => "\xCA\x8A", - /* U+01B2 */ "\xC6\xB2" => "\x76", - /* U+01B3 */ "\xC6\xB3" => "\x79", - /* U+01B4 */ "\xC6\xB4" => "\x79", - /* U+01B5 */ "\xC6\xB5" => "\x7A", - /* U+01B6 */ "\xC6\xB6" => "\x7A", - /* U+01B7 */ "\xC6\xB7" => "\xCA\x92", - /* U+01B8 */ "\xC6\xB8" => "\xC6\xB9", - /* U+01BA */ "\xC6\xBA" => "\xCA\x92", - /* U+01BC */ "\xC6\xBC" => "\xC6\xBD", - /* U+01C4 */ "\xC7\x84" => "\xC7\x86", - /* U+01C5 */ "\xC7\x85" => "\xC7\x86", - /* U+01C7 */ "\xC7\x87" => "\xC7\x89", - /* U+01C8 */ "\xC7\x88" => "\xC7\x89", - /* U+01CA */ "\xC7\x8A" => "\xC7\x8C", - /* U+01CB */ "\xC7\x8B" => "\xC7\x8C", - /* U+01CD */ "\xC7\x8D" => "\x61", - /* U+01CE */ "\xC7\x8E" => "\x61", - /* U+01CF */ "\xC7\x8F" => "\x69", - /* U+01D0 */ "\xC7\x90" => "\x69", - /* U+01D1 */ "\xC7\x91" => "\x6F", - /* U+01D2 */ "\xC7\x92" => "\x6F", - /* U+01D3 */ "\xC7\x93" => "\x75", - /* U+01D4 */ "\xC7\x94" => "\x75", - /* U+01D5 */ "\xC7\x95" => "\x75", - /* U+01D6 */ "\xC7\x96" => "\x75", - /* U+01D7 */ "\xC7\x97" => "\x75", - /* U+01D8 */ "\xC7\x98" => "\x75", - /* U+01D9 */ "\xC7\x99" => "\x75", - /* U+01DA */ "\xC7\x9A" => "\x75", - /* U+01DB */ "\xC7\x9B" => "\x75", - /* U+01DC */ "\xC7\x9C" => "\x75", - /* U+01DE */ "\xC7\x9E" => "\x61", - /* U+01DF */ "\xC7\x9F" => "\x61", - /* U+01E0 */ "\xC7\xA0" => "\x61", - /* U+01E1 */ "\xC7\xA1" => "\x61", - /* U+01E2 */ "\xC7\xA2" => "\xC3\xA6", - /* U+01E3 */ "\xC7\xA3" => "\xC3\xA6", - /* U+01E4 */ "\xC7\xA4" => "\x67", - /* U+01E5 */ "\xC7\xA5" => "\x67", - /* U+01E6 */ "\xC7\xA6" => "\x67", - /* U+01E7 */ "\xC7\xA7" => "\x67", - /* U+01E8 */ "\xC7\xA8" => "\x6B", - /* U+01E9 */ "\xC7\xA9" => "\x6B", - /* U+01EA */ "\xC7\xAA" => "\x6F", - /* U+01EB */ "\xC7\xAB" => "\x6F", - /* U+01EC */ "\xC7\xAC" => "\x6F", - /* U+01ED */ "\xC7\xAD" => "\x6F", - /* U+01EE */ "\xC7\xAE" => "\xCA\x92", - /* U+01EF */ "\xC7\xAF" => "\xCA\x92", - /* U+01F0 */ "\xC7\xB0" => "\x6A", - /* U+01F1 */ "\xC7\xB1" => "\xC7\xB3", - /* U+01F2 */ "\xC7\xB2" => "\xC7\xB3", - /* U+01F4 */ "\xC7\xB4" => "\x67", - /* U+01F5 */ "\xC7\xB5" => "\x67", - /* U+01F6 */ "\xC7\xB6" => "\xC6\x95", - /* U+01F7 */ "\xC7\xB7" => "\xC6\xBF", - /* U+01F8 */ "\xC7\xB8" => "\x6E", - /* U+01F9 */ "\xC7\xB9" => "\x6E", - /* U+01FA */ "\xC7\xBA" => "\x61", - /* U+01FB */ "\xC7\xBB" => "\x61", - /* U+01FC */ "\xC7\xBC" => "\xC3\xA6", - /* U+01FD */ "\xC7\xBD" => "\xC3\xA6", - /* U+01FE */ "\xC7\xBE" => "\x6F", - /* U+01FF */ "\xC7\xBF" => "\x6F", - /* U+0200 */ "\xC8\x80" => "\x61", - /* U+0201 */ "\xC8\x81" => "\x61", - /* U+0202 */ "\xC8\x82" => "\x61", - /* U+0203 */ "\xC8\x83" => "\x61", - /* U+0204 */ "\xC8\x84" => "\x65", - /* U+0205 */ "\xC8\x85" => "\x65", - /* U+0206 */ "\xC8\x86" => "\x65", - /* U+0207 */ "\xC8\x87" => "\x65", - /* U+0208 */ "\xC8\x88" => "\x69", - /* U+0209 */ "\xC8\x89" => "\x69", - /* U+020A */ "\xC8\x8A" => "\x69", - /* U+020B */ "\xC8\x8B" => "\x69", - /* U+020C */ "\xC8\x8C" => "\x6F", - /* U+020D */ "\xC8\x8D" => "\x6F", - /* U+020E */ "\xC8\x8E" => "\x6F", - /* U+020F */ "\xC8\x8F" => "\x6F", - /* U+0210 */ "\xC8\x90" => "\x72", - /* U+0211 */ "\xC8\x91" => "\x72", - /* U+0212 */ "\xC8\x92" => "\x72", - /* U+0213 */ "\xC8\x93" => "\x72", - /* U+0214 */ "\xC8\x94" => "\x75", - /* U+0215 */ "\xC8\x95" => "\x75", - /* U+0216 */ "\xC8\x96" => "\x75", - /* U+0217 */ "\xC8\x97" => "\x75", - /* U+0218 */ "\xC8\x98" => "\x73", - /* U+0219 */ "\xC8\x99" => "\x73", - /* U+021A */ "\xC8\x9A" => "\x74", - /* U+021B */ "\xC8\x9B" => "\x74", - /* U+021C */ "\xC8\x9C" => "\xC8\x9D", - /* U+021E */ "\xC8\x9E" => "\x68", - /* U+021F */ "\xC8\x9F" => "\x68", - /* U+0220 */ "\xC8\xA0" => "\x6E", - /* U+0221 */ "\xC8\xA1" => "\x64", - /* U+0222 */ "\xC8\xA2" => "\xC8\xA3", - /* U+0224 */ "\xC8\xA4" => "\x7A", - /* U+0225 */ "\xC8\xA5" => "\x7A", - /* U+0226 */ "\xC8\xA6" => "\x61", - /* U+0227 */ "\xC8\xA7" => "\x61", - /* U+0228 */ "\xC8\xA8" => "\x65", - /* U+0229 */ "\xC8\xA9" => "\x65", - /* U+022A */ "\xC8\xAA" => "\x6F", - /* U+022B */ "\xC8\xAB" => "\x6F", - /* U+022C */ "\xC8\xAC" => "\x6F", - /* U+022D */ "\xC8\xAD" => "\x6F", - /* U+022E */ "\xC8\xAE" => "\x6F", - /* U+022F */ "\xC8\xAF" => "\x6F", - /* U+0230 */ "\xC8\xB0" => "\x6F", - /* U+0231 */ "\xC8\xB1" => "\x6F", - /* U+0232 */ "\xC8\xB2" => "\x79", - /* U+0233 */ "\xC8\xB3" => "\x79", - /* U+0234 */ "\xC8\xB4" => "\x6C", - /* U+0235 */ "\xC8\xB5" => "\x6E", - /* U+0236 */ "\xC8\xB6" => "\x74", - /* U+023B */ "\xC8\xBB" => "\xC8\xBC", - /* U+023D */ "\xC8\xBD" => "\x6C", - /* U+0241 */ "\xC9\x81" => "\xCA\x94", - //------ U+0370..U+03FF : Greek and Coptic - /* U+0386 */ "\xCE\x86" => "\xCE\xB1", - /* U+0388 */ "\xCE\x88" => "\xCE\xB5", - /* U+0389 */ "\xCE\x89" => "\xCE\xB7", - /* U+038A */ "\xCE\x8A" => "\xCE\xB9", - /* U+038C */ "\xCE\x8C" => "\xCE\xBF", - /* U+038E */ "\xCE\x8E" => "\xCF\x85", - /* U+038F */ "\xCE\x8F" => "\xCF\x89", - /* U+0390 */ "\xCE\x90" => "\xCE\xB9", - /* U+0391 */ "\xCE\x91" => "\xCE\xB1", - /* U+0392 */ "\xCE\x92" => "\xCE\xB2", - /* U+0393 */ "\xCE\x93" => "\xCE\xB3", - /* U+0394 */ "\xCE\x94" => "\xCE\xB4", - /* U+0395 */ "\xCE\x95" => "\xCE\xB5", - /* U+0396 */ "\xCE\x96" => "\xCE\xB6", - /* U+0397 */ "\xCE\x97" => "\xCE\xB7", - /* U+0398 */ "\xCE\x98" => "\xCE\xB8", - /* U+0399 */ "\xCE\x99" => "\xCE\xB9", - /* U+039A */ "\xCE\x9A" => "\xCE\xBA", - /* U+039B */ "\xCE\x9B" => "\xCE\xBB", - /* U+039C */ "\xCE\x9C" => "\xCE\xBC", - /* U+039D */ "\xCE\x9D" => "\xCE\xBD", - /* U+039E */ "\xCE\x9E" => "\xCE\xBE", - /* U+039F */ "\xCE\x9F" => "\xCE\xBF", - /* U+03A0 */ "\xCE\xA0" => "\xCF\x80", - /* U+03A1 */ "\xCE\xA1" => "\xCF\x81", - /* U+03A3 */ "\xCE\xA3" => "\xCF\x83", - /* U+03A4 */ "\xCE\xA4" => "\xCF\x84", - /* U+03A5 */ "\xCE\xA5" => "\xCF\x85", - /* U+03A6 */ "\xCE\xA6" => "\xCF\x86", - /* U+03A7 */ "\xCE\xA7" => "\xCF\x87", - /* U+03A8 */ "\xCE\xA8" => "\xCF\x88", - /* U+03A9 */ "\xCE\xA9" => "\xCF\x89", - /* U+03AA */ "\xCE\xAA" => "\xCE\xB9", - /* U+03AB */ "\xCE\xAB" => "\xCF\x85", - /* U+03AC */ "\xCE\xAC" => "\xCE\xB1", - /* U+03AD */ "\xCE\xAD" => "\xCE\xB5", - /* U+03AE */ "\xCE\xAE" => "\xCE\xB7", - /* U+03AF */ "\xCE\xAF" => "\xCE\xB9", - /* U+03B0 */ "\xCE\xB0" => "\xCF\x85", - /* U+03CA */ "\xCF\x8A" => "\xCE\xB9", - /* U+03CB */ "\xCF\x8B" => "\xCF\x85", - /* U+03CC */ "\xCF\x8C" => "\xCE\xBF", - /* U+03CD */ "\xCF\x8D" => "\xCF\x85", - /* U+03CE */ "\xCF\x8E" => "\xCF\x89", - /* U+03D8 */ "\xCF\x98" => "\xCF\x99", - /* U+03DA */ "\xCF\x9A" => "\xCF\x9B", - /* U+03DC */ "\xCF\x9C" => "\xCF\x9D", - /* U+03DE */ "\xCF\x9E" => "\xCF\x9F", - /* U+03E0 */ "\xCF\xA0" => "\xCF\xA1", - /* U+03E2 */ "\xCF\xA2" => "\xCF\xA3", - /* U+03E4 */ "\xCF\xA4" => "\xCF\xA5", - /* U+03E6 */ "\xCF\xA6" => "\xCF\xA7", - /* U+03E8 */ "\xCF\xA8" => "\xCF\xA9", - /* U+03EA */ "\xCF\xAA" => "\xCF\xAB", - /* U+03EC */ "\xCF\xAC" => "\xCF\xAD", - /* U+03EE */ "\xCF\xAE" => "\xCF\xAF", - /* U+03F4 */ "\xCF\xB4" => "\xCE\xB8", - /* U+03F7 */ "\xCF\xB7" => "\xCF\xB8", - /* U+03F9 */ "\xCF\xB9" => "\xCF\xB2", - /* U+03FA */ "\xCF\xBA" => "\xCF\xBB", - //------ U+0400..U+04FF : Cyrillic - /* U+0400 */ "\xD0\x80" => "\xD0\xB5", - /* U+0401 */ "\xD0\x81" => "\xD1\x91", - /* U+0402 */ "\xD0\x82" => "\xD1\x92", - /* U+0403 */ "\xD0\x83" => "\xD1\x93", - /* U+0404 */ "\xD0\x84" => "\xD1\x94", - /* U+0405 */ "\xD0\x85" => "\xD1\x95", - /* U+0406 */ "\xD0\x86" => "\xD1\x96", - /* U+0407 */ "\xD0\x87" => "\xD1\x97", - /* U+0408 */ "\xD0\x88" => "\xD1\x98", - /* U+0409 */ "\xD0\x89" => "\xD1\x99", - /* U+040A */ "\xD0\x8A" => "\xD1\x9A", - /* U+040B */ "\xD0\x8B" => "\xD1\x9B", - /* U+040C */ "\xD0\x8C" => "\xD1\x9C", - /* U+040D */ "\xD0\x8D" => "\xD0\xB8", - /* U+040E */ "\xD0\x8E" => "\xD1\x9E", - /* U+040F */ "\xD0\x8F" => "\xD1\x9F", - /* U+0410 */ "\xD0\x90" => "\xD0\xB0", - /* U+0411 */ "\xD0\x91" => "\xD0\xB1", - /* U+0412 */ "\xD0\x92" => "\xD0\xB2", - /* U+0413 */ "\xD0\x93" => "\xD0\xB3", - /* U+0414 */ "\xD0\x94" => "\xD0\xB4", - /* U+0415 */ "\xD0\x95" => "\xD0\xB5", - /* U+0416 */ "\xD0\x96" => "\xD0\xB6", - /* U+0417 */ "\xD0\x97" => "\xD0\xB7", - /* U+0418 */ "\xD0\x98" => "\xD0\xB8", - /* U+0419 */ "\xD0\x99" => "\xD0\xB9", - /* U+041A */ "\xD0\x9A" => "\xD0\xBA", - /* U+041B */ "\xD0\x9B" => "\xD0\xBB", - /* U+041C */ "\xD0\x9C" => "\xD0\xBC", - /* U+041D */ "\xD0\x9D" => "\xD0\xBD", - /* U+041E */ "\xD0\x9E" => "\xD0\xBE", - /* U+041F */ "\xD0\x9F" => "\xD0\xBF", - /* U+0420 */ "\xD0\xA0" => "\xD1\x80", - /* U+0421 */ "\xD0\xA1" => "\xD1\x81", - /* U+0422 */ "\xD0\xA2" => "\xD1\x82", - /* U+0423 */ "\xD0\xA3" => "\xD1\x83", - /* U+0424 */ "\xD0\xA4" => "\xD1\x84", - /* U+0425 */ "\xD0\xA5" => "\xD1\x85", - /* U+0426 */ "\xD0\xA6" => "\xD1\x86", - /* U+0427 */ "\xD0\xA7" => "\xD1\x87", - /* U+0428 */ "\xD0\xA8" => "\xD1\x88", - /* U+0429 */ "\xD0\xA9" => "\xD1\x89", - /* U+042A */ "\xD0\xAA" => "\xD1\x8A", - /* U+042B */ "\xD0\xAB" => "\xD1\x8B", - /* U+042C */ "\xD0\xAC" => "\xD1\x8C", - /* U+042D */ "\xD0\xAD" => "\xD1\x8D", - /* U+042E */ "\xD0\xAE" => "\xD1\x8E", - /* U+042F */ "\xD0\xAF" => "\xD1\x8F", - /* U+0450 */ "\xD1\x90" => "\xD0\xB5", - /* U+045D */ "\xD1\x9D" => "\xD0\xB8", - /* U+0460 */ "\xD1\xA0" => "\xD1\xA1", - /* U+0462 */ "\xD1\xA2" => "\xD1\xA3", - /* U+0464 */ "\xD1\xA4" => "\xD1\xA5", - /* U+0466 */ "\xD1\xA6" => "\xD1\xA7", - /* U+0468 */ "\xD1\xA8" => "\xD1\xA9", - /* U+046A */ "\xD1\xAA" => "\xD1\xAB", - /* U+046C */ "\xD1\xAC" => "\xD1\xAD", - /* U+046E */ "\xD1\xAE" => "\xD1\xAF", - /* U+0470 */ "\xD1\xB0" => "\xD1\xB1", - /* U+0472 */ "\xD1\xB2" => "\xD1\xB3", - /* U+0474 */ "\xD1\xB4" => "\xD1\xB5", - /* U+0476 */ "\xD1\xB6" => "\xD1\xB5", - /* U+0477 */ "\xD1\xB7" => "\xD1\xB5", - /* U+0478 */ "\xD1\xB8" => "\xD1\xB9", - /* U+047A */ "\xD1\xBA" => "\xD1\xBB", - /* U+047C */ "\xD1\xBC" => "\xD1\xA1", - /* U+047D */ "\xD1\xBD" => "\xD1\xA1", - /* U+047E */ "\xD1\xBE" => "\xD1\xBF", - /* U+0480 */ "\xD2\x80" => "\xD2\x81", - /* U+048A */ "\xD2\x8A" => "\xD0\xB9", - /* U+048B */ "\xD2\x8B" => "\xD0\xB9", - /* U+048C */ "\xD2\x8C" => "\xD2\x8D", - /* U+048E */ "\xD2\x8E" => "\xD1\x80", - /* U+048F */ "\xD2\x8F" => "\xD1\x80", - /* U+0490 */ "\xD2\x90" => "\xD0\xB3", - /* U+0491 */ "\xD2\x91" => "\xD0\xB3", - /* U+0492 */ "\xD2\x92" => "\xD0\xB3", - /* U+0493 */ "\xD2\x93" => "\xD0\xB3", - /* U+0494 */ "\xD2\x94" => "\xD0\xB3", - /* U+0495 */ "\xD2\x95" => "\xD0\xB3", - /* U+0496 */ "\xD2\x96" => "\xD0\xB6", - /* U+0497 */ "\xD2\x97" => "\xD0\xB6", - /* U+0498 */ "\xD2\x98" => "\xD0\xB7", - /* U+0499 */ "\xD2\x99" => "\xD0\xB7", - /* U+049A */ "\xD2\x9A" => "\xD0\xBA", - /* U+049B */ "\xD2\x9B" => "\xD0\xBA", - /* U+049C */ "\xD2\x9C" => "\xD0\xBA", - /* U+049D */ "\xD2\x9D" => "\xD0\xBA", - /* U+049E */ "\xD2\x9E" => "\xD0\xBA", - /* U+049F */ "\xD2\x9F" => "\xD0\xBA", - /* U+04A0 */ "\xD2\xA0" => "\xD2\xA1", - /* U+04A2 */ "\xD2\xA2" => "\xD0\xBD", - /* U+04A3 */ "\xD2\xA3" => "\xD0\xBD", - /* U+04A4 */ "\xD2\xA4" => "\xD2\xA5", - /* U+04A6 */ "\xD2\xA6" => "\xD0\xBF", - /* U+04A7 */ "\xD2\xA7" => "\xD0\xBF", - /* U+04A8 */ "\xD2\xA8" => "\xD2\xA9", - /* U+04AA */ "\xD2\xAA" => "\xD1\x81", - /* U+04AB */ "\xD2\xAB" => "\xD1\x81", - /* U+04AC */ "\xD2\xAC" => "\xD1\x82", - /* U+04AD */ "\xD2\xAD" => "\xD1\x82", - /* U+04AE */ "\xD2\xAE" => "\xD2\xAF", - /* U+04B0 */ "\xD2\xB0" => "\xD2\xAF", - /* U+04B1 */ "\xD2\xB1" => "\xD2\xAF", - /* U+04B2 */ "\xD2\xB2" => "\xD0\xA5", - /* U+04B3 */ "\xD2\xB3" => "\xD0\xA5", - /* U+04B4 */ "\xD2\xB4" => "\xD2\xB5", - /* U+04B6 */ "\xD2\xB6" => "\xD2\xBC", - /* U+04B7 */ "\xD2\xB7" => "\xD2\xBC", - /* U+04B8 */ "\xD2\xB8" => "\xD1\x87", - /* U+04B9 */ "\xD2\xB9" => "\xD1\x87", - /* U+04BA */ "\xD2\xBA" => "\xD2\xBB", - /* U+04BC */ "\xD2\xBC" => "\xD2\xBD", - /* U+04BE */ "\xD2\xBE" => "\xD2\xBC", - /* U+04BF */ "\xD2\xBF" => "\xD2\xBC", - /* U+04C1 */ "\xD3\x81" => "\xD0\xB6", - /* U+04C2 */ "\xD3\x82" => "\xD0\xB6", - /* U+04C3 */ "\xD3\x83" => "\xD0\xBA", - /* U+04C4 */ "\xD3\x84" => "\xD0\xBA", - /* U+04C5 */ "\xD3\x85" => "\xD0\xBB", - /* U+04C6 */ "\xD3\x86" => "\xD0\xBB", - /* U+04C7 */ "\xD3\x87" => "\xD0\xBD", - /* U+04C8 */ "\xD3\x88" => "\xD0\xBD", - /* U+04C9 */ "\xD3\x89" => "\xD0\xBD", - /* U+04CA */ "\xD3\x8A" => "\xD0\xBD", - /* U+04CB */ "\xD3\x8B" => "\xD2\xBC", - /* U+04CC */ "\xD3\x8C" => "\xD2\xBC", - /* U+04CD */ "\xD3\x8D" => "\xD0\xBC", - /* U+04CE */ "\xD3\x8E" => "\xD0\xBC", - /* U+04D0 */ "\xD3\x90" => "\xD0\xB0", - /* U+04D1 */ "\xD3\x91" => "\xD0\xB0", - /* U+04D2 */ "\xD3\x92" => "\xD0\xB0", - /* U+04D3 */ "\xD3\x93" => "\xD0\xB0", - /* U+04D4 */ "\xD3\x94" => "\xD3\x95", - /* U+04D6 */ "\xD3\x96" => "\xD0\xB5", - /* U+04D7 */ "\xD3\x97" => "\xD0\xB5", - /* U+04D8 */ "\xD3\x98" => "\xD3\x99", - /* U+04DA */ "\xD3\x9A" => "\xD3\x99", - /* U+04DB */ "\xD3\x9B" => "\xD3\x99", - /* U+04DC */ "\xD3\x9C" => "\xD0\xB6", - /* U+04DD */ "\xD3\x9D" => "\xD0\xB6", - /* U+04DE */ "\xD3\x9E" => "\xD0\xB7", - /* U+04DF */ "\xD3\x9F" => "\xD0\xB7", - /* U+04E0 */ "\xD3\xA0" => "\xD3\xA1", - /* U+04E2 */ "\xD3\xA2" => "\xD0\xB8", - /* U+04E3 */ "\xD3\xA3" => "\xD0\xB8", - /* U+04E4 */ "\xD3\xA4" => "\xD0\xB8", - /* U+04E5 */ "\xD3\xA5" => "\xD0\xB8", - /* U+04E6 */ "\xD3\xA6" => "\xD0\xBE", - /* U+04E7 */ "\xD3\xA7" => "\xD0\xBE", - /* U+04E8 */ "\xD3\xA8" => "\xD3\xA9", - /* U+04EA */ "\xD3\xAA" => "\xD3\xA9", - /* U+04EB */ "\xD3\xAB" => "\xD3\xA9", - /* U+04EC */ "\xD3\xAC" => "\xD1\x8D", - /* U+04ED */ "\xD3\xAD" => "\xD1\x8D", - /* U+04EE */ "\xD3\xAE" => "\xD1\x83", - /* U+04EF */ "\xD3\xAF" => "\xD1\x83", - /* U+04F0 */ "\xD3\xB0" => "\xD1\x83", - /* U+04F1 */ "\xD3\xB1" => "\xD1\x83", - /* U+04F2 */ "\xD3\xB2" => "\xD1\x83", - /* U+04F3 */ "\xD3\xB3" => "\xD1\x83", - /* U+04F4 */ "\xD3\xB4" => "\xD1\x87", - /* U+04F5 */ "\xD3\xB5" => "\xD1\x87", - /* U+04F6 */ "\xD3\xB6" => "\xD3\xB7", - /* U+04F8 */ "\xD3\xB8" => "\xD1\x8B", - /* U+04F9 */ "\xD3\xB9" => "\xD1\x8B", - //------ U+0500..U+052F : Cyrillic Supplement - /* U+0500 */ "\xD4\x80" => "\xD4\x81", - /* U+0502 */ "\xD4\x82" => "\xD4\x83", - /* U+0504 */ "\xD4\x84" => "\xD4\x85", - /* U+0506 */ "\xD4\x86" => "\xD4\x87", - /* U+0508 */ "\xD4\x88" => "\xD4\x89", - /* U+050A */ "\xD4\x8A" => "\xD4\x8B", - /* U+050C */ "\xD4\x8C" => "\xD4\x8D", - /* U+050E */ "\xD4\x8E" => "\xD4\x8F", - //------ U+0530..U+058F : Armenian - /* U+0531 */ "\xD4\xB1" => "\xD5\xA1", - /* U+0532 */ "\xD4\xB2" => "\xD5\xA2", - /* U+0533 */ "\xD4\xB3" => "\xD5\xA3", - /* U+0534 */ "\xD4\xB4" => "\xD5\xA4", - /* U+0535 */ "\xD4\xB5" => "\xD5\xA5", - /* U+0536 */ "\xD4\xB6" => "\xD5\xA6", - /* U+0537 */ "\xD4\xB7" => "\xD5\xA7", - /* U+0538 */ "\xD4\xB8" => "\xD5\xA8", - /* U+0539 */ "\xD4\xB9" => "\xD5\xA9", - /* U+053A */ "\xD4\xBA" => "\xD5\xAA", - /* U+053B */ "\xD4\xBB" => "\xD5\xAB", - /* U+053C */ "\xD4\xBC" => "\xD5\xAC", - /* U+053D */ "\xD4\xBD" => "\xD5\xAD", - /* U+053E */ "\xD4\xBE" => "\xD5\xAE", - /* U+053F */ "\xD4\xBF" => "\xD5\xAF", - /* U+0540 */ "\xD5\x80" => "\xD5\xB0", - /* U+0541 */ "\xD5\x81" => "\xD5\xB1", - /* U+0542 */ "\xD5\x82" => "\xD5\xB2", - /* U+0543 */ "\xD5\x83" => "\xD5\xB3", - /* U+0544 */ "\xD5\x84" => "\xD5\xB4", - /* U+0545 */ "\xD5\x85" => "\xD5\xB5", - /* U+0546 */ "\xD5\x86" => "\xD5\xB6", - /* U+0547 */ "\xD5\x87" => "\xD5\xB7", - /* U+0548 */ "\xD5\x88" => "\xD5\xB8", - /* U+0549 */ "\xD5\x89" => "\xD5\xB9", - /* U+054A */ "\xD5\x8A" => "\xD5\xBA", - /* U+054B */ "\xD5\x8B" => "\xD5\xBB", - /* U+054C */ "\xD5\x8C" => "\xD5\xBC", - /* U+054D */ "\xD5\x8D" => "\xD5\xBD", - /* U+054E */ "\xD5\x8E" => "\xD5\xBE", - /* U+054F */ "\xD5\x8F" => "\xD5\xBF", - /* U+0550 */ "\xD5\x90" => "\xD6\x80", - /* U+0551 */ "\xD5\x91" => "\xD6\x81", - /* U+0552 */ "\xD5\x92" => "\xD6\x82", - /* U+0553 */ "\xD5\x93" => "\xD6\x83", - /* U+0554 */ "\xD5\x94" => "\xD6\x84", - /* U+0555 */ "\xD5\x95" => "\xD6\x85", - /* U+0556 */ "\xD5\x96" => "\xD6\x86", - //------ U+1E00..U+1EFF : Latin Extended Additional - /* U+1E00 */ "\xE1\xB8\x80" => "\x61", - /* U+1E01 */ "\xE1\xB8\x81" => "\x61", - /* U+1E02 */ "\xE1\xB8\x82" => "\x62", - /* U+1E03 */ "\xE1\xB8\x83" => "\x62", - /* U+1E04 */ "\xE1\xB8\x84" => "\x62", - /* U+1E05 */ "\xE1\xB8\x85" => "\x62", - /* U+1E06 */ "\xE1\xB8\x86" => "\x62", - /* U+1E07 */ "\xE1\xB8\x87" => "\x62", - /* U+1E08 */ "\xE1\xB8\x88" => "\x63", - /* U+1E09 */ "\xE1\xB8\x89" => "\x63", - /* U+1E0A */ "\xE1\xB8\x8A" => "\x64", - /* U+1E0B */ "\xE1\xB8\x8B" => "\x64", - /* U+1E0C */ "\xE1\xB8\x8C" => "\x64", - /* U+1E0D */ "\xE1\xB8\x8D" => "\x64", - /* U+1E0E */ "\xE1\xB8\x8E" => "\x64", - /* U+1E0F */ "\xE1\xB8\x8F" => "\x64", - /* U+1E10 */ "\xE1\xB8\x90" => "\x64", - /* U+1E11 */ "\xE1\xB8\x91" => "\x64", - /* U+1E12 */ "\xE1\xB8\x92" => "\x64", - /* U+1E13 */ "\xE1\xB8\x93" => "\x64", - /* U+1E14 */ "\xE1\xB8\x94" => "\x65", - /* U+1E15 */ "\xE1\xB8\x95" => "\x65", - /* U+1E16 */ "\xE1\xB8\x96" => "\x65", - /* U+1E17 */ "\xE1\xB8\x97" => "\x65", - /* U+1E18 */ "\xE1\xB8\x98" => "\x65", - /* U+1E19 */ "\xE1\xB8\x99" => "\x65", - /* U+1E1A */ "\xE1\xB8\x9A" => "\x65", - /* U+1E1B */ "\xE1\xB8\x9B" => "\x65", - /* U+1E1C */ "\xE1\xB8\x9C" => "\x65", - /* U+1E1D */ "\xE1\xB8\x9D" => "\x65", - /* U+1E1E */ "\xE1\xB8\x9E" => "\x66", - /* U+1E1F */ "\xE1\xB8\x9F" => "\x66", - /* U+1E20 */ "\xE1\xB8\xA0" => "\x67", - /* U+1E21 */ "\xE1\xB8\xA1" => "\x67", - /* U+1E22 */ "\xE1\xB8\xA2" => "\x68", - /* U+1E23 */ "\xE1\xB8\xA3" => "\x68", - /* U+1E24 */ "\xE1\xB8\xA4" => "\x68", - /* U+1E25 */ "\xE1\xB8\xA5" => "\x68", - /* U+1E26 */ "\xE1\xB8\xA6" => "\x68", - /* U+1E27 */ "\xE1\xB8\xA7" => "\x68", - /* U+1E28 */ "\xE1\xB8\xA8" => "\x68", - /* U+1E29 */ "\xE1\xB8\xA9" => "\x68", - /* U+1E2A */ "\xE1\xB8\xAA" => "\x68", - /* U+1E2B */ "\xE1\xB8\xAB" => "\x68", - /* U+1E2C */ "\xE1\xB8\xAC" => "\x69", - /* U+1E2D */ "\xE1\xB8\xAD" => "\x69", - /* U+1E2E */ "\xE1\xB8\xAE" => "\x69", - /* U+1E2F */ "\xE1\xB8\xAF" => "\x69", - /* U+1E30 */ "\xE1\xB8\xB0" => "\x6B", - /* U+1E31 */ "\xE1\xB8\xB1" => "\x6B", - /* U+1E32 */ "\xE1\xB8\xB2" => "\x6B", - /* U+1E33 */ "\xE1\xB8\xB3" => "\x6B", - /* U+1E34 */ "\xE1\xB8\xB4" => "\x6B", - /* U+1E35 */ "\xE1\xB8\xB5" => "\x6B", - /* U+1E36 */ "\xE1\xB8\xB6" => "\x6C", - /* U+1E37 */ "\xE1\xB8\xB7" => "\x6C", - /* U+1E38 */ "\xE1\xB8\xB8" => "\x6C", - /* U+1E39 */ "\xE1\xB8\xB9" => "\x6C", - /* U+1E3A */ "\xE1\xB8\xBA" => "\x6C", - /* U+1E3B */ "\xE1\xB8\xBB" => "\x6C", - /* U+1E3C */ "\xE1\xB8\xBC" => "\x6C", - /* U+1E3D */ "\xE1\xB8\xBD" => "\x6C", - /* U+1E3E */ "\xE1\xB8\xBE" => "\x6D", - /* U+1E3F */ "\xE1\xB8\xBF" => "\x6D", - /* U+1E40 */ "\xE1\xB9\x80" => "\x6D", - /* U+1E41 */ "\xE1\xB9\x81" => "\x6D", - /* U+1E42 */ "\xE1\xB9\x82" => "\x6D", - /* U+1E43 */ "\xE1\xB9\x83" => "\x6D", - /* U+1E44 */ "\xE1\xB9\x84" => "\x6E", - /* U+1E45 */ "\xE1\xB9\x85" => "\x6E", - /* U+1E46 */ "\xE1\xB9\x86" => "\x6E", - /* U+1E47 */ "\xE1\xB9\x87" => "\x6E", - /* U+1E48 */ "\xE1\xB9\x88" => "\x6E", - /* U+1E49 */ "\xE1\xB9\x89" => "\x6E", - /* U+1E4A */ "\xE1\xB9\x8A" => "\x6E", - /* U+1E4B */ "\xE1\xB9\x8B" => "\x6E", - /* U+1E4C */ "\xE1\xB9\x8C" => "\x6F", - /* U+1E4D */ "\xE1\xB9\x8D" => "\x6F", - /* U+1E4E */ "\xE1\xB9\x8E" => "\x6F", - /* U+1E4F */ "\xE1\xB9\x8F" => "\x6F", - /* U+1E50 */ "\xE1\xB9\x90" => "\x6F", - /* U+1E51 */ "\xE1\xB9\x91" => "\x6F", - /* U+1E52 */ "\xE1\xB9\x92" => "\x6F", - /* U+1E53 */ "\xE1\xB9\x93" => "\x6F", - /* U+1E54 */ "\xE1\xB9\x94" => "\x70", - /* U+1E55 */ "\xE1\xB9\x95" => "\x70", - /* U+1E56 */ "\xE1\xB9\x96" => "\x70", - /* U+1E57 */ "\xE1\xB9\x97" => "\x70", - /* U+1E58 */ "\xE1\xB9\x98" => "\x72", - /* U+1E59 */ "\xE1\xB9\x99" => "\x72", - /* U+1E5A */ "\xE1\xB9\x9A" => "\x72", - /* U+1E5B */ "\xE1\xB9\x9B" => "\x72", - /* U+1E5C */ "\xE1\xB9\x9C" => "\x72", - /* U+1E5D */ "\xE1\xB9\x9D" => "\x72", - /* U+1E5E */ "\xE1\xB9\x9E" => "\x72", - /* U+1E5F */ "\xE1\xB9\x9F" => "\x72", - /* U+1E60 */ "\xE1\xB9\xA0" => "\x73", - /* U+1E61 */ "\xE1\xB9\xA1" => "\x73", - /* U+1E62 */ "\xE1\xB9\xA2" => "\x73", - /* U+1E63 */ "\xE1\xB9\xA3" => "\x73", - /* U+1E64 */ "\xE1\xB9\xA4" => "\x73", - /* U+1E65 */ "\xE1\xB9\xA5" => "\x73", - /* U+1E66 */ "\xE1\xB9\xA6" => "\x73", - /* U+1E67 */ "\xE1\xB9\xA7" => "\x73", - /* U+1E68 */ "\xE1\xB9\xA8" => "\x73", - /* U+1E69 */ "\xE1\xB9\xA9" => "\x73", - /* U+1E6A */ "\xE1\xB9\xAA" => "\x74", - /* U+1E6B */ "\xE1\xB9\xAB" => "\x74", - /* U+1E6C */ "\xE1\xB9\xAC" => "\x74", - /* U+1E6D */ "\xE1\xB9\xAD" => "\x74", - /* U+1E6E */ "\xE1\xB9\xAE" => "\x74", - /* U+1E6F */ "\xE1\xB9\xAF" => "\x74", - /* U+1E70 */ "\xE1\xB9\xB0" => "\x74", - /* U+1E71 */ "\xE1\xB9\xB1" => "\x74", - /* U+1E72 */ "\xE1\xB9\xB2" => "\x75", - /* U+1E73 */ "\xE1\xB9\xB3" => "\x75", - /* U+1E74 */ "\xE1\xB9\xB4" => "\x75", - /* U+1E75 */ "\xE1\xB9\xB5" => "\x75", - /* U+1E76 */ "\xE1\xB9\xB6" => "\x75", - /* U+1E77 */ "\xE1\xB9\xB7" => "\x75", - /* U+1E78 */ "\xE1\xB9\xB8" => "\x75", - /* U+1E79 */ "\xE1\xB9\xB9" => "\x75", - /* U+1E7A */ "\xE1\xB9\xBA" => "\x75", - /* U+1E7B */ "\xE1\xB9\xBB" => "\x75", - /* U+1E7C */ "\xE1\xB9\xBC" => "\x76", - /* U+1E7D */ "\xE1\xB9\xBD" => "\x76", - /* U+1E7E */ "\xE1\xB9\xBE" => "\x76", - /* U+1E7F */ "\xE1\xB9\xBF" => "\x76", - /* U+1E80 */ "\xE1\xBA\x80" => "\x77", - /* U+1E81 */ "\xE1\xBA\x81" => "\x77", - /* U+1E82 */ "\xE1\xBA\x82" => "\x77", - /* U+1E83 */ "\xE1\xBA\x83" => "\x77", - /* U+1E84 */ "\xE1\xBA\x84" => "\x77", - /* U+1E85 */ "\xE1\xBA\x85" => "\x77", - /* U+1E86 */ "\xE1\xBA\x86" => "\x77", - /* U+1E87 */ "\xE1\xBA\x87" => "\x77", - /* U+1E88 */ "\xE1\xBA\x88" => "\x77", - /* U+1E89 */ "\xE1\xBA\x89" => "\x77", - /* U+1E8A */ "\xE1\xBA\x8A" => "\x78", - /* U+1E8B */ "\xE1\xBA\x8B" => "\x78", - /* U+1E8C */ "\xE1\xBA\x8C" => "\x78", - /* U+1E8D */ "\xE1\xBA\x8D" => "\x78", - /* U+1E8E */ "\xE1\xBA\x8E" => "\x79", - /* U+1E8F */ "\xE1\xBA\x8F" => "\x79", - /* U+1E90 */ "\xE1\xBA\x90" => "\x7A", - /* U+1E91 */ "\xE1\xBA\x91" => "\x7A", - /* U+1E92 */ "\xE1\xBA\x92" => "\x7A", - /* U+1E93 */ "\xE1\xBA\x93" => "\x7A", - /* U+1E94 */ "\xE1\xBA\x94" => "\x7A", - /* U+1E95 */ "\xE1\xBA\x95" => "\x7A", - /* U+1E96 */ "\xE1\xBA\x96" => "\x68", - /* U+1E97 */ "\xE1\xBA\x97" => "\x74", - /* U+1E98 */ "\xE1\xBA\x98" => "\x77", - /* U+1E99 */ "\xE1\xBA\x99" => "\x79", - /* U+1E9A */ "\xE1\xBA\x9A" => "\x61", - /* U+1E9B */ "\xE1\xBA\x9B" => "\xC5\xBF", - /* U+1EA0 */ "\xE1\xBA\xA0" => "\x61", - /* U+1EA1 */ "\xE1\xBA\xA1" => "\x61", - /* U+1EA2 */ "\xE1\xBA\xA2" => "\x61", - /* U+1EA3 */ "\xE1\xBA\xA3" => "\x61", - /* U+1EA4 */ "\xE1\xBA\xA4" => "\x61", - /* U+1EA5 */ "\xE1\xBA\xA5" => "\x61", - /* U+1EA6 */ "\xE1\xBA\xA6" => "\x61", - /* U+1EA7 */ "\xE1\xBA\xA7" => "\x61", - /* U+1EA8 */ "\xE1\xBA\xA8" => "\x61", - /* U+1EA9 */ "\xE1\xBA\xA9" => "\x61", - /* U+1EAA */ "\xE1\xBA\xAA" => "\x61", - /* U+1EAB */ "\xE1\xBA\xAB" => "\x61", - /* U+1EAC */ "\xE1\xBA\xAC" => "\x61", - /* U+1EAD */ "\xE1\xBA\xAD" => "\x61", - /* U+1EAE */ "\xE1\xBA\xAE" => "\x61", - /* U+1EAF */ "\xE1\xBA\xAF" => "\x61", - /* U+1EB0 */ "\xE1\xBA\xB0" => "\x61", - /* U+1EB1 */ "\xE1\xBA\xB1" => "\x61", - /* U+1EB2 */ "\xE1\xBA\xB2" => "\x61", - /* U+1EB3 */ "\xE1\xBA\xB3" => "\x61", - /* U+1EB4 */ "\xE1\xBA\xB4" => "\x61", - /* U+1EB5 */ "\xE1\xBA\xB5" => "\x61", - /* U+1EB6 */ "\xE1\xBA\xB6" => "\x61", - /* U+1EB7 */ "\xE1\xBA\xB7" => "\x61", - /* U+1EB8 */ "\xE1\xBA\xB8" => "\x65", - /* U+1EB9 */ "\xE1\xBA\xB9" => "\x65", - /* U+1EBA */ "\xE1\xBA\xBA" => "\x65", - /* U+1EBB */ "\xE1\xBA\xBB" => "\x65", - /* U+1EBC */ "\xE1\xBA\xBC" => "\x65", - /* U+1EBD */ "\xE1\xBA\xBD" => "\x65", - /* U+1EBE */ "\xE1\xBA\xBE" => "\x65", - /* U+1EBF */ "\xE1\xBA\xBF" => "\x65", - /* U+1EC0 */ "\xE1\xBB\x80" => "\x65", - /* U+1EC1 */ "\xE1\xBB\x81" => "\x65", - /* U+1EC2 */ "\xE1\xBB\x82" => "\x65", - /* U+1EC3 */ "\xE1\xBB\x83" => "\x65", - /* U+1EC4 */ "\xE1\xBB\x84" => "\x65", - /* U+1EC5 */ "\xE1\xBB\x85" => "\x65", - /* U+1EC6 */ "\xE1\xBB\x86" => "\x65", - /* U+1EC7 */ "\xE1\xBB\x87" => "\x65", - /* U+1EC8 */ "\xE1\xBB\x88" => "\x69", - /* U+1EC9 */ "\xE1\xBB\x89" => "\x69", - /* U+1ECA */ "\xE1\xBB\x8A" => "\x69", - /* U+1ECB */ "\xE1\xBB\x8B" => "\x69", - /* U+1ECC */ "\xE1\xBB\x8C" => "\x6F", - /* U+1ECD */ "\xE1\xBB\x8D" => "\x6F", - /* U+1ECE */ "\xE1\xBB\x8E" => "\x6F", - /* U+1ECF */ "\xE1\xBB\x8F" => "\x6F", - /* U+1ED0 */ "\xE1\xBB\x90" => "\x6F", - /* U+1ED1 */ "\xE1\xBB\x91" => "\x6F", - /* U+1ED2 */ "\xE1\xBB\x92" => "\x6F", - /* U+1ED3 */ "\xE1\xBB\x93" => "\x6F", - /* U+1ED4 */ "\xE1\xBB\x94" => "\x6F", - /* U+1ED5 */ "\xE1\xBB\x95" => "\x6F", - /* U+1ED6 */ "\xE1\xBB\x96" => "\x6F", - /* U+1ED7 */ "\xE1\xBB\x97" => "\x6F", - /* U+1ED8 */ "\xE1\xBB\x98" => "\x6F", - /* U+1ED9 */ "\xE1\xBB\x99" => "\x6F", - /* U+1EDA */ "\xE1\xBB\x9A" => "\x6F", - /* U+1EDB */ "\xE1\xBB\x9B" => "\x6F", - /* U+1EDC */ "\xE1\xBB\x9C" => "\x6F", - /* U+1EDD */ "\xE1\xBB\x9D" => "\x6F", - /* U+1EDE */ "\xE1\xBB\x9E" => "\x6F", - /* U+1EDF */ "\xE1\xBB\x9F" => "\x6F", - /* U+1EE0 */ "\xE1\xBB\xA0" => "\x6F", - /* U+1EE1 */ "\xE1\xBB\xA1" => "\x6F", - /* U+1EE2 */ "\xE1\xBB\xA2" => "\x6F", - /* U+1EE3 */ "\xE1\xBB\xA3" => "\x6F", - /* U+1EE4 */ "\xE1\xBB\xA4" => "\x75", - /* U+1EE5 */ "\xE1\xBB\xA5" => "\x75", - /* U+1EE6 */ "\xE1\xBB\xA6" => "\x75", - /* U+1EE7 */ "\xE1\xBB\xA7" => "\x75", - /* U+1EE8 */ "\xE1\xBB\xA8" => "\x75", - /* U+1EE9 */ "\xE1\xBB\xA9" => "\x75", - /* U+1EEA */ "\xE1\xBB\xAA" => "\x75", - /* U+1EEB */ "\xE1\xBB\xAB" => "\x75", - /* U+1EEC */ "\xE1\xBB\xAC" => "\x75", - /* U+1EED */ "\xE1\xBB\xAD" => "\x75", - /* U+1EEE */ "\xE1\xBB\xAE" => "\x75", - /* U+1EEF */ "\xE1\xBB\xAF" => "\x75", - /* U+1EF0 */ "\xE1\xBB\xB0" => "\x75", - /* U+1EF1 */ "\xE1\xBB\xB1" => "\x75", - /* U+1EF2 */ "\xE1\xBB\xB2" => "\x79", - /* U+1EF3 */ "\xE1\xBB\xB3" => "\x79", - /* U+1EF4 */ "\xE1\xBB\xB4" => "\x79", - /* U+1EF5 */ "\xE1\xBB\xB5" => "\x79", - /* U+1EF6 */ "\xE1\xBB\xB6" => "\x79", - /* U+1EF7 */ "\xE1\xBB\xB7" => "\x79", - /* U+1EF8 */ "\xE1\xBB\xB8" => "\x79", - /* U+1EF9 */ "\xE1\xBB\xB9" => "\x79", - //------ U+1F00..U+1FFF : Greek Extended - /* U+1F00 */ "\xE1\xBC\x80" => "\xCE\xB1", - /* U+1F01 */ "\xE1\xBC\x81" => "\xCE\xB1", - /* U+1F02 */ "\xE1\xBC\x82" => "\xCE\xB1", - /* U+1F03 */ "\xE1\xBC\x83" => "\xCE\xB1", - /* U+1F04 */ "\xE1\xBC\x84" => "\xCE\xB1", - /* U+1F05 */ "\xE1\xBC\x85" => "\xCE\xB1", - /* U+1F06 */ "\xE1\xBC\x86" => "\xCE\xB1", - /* U+1F07 */ "\xE1\xBC\x87" => "\xCE\xB1", - /* U+1F08 */ "\xE1\xBC\x88" => "\xCE\xB1", - /* U+1F09 */ "\xE1\xBC\x89" => "\xCE\xB1", - /* U+1F0A */ "\xE1\xBC\x8A" => "\xCE\xB1", - /* U+1F0B */ "\xE1\xBC\x8B" => "\xCE\xB1", - /* U+1F0C */ "\xE1\xBC\x8C" => "\xCE\xB1", - /* U+1F0D */ "\xE1\xBC\x8D" => "\xCE\xB1", - /* U+1F0E */ "\xE1\xBC\x8E" => "\xCE\xB1", - /* U+1F0F */ "\xE1\xBC\x8F" => "\xCE\xB1", - /* U+1F10 */ "\xE1\xBC\x90" => "\xCE\xB5", - /* U+1F11 */ "\xE1\xBC\x91" => "\xCE\xB5", - /* U+1F12 */ "\xE1\xBC\x92" => "\xCE\xB5", - /* U+1F13 */ "\xE1\xBC\x93" => "\xCE\xB5", - /* U+1F14 */ "\xE1\xBC\x94" => "\xCE\xB5", - /* U+1F15 */ "\xE1\xBC\x95" => "\xCE\xB5", - /* U+1F18 */ "\xE1\xBC\x98" => "\xCE\xB5", - /* U+1F19 */ "\xE1\xBC\x99" => "\xCE\xB5", - /* U+1F1A */ "\xE1\xBC\x9A" => "\xCE\xB5", - /* U+1F1B */ "\xE1\xBC\x9B" => "\xCE\xB5", - /* U+1F1C */ "\xE1\xBC\x9C" => "\xCE\xB5", - /* U+1F1D */ "\xE1\xBC\x9D" => "\xCE\xB5", - /* U+1F20 */ "\xE1\xBC\xA0" => "\xCE\xB7", - /* U+1F21 */ "\xE1\xBC\xA1" => "\xCE\xB7", - /* U+1F22 */ "\xE1\xBC\xA2" => "\xCE\xB7", - /* U+1F23 */ "\xE1\xBC\xA3" => "\xCE\xB7", - /* U+1F24 */ "\xE1\xBC\xA4" => "\xCE\xB7", - /* U+1F25 */ "\xE1\xBC\xA5" => "\xCE\xB7", - /* U+1F26 */ "\xE1\xBC\xA6" => "\xCE\xB7", - /* U+1F27 */ "\xE1\xBC\xA7" => "\xCE\xB7", - /* U+1F28 */ "\xE1\xBC\xA8" => "\xCE\xB7", - /* U+1F29 */ "\xE1\xBC\xA9" => "\xCE\xB7", - /* U+1F2A */ "\xE1\xBC\xAA" => "\xCE\xB7", - /* U+1F2B */ "\xE1\xBC\xAB" => "\xCE\xB7", - /* U+1F2C */ "\xE1\xBC\xAC" => "\xCE\xB7", - /* U+1F2D */ "\xE1\xBC\xAD" => "\xCE\xB7", - /* U+1F2E */ "\xE1\xBC\xAE" => "\xCE\xB7", - /* U+1F2F */ "\xE1\xBC\xAF" => "\xCE\xB7", - /* U+1F30 */ "\xE1\xBC\xB0" => "\xCE\xB9", - /* U+1F31 */ "\xE1\xBC\xB1" => "\xCE\xB9", - /* U+1F32 */ "\xE1\xBC\xB2" => "\xCE\xB9", - /* U+1F33 */ "\xE1\xBC\xB3" => "\xCE\xB9", - /* U+1F34 */ "\xE1\xBC\xB4" => "\xCE\xB9", - /* U+1F35 */ "\xE1\xBC\xB5" => "\xCE\xB9", - /* U+1F36 */ "\xE1\xBC\xB6" => "\xCE\xB9", - /* U+1F37 */ "\xE1\xBC\xB7" => "\xCE\xB9", - /* U+1F38 */ "\xE1\xBC\xB8" => "\xCE\xB9", - /* U+1F39 */ "\xE1\xBC\xB9" => "\xCE\xB9", - /* U+1F3A */ "\xE1\xBC\xBA" => "\xCE\xB9", - /* U+1F3B */ "\xE1\xBC\xBB" => "\xCE\xB9", - /* U+1F3C */ "\xE1\xBC\xBC" => "\xCE\xB9", - /* U+1F3D */ "\xE1\xBC\xBD" => "\xCE\xB9", - /* U+1F3E */ "\xE1\xBC\xBE" => "\xCE\xB9", - /* U+1F3F */ "\xE1\xBC\xBF" => "\xCE\xB9", - /* U+1F40 */ "\xE1\xBD\x80" => "\xCE\xBF", - /* U+1F41 */ "\xE1\xBD\x81" => "\xCE\xBF", - /* U+1F42 */ "\xE1\xBD\x82" => "\xCE\xBF", - /* U+1F43 */ "\xE1\xBD\x83" => "\xCE\xBF", - /* U+1F44 */ "\xE1\xBD\x84" => "\xCE\xBF", - /* U+1F45 */ "\xE1\xBD\x85" => "\xCE\xBF", - /* U+1F48 */ "\xE1\xBD\x88" => "\xCE\xBF", - /* U+1F49 */ "\xE1\xBD\x89" => "\xCE\xBF", - /* U+1F4A */ "\xE1\xBD\x8A" => "\xCE\xBF", - /* U+1F4B */ "\xE1\xBD\x8B" => "\xCE\xBF", - /* U+1F4C */ "\xE1\xBD\x8C" => "\xCE\xBF", - /* U+1F4D */ "\xE1\xBD\x8D" => "\xCE\xBF", - /* U+1F50 */ "\xE1\xBD\x90" => "\xCF\x85", - /* U+1F51 */ "\xE1\xBD\x91" => "\xCF\x85", - /* U+1F52 */ "\xE1\xBD\x92" => "\xCF\x85", - /* U+1F53 */ "\xE1\xBD\x93" => "\xCF\x85", - /* U+1F54 */ "\xE1\xBD\x94" => "\xCF\x85", - /* U+1F55 */ "\xE1\xBD\x95" => "\xCF\x85", - /* U+1F56 */ "\xE1\xBD\x96" => "\xCF\x85", - /* U+1F57 */ "\xE1\xBD\x97" => "\xCF\x85", - /* U+1F59 */ "\xE1\xBD\x99" => "\xCF\x85", - /* U+1F5B */ "\xE1\xBD\x9B" => "\xCF\x85", - /* U+1F5D */ "\xE1\xBD\x9D" => "\xCF\x85", - /* U+1F5F */ "\xE1\xBD\x9F" => "\xCF\x85", - /* U+1F60 */ "\xE1\xBD\xA0" => "\xCF\x89", - /* U+1F61 */ "\xE1\xBD\xA1" => "\xCF\x89", - /* U+1F62 */ "\xE1\xBD\xA2" => "\xCF\x89", - /* U+1F63 */ "\xE1\xBD\xA3" => "\xCF\x89", - /* U+1F64 */ "\xE1\xBD\xA4" => "\xCF\x89", - /* U+1F65 */ "\xE1\xBD\xA5" => "\xCF\x89", - /* U+1F66 */ "\xE1\xBD\xA6" => "\xCF\x89", - /* U+1F67 */ "\xE1\xBD\xA7" => "\xCF\x89", - /* U+1F68 */ "\xE1\xBD\xA8" => "\xCF\x89", - /* U+1F69 */ "\xE1\xBD\xA9" => "\xCF\x89", - /* U+1F6A */ "\xE1\xBD\xAA" => "\xCF\x89", - /* U+1F6B */ "\xE1\xBD\xAB" => "\xCF\x89", - /* U+1F6C */ "\xE1\xBD\xAC" => "\xCF\x89", - /* U+1F6D */ "\xE1\xBD\xAD" => "\xCF\x89", - /* U+1F6E */ "\xE1\xBD\xAE" => "\xCF\x89", - /* U+1F6F */ "\xE1\xBD\xAF" => "\xCF\x89", - /* U+1F70 */ "\xE1\xBD\xB0" => "\xCE\xB1", - /* U+1F71 */ "\xE1\xBD\xB1" => "\xCE\xB1", - /* U+1F72 */ "\xE1\xBD\xB2" => "\xCE\xB5", - /* U+1F73 */ "\xE1\xBD\xB3" => "\xCE\xB5", - /* U+1F74 */ "\xE1\xBD\xB4" => "\xCE\xB7", - /* U+1F75 */ "\xE1\xBD\xB5" => "\xCE\xB7", - /* U+1F76 */ "\xE1\xBD\xB6" => "\xCE\xB9", - /* U+1F77 */ "\xE1\xBD\xB7" => "\xCE\xB9", - /* U+1F78 */ "\xE1\xBD\xB8" => "\xCE\xBF", - /* U+1F79 */ "\xE1\xBD\xB9" => "\xCE\xBF", - /* U+1F7A */ "\xE1\xBD\xBA" => "\xCF\x85", - /* U+1F7B */ "\xE1\xBD\xBB" => "\xCF\x85", - /* U+1F7C */ "\xE1\xBD\xBC" => "\xCF\x89", - /* U+1F7D */ "\xE1\xBD\xBD" => "\xCF\x89", - /* U+1F80 */ "\xE1\xBE\x80" => "\xCE\xB1", - /* U+1F81 */ "\xE1\xBE\x81" => "\xCE\xB1", - /* U+1F82 */ "\xE1\xBE\x82" => "\xCE\xB1", - /* U+1F83 */ "\xE1\xBE\x83" => "\xCE\xB1", - /* U+1F84 */ "\xE1\xBE\x84" => "\xCE\xB1", - /* U+1F85 */ "\xE1\xBE\x85" => "\xCE\xB1", - /* U+1F86 */ "\xE1\xBE\x86" => "\xCE\xB1", - /* U+1F87 */ "\xE1\xBE\x87" => "\xCE\xB1", - /* U+1F88 */ "\xE1\xBE\x88" => "\xCE\xB1", - /* U+1F89 */ "\xE1\xBE\x89" => "\xCE\xB1", - /* U+1F8A */ "\xE1\xBE\x8A" => "\xCE\xB1", - /* U+1F8B */ "\xE1\xBE\x8B" => "\xCE\xB1", - /* U+1F8C */ "\xE1\xBE\x8C" => "\xCE\xB1", - /* U+1F8D */ "\xE1\xBE\x8D" => "\xCE\xB1", - /* U+1F8E */ "\xE1\xBE\x8E" => "\xCE\xB1", - /* U+1F8F */ "\xE1\xBE\x8F" => "\xCE\xB1", - /* U+1F90 */ "\xE1\xBE\x90" => "\xCE\xB7", - /* U+1F91 */ "\xE1\xBE\x91" => "\xCE\xB7", - /* U+1F92 */ "\xE1\xBE\x92" => "\xCE\xB7", - /* U+1F93 */ "\xE1\xBE\x93" => "\xCE\xB7", - /* U+1F94 */ "\xE1\xBE\x94" => "\xCE\xB7", - /* U+1F95 */ "\xE1\xBE\x95" => "\xCE\xB7", - /* U+1F96 */ "\xE1\xBE\x96" => "\xCE\xB7", - /* U+1F97 */ "\xE1\xBE\x97" => "\xCE\xB7", - /* U+1F98 */ "\xE1\xBE\x98" => "\xCE\xB7", - /* U+1F99 */ "\xE1\xBE\x99" => "\xCE\xB7", - /* U+1F9A */ "\xE1\xBE\x9A" => "\xCE\xB7", - /* U+1F9B */ "\xE1\xBE\x9B" => "\xCE\xB7", - /* U+1F9C */ "\xE1\xBE\x9C" => "\xCE\xB7", - /* U+1F9D */ "\xE1\xBE\x9D" => "\xCE\xB7", - /* U+1F9E */ "\xE1\xBE\x9E" => "\xCE\xB7", - /* U+1F9F */ "\xE1\xBE\x9F" => "\xCE\xB7", - /* U+1FA0 */ "\xE1\xBE\xA0" => "\xCF\x89", - /* U+1FA1 */ "\xE1\xBE\xA1" => "\xCF\x89", - /* U+1FA2 */ "\xE1\xBE\xA2" => "\xCF\x89", - /* U+1FA3 */ "\xE1\xBE\xA3" => "\xCF\x89", - /* U+1FA4 */ "\xE1\xBE\xA4" => "\xCF\x89", - /* U+1FA5 */ "\xE1\xBE\xA5" => "\xCF\x89", - /* U+1FA6 */ "\xE1\xBE\xA6" => "\xCF\x89", - /* U+1FA7 */ "\xE1\xBE\xA7" => "\xCF\x89", - /* U+1FA8 */ "\xE1\xBE\xA8" => "\xCF\x89", - /* U+1FA9 */ "\xE1\xBE\xA9" => "\xCF\x89", - /* U+1FAA */ "\xE1\xBE\xAA" => "\xCF\x89", - /* U+1FAB */ "\xE1\xBE\xAB" => "\xCF\x89", - /* U+1FAC */ "\xE1\xBE\xAC" => "\xCF\x89", - /* U+1FAD */ "\xE1\xBE\xAD" => "\xCF\x89", - /* U+1FAE */ "\xE1\xBE\xAE" => "\xCF\x89", - /* U+1FAF */ "\xE1\xBE\xAF" => "\xCF\x89", - /* U+1FB0 */ "\xE1\xBE\xB0" => "\xCE\xB1", - /* U+1FB1 */ "\xE1\xBE\xB1" => "\xCE\xB1", - /* U+1FB2 */ "\xE1\xBE\xB2" => "\xCE\xB1", - /* U+1FB3 */ "\xE1\xBE\xB3" => "\xCE\xB1", - /* U+1FB4 */ "\xE1\xBE\xB4" => "\xCE\xB1", - /* U+1FB6 */ "\xE1\xBE\xB6" => "\xCE\xB1", - /* U+1FB7 */ "\xE1\xBE\xB7" => "\xCE\xB1", - /* U+1FB8 */ "\xE1\xBE\xB8" => "\xCE\xB1", - /* U+1FB9 */ "\xE1\xBE\xB9" => "\xCE\xB1", - /* U+1FBA */ "\xE1\xBE\xBA" => "\xCE\xB1", - /* U+1FBB */ "\xE1\xBE\xBB" => "\xCE\xB1", - /* U+1FBC */ "\xE1\xBE\xBC" => "\xCE\xB1", - /* U+1FC2 */ "\xE1\xBF\x82" => "\xCE\xB7", - /* U+1FC3 */ "\xE1\xBF\x83" => "\xCE\xB7", - /* U+1FC4 */ "\xE1\xBF\x84" => "\xCE\xB7", - /* U+1FC6 */ "\xE1\xBF\x86" => "\xCE\xB7", - /* U+1FC7 */ "\xE1\xBF\x87" => "\xCE\xB7", - /* U+1FC8 */ "\xE1\xBF\x88" => "\xCE\xB5", - /* U+1FC9 */ "\xE1\xBF\x89" => "\xCE\xB5", - /* U+1FCA */ "\xE1\xBF\x8A" => "\xCE\xB7", - /* U+1FCB */ "\xE1\xBF\x8B" => "\xCE\xB7", - /* U+1FCC */ "\xE1\xBF\x8C" => "\xCE\xB7", - /* U+1FD0 */ "\xE1\xBF\x90" => "\xCE\xB9", - /* U+1FD1 */ "\xE1\xBF\x91" => "\xCE\xB9", - /* U+1FD2 */ "\xE1\xBF\x92" => "\xCE\xB9", - /* U+1FD3 */ "\xE1\xBF\x93" => "\xCE\xB9", - /* U+1FD6 */ "\xE1\xBF\x96" => "\xCE\xB9", - /* U+1FD7 */ "\xE1\xBF\x97" => "\xCE\xB9", - /* U+1FD8 */ "\xE1\xBF\x98" => "\xCE\xB9", - /* U+1FD9 */ "\xE1\xBF\x99" => "\xCE\xB9", - /* U+1FDA */ "\xE1\xBF\x9A" => "\xCE\xB9", - /* U+1FDB */ "\xE1\xBF\x9B" => "\xCE\xB9", - /* U+1FE0 */ "\xE1\xBF\xA0" => "\xCF\x85", - /* U+1FE1 */ "\xE1\xBF\xA1" => "\xCF\x85", - /* U+1FE2 */ "\xE1\xBF\xA2" => "\xCF\x85", - /* U+1FE3 */ "\xE1\xBF\xA3" => "\xCF\x85", - /* U+1FE4 */ "\xE1\xBF\xA4" => "\xCF\x81", - /* U+1FE5 */ "\xE1\xBF\xA5" => "\xCF\x81", - /* U+1FE6 */ "\xE1\xBF\xA6" => "\xCF\x85", - /* U+1FE7 */ "\xE1\xBF\xA7" => "\xCF\x85", - /* U+1FE8 */ "\xE1\xBF\xA8" => "\xCF\x85", - /* U+1FE9 */ "\xE1\xBF\xA9" => "\xCF\x85", - /* U+1FEA */ "\xE1\xBF\xAA" => "\xCF\x85", - /* U+1FEB */ "\xE1\xBF\xAB" => "\xCF\x85", - /* U+1FEC */ "\xE1\xBF\xAC" => "\xCF\x81", - /* U+1FF2 */ "\xE1\xBF\xB2" => "\xCF\x89", - /* U+1FF3 */ "\xE1\xBF\xB3" => "\xCF\x89", - /* U+1FF4 */ "\xE1\xBF\xB4" => "\xCF\x89", - /* U+1FF6 */ "\xE1\xBF\xB6" => "\xCF\x89", - /* U+1FF7 */ "\xE1\xBF\xB7" => "\xCF\x89", - /* U+1FF8 */ "\xE1\xBF\xB8" => "\xCE\xBF", - /* U+1FF9 */ "\xE1\xBF\xB9" => "\xCE\xBF", - /* U+1FFA */ "\xE1\xBF\xBA" => "\xCF\x89", - /* U+1FFB */ "\xE1\xBF\xBB" => "\xCF\x89", - /* U+1FFC */ "\xE1\xBF\xBC" => "\xCF\x89", - //------ U+2C00..U+2C5F : Glagolitic - /* U+2C00 */ "\xE2\xB0\x80" => "\xE2\xB0\xB0", - /* U+2C01 */ "\xE2\xB0\x81" => "\xE2\xB0\xB1", - /* U+2C02 */ "\xE2\xB0\x82" => "\xE2\xB0\xB2", - /* U+2C03 */ "\xE2\xB0\x83" => "\xE2\xB0\xB3", - /* U+2C04 */ "\xE2\xB0\x84" => "\xE2\xB0\xB4", - /* U+2C05 */ "\xE2\xB0\x85" => "\xE2\xB0\xB5", - /* U+2C06 */ "\xE2\xB0\x86" => "\xE2\xB0\xB6", - /* U+2C07 */ "\xE2\xB0\x87" => "\xE2\xB0\xB7", - /* U+2C08 */ "\xE2\xB0\x88" => "\xE2\xB0\xB8", - /* U+2C09 */ "\xE2\xB0\x89" => "\xE2\xB0\xB9", - /* U+2C0A */ "\xE2\xB0\x8A" => "\xE2\xB0\xBA", - /* U+2C0B */ "\xE2\xB0\x8B" => "\xE2\xB0\xBB", - /* U+2C0C */ "\xE2\xB0\x8C" => "\xE2\xB0\xBC", - /* U+2C0D */ "\xE2\xB0\x8D" => "\xE2\xB0\xBD", - /* U+2C0E */ "\xE2\xB0\x8E" => "\xE2\xB0\xBE", - /* U+2C0F */ "\xE2\xB0\x8F" => "\xE2\xB0\xBF", - /* U+2C10 */ "\xE2\xB0\x90" => "\xE2\xB1\x80", - /* U+2C11 */ "\xE2\xB0\x91" => "\xE2\xB1\x81", - /* U+2C12 */ "\xE2\xB0\x92" => "\xE2\xB1\x82", - /* U+2C13 */ "\xE2\xB0\x93" => "\xE2\xB1\x83", - /* U+2C14 */ "\xE2\xB0\x94" => "\xE2\xB1\x84", - /* U+2C15 */ "\xE2\xB0\x95" => "\xE2\xB1\x85", - /* U+2C16 */ "\xE2\xB0\x96" => "\xE2\xB1\x86", - /* U+2C17 */ "\xE2\xB0\x97" => "\xE2\xB1\x87", - /* U+2C18 */ "\xE2\xB0\x98" => "\xE2\xB1\x88", - /* U+2C19 */ "\xE2\xB0\x99" => "\xE2\xB1\x89", - /* U+2C1A */ "\xE2\xB0\x9A" => "\xE2\xB1\x8A", - /* U+2C1B */ "\xE2\xB0\x9B" => "\xE2\xB1\x8B", - /* U+2C1C */ "\xE2\xB0\x9C" => "\xE2\xB1\x8C", - /* U+2C1D */ "\xE2\xB0\x9D" => "\xE2\xB1\x8D", - /* U+2C1E */ "\xE2\xB0\x9E" => "\xE2\xB1\x8E", - /* U+2C1F */ "\xE2\xB0\x9F" => "\xE2\xB1\x8F", - /* U+2C20 */ "\xE2\xB0\xA0" => "\xE2\xB1\x90", - /* U+2C21 */ "\xE2\xB0\xA1" => "\xE2\xB1\x91", - /* U+2C22 */ "\xE2\xB0\xA2" => "\xE2\xB1\x92", - /* U+2C23 */ "\xE2\xB0\xA3" => "\xE2\xB1\x93", - /* U+2C24 */ "\xE2\xB0\xA4" => "\xE2\xB1\x94", - /* U+2C25 */ "\xE2\xB0\xA5" => "\xE2\xB1\x95", - /* U+2C26 */ "\xE2\xB0\xA6" => "\xE2\xB1\x96", - /* U+2C27 */ "\xE2\xB0\xA7" => "\xE2\xB1\x97", - /* U+2C28 */ "\xE2\xB0\xA8" => "\xE2\xB1\x98", - /* U+2C29 */ "\xE2\xB0\xA9" => "\xE2\xB1\x99", - /* U+2C2A */ "\xE2\xB0\xAA" => "\xE2\xB1\x9A", - /* U+2C2B */ "\xE2\xB0\xAB" => "\xE2\xB1\x9B", - /* U+2C2C */ "\xE2\xB0\xAC" => "\xE2\xB1\x9C", - /* U+2C2D */ "\xE2\xB0\xAD" => "\xE2\xB1\x9D", - /* U+2C2E */ "\xE2\xB0\xAE" => "\xE2\xB1\x9E", - //------ U+2C80..U+2CFF : Coptic - /* U+2C80 */ "\xE2\xB2\x80" => "\xE2\xB2\x81", - /* U+2C82 */ "\xE2\xB2\x82" => "\xE2\xB2\x83", - /* U+2C84 */ "\xE2\xB2\x84" => "\xE2\xB2\x85", - /* U+2C86 */ "\xE2\xB2\x86" => "\xE2\xB2\x87", - /* U+2C88 */ "\xE2\xB2\x88" => "\xE2\xB2\x89", - /* U+2C8A */ "\xE2\xB2\x8A" => "\xE2\xB2\x8B", - /* U+2C8C */ "\xE2\xB2\x8C" => "\xE2\xB2\x8D", - /* U+2C8E */ "\xE2\xB2\x8E" => "\xE2\xB2\x8F", - /* U+2C90 */ "\xE2\xB2\x90" => "\xE2\xB2\x91", - /* U+2C92 */ "\xE2\xB2\x92" => "\xE2\xB2\x93", - /* U+2C94 */ "\xE2\xB2\x94" => "\xE2\xB2\x95", - /* U+2C96 */ "\xE2\xB2\x96" => "\xE2\xB2\x97", - /* U+2C98 */ "\xE2\xB2\x98" => "\xE2\xB2\x99", - /* U+2C9A */ "\xE2\xB2\x9A" => "\xE2\xB2\x9B", - /* U+2C9C */ "\xE2\xB2\x9C" => "\xE2\xB2\x9D", - /* U+2C9E */ "\xE2\xB2\x9E" => "\xE2\xB2\x9F", - /* U+2CA0 */ "\xE2\xB2\xA0" => "\xE2\xB2\xA1", - /* U+2CA2 */ "\xE2\xB2\xA2" => "\xE2\xB2\xA3", - /* U+2CA4 */ "\xE2\xB2\xA4" => "\xE2\xB2\xA5", - /* U+2CA6 */ "\xE2\xB2\xA6" => "\xE2\xB2\xA7", - /* U+2CA8 */ "\xE2\xB2\xA8" => "\xE2\xB2\xA9", - /* U+2CAA */ "\xE2\xB2\xAA" => "\xE2\xB2\xAB", - /* U+2CAC */ "\xE2\xB2\xAC" => "\xE2\xB2\xAD", - /* U+2CAE */ "\xE2\xB2\xAE" => "\xE2\xB2\xAF", - /* U+2CB0 */ "\xE2\xB2\xB0" => "\xE2\xB2\xB1", - /* U+2CB2 */ "\xE2\xB2\xB2" => "\xE2\xB2\xB3", - /* U+2CB4 */ "\xE2\xB2\xB4" => "\xE2\xB2\xB5", - /* U+2CB6 */ "\xE2\xB2\xB6" => "\xE2\xB2\xB7", - /* U+2CB8 */ "\xE2\xB2\xB8" => "\xE2\xB2\xB9", - /* U+2CBA */ "\xE2\xB2\xBA" => "\xE2\xB2\xBB", - /* U+2CBC */ "\xE2\xB2\xBC" => "\xE2\xB2\xBD", - /* U+2CBE */ "\xE2\xB2\xBE" => "\xE2\xB2\xBF", - /* U+2CC0 */ "\xE2\xB3\x80" => "\xE2\xB3\x81", - /* U+2CC2 */ "\xE2\xB3\x82" => "\xE2\xB3\x83", - /* U+2CC4 */ "\xE2\xB3\x84" => "\xE2\xB3\x85", - /* U+2CC6 */ "\xE2\xB3\x86" => "\xE2\xB3\x87", - /* U+2CC8 */ "\xE2\xB3\x88" => "\xE2\xB3\x89", - /* U+2CCA */ "\xE2\xB3\x8A" => "\xE2\xB3\x8B", - /* U+2CCC */ "\xE2\xB3\x8C" => "\xE2\xB3\x8D", - /* U+2CCE */ "\xE2\xB3\x8E" => "\xE2\xB3\x8F", - /* U+2CD0 */ "\xE2\xB3\x90" => "\xE2\xB3\x91", - /* U+2CD2 */ "\xE2\xB3\x92" => "\xE2\xB3\x93", - /* U+2CD4 */ "\xE2\xB3\x94" => "\xE2\xB3\x95", - /* U+2CD6 */ "\xE2\xB3\x96" => "\xE2\xB3\x97", - /* U+2CD8 */ "\xE2\xB3\x98" => "\xE2\xB3\x99", - /* U+2CDA */ "\xE2\xB3\x9A" => "\xE2\xB3\x9B", - /* U+2CDC */ "\xE2\xB3\x9C" => "\xE2\xB3\x9D", - /* U+2CDE */ "\xE2\xB3\x9E" => "\xE2\xB3\x9F", - /* U+2CE0 */ "\xE2\xB3\xA0" => "\xE2\xB3\xA1", - /* U+2CE2 */ "\xE2\xB3\xA2" => "\xE2\xB3\xA3", - //------ U+FB00..U+FB4F : Alphabetic Presentation Forms - /* U+FB1D */ "\xEF\xAC\x9D" => "\xD7\x99", - /* U+FB2A */ "\xEF\xAC\xAA" => "\xD7\xA9", - /* U+FB2B */ "\xEF\xAC\xAB" => "\xD7\xA9", - /* U+FB2C */ "\xEF\xAC\xAC" => "\xD7\xA9", - /* U+FB2D */ "\xEF\xAC\xAD" => "\xD7\xA9", - /* U+FB2E */ "\xEF\xAC\xAE" => "\xD7\x90", - /* U+FB2F */ "\xEF\xAC\xAF" => "\xD7\x90", - /* U+FB30 */ "\xEF\xAC\xB0" => "\xD7\x90", - /* U+FB31 */ "\xEF\xAC\xB1" => "\xD7\x91", - /* U+FB32 */ "\xEF\xAC\xB2" => "\xD7\x92", - /* U+FB33 */ "\xEF\xAC\xB3" => "\xD7\x93", - /* U+FB34 */ "\xEF\xAC\xB4" => "\xD7\x94", - /* U+FB35 */ "\xEF\xAC\xB5" => "\xD7\x95", - /* U+FB36 */ "\xEF\xAC\xB6" => "\xD7\x96", - /* U+FB38 */ "\xEF\xAC\xB8" => "\xD7\x98", - /* U+FB39 */ "\xEF\xAC\xB9" => "\xD7\x99", - /* U+FB3A */ "\xEF\xAC\xBA" => "\xD7\x9A", - /* U+FB3B */ "\xEF\xAC\xBB" => "\xD7\x9B", - /* U+FB3C */ "\xEF\xAC\xBC" => "\xD7\x9C", - /* U+FB3E */ "\xEF\xAC\xBE" => "\xD7\x9E", - /* U+FB40 */ "\xEF\xAD\x80" => "\xD7\xA0", - /* U+FB41 */ "\xEF\xAD\x81" => "\xD7\xA1", - /* U+FB43 */ "\xEF\xAD\x83" => "\xD7\xA3", - /* U+FB44 */ "\xEF\xAD\x84" => "\xD7\xA4", - /* U+FB46 */ "\xEF\xAD\x86" => "\xD7\xA6", - /* U+FB47 */ "\xEF\xAD\x87" => "\xD7\xA7", - /* U+FB48 */ "\xEF\xAD\x88" => "\xD7\xA8", - /* U+FB49 */ "\xEF\xAD\x89" => "\xD7\xA9", - /* U+FB4A */ "\xEF\xAD\x8A" => "\xD7\xAA", - /* U+FB4B */ "\xEF\xAD\x8B" => "\xD7\x95", - /* U+FB4C */ "\xEF\xAD\x8C" => "\xD7\x91", - /* U+FB4D */ "\xEF\xAD\x8D" => "\xD7\x9B", - /* U+FB4E */ "\xEF\xAD\x8E" => "\xD7\xA4", - //------ U+FF00..U+FFEF : Halfwidth and Fullwidth Forms - /* U+FF21 */ "\xEF\xBC\xA1" => "\xEF\xBD\x81", - /* U+FF22 */ "\xEF\xBC\xA2" => "\xEF\xBD\x82", - /* U+FF23 */ "\xEF\xBC\xA3" => "\xEF\xBD\x83", - /* U+FF24 */ "\xEF\xBC\xA4" => "\xEF\xBD\x84", - /* U+FF25 */ "\xEF\xBC\xA5" => "\xEF\xBD\x85", - /* U+FF26 */ "\xEF\xBC\xA6" => "\xEF\xBD\x86", - /* U+FF27 */ "\xEF\xBC\xA7" => "\xEF\xBD\x87", - /* U+FF28 */ "\xEF\xBC\xA8" => "\xEF\xBD\x88", - /* U+FF29 */ "\xEF\xBC\xA9" => "\xEF\xBD\x89", - /* U+FF2A */ "\xEF\xBC\xAA" => "\xEF\xBD\x8A", - /* U+FF2B */ "\xEF\xBC\xAB" => "\xEF\xBD\x8B", - /* U+FF2C */ "\xEF\xBC\xAC" => "\xEF\xBD\x8C", - /* U+FF2D */ "\xEF\xBC\xAD" => "\xEF\xBD\x8D", - /* U+FF2E */ "\xEF\xBC\xAE" => "\xEF\xBD\x8E", - /* U+FF2F */ "\xEF\xBC\xAF" => "\xEF\xBD\x8F", - /* U+FF30 */ "\xEF\xBC\xB0" => "\xEF\xBD\x90", - /* U+FF31 */ "\xEF\xBC\xB1" => "\xEF\xBD\x91", - /* U+FF32 */ "\xEF\xBC\xB2" => "\xEF\xBD\x92", - /* U+FF33 */ "\xEF\xBC\xB3" => "\xEF\xBD\x93", - /* U+FF34 */ "\xEF\xBC\xB4" => "\xEF\xBD\x94", - /* U+FF35 */ "\xEF\xBC\xB5" => "\xEF\xBD\x95", - /* U+FF36 */ "\xEF\xBC\xB6" => "\xEF\xBD\x96", - /* U+FF37 */ "\xEF\xBC\xB7" => "\xEF\xBD\x97", - /* U+FF38 */ "\xEF\xBC\xB8" => "\xEF\xBD\x98", - /* U+FF39 */ "\xEF\xBC\xB9" => "\xEF\xBD\x99", - /* U+FF3A */ "\xEF\xBC\xBA" => "\xEF\xBD\x9A", - //------ U+10400..U+1044F : Deseret - /* U+10400 */ "\xF0\x90\x90\x80" => "\xF0\x90\x90\xA8", - /* U+10401 */ "\xF0\x90\x90\x81" => "\xF0\x90\x90\xA9", - /* U+10402 */ "\xF0\x90\x90\x82" => "\xF0\x90\x90\xAA", - /* U+10403 */ "\xF0\x90\x90\x83" => "\xF0\x90\x90\xAB", - /* U+10404 */ "\xF0\x90\x90\x84" => "\xF0\x90\x90\xAC", - /* U+10405 */ "\xF0\x90\x90\x85" => "\xF0\x90\x90\xAD", - /* U+10406 */ "\xF0\x90\x90\x86" => "\xF0\x90\x90\xAE", - /* U+10407 */ "\xF0\x90\x90\x87" => "\xF0\x90\x90\xAF", - /* U+10408 */ "\xF0\x90\x90\x88" => "\xF0\x90\x90\xB0", - /* U+10409 */ "\xF0\x90\x90\x89" => "\xF0\x90\x90\xB1", - /* U+1040A */ "\xF0\x90\x90\x8A" => "\xF0\x90\x90\xB2", - /* U+1040B */ "\xF0\x90\x90\x8B" => "\xF0\x90\x90\xB3", - /* U+1040C */ "\xF0\x90\x90\x8C" => "\xF0\x90\x90\xB4", - /* U+1040D */ "\xF0\x90\x90\x8D" => "\xF0\x90\x90\xB5", - /* U+1040E */ "\xF0\x90\x90\x8E" => "\xF0\x90\x90\xB6", - /* U+1040F */ "\xF0\x90\x90\x8F" => "\xF0\x90\x90\xB7", - /* U+10410 */ "\xF0\x90\x90\x90" => "\xF0\x90\x90\xB8", - /* U+10411 */ "\xF0\x90\x90\x91" => "\xF0\x90\x90\xB9", - /* U+10412 */ "\xF0\x90\x90\x92" => "\xF0\x90\x90\xBA", - /* U+10413 */ "\xF0\x90\x90\x93" => "\xF0\x90\x90\xBB", - /* U+10414 */ "\xF0\x90\x90\x94" => "\xF0\x90\x90\xBC", - /* U+10415 */ "\xF0\x90\x90\x95" => "\xF0\x90\x90\xBD", - /* U+10416 */ "\xF0\x90\x90\x96" => "\xF0\x90\x90\xBE", - /* U+10417 */ "\xF0\x90\x90\x97" => "\xF0\x90\x90\xBF", - /* U+10418 */ "\xF0\x90\x90\x98" => "\xF0\x90\x91\x80", - /* U+10419 */ "\xF0\x90\x90\x99" => "\xF0\x90\x91\x81", - /* U+1041A */ "\xF0\x90\x90\x9A" => "\xF0\x90\x91\x82", - /* U+1041B */ "\xF0\x90\x90\x9B" => "\xF0\x90\x91\x83", - /* U+1041C */ "\xF0\x90\x90\x9C" => "\xF0\x90\x91\x84", - /* U+1041D */ "\xF0\x90\x90\x9D" => "\xF0\x90\x91\x85", - /* U+1041E */ "\xF0\x90\x90\x9E" => "\xF0\x90\x91\x86", - /* U+1041F */ "\xF0\x90\x90\x9F" => "\xF0\x90\x91\x87", - /* U+10420 */ "\xF0\x90\x90\xA0" => "\xF0\x90\x91\x88", - /* U+10421 */ "\xF0\x90\x90\xA1" => "\xF0\x90\x91\x89", - /* U+10422 */ "\xF0\x90\x90\xA2" => "\xF0\x90\x91\x8A", - /* U+10423 */ "\xF0\x90\x90\xA3" => "\xF0\x90\x91\x8B", - /* U+10424 */ "\xF0\x90\x90\xA4" => "\xF0\x90\x91\x8C", - /* U+10425 */ "\xF0\x90\x90\xA5" => "\xF0\x90\x91\x8D", - /* U+10426 */ "\xF0\x90\x90\xA6" => "\xF0\x90\x91\x8E", - /* U+10427 */ "\xF0\x90\x90\xA7" => "\xF0\x90\x91\x8F" - ); - protected $endCharacters_utf8 = "\t\r\n !\"#\$%&'()+,-./:;<=>@[\]^_`{|}~£§¨°"; - - public function get_indexer_bad_chars() - { - return $this->endCharacters_utf8; - } - - public function has_indexer_bad_char($string) - { - return mb_strpos($this->endCharacters_utf8, $string); - } - - public function remove_indexer_chars($string) - { - - $so = ""; - - $l = mb_strlen($string, "UTF-8"); - $lastwasblank = false; - for ($i = 0; $i < $l; $i++) + public function get_indexer_bad_chars() { - $c = mb_substr($string, $i, 1, "UTF-8"); - $c = isset($this->map[$c]) ? $this->map[$c] : $c; - if (mb_strpos($this->endCharacters_utf8, $c) !== FALSE) - { - $lastwasblank = true; - } - else - { - if ($lastwasblank && $so != "") - $so .= " "; - $so .= $c; + return $this->endCharacters_utf8; + } + + public function has_indexer_bad_char($string) + { + return mb_strpos($this->endCharacters_utf8, $string); + } + + public function remove_indexer_chars($string) + { + + $so = ""; + + $l = mb_strlen($string, "UTF-8"); $lastwasblank = false; - } + for ($i = 0; $i < $l; $i ++ ) { + $c = mb_substr($string, $i, 1, "UTF-8"); + $c = isset($this->map[$c]) ? $this->map[$c] : $c; + if (mb_strpos($this->endCharacters_utf8, $c) !== FALSE) { + $lastwasblank = true; + } else { + if ($lastwasblank && $so != "") + $so .= " "; + $so .= $c; + $lastwasblank = false; + } + } + + return($so); } - return($so); - } - - function remove_diacritics($string) - { - $no_diacritics = ''; - - $l = mb_strlen($string); - - $regexp = '/[a-zA-Z0-9]{1}/'; - for ($i = 0; $i < $l; $i++) + function remove_diacritics($string) { - $c = mb_substr($string, $i, 1); - if (!preg_match($regexp, $c)) - $c = isset($this->map[$c]) ? $this->map[$c] : $c; - $no_diacritics .= $c; + $no_diacritics = ''; + + $l = mb_strlen($string); + + $regexp = '/[a-zA-Z0-9]{1}/'; + for ($i = 0; $i < $l; $i ++ ) { + $c = mb_substr($string, $i, 1); + if ( ! preg_match($regexp, $c)) + $c = isset($this->map[$c]) ? $this->map[$c] : $c; + $no_diacritics .= $c; + } + + return $no_diacritics; } - return $no_diacritics; - } - - public function remove_nonazAZ09($string, $keep_underscores = true, $keep_minus = true, $keep_dot = false) - { - $regexp = '/[a-zA-Z0-9'; - if ($keep_minus === true) + public function remove_nonazAZ09($string, $keep_underscores = true, $keep_minus = true, $keep_dot = false) { - $regexp .= '-'; + $regexp = '/[a-zA-Z0-9'; + if ($keep_minus === true) { + $regexp .= '-'; + } + if ($keep_underscores === true) { + $regexp .= '_'; + } + if ($keep_dot === true) { + $regexp .= '\.'; + } + + $regexp .= ']{1}/'; + + $string = $this->remove_diacritics($string); + + $out = ''; + + $l = mb_strlen($string); + for ($i = 0; $i < $l; $i ++ ) { + $c = mb_substr($string, $i, 1); + if (preg_match($regexp, $c)) + $out .= $c; + } + + return $out; } - if ($keep_underscores === true) + + /** + * Removes all digits a the begining of a string + * @Example : returns 'soleil' for '123soleil' and 'bb2' for '1bb2' + * + * @param type $string + * @return type + */ + public function remove_first_digits($string) { - $regexp .= '_'; + while ($string != '' && ctype_digit($string[0])) { + $string = substr($string, 1); + } + + return $string; } - if ($keep_dot === true) - { - $regexp .= '\.'; - } - - $regexp .= ']{1}/'; - - $string = $this->remove_diacritics($string); - - $out = ''; - - $l = mb_strlen($string); - for ($i = 0; $i < $l; $i++) - { - $c = mb_substr($string, $i, 1); - if (preg_match($regexp, $c)) - $out .= $c; - } - - return $out; - } - - /** - * Removes all digits a the begining of a string - * @Example : returns 'soleil' for '123soleil' and 'bb2' for '1bb2' - * - * @param type $string - * @return type - */ - public function remove_first_digits($string) - { - while ($string != '' && ctype_digit($string[0])) - { - $string = substr($string, 1); - } - - return $string; - } - } diff --git a/lib/classes/uuid.class.php b/lib/classes/uuid.class.php index 083c6cbd8e..fd85353f4c 100644 --- a/lib/classes/uuid.class.php +++ b/lib/classes/uuid.class.php @@ -9,147 +9,142 @@ class uuid { - /** - * @desc UUID named based version that use MD5(hash) - * @param string $namespace - * @param string $name - * @return string - */ - public static function generate_v3($namespace, $name) - { - if (!self::is_valid($namespace)) - - return false; - - // Get hexadecimal components of namespace - $nhex = str_replace(array('-', '{', '}'), '', $namespace); - - // Binary Value - $nstr = ''; - - // Convert Namespace UUID to bits - for ($i = 0; $i < strlen($nhex); $i+=2) + /** + * @desc UUID named based version that use MD5(hash) + * @param string $namespace + * @param string $name + * @return string + */ + public static function generate_v3($namespace, $name) { - $nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1])); + if ( ! self::is_valid($namespace)) + return false; + + // Get hexadecimal components of namespace + $nhex = str_replace(array('-', '{', '}'), '', $namespace); + + // Binary Value + $nstr = ''; + + // Convert Namespace UUID to bits + for ($i = 0; $i < strlen($nhex); $i+=2) { + $nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1])); + } + + // Calculate hash value + $hash = md5($nstr . $name); + + return sprintf('%08s-%04s-%04x-%04x-%12s', + // 32 bits for "time_low" + substr($hash, 0, 8), + // 16 bits for "time_mid" + substr($hash, 8, 4), + // 16 bits for "time_hi_and_version", + // four most significant bits holds version number 3 + (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000, + // 16 bits, 8 bits for "clk_seq_hi_res", + // 8 bits for "clk_seq_low", + // two most significant bits holds zero and one for variant DCE1.1 + (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, + // 48 bits for "node" + substr($hash, 20, 12) + ); } - // Calculate hash value - $hash = md5($nstr . $name); - - return sprintf('%08s-%04s-%04x-%04x-%12s', - // 32 bits for "time_low" - substr($hash, 0, 8), - // 16 bits for "time_mid" - substr($hash, 8, 4), - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 3 - (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000, - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, - // 48 bits for "node" - substr($hash, 20, 12) - ); - } - - /** - * @desc UUID randomly generated version - * @return string - */ - public static function generate_v4() - { - return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', - // 32 bits for "time_low" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), - // 16 bits for "time_mid" - mt_rand(0, 0xffff), - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 4 - mt_rand(0, 0x0fff) | 0x4000, - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - mt_rand(0, 0x3fff) | 0x8000, - // 48 bits for "node" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) - ); - } - - /** - * @desc UUID named version that use SHA-1 hashing - * @param string $namespace - * @param string $name - * @return string - */ - public static function generate_v5($namespace, $name) - { - if (!self::is_valid($namespace)) - - return false; - - // Get hexadecimal components of namespace - $nhex = str_replace(array('-', '{', '}'), '', $namespace); - - // Binary Value - $nstr = ''; - - // Convert Namespace UUID to bits - for ($i = 0; $i < strlen($nhex); $i+=2) + /** + * @desc UUID randomly generated version + * @return string + */ + public static function generate_v4() { - $nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1])); + return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + // 32 bits for "time_low" + mt_rand(0, 0xffff), mt_rand(0, 0xffff), + // 16 bits for "time_mid" + mt_rand(0, 0xffff), + // 16 bits for "time_hi_and_version", + // four most significant bits holds version number 4 + mt_rand(0, 0x0fff) | 0x4000, + // 16 bits, 8 bits for "clk_seq_hi_res", + // 8 bits for "clk_seq_low", + // two most significant bits holds zero and one for variant DCE1.1 + mt_rand(0, 0x3fff) | 0x8000, + // 48 bits for "node" + mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) + ); } - // Calculate hash value - $hash = sha1($nstr . $name); + /** + * @desc UUID named version that use SHA-1 hashing + * @param string $namespace + * @param string $name + * @return string + */ + public static function generate_v5($namespace, $name) + { + if ( ! self::is_valid($namespace)) + return false; - return sprintf('%08s-%04s-%04x-%04x-%12s', - // 32 bits for "time_low" - substr($hash, 0, 8), - // 16 bits for "time_mid" - substr($hash, 8, 4), - // 16 bits for "time_hi_and_version", - // four most significant bits holds version number 5 - (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000, - // 16 bits, 8 bits for "clk_seq_hi_res", - // 8 bits for "clk_seq_low", - // two most significant bits holds zero and one for variant DCE1.1 - (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, - // 48 bits for "node" - substr($hash, 20, 12) - ); - } + // Get hexadecimal components of namespace + $nhex = str_replace(array('-', '{', '}'), '', $namespace); - /** - * @desc check if an uuid is a valid one - * @param string $uuid - * @return boolean - */ - public static function is_valid($uuid) - { - return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?' . - '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1; - } + // Binary Value + $nstr = ''; - /** - * @desc Compare two UUID's "lexically" - * @param stiring $uuid1 - * @param string $uuid2 - * @return int - * -1 uuid1uuid2 - */ - public static function compare($uuid1, $uuid2) - { - return (strcmp($uuid1, $uuid2) === 0); - } + // Convert Namespace UUID to bits + for ($i = 0; $i < strlen($nhex); $i+=2) { + $nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1])); + } - /** - * @desc Check wheter an UUID is the NULL UUID 00000000-0000-0000-0000-000000000000 - * @return string - */ - public static function is_null($uuid) - { - return (0 === strcmp($uuid, '00000000-0000-0000-0000-000000000000')); - } + // Calculate hash value + $hash = sha1($nstr . $name); + return sprintf('%08s-%04s-%04x-%04x-%12s', + // 32 bits for "time_low" + substr($hash, 0, 8), + // 16 bits for "time_mid" + substr($hash, 8, 4), + // 16 bits for "time_hi_and_version", + // four most significant bits holds version number 5 + (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000, + // 16 bits, 8 bits for "clk_seq_hi_res", + // 8 bits for "clk_seq_low", + // two most significant bits holds zero and one for variant DCE1.1 + (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000, + // 48 bits for "node" + substr($hash, 20, 12) + ); + } + + /** + * @desc check if an uuid is a valid one + * @param string $uuid + * @return boolean + */ + public static function is_valid($uuid) + { + return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?' . + '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1; + } + + /** + * @desc Compare two UUID's "lexically" + * @param stiring $uuid1 + * @param string $uuid2 + * @return int + * -1 uuid1uuid2 + */ + public static function compare($uuid1, $uuid2) + { + return (strcmp($uuid1, $uuid2) === 0); + } + + /** + * @desc Check wheter an UUID is the NULL UUID 00000000-0000-0000-0000-000000000000 + * @return string + */ + public static function is_null($uuid) + { + return (0 === strcmp($uuid, '00000000-0000-0000-0000-000000000000')); + } } diff --git a/lib/conf.d/PhraseaFixture/AbstractWZ.php b/lib/conf.d/PhraseaFixture/AbstractWZ.php index 8c80f2d384..83ae6e31a6 100644 --- a/lib/conf.d/PhraseaFixture/AbstractWZ.php +++ b/lib/conf.d/PhraseaFixture/AbstractWZ.php @@ -21,30 +21,26 @@ use Doctrine\Common\DataFixtures\AbstractFixture; */ abstract class AbstractWZ extends AbstractFixture { - protected $user; + protected $user; + protected $record; - protected $record; + public function getUser() + { + return $this->user; + } + public function setUser(\User_Adapter $user) + { + $this->user = $user; + } - public function getUser() - { - return $this->user; - } - - public function setUser(\User_Adapter $user) - { - $this->user = $user; - } - - - public function getRecord() - { - return $this->record; - } - - public function setRecord(\record_adapter $record) - { - $this->record = $record; - } + public function getRecord() + { + return $this->record; + } + public function setRecord(\record_adapter $record) + { + $this->record = $record; + } } diff --git a/lib/conf.d/PhraseaFixture/Basket/LoadFiveBaskets.php b/lib/conf.d/PhraseaFixture/Basket/LoadFiveBaskets.php index 5e5918791f..24789de0c8 100644 --- a/lib/conf.d/PhraseaFixture/Basket/LoadFiveBaskets.php +++ b/lib/conf.d/PhraseaFixture/Basket/LoadFiveBaskets.php @@ -23,35 +23,31 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadFiveBaskets extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var array + */ + public $baskets; - /** - * - * @var array - */ - public $baskets; - - public function load(ObjectManager $manager) - { - for ($i = 0; $i < 5; $i++) + public function load(ObjectManager $manager) { - $basket = new \Entities\Basket(); + for ($i = 0; $i < 5; $i ++ ) { + $basket = new \Entities\Basket(); - $basket->setName('test ' . $i); - $basket->setDescription('description'); + $basket->setName('test ' . $i); + $basket->setDescription('description'); - if (null === $this->user) - { - throw new \LogicException('Fill a user to store a new basket'); - } + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new basket'); + } - $basket->setOwner($this->user); + $basket->setOwner($this->user); - $manager->persist($basket); + $manager->persist($basket); - $this->baskets[] = $basket; + $this->baskets[] = $basket; + } + $this->addReference('five-basket', $basket); + $manager->flush(); } - $this->addReference('five-basket', $basket); - $manager->flush(); - } - } diff --git a/lib/conf.d/PhraseaFixture/Basket/LoadOneBasket.php b/lib/conf.d/PhraseaFixture/Basket/LoadOneBasket.php index e6bc9502c4..333f79c778 100644 --- a/lib/conf.d/PhraseaFixture/Basket/LoadOneBasket.php +++ b/lib/conf.d/PhraseaFixture/Basket/LoadOneBasket.php @@ -23,33 +23,30 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadOneBasket extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\Basket + */ + public $basket; - /** - * - * @var \Entities\Basket - */ - public $basket; - - public function load(ObjectManager $manager) - { - $basket = new \Entities\Basket(); - - $basket->setName('test'); - $basket->setDescription('description'); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new basket'); + $basket = new \Entities\Basket(); + + $basket->setName('test'); + $basket->setDescription('description'); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new basket'); + } + + $basket->setOwner($this->user); + + $manager->persist($basket); + $manager->flush(); + + $this->basket = $basket; + + $this->addReference('one-basket', $basket); } - - $basket->setOwner($this->user); - - $manager->persist($basket); - $manager->flush(); - - $this->basket = $basket; - - $this->addReference('one-basket', $basket); - } - } diff --git a/lib/conf.d/PhraseaFixture/Basket/LoadOneBasketEnv.php b/lib/conf.d/PhraseaFixture/Basket/LoadOneBasketEnv.php index 86039c527b..4a70836178 100644 --- a/lib/conf.d/PhraseaFixture/Basket/LoadOneBasketEnv.php +++ b/lib/conf.d/PhraseaFixture/Basket/LoadOneBasketEnv.php @@ -23,117 +23,109 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadOneBasketEnv extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\Basket + */ + public $basket; - /** - * - * @var \Entities\Basket - */ - public $basket; + /** + * + * @var Array + */ + protected $participants = array(); - /** - * - * @var Array - */ - protected $participants = array(); + /** + * + * @var Array + */ + protected $basketElements = array(); - /** - * - * @var Array - */ - protected $basketElements = array(); - - public function addParticipant(\User_Adapter $user) - { - $this->participants[] = $user; - } - - public function addBasketElement(\record_adapter $record) - { - $this->basketElements[] = $record; - } - - public function load(ObjectManager $manager) - { - $basket = new \Entities\Basket(); - - $basket->setName('test'); - - $basket->setDescription('description'); - - if (null === $this->user) + public function addParticipant(\User_Adapter $user) { - throw new \LogicException('Fill a user to store a new basket'); + $this->participants[] = $user; } - $basket->setOwner($this->user); - - $this->addElementToBasket($manager, $basket); - - $validationSession = new \Entities\ValidationSession(); - - $validationSession->setBasket($basket); - - $validationSession->setDescription('Une description au hasard'); - - $validationSession->setName('Un nom de validation'); - - $expires = new \DateTime(); - $expires->modify('+1 week'); - - $validationSession->setExpires($expires); - - if (null === $this->user) + public function addBasketElement(\record_adapter $record) { - throw new \LogicException('Fill a user to store a new validation Session'); + $this->basketElements[] = $record; } - $validationSession->setInitiator($this->user); - - $this->addParticipantsToSession($manager, $validationSession); - - $this->basket = $basket; - } - - private function addParticipantsToSession(\Doctrine\ORM\EntityManager $manager, \Entities\ValidationSession $validationSession) - { - if (0 === count($this->participants)) + public function load(ObjectManager $manager) { - throw new \LogicException('Add new participants to validation session'); + $basket = new \Entities\Basket(); + + $basket->setName('test'); + + $basket->setDescription('description'); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new basket'); + } + + $basket->setOwner($this->user); + + $this->addElementToBasket($manager, $basket); + + $validationSession = new \Entities\ValidationSession(); + + $validationSession->setBasket($basket); + + $validationSession->setDescription('Une description au hasard'); + + $validationSession->setName('Un nom de validation'); + + $expires = new \DateTime(); + $expires->modify('+1 week'); + + $validationSession->setExpires($expires); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new validation Session'); + } + + $validationSession->setInitiator($this->user); + + $this->addParticipantsToSession($manager, $validationSession); + + $this->basket = $basket; } - foreach ($this->participants as $participant) + private function addParticipantsToSession(\Doctrine\ORM\EntityManager $manager, \Entities\ValidationSession $validationSession) { - $validationParticipant = new \Entities\ValidationParticipant(); + if (0 === count($this->participants)) { + throw new \LogicException('Add new participants to validation session'); + } - $validationParticipant->setUser($participant); + foreach ($this->participants as $participant) { + $validationParticipant = new \Entities\ValidationParticipant(); - $validationParticipant->setSession($validationSession); + $validationParticipant->setUser($participant); - $manager->persist($validationParticipant); + $validationParticipant->setSession($validationSession); + + $manager->persist($validationParticipant); + } + + $manager->flush(); } - $manager->flush(); - } - - private function addElementToBasket(\Doctrine\ORM\EntityManager $manager, \Entities\Basket $basket) - { - if (0 === count($this->basketElements)) + private function addElementToBasket(\Doctrine\ORM\EntityManager $manager, \Entities\Basket $basket) { - throw new \LogicException('Add new elements to basket'); + if (0 === count($this->basketElements)) { + throw new \LogicException('Add new elements to basket'); + } + + foreach ($this->basketElements as $record) { + $basketElement = new \Entities\BasketElement(); + + $basketElement->setRecord($record); + + $basketElement->setBasket($basket); + + $manager->persist($basketElement); + } + + $manager->flush(); } - - foreach ($this->basketElements as $record) - { - $basketElement = new \Entities\BasketElement(); - - $basketElement->setRecord($record); - - $basketElement->setBasket($basket); - - $manager->persist($basketElement); - } - - $manager->flush(); - } - } diff --git a/lib/conf.d/PhraseaFixture/Story/LoadOneStory.php b/lib/conf.d/PhraseaFixture/Story/LoadOneStory.php index a5b0754a4b..cfcbdc8ec4 100644 --- a/lib/conf.d/PhraseaFixture/Story/LoadOneStory.php +++ b/lib/conf.d/PhraseaFixture/Story/LoadOneStory.php @@ -23,36 +23,32 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadOneStory extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\StoryWZ + */ + public $story; - /** - * - * @var \Entities\StoryWZ - */ - public $story; - - public function load(ObjectManager $manager) - { - $story = new \Entities\StoryWZ(); - - if (null === $this->record) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a record to store a new story'); + $story = new \Entities\StoryWZ(); + + if (null === $this->record) { + throw new \LogicException('Fill a record to store a new story'); + } + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new story'); + } + + $story->setRecord($this->record); + $story->setUser($this->user); + + $manager->persist($story); + $manager->flush(); + + $this->story = $story; + + $this->addReference('one-story', $story); } - - if (null === $this->user) - { - throw new \LogicException('Fill a user to store a new story'); - } - - $story->setRecord($this->record); - $story->setUser($this->user); - - $manager->persist($story); - $manager->flush(); - - $this->story = $story; - - $this->addReference('one-story', $story); - } - } diff --git a/lib/conf.d/PhraseaFixture/UsrLists/ListAbstract.php b/lib/conf.d/PhraseaFixture/UsrLists/ListAbstract.php index 75feee96bd..571738e7dd 100644 --- a/lib/conf.d/PhraseaFixture/UsrLists/ListAbstract.php +++ b/lib/conf.d/PhraseaFixture/UsrLists/ListAbstract.php @@ -8,12 +8,14 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + namespace PhraseaFixture\UsrLists; use Doctrine\ORM\EntityManager; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\AbstractFixture; + /** * * @package @@ -22,29 +24,26 @@ use Doctrine\Common\DataFixtures\AbstractFixture; */ abstract class ListAbstract extends AbstractFixture { + protected $user; + protected $list; - protected $user; + public function getUser() + { + return $this->user; + } - protected $list; + public function setUser(\User_Adapter $user) + { + $this->user = $user; + } - public function getUser() - { - return $this->user; - } - - public function setUser(\User_Adapter $user) - { - $this->user = $user; - } - - public function getList() - { - return $this->list; - } - - public function setList(\Entities\UsrList $list) - { - $this->list = $list; - } + public function getList() + { + return $this->list; + } + public function setList(\Entities\UsrList $list) + { + $this->list = $list; + } } diff --git a/lib/conf.d/PhraseaFixture/UsrLists/UsrList.php b/lib/conf.d/PhraseaFixture/UsrLists/UsrList.php index 32c4be4128..559ec1d292 100644 --- a/lib/conf.d/PhraseaFixture/UsrLists/UsrList.php +++ b/lib/conf.d/PhraseaFixture/UsrLists/UsrList.php @@ -23,32 +23,30 @@ use Doctrine\Common\Persistence\ObjectManager; */ class UsrList extends ListAbstract implements FixtureInterface { + /** + * + * @var \Entities\UsrList + */ + public $list; - /** - * - * @var \Entities\UsrList - */ - public $list; + public function load(ObjectManager $manager) + { + $list = new \Entities\UsrList(); - public function load(ObjectManager $manager) - { - $list = new \Entities\UsrList(); + $owner = $this->getReference('one-listowner'); - $owner = $this->getReference('one-listowner'); + $list->setName('new list'); + $list->addUsrListOwner($owner); - $list->setName('new list'); - $list->addUsrListOwner($owner); + /* @var $owner \Entities\UsrListOwner */ + $owner->setList($list); - /* @var $owner \Entities\UsrListOwner */ - $owner->setList($list); + $manager->persist($list); + $manager->merge($owner); + $manager->flush(); - $manager->persist($list); - $manager->merge($owner); - $manager->flush(); - - $this->list = $list; - - $this->addReference('one-list', $list); - } + $this->list = $list; + $this->addReference('one-list', $list); + } } diff --git a/lib/conf.d/PhraseaFixture/UsrLists/UsrListEntry.php b/lib/conf.d/PhraseaFixture/UsrLists/UsrListEntry.php index aa134a99c8..253abf7bf4 100644 --- a/lib/conf.d/PhraseaFixture/UsrLists/UsrListEntry.php +++ b/lib/conf.d/PhraseaFixture/UsrLists/UsrListEntry.php @@ -30,36 +30,33 @@ use Doctrine\Common\Persistence\ObjectManager; */ class UsrListEntry extends ListAbstract implements FixtureInterface { + /** + * + * @var \Entities\UsrListEntry + */ + public $entry; - /** - * - * @var \Entities\UsrListEntry - */ - public $entry; - - public function load(ObjectManager $manager) - { - $entry = new \Entities\UsrListEntry(); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new basket'); + $entry = new \Entities\UsrListEntry(); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new basket'); + } + + $list = $this->getReference('one-list'); + + $entry->setUser($this->user); + $entry->setList($list); + + /* @var $list \Entities\UsrList */ + $list->addUsrListEntry($entry); + + $manager->persist($entry); + $manager->flush(); + + $this->entry = $entry; + + $this->addReference('one-entry', $entry); } - - $list = $this->getReference('one-list'); - - $entry->setUser($this->user); - $entry->setList($list); - - /* @var $list \Entities\UsrList */ - $list->addUsrListEntry($entry); - - $manager->persist($entry); - $manager->flush(); - - $this->entry = $entry; - - $this->addReference('one-entry', $entry); - } - } diff --git a/lib/conf.d/PhraseaFixture/UsrLists/UsrListOwner.php b/lib/conf.d/PhraseaFixture/UsrLists/UsrListOwner.php index daf58b29aa..5d8ab55c22 100644 --- a/lib/conf.d/PhraseaFixture/UsrLists/UsrListOwner.php +++ b/lib/conf.d/PhraseaFixture/UsrLists/UsrListOwner.php @@ -8,6 +8,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + namespace PhraseaFixture\UsrLists; use Doctrine\ORM\EntityManager; @@ -22,32 +23,29 @@ use Doctrine\Common\Persistence\ObjectManager; */ class UsrListOwner extends ListAbstract implements FixtureInterface { + /** + * + * @var \Entities\StoryWZ + */ + public $owner; - /** - * - * @var \Entities\StoryWZ - */ - public $owner; - - public function load(ObjectManager $manager) - { - $owner = new \Entities\UsrListOwner(); - - $owner->setRole(\Entities\UsrListOwner::ROLE_ADMIN); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new basket'); + $owner = new \Entities\UsrListOwner(); + + $owner->setRole(\Entities\UsrListOwner::ROLE_ADMIN); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new basket'); + } + + $owner->setUser($this->user); + + $manager->persist($owner); + $manager->flush(); + + $this->owner = $owner; + + $this->addReference('one-listowner', $owner); } - - $owner->setUser($this->user); - - $manager->persist($owner); - $manager->flush(); - - $this->owner = $owner; - - $this->addReference('one-listowner', $owner); - } - } diff --git a/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadOneParticipant.php b/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadOneParticipant.php index 401343448e..1d05b4db83 100644 --- a/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadOneParticipant.php +++ b/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadOneParticipant.php @@ -23,33 +23,30 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadOneParticipant extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\ValidationParticipant + */ + public $validationParticipant; - /** - * - * @var \Entities\ValidationParticipant - */ - public $validationParticipant; - - public function load(ObjectManager $manager) - { - $validationParticipant = new \Entities\ValidationParticipant(); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new validation Session'); - } - $validationParticipant->setParticipant($this->user); + $validationParticipant = new \Entities\ValidationParticipant(); - $validationParticipant->setSession( + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new validation Session'); + } + $validationParticipant->setParticipant($this->user); + + $validationParticipant->setSession( $this->getReference('one-validation-session') - ); + ); - $manager->persist($validationParticipant); - $manager->flush(); + $manager->persist($validationParticipant); + $manager->flush(); - $this->validationParticipant = $validationParticipant; - - $this->addReference('one-validation-participant', $validationParticipant); - } + $this->validationParticipant = $validationParticipant; + $this->addReference('one-validation-participant', $validationParticipant); + } } diff --git a/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadParticipantWithSession.php b/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadParticipantWithSession.php index 216071d0dd..79d35dc716 100644 --- a/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadParticipantWithSession.php +++ b/lib/conf.d/PhraseaFixture/ValidationParticipant/LoadParticipantWithSession.php @@ -23,45 +23,40 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadParticipantWithSession extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\ValidationParticipant + */ + public $validationParticipant; - /** - * - * @var \Entities\ValidationParticipant - */ - public $validationParticipant; + /** + * + * @var \Entities\ValidationSession + */ + private $session; - /** - * - * @var \Entities\ValidationSession - */ - private $session; - - public function load(ObjectManager $manager) - { - $validationParticipant = new \Entities\ValidationParticipant(); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new validation Session'); - } - $validationParticipant->setUser($this->user); + $validationParticipant = new \Entities\ValidationParticipant(); - if (null === $this->session) + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new validation Session'); + } + $validationParticipant->setUser($this->user); + + if (null === $this->session) { + throw new \LogicException('Attach a session to the current participant'); + } + $validationParticipant->setSession($this->session); + + $manager->persist($validationParticipant); + $manager->flush(); + + $this->validationParticipant = $validationParticipant; + } + + public function setSession(\Entities\ValidationSession $session) { - throw new \LogicException('Attach a session to the current participant'); + $this->session = $session; } - $validationParticipant->setSession($this->session); - - $manager->persist($validationParticipant); - $manager->flush(); - - $this->validationParticipant = $validationParticipant; - } - - public function setSession(\Entities\ValidationSession $session) - { - $this->session = $session; - } - - } diff --git a/lib/conf.d/PhraseaFixture/ValidationSession/LoadOneValidationSession.php b/lib/conf.d/PhraseaFixture/ValidationSession/LoadOneValidationSession.php index d81b72b7c2..7bb42d290d 100644 --- a/lib/conf.d/PhraseaFixture/ValidationSession/LoadOneValidationSession.php +++ b/lib/conf.d/PhraseaFixture/ValidationSession/LoadOneValidationSession.php @@ -23,40 +23,37 @@ use Doctrine\Common\Persistence\ObjectManager; */ class LoadOneValidationSession extends \PhraseaFixture\AbstractWZ implements FixtureInterface { + /** + * + * @var \Entities\ValidationSession + */ + public $validationSession; - /** - * - * @var \Entities\ValidationSession - */ - public $validationSession; - - public function load(ObjectManager $manager) - { - $validationSession = new \Entities\ValidationSession(); - - $validationSession->setBasket( - $this->getReference('one-basket') // load the one-basket stored reference - ); - - $validationSession->setDescription('Une description au hasard'); - $validationSession->setName('Un nom de validation'); - - $expires = new \DateTime(); - $expires->modify('+1 week'); - $validationSession->setExpires($expires); - - if (null === $this->user) + public function load(ObjectManager $manager) { - throw new \LogicException('Fill a user to store a new validation Session'); + $validationSession = new \Entities\ValidationSession(); + + $validationSession->setBasket( + $this->getReference('one-basket') // load the one-basket stored reference + ); + + $validationSession->setDescription('Une description au hasard'); + $validationSession->setName('Un nom de validation'); + + $expires = new \DateTime(); + $expires->modify('+1 week'); + $validationSession->setExpires($expires); + + if (null === $this->user) { + throw new \LogicException('Fill a user to store a new validation Session'); + } + $validationSession->setInitiator($this->user); + + $manager->persist($validationSession); + $manager->flush(); + + $this->validationSession = $validationSession; + + $this->addReference('one-validation-session', $validationSession); } - $validationSession->setInitiator($this->user); - - $manager->persist($validationSession); - $manager->flush(); - - $this->validationSession = $validationSession; - - $this->addReference('one-validation-session', $validationSession); - } - } diff --git a/lib/conf.d/_GV_template.inc b/lib/conf.d/_GV_template.inc index f2e4a8a24c..3598e40d1b 100644 --- a/lib/conf.d/_GV_template.inc +++ b/lib/conf.d/_GV_template.inc @@ -2,7 +2,7 @@ $cwd = str_replace('\\', '/', dirname(__FILE__)); if (($pos = strpos($cwd, 'lib/conf.d')) !== false) - $cwd = substr($cwd, 0, $pos); + $cwd = substr($cwd, 0, $pos); $EOL = PHP_EOL; @@ -11,33 +11,29 @@ $GV_sit = md5(time() . '--' . mt_rand(1000000, 9999999)); include_once dirname(__FILE__) . "/../../lib/classes/User/Interface.class.php"; include_once dirname(__FILE__) . "/../../lib/classes/User/Adapter.class.php"; -$lngs = User_Adapter::avLanguages(); +$lngs = User_Adapter::avLanguages(); $avLanguages = array(); -foreach ($lngs as $lng => $locales) -{ - foreach ($locales as $loc => $locname) - { - $avLanguages[$loc] = $locname['name']; - } +foreach ($lngs as $lng => $locales) { + foreach ($locales as $loc => $locname) { + $avLanguages[$loc] = $locname['name']; + } } -$Core = \bootstrap::getCore(); +$Core = \bootstrap::getCore(); $extractDateFields = function(\Alchemy\Phrasea\Core $Core) { - $date_sort_fields = array(''=>''); - if ($Core->getConfiguration()->isInstalled()) - { - $ProdHelper = new Alchemy\Phrasea\Helper\Prod($Core, Symfony\Component\HttpFoundation\Request::createFromGlobals()); - $datas = $ProdHelper->get_search_datas(); - foreach ($datas['dates'] as $date) - { - $date_sort_fields[$date['fieldname']] = $date['fieldname']; - } - } + $date_sort_fields = array('' => ''); + if ($Core->getConfiguration()->isInstalled()) { + $ProdHelper = new Alchemy\Phrasea\Helper\Prod($Core, Symfony\Component\HttpFoundation\Request::createFromGlobals()); + $datas = $ProdHelper->get_search_datas(); + foreach ($datas['dates'] as $date) { + $date_sort_fields[$date['fieldname']] = $date['fieldname']; + } + } - return $date_sort_fields; -}; + return $date_sort_fields; + }; $date_sort_fields = $extractDateFields($Core); @@ -45,25 +41,25 @@ $date_sort_fields = $extractDateFields($Core); $eventsmanager = eventsmanager_broker::getInstance(appbox::get_instance($Core), $Core); $PHP_CONF = array( - 'output_buffering' => '4096' //INI_ALL - , 'memory_limit' => '1024M' //INI_ALL - , 'error_reporting' => '6143' //INI_ALL - , 'default_charset' => 'UTF-8' //INI_ALL - , 'session.use_cookies' => '1' //INI_ALL - , 'session.use_only_cookies' => '1' //INI_ALL - , 'session.auto_start' => '0' //INI_ALL - , 'session.hash_function' => '1' //INI_ALL - , 'session.hash_bits_per_character' => '6' //INI_ALL - , 'allow_url_fopen' => 'on' //INI_ALL - , 'display_errors' => 'off' //INI_ALL - , 'display_startup_errors' => 'off' //INI_ALL - , 'log_errors' => 'off' //INI_ALL + 'output_buffering' => '4096' //INI_ALL + , 'memory_limit' => '1024M' //INI_ALL + , 'error_reporting' => '6143' //INI_ALL + , 'default_charset' => 'UTF-8' //INI_ALL + , 'session.use_cookies' => '1' //INI_ALL + , 'session.use_only_cookies' => '1' //INI_ALL + , 'session.auto_start' => '0' //INI_ALL + , 'session.hash_function' => '1' //INI_ALL + , 'session.hash_bits_per_character' => '6' //INI_ALL + , 'allow_url_fopen' => 'on' //INI_ALL + , 'display_errors' => 'off' //INI_ALL + , 'display_startup_errors' => 'off' //INI_ALL + , 'log_errors' => 'off' //INI_ALL ); -$PHP_REQ = array( - 'safe_mode' => 'off' - , 'file_uploads' => '1' - , 'magic_quotes_runtime' => 'off' //INI_ALL - , 'magic_quotes_gpc' => 'off' //INI_PER_DIR -- just for check +$PHP_REQ = array( + 'safe_mode' => 'off' + , 'file_uploads' => '1' + , 'magic_quotes_runtime' => 'off' //INI_ALL + , 'magic_quotes_gpc' => 'off' //INI_PER_DIR -- just for check ); $youtube_console_url = 'https://code.google.com/apis/console/'; @@ -79,452 +75,452 @@ $dailymotion_callback = '/prod/bridge/callback/dailymotion/'; $create_api_dailymotion = 'http://www.dailymotion.com/profile/developer'; $GV = array( - array( - 'section' => _('GV::section:: Serveur HTTP'), - 'vars' => array( - array( - 'type' => 'timezone', - 'name' => 'GV_timezone', - 'comment' => _('reglages:: Timezone de l\'installation'), - 'default' => 'Europe/Paris', - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_sit', - 'comment' => _('reglages:: Nom de linstallation'), - 'default' => $GV_sit, - 'readonly' => true, - 'required' => true - ), - array( - 'type' => 'enum', - 'name' => 'GV_default_lng', - 'comment' => _('reglages:: Langue par defaut'), - 'default' => 'fr_FR', - 'available' => $avLanguages, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_STATIC_URL', - 'end_slash' => false, - 'comment' => _('reglages:: URL statique (optionnel)'), - 'default' => '', - 'required' => false - ) + array( + 'section' => _('GV::section:: Serveur HTTP'), + 'vars' => array( + array( + 'type' => 'timezone', + 'name' => 'GV_timezone', + 'comment' => _('reglages:: Timezone de l\'installation'), + 'default' => 'Europe/Paris', + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_sit', + 'comment' => _('reglages:: Nom de linstallation'), + 'default' => $GV_sit, + 'readonly' => true, + 'required' => true + ), + array( + 'type' => 'enum', + 'name' => 'GV_default_lng', + 'comment' => _('reglages:: Langue par defaut'), + 'default' => 'fr_FR', + 'available' => $avLanguages, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_STATIC_URL', + 'end_slash' => false, + 'comment' => _('reglages:: URL statique (optionnel)'), + 'default' => '', + 'required' => false + ) + ) + ), array( + 'section' => _('GV::section:: Etat de maintenance'), + 'rolled' => true, + 'vars' => array( + array( + 'type' => 'text', + 'name' => 'GV_message', + 'comment' => _('reglages:: Message a diffuser aux utilisateurs'), + 'default' => "May the force be with you" + ), + array( + 'type' => 'boolean', + 'name' => 'GV_message_on', + 'comment' => _('reglages:: activation du message a diffuser aux utilistaeurs'), + 'default' => false + ), + array( + 'type' => 'boolean', + 'name' => 'GV_log_errors', + 'comment' => _('reglages:: logguer les erreurs'), + 'default' => false + ) + ) + ), array( + 'section' => _('GV::section:: Connectivite aux webservices'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_google_api', + 'comment' => _('reglages:: Utiliser els google apis'), + 'default' => true, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_i18n_service', + 'comment' => _('reglages:: Service phrasea de localisation'), + 'default' => 'http://localization.webservice.alchemyasp.com/', + 'end_slash' => true, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_bitly_user', + 'comment' => _('reglages:: Nom d\'utilisateur pour l\'api bit.ly'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_bitly_key', + 'comment' => _('reglages:: ccle d\'api pour l\'api bit.ly'), + 'default' => '', + ), + array( + 'type' => 'boolean', + 'name' => 'GV_captchas', + 'comment' => _('reglages:: Utilisation de l\'api recpatcha'), + 'default' => false, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_captcha_public_key', + 'comment' => _('reglages:: clef publique recaptcha'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_captcha_private_key', + 'comment' => _('reglages:: clef privee recaptcha'), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Connectivite a Youtube'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_youtube_api', + 'comment' => sprintf(_('reglages:: Utiliser l\'api youtube, voir %s,
                  mettre la callback a WEBSITE_URL/prod/bridge/callback/youtube'), $youtube_console_url), + 'default' => false, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_youtube_client_id', + 'comment' => _('reglages:: Youtube client id'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_youtube_client_secret', + 'comment' => _('reglages:: Youtube clientsecret'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_youtube_dev_key', + 'comment' => sprintf(_('reglages:: Youtube cle developpeur, voir %s'), $dashboard_youtube), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Connectivite a FlickR'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_flickr_api', + 'comment' => sprintf(_('reglages:: Utiliser l api flickr, voir %s, puis set la callback a %s'), $create_api_flickr, $flickr_callback), + 'default' => false, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_flickr_client_id', + 'comment' => _('reglages:: FlickR client id'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_flickr_client_secret', + 'comment' => _('reglages:: FlickR client secret'), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Connectivite a Dailymotion'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_dailymotion_api', + 'comment' => sprintf(_('reglages:: Utiliser l api dailymotion, voir %s, puis set la callback a %s'), $create_api_dailymotion, $dailymotion_callback), + 'default' => false, + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_dailymotion_client_id', + 'comment' => _('reglages:: dailymotion client id'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_dailymotion_client_secret', + 'comment' => _('reglages:: dailymotion client secret'), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Gestionnaire d\'evenements'), + 'vars' => array( + array( + 'type' => 'enum_multi', + 'name' => 'GV_events', + 'default' => null, + 'comment' => _('reglages:: Evenements'), + 'available' => $eventsmanager->list_all('event'), + 'default' => array_keys($eventsmanager->list_all('event')) + ), + array( + 'type' => 'enum_multi', + 'name' => 'GV_notifications', + 'default' => null, + 'comment' => _('reglages:: Notifications'), + 'available' => $eventsmanager->list_all('notify'), + 'default' => array_keys($eventsmanager->list_all('notify')) + ) + ) + ), array( + 'section' => _('GV::section:: Stockage des documents'), + 'vars' => array( + array( + 'type' => 'string', + 'name' => 'GV_appletAllowedFileExt', + 'comment' => _('reglages:: extensions de fichier autorisees en upload, separees par des virgules. * pour autoriser tous les fichiers'), + 'default' => 'jpg,jpeg,bmp,tif,gif,png,pdf,doc,odt,mpg,mpeg,mov,avi,xls,flv,mp3,mp2', + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_base_datapath_web', + 'end_slash' => true, + 'comment' => _('reglages:: dossier de stockage des vignettes publiees en acces direct'), + 'default' => '', + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_base_datapath_noweb', + 'end_slash' => true, + 'comment' => _('reglages:: dossier de stockage des fichiers proteges de l\'acces direct'), + 'default' => '', + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_base_dataurl', + 'comment' => _('reglages:: point de montage des vignettes publiees en acces direct'), + 'default' => 'web', + 'end_slash' => false, + 'required' => true + ) + ) ) - ), array( - 'section' => _('GV::section:: Etat de maintenance'), - 'rolled' => true, - 'vars' => array( - array( - 'type' => 'text', - 'name' => 'GV_message', - 'comment' => _('reglages:: Message a diffuser aux utilisateurs'), - 'default' => "May the force be with you" - ), - array( - 'type' => 'boolean', - 'name' => 'GV_message_on', - 'comment' => _('reglages:: activation du message a diffuser aux utilistaeurs'), - 'default' => false - ), - array( - 'type' => 'boolean', - 'name' => 'GV_log_errors', - 'comment' => _('reglages:: logguer les erreurs'), - 'default' => false - ) + , array( + 'section' => _('GV::section:: Serveur Sphinx'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_sphinx', + 'comment' => _('Utiliser Sphinx'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_sphinx_host', + 'comment' => _('reglages:: de l\'adresse du serveur sphinx'), + 'default' => '127.0.0.1' + ), + array( + 'type' => 'integer', + 'name' => 'GV_sphinx_port', + 'comment' => _('reglages:: port du serveur sphinx'), + 'default' => 9306 + ), + array( + 'type' => 'string', + 'name' => 'GV_sphinx_rt_host', + 'comment' => _('reglages:: de l\'adresse du serveur RT sphinx'), + 'default' => '127.0.0.1' + ), + array( + 'type' => 'integer', + 'name' => 'GV_sphinx_rt_port', + 'comment' => _('reglages:: port du serveur RT sphinx'), + 'default' => 9308 + ) + ) ) - ), array( - 'section' => _('GV::section:: Connectivite aux webservices'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_google_api', - 'comment' => _('reglages:: Utiliser els google apis'), - 'default' => true, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_i18n_service', - 'comment' => _('reglages:: Service phrasea de localisation'), - 'default' => 'http://localization.webservice.alchemyasp.com/', - 'end_slash' => true, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_bitly_user', - 'comment' => _('reglages:: Nom d\'utilisateur pour l\'api bit.ly'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_bitly_key', - 'comment' => _('reglages:: ccle d\'api pour l\'api bit.ly'), - 'default' => '', - ), - array( - 'type' => 'boolean', - 'name' => 'GV_captchas', - 'comment' => _('reglages:: Utilisation de l\'api recpatcha'), - 'default' => false, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_captcha_public_key', - 'comment' => _('reglages:: clef publique recaptcha'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_captcha_private_key', - 'comment' => _('reglages:: clef privee recaptcha'), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Connectivite a Youtube'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_youtube_api', - 'comment' => sprintf(_('reglages:: Utiliser l\'api youtube, voir %s,
                  mettre la callback a WEBSITE_URL/prod/bridge/callback/youtube'), $youtube_console_url), - 'default' => false, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_youtube_client_id', - 'comment' => _('reglages:: Youtube client id'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_youtube_client_secret', - 'comment' => _('reglages:: Youtube clientsecret'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_youtube_dev_key', - 'comment' => sprintf(_('reglages:: Youtube cle developpeur, voir %s'), $dashboard_youtube), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Connectivite a FlickR'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_flickr_api', - 'comment' => sprintf(_('reglages:: Utiliser l api flickr, voir %s, puis set la callback a %s'), $create_api_flickr, $flickr_callback), - 'default' => false, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_flickr_client_id', - 'comment' => _('reglages:: FlickR client id'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_flickr_client_secret', - 'comment' => _('reglages:: FlickR client secret'), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Connectivite a Dailymotion'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_dailymotion_api', - 'comment' => sprintf(_('reglages:: Utiliser l api dailymotion, voir %s, puis set la callback a %s'), $create_api_dailymotion, $dailymotion_callback), - 'default' => false, - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_dailymotion_client_id', - 'comment' => _('reglages:: dailymotion client id'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_dailymotion_client_secret', - 'comment' => _('reglages:: dailymotion client secret'), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Gestionnaire d\'evenements'), - 'vars' => array( - array( - 'type' => 'enum_multi', - 'name' => 'GV_events', - 'default' => null, - 'comment' => _('reglages:: Evenements'), - 'available' => $eventsmanager->list_all('event'), - 'default' => array_keys($eventsmanager->list_all('event')) - ), - array( - 'type' => 'enum_multi', - 'name' => 'GV_notifications', - 'default' => null, - 'comment' => _('reglages:: Notifications'), - 'available' => $eventsmanager->list_all('notify'), - 'default' => array_keys($eventsmanager->list_all('notify')) - ) - ) - ), array( - 'section' => _('GV::section:: Stockage des documents'), - 'vars' => array( - array( - 'type' => 'string', - 'name' => 'GV_appletAllowedFileExt', - 'comment' => _('reglages:: extensions de fichier autorisees en upload, separees par des virgules. * pour autoriser tous les fichiers'), - 'default' => 'jpg,jpeg,bmp,tif,gif,png,pdf,doc,odt,mpg,mpeg,mov,avi,xls,flv,mp3,mp2', - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_base_datapath_web', - 'end_slash' => true, - 'comment' => _('reglages:: dossier de stockage des vignettes publiees en acces direct'), - 'default' => '', - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_base_datapath_noweb', - 'end_slash' => true, - 'comment' => _('reglages:: dossier de stockage des fichiers proteges de l\'acces direct'), - 'default' => '', - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_base_dataurl', - 'comment' => _('reglages:: point de montage des vignettes publiees en acces direct'), - 'default' => 'web', - 'end_slash' => false, - 'required' => true - ) - ) - ) - , array( - 'section' => _('GV::section:: Serveur Sphinx'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_sphinx', - 'comment' => _('Utiliser Sphinx'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_sphinx_host', - 'comment' => _('reglages:: de l\'adresse du serveur sphinx'), - 'default' => '127.0.0.1' - ), - array( - 'type' => 'integer', - 'name' => 'GV_sphinx_port', - 'comment' => _('reglages:: port du serveur sphinx'), - 'default' => 9306 - ), - array( - 'type' => 'string', - 'name' => 'GV_sphinx_rt_host', - 'comment' => _('reglages:: de l\'adresse du serveur RT sphinx'), - 'default' => '127.0.0.1' - ), - array( - 'type' => 'integer', - 'name' => 'GV_sphinx_rt_port', - 'comment' => _('reglages:: port du serveur RT sphinx'), - 'default' => 9308 - ) - ) - ) - , array( - 'section' => _('Phrasea Engine'), - 'vars' => array( - array( - 'type' => 'enum', - 'name' => 'GV_phrasea_sort', - 'comment' => _('Default results sort'), - 'default' => '', - 'available' => $date_sort_fields - ) - ) - ), array( - 'section' => _('GV::section:: Executables externes'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_modxsendfile', - 'comment' => _('reglages:: mod_xsendfileapache active'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_X_Accel_Redirect', - 'comment' => _('reglages:: Path en acces pour X-Accel-Redirect (NginX Uniquement)'), - 'default' => '', - 'end_slash' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_X_Accel_Redirect_mount_point', - 'comment' => _('reglages:: Point de montage pour X-Accel-Redirect (NginX Uniquement)'), - 'default' => 'noweb', - 'end_slash' => false - ), - array( - 'type' => 'boolean', - 'name' => 'GV_h264_streaming', - 'comment' => _('reglages:: activation du stream h264 via mod_token - attention, necessite les modules apache mod_h264_streaming et mod_auth_token'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_mod_auth_token_directory', - 'end_slash' => true, - 'comment' => _('reglages:: point de montage du dossier protege via auth_token'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_mod_auth_token_directory_path', - 'end_slash' => false, - 'comment' => _('reglages:: path complet du dossier protege via auth_token'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_mod_auth_token_passphrase', - 'comment' => _('reglages:: passphrase du mod_auth_token (definie dans le fichier de configuration apache)'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_cli', - 'comment' => _('reglages:: executable PHP CLI'), - 'default' => '', - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_PHP_INI', - 'comment' => _('reglages:: path du php.ini specifique (vide si non utilise)'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_imagick', - 'default' => '', - 'comment' => _('reglages:: chemin de l\'executable convert'), - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_pathcomposite', - 'default' => '', - 'comment' => _('reglages:: chemin de l\'executable composite'), - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_exiftool', - 'default' => '', - 'comment' => _('reglages:: chemin de l\'executable exiftools'), - 'required' => true - ), - array( - 'type' => 'string', - 'name' => 'GV_swf_extract', - 'comment' => _('reglages:: chemin de l\'executable swfextract'), - 'default' => '', - 'required' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_pdf2swf', - 'comment' => _('reglages:: chemin de l\'executable pdf2swf'), - 'default' => '', - 'required' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_swf_render', - 'comment' => _('reglages:: chemin de l\'executable swfrender'), - 'default' => '', - 'required' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_unoconv', - 'comment' => _('reglages:: chemin de l\'executable unoconv'), - 'default' => '', - 'required' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_ffmpeg', - 'comment' => _('reglages:: chemin de l\'executable FFmpeg'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_mp4box', - 'comment' => _('reglages:: chemin de l\'executable MP4Box'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_mplayer', - 'comment' => _('reglages:: chemin de l\'executable Mplayer'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_pdftotext', - 'comment' => _('reglages:: chemin de l\'executable pdftotext (xpdf)'), - 'default' => '' - ), - array( - 'type' => 'integer', - 'name' => 'GV_pdfmaxpages', - 'comment' => _('reglages:: nombre maximum de page a extraire (PDF)'), - 'default' => 5 - ) - ) - ), array( - 'section' => _('GV::section:: Repertoires utilitaires'), - 'vars' => array( - array( - 'type' => 'string', - 'name' => 'GV_filesOwner', - 'comment' => _('reglages:: proprietaire des fichiers'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_filesGroup', - 'comment' => _('reglages:: groupes des fichiers'), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Configuration principale'), - 'vars' => array( + , array( + 'section' => _('Phrasea Engine'), + 'vars' => array( + array( + 'type' => 'enum', + 'name' => 'GV_phrasea_sort', + 'comment' => _('Default results sort'), + 'default' => '', + 'available' => $date_sort_fields + ) + ) + ), array( + 'section' => _('GV::section:: Executables externes'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_modxsendfile', + 'comment' => _('reglages:: mod_xsendfileapache active'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_X_Accel_Redirect', + 'comment' => _('reglages:: Path en acces pour X-Accel-Redirect (NginX Uniquement)'), + 'default' => '', + 'end_slash' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_X_Accel_Redirect_mount_point', + 'comment' => _('reglages:: Point de montage pour X-Accel-Redirect (NginX Uniquement)'), + 'default' => 'noweb', + 'end_slash' => false + ), + array( + 'type' => 'boolean', + 'name' => 'GV_h264_streaming', + 'comment' => _('reglages:: activation du stream h264 via mod_token - attention, necessite les modules apache mod_h264_streaming et mod_auth_token'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_mod_auth_token_directory', + 'end_slash' => true, + 'comment' => _('reglages:: point de montage du dossier protege via auth_token'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_mod_auth_token_directory_path', + 'end_slash' => false, + 'comment' => _('reglages:: path complet du dossier protege via auth_token'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_mod_auth_token_passphrase', + 'comment' => _('reglages:: passphrase du mod_auth_token (definie dans le fichier de configuration apache)'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_cli', + 'comment' => _('reglages:: executable PHP CLI'), + 'default' => '', + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_PHP_INI', + 'comment' => _('reglages:: path du php.ini specifique (vide si non utilise)'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_imagick', + 'default' => '', + 'comment' => _('reglages:: chemin de l\'executable convert'), + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_pathcomposite', + 'default' => '', + 'comment' => _('reglages:: chemin de l\'executable composite'), + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_exiftool', + 'default' => '', + 'comment' => _('reglages:: chemin de l\'executable exiftools'), + 'required' => true + ), + array( + 'type' => 'string', + 'name' => 'GV_swf_extract', + 'comment' => _('reglages:: chemin de l\'executable swfextract'), + 'default' => '', + 'required' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_pdf2swf', + 'comment' => _('reglages:: chemin de l\'executable pdf2swf'), + 'default' => '', + 'required' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_swf_render', + 'comment' => _('reglages:: chemin de l\'executable swfrender'), + 'default' => '', + 'required' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_unoconv', + 'comment' => _('reglages:: chemin de l\'executable unoconv'), + 'default' => '', + 'required' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_ffmpeg', + 'comment' => _('reglages:: chemin de l\'executable FFmpeg'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_mp4box', + 'comment' => _('reglages:: chemin de l\'executable MP4Box'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_mplayer', + 'comment' => _('reglages:: chemin de l\'executable Mplayer'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_pdftotext', + 'comment' => _('reglages:: chemin de l\'executable pdftotext (xpdf)'), + 'default' => '' + ), + array( + 'type' => 'integer', + 'name' => 'GV_pdfmaxpages', + 'comment' => _('reglages:: nombre maximum de page a extraire (PDF)'), + 'default' => 5 + ) + ) + ), array( + 'section' => _('GV::section:: Repertoires utilitaires'), + 'vars' => array( + array( + 'type' => 'string', + 'name' => 'GV_filesOwner', + 'comment' => _('reglages:: proprietaire des fichiers'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_filesGroup', + 'comment' => _('reglages:: groupes des fichiers'), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Configuration principale'), + 'vars' => array( // array( // 'type' => 'boolean', // 'name' => 'GV_logobeforebas', @@ -532,33 +528,33 @@ $GV = array( // 'default' => false, // 'required' => true // ), - array( - 'type' => 'string', - 'name' => 'GV_adminMail', - 'comment' => _('reglages:: email de l\'administrateur'), - 'default' => 'support@alchemy.fr' - ), - array( - 'type' => 'boolean', - 'name' => 'GV_view_bas_and_coll', - 'comment' => _('reglages:: Afficher le nom des bases et des collections'), - 'default' => true, - 'required' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_choose_export_title', - 'comment' => _('reglages:: activer le choix du nom de fichier a l\'export'), - 'default' => false, - 'required' => true - ), - array( - 'type' => 'enum', - 'name' => 'GV_default_export_title', - 'comment' => _('reglages:: choix par defaut des noms de fichier a l\'export'), - 'default' => 'support@alchemy.fr', - 'available' => array('title' => 'Titre du document', 'original' => 'Nom original') - ), + array( + 'type' => 'string', + 'name' => 'GV_adminMail', + 'comment' => _('reglages:: email de l\'administrateur'), + 'default' => 'support@alchemy.fr' + ), + array( + 'type' => 'boolean', + 'name' => 'GV_view_bas_and_coll', + 'comment' => _('reglages:: Afficher le nom des bases et des collections'), + 'default' => true, + 'required' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_choose_export_title', + 'comment' => _('reglages:: activer le choix du nom de fichier a l\'export'), + 'default' => false, + 'required' => true + ), + array( + 'type' => 'enum', + 'name' => 'GV_default_export_title', + 'comment' => _('reglages:: choix par defaut des noms de fichier a l\'export'), + 'default' => 'support@alchemy.fr', + 'available' => array('title' => 'Titre du document', 'original' => 'Nom original') + ), // array( // 'type' => 'boolean', // 'name' => 'GV_ArchiveSorted', @@ -566,19 +562,19 @@ $GV = array( // 'default' => true, // 'required' => true // ), - array( - 'type' => 'enum', - 'name' => 'GV_social_tools', - 'comment' => _('reglages:: Active les partages Facebook et Twitter'), - 'available' => array('none' => 'Disabled', 'publishers' => 'Publishers', 'all' => 'Activated'), - 'default' => 'none', - 'required' => false - ) - ) - ), array( - 'section' => _('GV::section:: Page d\'accueil'), - 'rolled' => true, - 'vars' => array( + array( + 'type' => 'enum', + 'name' => 'GV_social_tools', + 'comment' => _('reglages:: Active les partages Facebook et Twitter'), + 'available' => array('none' => 'Disabled', 'publishers' => 'Publishers', 'all' => 'Activated'), + 'default' => 'none', + 'required' => false + ) + ) + ), array( + 'section' => _('GV::section:: Page d\'accueil'), + 'rolled' => true, + 'vars' => array( // array( // 'type' => 'boolean', // 'name' => 'GV_find_password', @@ -586,78 +582,78 @@ $GV = array( // 'default' => true, // 'required' => true // ), - array( - 'type' => 'enum', - 'name' => 'GV_home_publi', - 'comment' => _('reglages:: presentation sur la home'), - 'default' => 'COOLIRIS', - 'available' => array('DISPLAYx1' => 'slideshow', 'SCROLL' => 'Bandeau defilant', 'COOLIRIS' => 'Cooliris'), - 'required' => true - ) + array( + 'type' => 'enum', + 'name' => 'GV_home_publi', + 'comment' => _('reglages:: presentation sur la home'), + 'default' => 'COOLIRIS', + 'available' => array('DISPLAYx1' => 'slideshow', 'SCROLL' => 'Bandeau defilant', 'COOLIRIS' => 'Cooliris'), + 'required' => true + ) + ) + ), array( + 'section' => _('GV::section:: Moteur de recherche'), + 'rolled' => true, + 'vars' => array( + array( + 'type' => 'integer', + 'name' => 'GV_min_letters_truncation', + 'comment' => _('reglages:: Nombre minimal de lettre avec la troncature (Recherche)'), + 'default' => 1 + ), + array( + 'type' => 'string', + 'name' => 'GV_defaultQuery', + 'comment' => _('reglages:: Question par defaut'), + 'default' => 'all' + ), + array( + 'type' => 'enum', + 'name' => 'GV_defaultQuery_type', + 'comment' => _('reglages:: type de document cherches par defaut e l\'ouverture du site'), + 'available' => array('0' => 'Documents', '1' => 'Regroupements'), + 'default' => '0' + ) + ) + ), array( + 'section' => _('GV::section:: Report'), + 'rolled' => true, + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_anonymousReport', + 'comment' => _('reglages:: report anonyme (masque les infos concernant les utilisateurs)'), + 'default' => false, + 'required' => true + ) + ) + ), array( + 'section' => _('GV::section:: Modules supplementaires'), + 'rolled' => true, + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_thesaurus', + 'comment' => _('reglages:: Activation de l\'outil thesaurus'), + 'default' => true + ), array( + 'type' => 'boolean', + 'name' => 'GV_multiAndReport', + 'comment' => _('reglages:: Activation du Mode MultiDOC'), + 'default' => true + ), array( + 'type' => 'boolean', + 'name' => 'GV_seeOngChgDoc', + 'comment' => _('reglages:: Substitution de HD d\'un record '), + 'default' => false + ), array( + 'type' => 'boolean', + 'name' => 'GV_seeNewThumb', + 'comment' => _('reglages:: Substitution de thumbnail d\'un record'), + 'default' => false + ) + ) ) - ), array( - 'section' => _('GV::section:: Moteur de recherche'), - 'rolled' => true, - 'vars' => array( - array( - 'type' => 'integer', - 'name' => 'GV_min_letters_truncation', - 'comment' => _('reglages:: Nombre minimal de lettre avec la troncature (Recherche)'), - 'default' => 1 - ), - array( - 'type' => 'string', - 'name' => 'GV_defaultQuery', - 'comment' => _('reglages:: Question par defaut'), - 'default' => 'all' - ), - array( - 'type' => 'enum', - 'name' => 'GV_defaultQuery_type', - 'comment' => _('reglages:: type de document cherches par defaut e l\'ouverture du site'), - 'available' => array('0' => 'Documents', '1' => 'Regroupements'), - 'default' => '0' - ) - ) - ), array( - 'section' => _('GV::section:: Report'), - 'rolled' => true, - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_anonymousReport', - 'comment' => _('reglages:: report anonyme (masque les infos concernant les utilisateurs)'), - 'default' => false, - 'required' => true - ) - ) - ), array( - 'section' => _('GV::section:: Modules supplementaires'), - 'rolled' => true, - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_thesaurus', - 'comment' => _('reglages:: Activation de l\'outil thesaurus'), - 'default' => true - ), array( - 'type' => 'boolean', - 'name' => 'GV_multiAndReport', - 'comment' => _('reglages:: Activation du Mode MultiDOC'), - 'default' => true - ), array( - 'type' => 'boolean', - 'name' => 'GV_seeOngChgDoc', - 'comment' => _('reglages:: Substitution de HD d\'un record '), - 'default' => false - ), array( - 'type' => 'boolean', - 'name' => 'GV_seeNewThumb', - 'comment' => _('reglages:: Substitution de thumbnail d\'un record'), - 'default' => false - ) - ) - ) // , array( // 'section' => _('GV::section:: Authentification LDAP'), // 'rolled' => true, @@ -736,242 +732,242 @@ $GV = array( // ) // ) // ) - , array( - 'section' => _('GV::section:: Envois de mails'), - 'vars' => array( + , array( + 'section' => _('GV::section:: Envois de mails'), + 'vars' => array( // array( // 'type' => 'boolean', // 'name' => 'GV_exportmail', // 'comment' => _('reglages:: Activation de l\'export par mail'), // 'default' => true // ), - array( - 'type' => 'string', - 'name' => 'GV_defaulmailsenderaddr', - 'comment' => _('reglages:: Expediteur mail par defaut'), - 'default' => 'phraseanet@example.com' - ), - array( - 'type' => 'boolean', - 'name' => 'GV_smtp', - 'comment' => _('reglages:: Utilisation d\'un serveur SMTP'), - 'default' => false - ), - array( - 'type' => 'boolean', - 'name' => 'GV_smtp_auth', - 'comment' => _('reglages:: Activation de l\'authentification smtp'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_smtp_host', - 'comment' => _('reglages:: Hote SMTP'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_smtp_port', - 'comment' => _('reglages:: Port SMTP'), - 'default' => '' - ), - array( - 'type' => 'boolean', - 'name' => 'GV_smtp_secure', - 'comment' => _('reglages:: Utiliser une conenction SSL'), - 'default' => false - ), - array( - 'type' => 'string', - 'name' => 'GV_smtp_user', - 'comment' => _('reglages:: User SMTP'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_smtp_password', - 'comment' => _('reglages:: Mot de passe SMTP'), - 'default' => '' - ) - ) - ), array( - 'section' => _('GV::section:: Exports FTP'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_activeFTP', - 'comment' => _('reglages:: active la possibilite d\'exports FTP ou non (onglet dans multiexports)'), - 'default' => false - ), - array( - 'type' => 'boolean', - 'name' => 'GV_ftp_for_user', - 'comment' => _('reglages:: Donne ou non export FTP aux utilisateurs ou e l\'admin uniquement'), - 'default' => false - ) - ) - ), array( - 'section' => _('GV::section:: Configuration du client'), - 'vars' => array( - array( - 'type' => 'integer', - 'name' => 'GV_download_max', - 'comment' => _('Maximum megabytes allowed in download (if request is bigger, then mail is still available)'), - 'default' => 120 - ), - array( - 'type' => 'integer', - 'name' => 'GV_ong_search', - 'comment' => _('reglages:: position de l\'onglet de recherche'), - 'default' => 1 - ), - array( - 'type' => 'integer', - 'name' => 'GV_ong_advsearch', - 'comment' => _('reglages:: position de l\'onglet de recherche avancee'), - 'default' => 2 - ), - array( - 'type' => 'integer', - 'name' => 'GV_ong_topics', - 'comment' => _('reglages:: position de l\'onglet des topics'), - 'default' => 0 - ), - array( - 'type' => 'integer', - 'name' => 'GV_ong_actif', - 'comment' => _('reglages:: numero de l\'onglet actif'), - 'default' => 1 - ), - array( - 'type' => 'enum', - 'name' => 'GV_client_render_topics', - 'comment' => _('reglages:: rendu des topics'), - 'available' => array('tree' => 'Arbres', 'popups' => 'Menus deroulants'), - 'default' => 'tree' - ), + array( + 'type' => 'string', + 'name' => 'GV_defaulmailsenderaddr', + 'comment' => _('reglages:: Expediteur mail par defaut'), + 'default' => 'phraseanet@example.com' + ), + array( + 'type' => 'boolean', + 'name' => 'GV_smtp', + 'comment' => _('reglages:: Utilisation d\'un serveur SMTP'), + 'default' => false + ), + array( + 'type' => 'boolean', + 'name' => 'GV_smtp_auth', + 'comment' => _('reglages:: Activation de l\'authentification smtp'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_smtp_host', + 'comment' => _('reglages:: Hote SMTP'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_smtp_port', + 'comment' => _('reglages:: Port SMTP'), + 'default' => '' + ), + array( + 'type' => 'boolean', + 'name' => 'GV_smtp_secure', + 'comment' => _('reglages:: Utiliser une conenction SSL'), + 'default' => false + ), + array( + 'type' => 'string', + 'name' => 'GV_smtp_user', + 'comment' => _('reglages:: User SMTP'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_smtp_password', + 'comment' => _('reglages:: Mot de passe SMTP'), + 'default' => '' + ) + ) + ), array( + 'section' => _('GV::section:: Exports FTP'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_activeFTP', + 'comment' => _('reglages:: active la possibilite d\'exports FTP ou non (onglet dans multiexports)'), + 'default' => false + ), + array( + 'type' => 'boolean', + 'name' => 'GV_ftp_for_user', + 'comment' => _('reglages:: Donne ou non export FTP aux utilisateurs ou e l\'admin uniquement'), + 'default' => false + ) + ) + ), array( + 'section' => _('GV::section:: Configuration du client'), + 'vars' => array( + array( + 'type' => 'integer', + 'name' => 'GV_download_max', + 'comment' => _('Maximum megabytes allowed in download (if request is bigger, then mail is still available)'), + 'default' => 120 + ), + array( + 'type' => 'integer', + 'name' => 'GV_ong_search', + 'comment' => _('reglages:: position de l\'onglet de recherche'), + 'default' => 1 + ), + array( + 'type' => 'integer', + 'name' => 'GV_ong_advsearch', + 'comment' => _('reglages:: position de l\'onglet de recherche avancee'), + 'default' => 2 + ), + array( + 'type' => 'integer', + 'name' => 'GV_ong_topics', + 'comment' => _('reglages:: position de l\'onglet des topics'), + 'default' => 0 + ), + array( + 'type' => 'integer', + 'name' => 'GV_ong_actif', + 'comment' => _('reglages:: numero de l\'onglet actif'), + 'default' => 1 + ), + array( + 'type' => 'enum', + 'name' => 'GV_client_render_topics', + 'comment' => _('reglages:: rendu des topics'), + 'available' => array('tree' => 'Arbres', 'popups' => 'Menus deroulants'), + 'default' => 'tree' + ), // array( // 'type' => 'boolean', // 'name' => 'GV_grp_preview_list', // 'comment' => _('reglages:: Voir les elements d\'un reportage sans Thumbnail (fenetre de preview)'), // 'default' => false // ), - array( - 'type' => 'boolean', - 'name' => 'GV_rollover_reg_preview', - 'comment' => _('reglages:: Voir le rollover sur les regroupements (fenetre de preview)'), - 'default' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_rollover_chu', - 'comment' => _('reglages:: Voir le rollover sur les elements du chutier'), - 'default' => true - ), - array( - 'type' => 'enum', - 'name' => 'GV_client_coll_ckbox', - 'comment' => _('reglages:: Presentation des collections'), - 'default' => 'checkbox', - 'available' => array('popup' => 'Menu deroulant', 'checkbox' => 'case a cocher') - ), - array( - 'type' => 'boolean', - 'name' => 'GV_viewSizeBaket', - 'comment' => _('reglages:: Voir taille HD total des doc d\'un chutiers'), - 'default' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_clientAutoShowProposals', - 'comment' => _('reglages:: Afficher automatiquement l\'onglet des propositions s\'il y\'en a'), - 'default' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_needAuth2DL', - 'comment' => _('reglages:: Il est necessaire d\'etre connecte pour pouvoir telecharger en compte invite'), - 'default' => true - ) - ) - ), array( - 'section' => _('GV::section:: Parametrage de l\'inscription'), - 'vars' => array( - array( - 'type' => 'boolean', - 'name' => 'GV_autoselectDB', - 'comment' => _('reglages:: A true, cette option descative le choix de selection des bases sur lesquelles on s\'inscrit, et l\'inscription se fait sur toutes les bases ou jai le droit de m\'inscrire'), - 'default' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_autoregister', - 'comment' => _('reglages:: Activation de l\'autoinscription'), - 'default' => false - ) - ) - ), array( - 'section' => _('GV::section:: Configuration du push'), - 'vars' => array( - array( - 'type' => 'integer', - 'name' => 'GV_validation_reminder', - 'comment' => _('reglages:: Nombre de jour avant la fin de la validation pour envoie de mail de rappel'), - 'default' => 2 - ), + array( + 'type' => 'boolean', + 'name' => 'GV_rollover_reg_preview', + 'comment' => _('reglages:: Voir le rollover sur les regroupements (fenetre de preview)'), + 'default' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_rollover_chu', + 'comment' => _('reglages:: Voir le rollover sur les elements du chutier'), + 'default' => true + ), + array( + 'type' => 'enum', + 'name' => 'GV_client_coll_ckbox', + 'comment' => _('reglages:: Presentation des collections'), + 'default' => 'checkbox', + 'available' => array('popup' => 'Menu deroulant', 'checkbox' => 'case a cocher') + ), + array( + 'type' => 'boolean', + 'name' => 'GV_viewSizeBaket', + 'comment' => _('reglages:: Voir taille HD total des doc d\'un chutiers'), + 'default' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_clientAutoShowProposals', + 'comment' => _('reglages:: Afficher automatiquement l\'onglet des propositions s\'il y\'en a'), + 'default' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_needAuth2DL', + 'comment' => _('reglages:: Il est necessaire d\'etre connecte pour pouvoir telecharger en compte invite'), + 'default' => true + ) + ) + ), array( + 'section' => _('GV::section:: Parametrage de l\'inscription'), + 'vars' => array( + array( + 'type' => 'boolean', + 'name' => 'GV_autoselectDB', + 'comment' => _('reglages:: A true, cette option descative le choix de selection des bases sur lesquelles on s\'inscrit, et l\'inscription se fait sur toutes les bases ou jai le droit de m\'inscrire'), + 'default' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_autoregister', + 'comment' => _('reglages:: Activation de l\'autoinscription'), + 'default' => false + ) + ) + ), array( + 'section' => _('GV::section:: Configuration du push'), + 'vars' => array( + array( + 'type' => 'integer', + 'name' => 'GV_validation_reminder', + 'comment' => _('reglages:: Nombre de jour avant la fin de la validation pour envoie de mail de rappel'), + 'default' => 2 + ), // array( // 'type' => 'boolean', // 'name' => 'GV_DL_checkit', // 'comment' => _('reglages:: Autorise le telechargement des fichiers pendant le process de validation'), // 'default' => true // ), - array( - 'type' => 'integer', - 'name' => 'GV_val_expiration', - 'comment' => _('reglages:: dure de validite des liens genere pour les validations, si 0 => validite permanente'), - 'default' => 10 - ) + array( + 'type' => 'integer', + 'name' => 'GV_val_expiration', + 'comment' => _('reglages:: dure de validite des liens genere pour les validations, si 0 => validite permanente'), + 'default' => 10 + ) + ) + ), array( + 'section' => _('GV::section:: Indexation par les robots'), + 'vars' => array( + array( + 'type' => 'string', + 'name' => 'GV_homeTitle', + 'comment' => _('reglages :: Titre de l\'installation'), + 'default' => 'Phraseanet' + ), + array( + 'type' => 'string', + 'name' => 'GV_metaKeywords', + 'comment' => _('reglages:: Mots clefs pour l\'indexation des robots de moteurs de recherche'), + 'default' => '' + ), + array( + 'type' => 'text', + 'name' => 'GV_metaDescription', + 'comment' => _('reglages :: Description de l\'installation'), + 'default' => '' + ), + array( + 'type' => 'string', + 'name' => 'GV_googleAnalytics', + 'comment' => _('reglages:: identifiant google analytics'), + 'default' => '' + ), + array( + 'type' => 'boolean', + 'name' => 'GV_allow_search_engine', + 'comment' => _('Allow the website to be indexed by search engines like Google'), + 'default' => true + ), + array( + 'type' => 'boolean', + 'name' => 'GV_display_gcf', + 'comment' => _('reglages:: Afficher le bandeau Google Chrome Frame'), + 'default' => true + ) + ) ) - ), array( - 'section' => _('GV::section:: Indexation par les robots'), - 'vars' => array( - array( - 'type' => 'string', - 'name' => 'GV_homeTitle', - 'comment' => _('reglages :: Titre de l\'installation'), - 'default' => 'Phraseanet' - ), - array( - 'type' => 'string', - 'name' => 'GV_metaKeywords', - 'comment' => _('reglages:: Mots clefs pour l\'indexation des robots de moteurs de recherche'), - 'default' => '' - ), - array( - 'type' => 'text', - 'name' => 'GV_metaDescription', - 'comment' => _('reglages :: Description de l\'installation'), - 'default' => '' - ), - array( - 'type' => 'string', - 'name' => 'GV_googleAnalytics', - 'comment' => _('reglages:: identifiant google analytics'), - 'default' => '' - ), - array( - 'type' => 'boolean', - 'name' => 'GV_allow_search_engine', - 'comment' => _('Allow the website to be indexed by search engines like Google'), - 'default' => true - ), - array( - 'type' => 'boolean', - 'name' => 'GV_display_gcf', - 'comment' => _('reglages:: Afficher le bandeau Google Chrome Frame'), - 'default' => true - ) ) - ) - ) ?> diff --git a/localesToLaunchPad.php b/localesToLaunchPad.php index ea25132c39..d48541ec9d 100755 --- a/localesToLaunchPad.php +++ b/localesToLaunchPad.php @@ -1,10 +1,10 @@ #!/usr/bin/env php files() - ->name('phraseanet.po') - ->in( - array( - __DIR__ . '/locale', + ->files() + ->name('phraseanet.po') + ->in( + array( + __DIR__ . '/locale', + ) ) - ) ; $count = 0; -foreach ($finder as $file) -{ - $cmd = sprintf( - 'cp %s ./locale/phraseanet-%s.po' - , $file->getRealPath() - , basename(dirname(dirname($file->getRealPath()))) - ) . PHP_EOL; +foreach ($finder as $file) { + $cmd = sprintf( + 'cp %s ./locale/phraseanet-%s.po' + , $file->getRealPath() + , basename(dirname(dirname($file->getRealPath()))) + ) . PHP_EOL; - system($cmd); - $count++; + system($cmd); + $count ++; } echo "$count files copied" . PHP_EOL; diff --git a/vendors.php b/vendors.php index 781b07f373..8d0323d6da 100755 --- a/vendors.php +++ b/vendors.php @@ -18,16 +18,14 @@ set_time_limit(0); $composer = __DIR__ . '/composer.phar'; -if (!file_exists($composer)) -{ - system('curl -s http://getcomposer.org/installer | php'); - system('chmod +x ' . $composer); - system($composer . ' install'); +if ( ! file_exists($composer)) { + system('curl -s http://getcomposer.org/installer | php'); + system('chmod +x ' . $composer); + system($composer . ' install'); } -if (!is_executable($composer)) -{ - system('chmod +x ' . $composer); +if ( ! is_executable($composer)) { + system('chmod +x ' . $composer); } system($composer . ' self-update'); @@ -38,12 +36,10 @@ system('git submodule update'); $iterator = new RecursiveDirectoryIterator(__DIR__ . '/lib/vendor/'); -foreach ($iterator as $file) -{ - /* @var $file SplFileInfo */ - if ($file->isDir()) - { - $cmd = sprintf('cd %s && git submodule init && git submodule update', escapeshellarg($file->getPathname())); - system($cmd); - } +foreach ($iterator as $file) { + /* @var $file SplFileInfo */ + if ($file->isDir()) { + $cmd = sprintf('cd %s && git submodule init && git submodule update', escapeshellarg($file->getPathname())); + system($cmd); + } } diff --git a/vendors.win.php b/vendors.win.php index b23e10fa53..02f231f8a5 100755 --- a/vendors.win.php +++ b/vendors.win.php @@ -12,14 +12,13 @@ /** * Get all dependencies needed for Phraseanet (Windows Version) */ - -/* Set the variables gitDir and phpDir with a trailing slash if it is not set in Windows' %PATH% +/* Set the variables gitDir and phpDir with a trailing slash if it is not set in Windows' %PATH% * For example : * $gitDir="c:/msysgit/bin/"; * $phpDir="c:/php5310/" */ -$gitDir=""; -$phpDir=""; +$gitDir = ""; +$phpDir = ""; chdir(__DIR__); @@ -28,10 +27,9 @@ set_time_limit(0); $composer = __DIR__ . '/composer.phar'; -if (!file_exists($composer)) -{ - file_put_contents($composer, file_get_contents('http://getcomposer.org/installer'), LOCK_EX); - system($phpDir . 'php ' . $composer . ' install'); +if ( ! file_exists($composer)) { + file_put_contents($composer, file_get_contents('http://getcomposer.org/installer'), LOCK_EX); + system($phpDir . 'php ' . $composer . ' install'); } system($phpDir . 'php ' . $composer . ' self-update'); @@ -42,12 +40,10 @@ system($gitDir . 'git submodule update'); $iterator = new RecursiveDirectoryIterator(__DIR__ . '/lib/vendor/'); -foreach ($iterator as $file) -{ - /* @var $file SplFileInfo */ - if ($file->isDir()) - { - $cmd = sprintf('cd %s && ' . $gitDir . 'git submodule init && ' . $gitDir . 'git submodule update', escapeshellarg($file->getPathname())); - system($cmd); - } +foreach ($iterator as $file) { + /* @var $file SplFileInfo */ + if ($file->isDir()) { + $cmd = sprintf('cd %s && ' . $gitDir . 'git submodule init && ' . $gitDir . 'git submodule update', escapeshellarg($file->getPathname())); + system($cmd); + } } diff --git a/www/admin/adminFeedback.php b/www/admin/adminFeedback.php index 9b6859d334..021ecd619f 100644 --- a/www/admin/adminFeedback.php +++ b/www/admin/adminFeedback.php @@ -25,350 +25,311 @@ $parm = $request->get_parms('action', 'position', 'test', 'renew', 'path', 'test $output = ''; -switch ($parm['action']) -{ - case 'TREE': - $output = module_admin::getTree($parm['position']); - break; - case 'APACHE': - if ($parm['test'] == 'success') - $output = '1'; - else - $output = '0'; - break; - case 'SCHEDULERKEY': - $output = $registry->get('GV_ServerName') . 'admin/runscheduler.php?key=' . urlencode(phrasea::scheduler_key(!!$parm['renew'])); - break; - - case 'TESTPATH': - $tests = true; - foreach ($parm['tests'] as $test) - { - switch ($test) - { - case 'writeable': - if (!is_writable($parm['path'])) - { - $tests = false; - } - break; - case 'readable': - default: - if (!is_readable($parm['path'])) - { - $tests = true; - } - break; - } - } - $output = p4string::jsonencode(array('results' => ($tests ? '1' : '0'))); - break; - - case 'EMPTYBASE': - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $message = _('Base empty successful'); - try - { - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $class_name = 'task_period_emptyColl'; - foreach ($databox->get_collections() as $collection) - { - if($collection->get_record_amount() <= 500) - { - $collection->empty_collection(500); - } +switch ($parm['action']) { + case 'TREE': + $output = module_admin::getTree($parm['position']); + break; + case 'APACHE': + if ($parm['test'] == 'success') + $output = '1'; else - { - $settings = "" . $collection->get_base_id() . ""; - task_abstract::create($appbox, $class_name, $settings); - $message = _('A task has been creted, please run it to complete empty collection'); + $output = '0'; + break; + case 'SCHEDULERKEY': + $output = $registry->get('GV_ServerName') . 'admin/runscheduler.php?key=' . urlencode(phrasea::scheduler_key( ! ! $parm['renew'])); + break; + + case 'TESTPATH': + $tests = true; + foreach ($parm['tests'] as $test) { + switch ($test) { + case 'writeable': + if ( ! is_writable($parm['path'])) { + $tests = false; + } + break; + case 'readable': + default: + if ( ! is_readable($parm['path'])) { + $tests = true; + } + break; + } } - } - } - catch (Exception $e) - { - $message = _('An error occurred'); - } - $output = p4string::jsonencode(array('message'=>$message)); - break; - case 'EMPTYCOLL': - $message = _('Collection empty successful'); - $parm = $request->get_parms( - array( - "sbas_id" => http_request::SANITIZE_NUMBER_INT - , "coll_id" => http_request::SANITIZE_NUMBER_INT - ) - ); - try - { - $databox = databox::get_instance($parm['sbas_id']); - $collection = collection::get_from_coll_id($databox, $parm['coll_id']); + $output = p4string::jsonencode(array('results' => ($tests ? '1' : '0'))); + break; - if($collection->get_record_amount() <= 500) - { - $collection->empty_collection(500); - } - else - { - $class_name = 'task_period_emptyColl'; - $settings = "\n\n" . $collection->get_base_id() . ""; + case 'EMPTYBASE': + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $message = _('Base empty successful'); + try { + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $class_name = 'task_period_emptyColl'; + foreach ($databox->get_collections() as $collection) { + if ($collection->get_record_amount() <= 500) { + $collection->empty_collection(500); + } else { + $settings = "" . $collection->get_base_id() . ""; + task_abstract::create($appbox, $class_name, $settings); + $message = _('A task has been creted, please run it to complete empty collection'); + } + } + } catch (Exception $e) { + $message = _('An error occurred'); + } + $output = p4string::jsonencode(array('message' => $message)); + break; + case 'EMPTYCOLL': + $message = _('Collection empty successful'); + $parm = $request->get_parms( + array( + "sbas_id" => http_request::SANITIZE_NUMBER_INT + , "coll_id" => http_request::SANITIZE_NUMBER_INT + ) + ); + try { + $databox = databox::get_instance($parm['sbas_id']); + $collection = collection::get_from_coll_id($databox, $parm['coll_id']); - task_abstract::create($appbox, $class_name, $settings); - $message = _('A task has been creted, please run it to complete empty collection'); - } - } - catch (Exception $e) - { - $message = _('An error occurred'); - } - $output = p4string::jsonencode(array('message'=>$message)); - break; + if ($collection->get_record_amount() <= 500) { + $collection->empty_collection(500); + } else { + $class_name = 'task_period_emptyColl'; + $settings = "\n\n" . $collection->get_base_id() . ""; - case 'SETTASKSTATUS': - $parm = $request->get_parms('task_id', 'status', 'signal'); - try - { - $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm['task_id']); - $pid = (int)($task->get_pid()); - $task->set_status($parm["status"]); - $signal = (int)($parm['signal']); - if( $signal > 0 && $pid ) - posix_kill($pid, $signal); - } - catch (Exception $e) - { + task_abstract::create($appbox, $class_name, $settings); + $message = _('A task has been creted, please run it to complete empty collection'); + } + } catch (Exception $e) { + $message = _('An error occurred'); + } + $output = p4string::jsonencode(array('message' => $message)); + break; - } - $output = json_encode($pid); - break; + case 'SETTASKSTATUS': + $parm = $request->get_parms('task_id', 'status', 'signal'); + try { + $task_manager = new task_manager($appbox); + $task = $task_manager->get_task($parm['task_id']); + $pid = (int) ($task->get_pid()); + $task->set_status($parm["status"]); + $signal = (int) ($parm['signal']); + if ($signal > 0 && $pid) + posix_kill($pid, $signal); + } catch (Exception $e) { - case 'SETSCHEDSTATUS': - $parm = $request->get_parms('status', 'signal'); - try - { - $task_manager = new task_manager($appbox); + } + $output = json_encode($pid); + break; - $task_manager->set_sched_status($parm['status']); - } - catch (Exception $e) - { + case 'SETSCHEDSTATUS': + $parm = $request->get_parms('status', 'signal'); + try { + $task_manager = new task_manager($appbox); - } - break; + $task_manager->set_sched_status($parm['status']); + } catch (Exception $e) { - case 'RESETTASKCRASHCOUNTER': - $parm = $request->get_parms("task_id"); - try - { - $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm['task_id']); - $task->reset_crash_counter(); - } - catch (Exception $e) - { + } + break; - } - $ret = new DOMDocument("1.0", "UTF-8"); - $ret->standalone = true; - $ret->preserveWhiteSpace = false; - $root = $ret->appendChild($ret->createElement("result")); - $root->appendChild($ret->createCDATASection(var_export($parm, true))); + case 'RESETTASKCRASHCOUNTER': + $parm = $request->get_parms("task_id"); + try { + $task_manager = new task_manager($appbox); + $task = $task_manager->get_task($parm['task_id']); + $task->reset_crash_counter(); + } catch (Exception $e) { - $output = $ret->saveXML(); - break; + } + $ret = new DOMDocument("1.0", "UTF-8"); + $ret->standalone = true; + $ret->preserveWhiteSpace = false; + $root = $ret->appendChild($ret->createElement("result")); + $root->appendChild($ret->createCDATASection(var_export($parm, true))); - case 'CHANGETASK': - $parm = $request->get_parms('act', 'task_id', "usr"); - $ret = new DOMDocument("1.0", "UTF-8"); - $ret->standalone = true; - $ret->preserveWhiteSpace = false; - $root = $ret->appendChild($ret->createElement("result")); - $root->setAttribute("saved", "0"); - $root->appendChild($ret->createCDATASection(var_export($parm, true))); + $output = $ret->saveXML(); + break; - try - { - $task_manager = new task_manager($appbox); - $task = $task_manager->get_task($parm["task_id"]); - /** - * @todo checker, cette methode n'est pas implementee partout - */ - $root->setAttribute("crashed", $task->get_crash_counter()); - if ($task->saveChanges($conn, $parm["task_id"], $row)) - $root->setAttribute("saved", "1"); - } - catch (Exception $e) - { + case 'CHANGETASK': + $parm = $request->get_parms('act', 'task_id', "usr"); + $ret = new DOMDocument("1.0", "UTF-8"); + $ret->standalone = true; + $ret->preserveWhiteSpace = false; + $root = $ret->appendChild($ret->createElement("result")); + $root->setAttribute("saved", "0"); + $root->appendChild($ret->createCDATASection(var_export($parm, true))); - } + try { + $task_manager = new task_manager($appbox); + $task = $task_manager->get_task($parm["task_id"]); + /** + * @todo checker, cette methode n'est pas implementee partout + */ + $root->setAttribute("crashed", $task->get_crash_counter()); + if ($task->saveChanges($conn, $parm["task_id"], $row)) + $root->setAttribute("saved", "1"); + } catch (Exception $e) { - $output = $ret->saveXML(); - break; - case 'PINGSCHEDULER_JS': - $ret = array('time'=> date("H:i:s") ); + } - $task_manager = new task_manager($appbox); - $ret['scheduler'] = $task_manager->get_scheduler_state(); + $output = $ret->saveXML(); + break; + case 'PINGSCHEDULER_JS': + $ret = array('time' => date("H:i:s")); - $ret['tasks'] = array(); + $task_manager = new task_manager($appbox); + $ret['scheduler'] = $task_manager->get_scheduler_state(); - foreach ($task_manager->get_tasks(true) as $task) - { - $id = $task->get_task_id(); - $ret['tasks'][$id] = array( - 'id'=>$id - , 'pid' =>$task->get_pid() - , 'crashed'=>$task->get_crash_counter() - , 'completed'=>$task->get_completed_percentage() - , 'status'=>$task->get_status() - ); - } + $ret['tasks'] = array(); - if(1) - { - $sql = 'SHOW PROCESSLIST'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rows = $stmt->fetchALL(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $ret['db_processlist'] = array(); - foreach($rows as $row) - { - if($row['Info'] != $sql) - $ret['db_processlist'][] = $row; - } - } + foreach ($task_manager->get_tasks(true) as $task) { + $id = $task->get_task_id(); + $ret['tasks'][$id] = array( + 'id' => $id + , 'pid' => $task->get_pid() + , 'crashed' => $task->get_crash_counter() + , 'completed' => $task->get_completed_percentage() + , 'status' => $task->get_status() + ); + } - $output = p4string::jsonencode($ret); - break; + if (1) { + $sql = 'SHOW PROCESSLIST'; + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(); + $rows = $stmt->fetchALL(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + $ret['db_processlist'] = array(); + foreach ($rows as $row) { + if ($row['Info'] != $sql) + $ret['db_processlist'][] = $row; + } + } - case 'UNMOUNTBASE': - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $ret = array('sbas_id' => null); + $output = p4string::jsonencode($ret); + break; - $databox = databox::get_instance((int) $parm['sbas_id']); - $databox->unmount_databox($appbox); + case 'UNMOUNTBASE': + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $ret = array('sbas_id' => null); - $ret['sbas_id'] = $parm['sbas_id']; - $output = p4string::jsonencode($ret); - break; - - case 'P_BAR_INFO': - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $ret = array( - 'sbas_id' => null, - 'indexable' => false, - 'records' => 0, - 'xml_indexed' => 0, - 'thesaurus_indexed' => 0, - 'viewname' => null, - 'printLogoURL' => NULL - ); - - $databox = databox::get_instance((int) $parm['sbas_id']); - - $ret['indexable'] = $appbox->is_databox_indexable($databox); - $ret['viewname'] = (($databox->get_dbname() == $databox->get_viewname()) ? _('admin::base: aucun alias') : $databox->get_viewname()); - - $ret['records'] = $databox->get_record_amount(); - - $datas = $databox->get_indexed_record_amount(); - - $ret['sbas_id'] = $parm['sbas_id']; - $tot = $idxxml = $idxth = 0; - - $ret['xml_indexed'] = $datas['xml_indexed']; - $ret['thesaurus_indexed'] = $datas['thesaurus_indexed']; - - if (file_exists($registry->get('GV_RootPath') . 'config/minilogos/logopdf_' . $parm['sbas_id'] . '.jpg')) - $ret['printLogoURL'] = '/print/' . $parm['sbas_id']; - $output = p4string::jsonencode($ret); - break; - - case 'CHGVIEWNAME': - - $parm = $request->get_parms('sbas_id', 'viewname'); - $ret = array('sbas_id' => null, 'viewname' => null); - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $appbox->set_databox_viewname($databox, $parm['viewname']); - $output = p4string::jsonencode($ret); - break; - - case 'MAKEINDEXABLE': - - $parm = $request->get_parms('sbas_id', 'INDEXABLE'); - $ret = array('sbas_id' => null, 'indexable' => null); - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $appbox->set_databox_indexable($databox, $parm['INDEXABLE']); - $ret['sbas_id'] = $parm['sbas_id']; - $ret['indexable'] = $parm['INDEXABLE']; - $output = p4string::jsonencode($ret); - break; - - case 'REINDEX': - - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $ret = array('sbas_id' => null); - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $databox->reindex(); - $output = p4string::jsonencode($ret); - break; - - case 'CLEARALLLOG': - - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $ret = array('sbas_id' => null); - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $databox->clear_logs(); - $ret['sbas_id'] = $parm['sbas_id']; - $output = p4string::jsonencode($ret); - break; - - case 'DELLOGOPDF': - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - $ret = array('sbas_id' => null); - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - $appbox->write_databox_pic($databox, null, databox::PIC_PDF); - $ret['sbas_id'] = $parm['sbas_id']; - - $output = p4string::jsonencode($ret); - break; - - case 'DELETEBASE': - $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); - - $ret = array('sbas_id' => null, 'err' => -1, 'errmsg' => null); - - try - { - $sbas_id = (int) $parm['sbas_id']; - $databox = databox::get_instance($sbas_id); - if ($databox->get_record_amount() == 0) - { + $databox = databox::get_instance((int) $parm['sbas_id']); $databox->unmount_databox($appbox); - $appbox->write_databox_pic($databox, null, databox::PIC_PDF); - $databox->delete(); + $ret['sbas_id'] = $parm['sbas_id']; - $ret['err'] = 0; - } - else - { - $ret['errmsg'] = _('admin::base: vider la base avant de la supprimer'); - } - } - catch (Exception $e) - { - $ret['errmsg'] = $e->getMessage(); - } - $output = p4string::jsonencode($ret); - break; + $output = p4string::jsonencode($ret); + break; + + case 'P_BAR_INFO': + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $ret = array( + 'sbas_id' => null, + 'indexable' => false, + 'records' => 0, + 'xml_indexed' => 0, + 'thesaurus_indexed' => 0, + 'viewname' => null, + 'printLogoURL' => NULL + ); + + $databox = databox::get_instance((int) $parm['sbas_id']); + + $ret['indexable'] = $appbox->is_databox_indexable($databox); + $ret['viewname'] = (($databox->get_dbname() == $databox->get_viewname()) ? _('admin::base: aucun alias') : $databox->get_viewname()); + + $ret['records'] = $databox->get_record_amount(); + + $datas = $databox->get_indexed_record_amount(); + + $ret['sbas_id'] = $parm['sbas_id']; + $tot = $idxxml = $idxth = 0; + + $ret['xml_indexed'] = $datas['xml_indexed']; + $ret['thesaurus_indexed'] = $datas['thesaurus_indexed']; + + if (file_exists($registry->get('GV_RootPath') . 'config/minilogos/logopdf_' . $parm['sbas_id'] . '.jpg')) + $ret['printLogoURL'] = '/print/' . $parm['sbas_id']; + $output = p4string::jsonencode($ret); + break; + + case 'CHGVIEWNAME': + + $parm = $request->get_parms('sbas_id', 'viewname'); + $ret = array('sbas_id' => null, 'viewname' => null); + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $appbox->set_databox_viewname($databox, $parm['viewname']); + $output = p4string::jsonencode($ret); + break; + + case 'MAKEINDEXABLE': + + $parm = $request->get_parms('sbas_id', 'INDEXABLE'); + $ret = array('sbas_id' => null, 'indexable' => null); + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $appbox->set_databox_indexable($databox, $parm['INDEXABLE']); + $ret['sbas_id'] = $parm['sbas_id']; + $ret['indexable'] = $parm['INDEXABLE']; + $output = p4string::jsonencode($ret); + break; + + case 'REINDEX': + + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $ret = array('sbas_id' => null); + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $databox->reindex(); + $output = p4string::jsonencode($ret); + break; + + case 'CLEARALLLOG': + + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $ret = array('sbas_id' => null); + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $databox->clear_logs(); + $ret['sbas_id'] = $parm['sbas_id']; + $output = p4string::jsonencode($ret); + break; + + case 'DELLOGOPDF': + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + $ret = array('sbas_id' => null); + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + $appbox->write_databox_pic($databox, null, databox::PIC_PDF); + $ret['sbas_id'] = $parm['sbas_id']; + + $output = p4string::jsonencode($ret); + break; + + case 'DELETEBASE': + $parm = $request->get_parms(array('sbas_id' => http_request::SANITIZE_NUMBER_INT)); + + $ret = array('sbas_id' => null, 'err' => -1, 'errmsg' => null); + + try { + $sbas_id = (int) $parm['sbas_id']; + $databox = databox::get_instance($sbas_id); + if ($databox->get_record_amount() == 0) { + $databox->unmount_databox($appbox); + $appbox->write_databox_pic($databox, null, databox::PIC_PDF); + $databox->delete(); + $ret['sbas_id'] = $parm['sbas_id']; + $ret['err'] = 0; + } else { + $ret['errmsg'] = _('admin::base: vider la base avant de la supprimer'); + } + } catch (Exception $e) { + $ret['errmsg'] = $e->getMessage(); + } + $output = p4string::jsonencode($ret); + break; } unset($appbox); diff --git a/www/admin/cgus.php b/www/admin/cgus.php index 49c7570c56..ec5fd845e5 100644 --- a/www/admin/cgus.php +++ b/www/admin/cgus.php @@ -22,27 +22,24 @@ $registry = $appbox->get_registry(); $request = http_request::getInstance(); $parm = $request->get_parms( - "p0", 'TOU', 'test', 'valid' + "p0", 'TOU', 'test', 'valid' ); if (is_null($parm['p0'])) - phrasea::headers(400); + phrasea::headers(400); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if (!$user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) -{ - phrasea::headers(403); +if ( ! $user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) { + phrasea::headers(403); } phrasea::headers(); $databox = databox::get_instance((int) $parm['p0']); -if ((int) $parm['p0'] > 0 && is_array($parm['TOU'])) -{ - foreach ($parm['TOU'] as $loc => $terms) - { - $databox->update_cgus($loc, $terms, $parm['valid']); - } +if ((int) $parm['p0'] > 0 && is_array($parm['TOU'])) { + foreach ($parm['TOU'] as $loc => $terms) { + $databox->update_cgus($loc, $terms, $parm['valid']); + } } $avLanguages = \Alchemy\Phrasea\Core::getAvailableLanguages(); @@ -50,74 +47,70 @@ $TOU = $databox->get_cgus(); ?> - - - - - - - - -

                  + + + + + + + + +

                  -
                  -
                  - - -
                  -
                  -
                    - $lang) - { - if (isset($TOU[$code])) - { - $s = ( $code == Session_Handler::get_locale() ? 'selected' : '' ); - echo '
                  • ' . $lang . '
                  • '; - } - } - ?> -
                  - $lang) - { - if (isset($TOU[$code])) - { - ?> -
                  - -
                  - -
                  -
                  - +
                  +
                  + + +
                  +
                  +
                    + $lang) { + if (isset($TOU[$code])) { + $s = ( $code == Session_Handler::get_locale() ? 'selected' : '' ); + echo '
                  • ' . $lang . '
                  • '; + } +} +?> +
                  + $lang) { + if (isset($TOU[$code])) { + ?> +
                  + +
                  + +
                  +
                  + diff --git a/www/admin/collection.php b/www/admin/collection.php index 61304077f7..1e8aa30fe7 100644 --- a/www/admin/collection.php +++ b/www/admin/collection.php @@ -28,9 +28,8 @@ $base_id = (int) $parm['p1']; $ACL = User_Adapter::getInstance($usr_id, $appbox)->ACL(); -if (!$ACL->has_access_to_base($base_id)) -{ - phrasea::headers(403); +if ( ! $ACL->has_access_to_base($base_id)) { + phrasea::headers(403); } $collection = collection::get_from_base_id($parm['p1']); @@ -44,771 +43,682 @@ $msg = array(); $refreshFinder = false; -if (is_array($parm['admins'])) -{ - $admins = array(); +if (is_array($parm['admins'])) { + $admins = array(); - foreach ($parm['admins'] as $a) - { - if (trim($a) == '') - continue; + foreach ($parm['admins'] as $a) { + if (trim($a) == '') + continue; - $admins[] = $a; - } + $admins[] = $a; + } - if ($admins > 0) - { - set_exportorder::set_order_admins($admins, $base_id); - } + if ($admins > 0) { + set_exportorder::set_order_admins($admins, $base_id); + } } -switch ($parm['act']) -{ - case 'ENABLED': - $collection->enable($appbox); - break; - case 'DISABLED'; - $collection->disable($appbox); - break; - case 'pub_wm': - if ($ACL->has_right_on_base($base_id, 'canadmin') == 1) - { - $collection->set_public_presentation($parm['pub_wm']); - } - break; - case 'APPLYNEWNAMECOLL': - $collection->set_name($parm['p2']); - $refreshFinder = true; - break; - case 'UMOUNTCOLL': - $collection->unmount_collection($appbox); - $msg['ACTDONE'] = $collection->get_name() . ' ' . _('forms::operation effectuee OK'); - $refreshFinder = true; - break; - case 'DODELETECOLL': - if ($collection->get_record_amount() > 0) - { - $msg['ACTDONE'] = _('admin::base:collection: vider la collection avant de la supprimer'); - } - else - { - $collection->unmount_collection($appbox); - $collection->delete(); - - $msg['ACTDONE'] = _('forms::operation effectuee OK'); - $refreshFinder = true; - } - break; - - case 'SENDMINILOGO': - if (isset($_FILES['newLogo'])) - { - if ($_FILES['newLogo']['size'] > 65535) - { - $msg['SENDMINILOGO'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 64Ko
                  '; - } - elseif ($_FILES['newLogo']['error']) - { - $msg['SENDMINILOGO'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; - } - elseif (( $_FILES['newLogo']['error'] == UPLOAD_ERR_OK)) - { - try - { - $appbox->write_collection_pic($collection, new system_file($_FILES['newLogo']['tmp_name']), collection::PIC_LOGO); +switch ($parm['act']) { + case 'ENABLED': + $collection->enable($appbox); + break; + case 'DISABLED'; + $collection->disable($appbox); + break; + case 'pub_wm': + if ($ACL->has_right_on_base($base_id, 'canadmin') == 1) { + $collection->set_public_presentation($parm['pub_wm']); } - catch (Exception $e) - { - $msg['SENDMINILOGO'] = $e->getMessage(); - } - } - } - break; + break; + case 'APPLYNEWNAMECOLL': + $collection->set_name($parm['p2']); + $refreshFinder = true; + break; + case 'UMOUNTCOLL': + $collection->unmount_collection($appbox); + $msg['ACTDONE'] = $collection->get_name() . ' ' . _('forms::operation effectuee OK'); + $refreshFinder = true; + break; + case 'DODELETECOLL': + if ($collection->get_record_amount() > 0) { + $msg['ACTDONE'] = _('admin::base:collection: vider la collection avant de la supprimer'); + } else { + $collection->unmount_collection($appbox); + $collection->delete(); - case 'DELMINILOGO': - try - { - $collection->update_logo(null); - $appbox->write_collection_pic($collection, null, collection::PIC_LOGO); - } - catch (Exception $e) - { - $msg['DELMINILOGO'] = $e->getMessage(); - } - break; - - case 'SENDWM': - case 'DELWM': - - if ($parm['act'] == 'SENDWM' && isset($_FILES['newWm'])) - { - if ($_FILES['newWm']['size'] > 65535) - { - $msg['SENDWM'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . " 64Ko" . "
                  "; - } - elseif ($_FILES['newWm']['error']) - { - $msg['SENDWM'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . "
                  "; // par le serveur (fichier php.ini) - } - elseif (($_FILES['newWm']['error'] == UPLOAD_ERR_OK)) - { - try - { - $appbox->write_collection_pic($collection, new system_file($_FILES['newWm']["tmp_name"]), collection::PIC_WM); + $msg['ACTDONE'] = _('forms::operation effectuee OK'); + $refreshFinder = true; } - catch(Exception $e) - { - $msg['SENDWM'] = '
                  ' . $e->getMessage() . "
                  "; - } - unlink($_FILES['newWm']["tmp_name"]); - } - } - elseif ($parm['act'] == "DELWM") - { - try - { - $appbox->write_collection_pic($collection, null, collection::PIC_WM); - } - catch(Exception $e) - { - $msg['DELWM'] = '
                  ' . $e->getMessage() . "
                  "; - } - } - break; + break; - case 'SENDSTAMPLOGO': - if (isset($_FILES['newStampLogo'])) - { - if ($_FILES['newStampLogo']['size'] > 1024 * 1024) - { - $msg['SENDSTAMPLOGO'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 1Mo
                  '; - } - elseif ($_FILES['newStampLogo']['error']) - { - $msg['SENDSTAMPLOGO'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; // par le serveur (fichier php.ini) - } - elseif (( $_FILES['newStampLogo']['error'] == UPLOAD_ERR_OK)) - { - try - { - $appbox->write_collection_pic($collection, new system_file($_FILES['newStampLogo']["tmp_name"]), collection::PIC_STAMP); + case 'SENDMINILOGO': + if (isset($_FILES['newLogo'])) { + if ($_FILES['newLogo']['size'] > 65535) { + $msg['SENDMINILOGO'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 64Ko
                  '; + } elseif ($_FILES['newLogo']['error']) { + $msg['SENDMINILOGO'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; + } elseif (( $_FILES['newLogo']['error'] == UPLOAD_ERR_OK)) { + try { + $appbox->write_collection_pic($collection, new system_file($_FILES['newLogo']['tmp_name']), collection::PIC_LOGO); + } catch (Exception $e) { + $msg['SENDMINILOGO'] = $e->getMessage(); + } + } } - catch(Exception $e) - { - $msg['SENDSTAMPLOGO'] = '
                  ' . $e->getMessage() . "
                  "; - } - unlink($_FILES['newStampLogo']["tmp_name"]); - } - } - break; + break; - case 'DELSTAMPLOGO': - try - { - $appbox->write_collection_pic($collection, null, collection::PIC_STAMP); - } - catch(Exception $e) - { - $msg['DELSTAMPLOGO'] = '
                  ' . $e->getMessage() . "
                  "; - } - break; - - case 'SENDPRESENTPICT': - if (isset($_FILES['newPresentPict'])) - { - if ($_FILES['newPresentPict']['size'] > 1024 * 1024 * 2) - { - $msg['SENDPRESENTPICT'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 2Mo
                  '; - } - elseif ($_FILES['newPresentPict']['error']) - { - $msg['SENDPRESENTPICT'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; // par le serveur (fichier php.ini) - } - elseif ($_FILES['newPresentPict']['error'] == UPLOAD_ERR_OK) - { - try - { - $appbox->write_collection_pic($collection, new system_file($_FILES['newPresentPict']["tmp_name"]), collection::PIC_PRESENTATION); + case 'DELMINILOGO': + try { + $collection->update_logo(null); + $appbox->write_collection_pic($collection, null, collection::PIC_LOGO); + } catch (Exception $e) { + $msg['DELMINILOGO'] = $e->getMessage(); } - catch(Exception $e) - { - $msg['SENDPRESENTPICT'] = '
                  ' . $e->getMessage() . "
                  "; - } - unlink($_FILES['newPresentPict']["tmp_name"]); - } - } - break; + break; - case 'DELPRESENTPICT': - try - { - $appbox->write_collection_pic($collection, null, collection::PIC_PRESENTATION); - } - catch(Exception $e) - { - $msg['DELPRESENTPICT'] = '
                  ' . $e->getMessage() . "
                  "; - } - @unlink($registry->get('GV_RootPath') . 'config/presentation/' . $base_id); - break; + case 'SENDWM': + case 'DELWM': + + if ($parm['act'] == 'SENDWM' && isset($_FILES['newWm'])) { + if ($_FILES['newWm']['size'] > 65535) { + $msg['SENDWM'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . " 64Ko" . "
                  "; + } elseif ($_FILES['newWm']['error']) { + $msg['SENDWM'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . "
                  "; // par le serveur (fichier php.ini) + } elseif (($_FILES['newWm']['error'] == UPLOAD_ERR_OK)) { + try { + $appbox->write_collection_pic($collection, new system_file($_FILES['newWm']["tmp_name"]), collection::PIC_WM); + } catch (Exception $e) { + $msg['SENDWM'] = '
                  ' . $e->getMessage() . "
                  "; + } + unlink($_FILES['newWm']["tmp_name"]); + } + } elseif ($parm['act'] == "DELWM") { + try { + $appbox->write_collection_pic($collection, null, collection::PIC_WM); + } catch (Exception $e) { + $msg['DELWM'] = '
                  ' . $e->getMessage() . "
                  "; + } + } + break; + + case 'SENDSTAMPLOGO': + if (isset($_FILES['newStampLogo'])) { + if ($_FILES['newStampLogo']['size'] > 1024 * 1024) { + $msg['SENDSTAMPLOGO'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 1Mo
                  '; + } elseif ($_FILES['newStampLogo']['error']) { + $msg['SENDSTAMPLOGO'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; // par le serveur (fichier php.ini) + } elseif (( $_FILES['newStampLogo']['error'] == UPLOAD_ERR_OK)) { + try { + $appbox->write_collection_pic($collection, new system_file($_FILES['newStampLogo']["tmp_name"]), collection::PIC_STAMP); + } catch (Exception $e) { + $msg['SENDSTAMPLOGO'] = '
                  ' . $e->getMessage() . "
                  "; + } + unlink($_FILES['newStampLogo']["tmp_name"]); + } + } + break; + + case 'DELSTAMPLOGO': + try { + $appbox->write_collection_pic($collection, null, collection::PIC_STAMP); + } catch (Exception $e) { + $msg['DELSTAMPLOGO'] = '
                  ' . $e->getMessage() . "
                  "; + } + break; + + case 'SENDPRESENTPICT': + if (isset($_FILES['newPresentPict'])) { + if ($_FILES['newPresentPict']['size'] > 1024 * 1024 * 2) { + $msg['SENDPRESENTPICT'] = '
                  ' . _('admin::base:collection le fichier envoye est trop volumineux.') . ' 2Mo
                  '; + } elseif ($_FILES['newPresentPict']['error']) { + $msg['SENDPRESENTPICT'] = '
                  ' . _('forms::erreur lors de l\'envoi du fichier') . '
                  '; // par le serveur (fichier php.ini) + } elseif ($_FILES['newPresentPict']['error'] == UPLOAD_ERR_OK) { + try { + $appbox->write_collection_pic($collection, new system_file($_FILES['newPresentPict']["tmp_name"]), collection::PIC_PRESENTATION); + } catch (Exception $e) { + $msg['SENDPRESENTPICT'] = '
                  ' . $e->getMessage() . "
                  "; + } + unlink($_FILES['newPresentPict']["tmp_name"]); + } + } + break; + + case 'DELPRESENTPICT': + try { + $appbox->write_collection_pic($collection, null, collection::PIC_PRESENTATION); + } catch (Exception $e) { + $msg['DELPRESENTPICT'] = '
                  ' . $e->getMessage() . "
                  "; + } + @unlink($registry->get('GV_RootPath') . 'config/presentation/' . $base_id); + break; } function showMsg($k) { - global $msg; - if (isset($msg[$k])) - echo($msg[$k]); + global $msg; + if (isset($msg[$k])) + echo($msg[$k]); } - phrasea::headers(); ?> - - - - - + + - + + - - - - -

                  - get_name(); ?> -

                  -
                  - :   -
                  - -
                  - :   -
                  + return $( "
                • " ) + .data( "item.autocomplete", item ) + .append( "" + item.name + login + email + "" ) + .appendTo( ul ); + }; + }); + + + +

                  + get_name(); ?> +

                  +
                  + :   +
                  + +
                  + :   +
                  - is_active() ? _('admin::base:collection: activer la collection') : _('admin::base:collection: descativer la collection') ) ?>  -
                  +is_active() ? _('admin::base:collection: activer la collection') : _('admin::base:collection: descativer la collection') ) ?>  +
      -
      - get_record_amount() . ' records' . "\n"; +
      +get_record_amount() . ' records' . "\n"; - if ($parm["sta"] == "" || $parm["sta"] == NULL || $parm["sta"] == 0) - { - ?> - ( - - ) -
      - get_record_details(); - ?> - ( - - ) -
      -
      - - - - - - - - - - - - - - - - + ( + + ) +
      + get_record_details(); + ?> + ( + + ) +
      +
      +
      - '); - print(_('admin::base: objet')); -?> - - - - (Mo) - - (Go) -
      + + + + + + + + + + + + + + + 0 || $last_k1 !== $vrow["coll_id"]) - { - if (extension_loaded("bcmath")) - $midsiz = bcadd($midsiz, $vrow["size"], 0); - else - $midsiz += $vrow["size"]; - if (extension_loaded("bcmath")) - $mega = bcdiv($vrow["size"], 1024 * 1024, 5); - else - $mega = $vrow["size"] / (1024 * 1024); - if (extension_loaded("bcmath")) - $giga = bcdiv($vrow["size"], 1024 * 1024 * 1024, 5); - else - $giga = $vrow["size"] / (1024 * 1024 * 1024); -?> - - + - - - - - + + + + + + - - - - - - - - - - - - - - - - - -
      +  '); + print(_('admin::base: objet')); + ?> + + + + (Mo) + + (Go) +
      - 0 || $last_k1 !== $vrow["coll_id"]) { + if (extension_loaded("bcmath")) + $midsiz = bcadd($midsiz, $vrow["size"], 0); + else + $midsiz += $vrow["size"]; + if (extension_loaded("bcmath")) + $mega = bcdiv($vrow["size"], 1024 * 1024, 5); + else + $mega = $vrow["size"] / (1024 * 1024); + if (extension_loaded("bcmath")) + $giga = bcdiv($vrow["size"], 1024 * 1024 * 1024, 5); + else + $giga = $vrow["size"] / (1024 * 1024 * 1024); + ?> +
      + - -   - -   - -   - -   - -   - -   -
      +   + +   + +   + +   + +   + +   +
      - total - -   - -   - -   - -   - -   - -   -
      -
      -
      - total - -   - -   - -   - -   - -   - -   -
      - -
      -has_right_on_base($base_id, 'manage')) - { - $pub_wm = $collection->get_pub_wm(); -?> -
      - - - -
      -on_base_ids(array($base_id)) - ->who_have_right(array('order_master')) - ->execute()->get_results(); - - foreach ($admins as $usr_id => $user) - { -?> -
      - -
      - - - - -
      -
      - -
      - " /> - " /> - - - - " /> - - - - -
      - value='none' /> - value='wm' /> - value='stamp' /> -
      - -
      - - - - - -
      - - - - -
      - - " /> - + if (extension_loaded("bcmath")) + $giga = bcdiv($midsiz, 1024 * 1024 * 1024, 5); + else + $giga = $midsiz / (1024 * 1024 * 1024); + ?> + + + total + + +   + +   + + +   + +   + + +   + +   + + + + +
      + + + + + + total + + +   + +   + + +   + +   + + +   + +   + + + + +
      + has_right_on_base($base_id, 'manage')) { + $pub_wm = $collection->get_pub_wm(); + ?> + + + + +
      + on_base_ids(array($base_id)) + ->who_have_right(array('order_master')) + ->execute()->get_results(); - - - - -
      -
      -
      - - -
      -
      - $user) { + ?> +
      + +
      + + + +
      +
      + +
      + " /> + " /> + + + + " /> + + + + +
      + value='none' /> + value='wm' /> + value='stamp' /> +
      + +
      + + + + + +
      + + + + +
      + + " /> + +
      + + + + + +
      +
      +
      + + +
      +
      + -
      -
      +
      +
      : - -
      + +
      has_right_on_base($base_id, 'manage')) - { - if (file_exists($registry->get('GV_RootPath') . 'config/minilogos/' . $base_id)) - { -?> -
      -getLogo($base_id) ?> - - - +if ($ACL->has_right_on_base($base_id, 'manage')) { + if (file_exists($registry->get('GV_RootPath') . 'config/minilogos/' . $base_id)) { + ?> +
      + getLogo($base_id) ?> + + + +
      + + + + +
      - +
      + Watermark : + +
      + has_right_on_base($base_id, 'manage')) { + if (file_exists($registry->get('GV_RootPath') . 'config/wm/' . $collection->get_base_id())) { + ?> +
      + getWatermark($base_id) ?> + + + +
      + + + + + - - - - -
      -
      -
      - Watermark : - -
      -has_right_on_base($base_id, 'manage')) - { - if (file_exists($registry->get('GV_RootPath') . 'config/wm/' . $collection->get_base_id())) - { -?> -
      -getWatermark($base_id) ?> - - -
      - +
      + StampLogo : + +
      + has_right_on_base($base_id, 'manage')) { + if (file_exists($registry->get('GV_RootPath') . 'config/stamp/' . $base_id)) { + ?> +
      + getStamp($base_id) ?> + + + +
      + + + + - - - - -
      -
      -
      - StampLogo : - -
      -has_right_on_base($base_id, 'manage')) - { - if (file_exists($registry->get('GV_RootPath') . 'config/stamp/' . $base_id)) - { -?> -
      -getStamp($base_id) ?> - - - + ?>
      - - - - -
      -
      -
      - - -
      -has_right_on_base($base_id, 'manage')) - { - if (file_exists($registry->get('GV_RootPath') . 'config/presentation/' . $base_id)) - { -?> -
      -getPresentation($base_id) ?> - - - +
      +
      + + +
      + has_right_on_base($base_id, 'manage')) { + if (file_exists($registry->get('GV_RootPath') . 'config/presentation/' . $base_id)) { + ?> +
      + getPresentation($base_id) ?> + + + +
      + + + +
      ( max : 650x200 ) +
      - - - -
      ( max : 650x200 ) - -
      - - + + diff --git a/www/admin/collorder.php b/www/admin/collorder.php index 262c6f183f..f2f9ecf87c 100644 --- a/www/admin/collorder.php +++ b/www/admin/collorder.php @@ -21,204 +21,191 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "act", - "p0", - "send" + "act", "p0", "send" ); $sbas_id = (int) $parm['p0']; $databox = databox::get_instance($sbas_id); if (is_null($parm['p0'])) - phrasea::headers(400); + phrasea::headers(400); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if (!$user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) -{ - phrasea::headers(403); +if ( ! $user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) { + phrasea::headers(403); } phrasea::headers(); ?> - - - + + + ", sprintf(_('admin::base: reglage des ordres des collection de la base %s'), phrasea::sbas_names($parm['p0'])), ""; -if ($parm["act"] == "APPLY") -{ - $newOrder = NULL; - $change = "" . $parm["send"] . ""; - $xml = simplexml_load_string($change); - foreach ($xml->children() as $name => $val) - { - $nodename = (string) $name; - $nodeval = (string) $val; - if (substr($nodename, 0, 3) == "ord") - { - $idx = substr($nodename, 3) * 10; - $newOrder[$idx] = $nodeval; +if ($parm["act"] == "APPLY") { + $newOrder = NULL; + $change = "" . $parm["send"] . ""; + $xml = simplexml_load_string($change); + foreach ($xml->children() as $name => $val) { + $nodename = (string) $name; + $nodeval = (string) $val; + if (substr($nodename, 0, 3) == "ord") { + $idx = substr($nodename, 3) * 10; + $newOrder[$idx] = $nodeval; + } + } + foreach ($newOrder as $ord => $base_id) { + $collection = collection::get_from_base_id($base_id); + $appbox->set_collection_order($collection, $ord); + unset($collection); + $update = true; } - } - foreach ($newOrder as $ord => $base_id) - { - $collection = collection::get_from_base_id($base_id); - $appbox->set_collection_order($collection, $ord); - unset($collection); - $update = true; - } } else - echo "

      "; - - + echo "

      "; ?> - - - + } + } + + + - - -'); + + - - - +
      - + + + - - + - + - + + - -
      + + + + +
      + +
      +
      +
      - -
      - -
      -
      -
      -
      -
      -
      - - - " /> -
      - +
      +
      + + + " /> +
      + diff --git a/www/admin/createSYLK.php b/www/admin/createSYLK.php index b042f57471..eef5cc0dd4 100644 --- a/www/admin/createSYLK.php +++ b/www/admin/createSYLK.php @@ -15,193 +15,181 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - define("FORMAT_REEL", 1); // #,##0.00 define("FORMAT_ENTIER", 2); // #,##0 define("FORMAT_TEXTE", 3); // @ class fileSYLK { + var $myhandler = null; + var $fileName = null; + var $fieldsToExport = null; + var $cfg_formats = null; + var $nblines = null; + var $nbrows = null; + var $row_format = null; + var $format = null; - var $myhandler = null; - var $fileName = null; - var $fieldsToExport = null; - var $cfg_formats = null; - var $nblines = null; - var $nbrows = null; - var $row_format = null; - var $format = null; - - function fileSYLK() - { - $this->cfg_formats[FORMAT_ENTIER] = "FF0"; - $this->cfg_formats[FORMAT_REEL] = "FF2"; - $this->cfg_formats[FORMAT_TEXTE] = "FG0"; - } - - function setfilename($aFileName) - { - - $registry = registry::get_instance(); - $pathtmp = $registry->get('GV_RootPath') . 'tmp/'; - $this->fileName = $pathtmp . $aFileName; - } - - function setFieldsNamesList($arrayFields) - { - //$this->fieldsToExport = $arrayFields; - foreach ($arrayFields as $idx => $a) + function fileSYLK() { - $this->fieldsToExport[$idx] = $arrayFields[$idx]['name']; + $this->cfg_formats[FORMAT_ENTIER] = "FF0"; + $this->cfg_formats[FORMAT_REEL] = "FF2"; + $this->cfg_formats[FORMAT_TEXTE] = "FG0"; + } - if (isset($arrayFields[$idx]['format'])) - { - switch ($arrayFields[$idx]['format']) - { - case "integer": - $this->row_format[$idx] = FORMAT_ENTIER; - $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "R"; - break; + function setfilename($aFileName) + { - case "double": - $this->row_format[$idx] = FORMAT_REEL; - $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "R"; - break; + $registry = registry::get_instance(); + $pathtmp = $registry->get('GV_RootPath') . 'tmp/'; + $this->fileName = $pathtmp . $aFileName; + } - default: - $this->row_format[$idx] = FORMAT_TEXTE; - $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "L"; - break; + function setFieldsNamesList($arrayFields) + { + //$this->fieldsToExport = $arrayFields; + foreach ($arrayFields as $idx => $a) { + $this->fieldsToExport[$idx] = $arrayFields[$idx]['name']; + + if (isset($arrayFields[$idx]['format'])) { + switch ($arrayFields[$idx]['format']) { + case "integer": + $this->row_format[$idx] = FORMAT_ENTIER; + $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "R"; + break; + + case "double": + $this->row_format[$idx] = FORMAT_REEL; + $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "R"; + break; + + default: + $this->row_format[$idx] = FORMAT_TEXTE; + $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "L"; + break; + } + } else { + $this->row_format[$idx] = FORMAT_TEXTE; + $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "L"; + } } - } - else - { - $this->row_format[$idx] = FORMAT_TEXTE; - $this->format[$idx] = $this->cfg_formats[$this->row_format[$idx]] . "L"; - } + + $this->nbrows = count($this->fieldsToExport); } - $this->nbrows = count($this->fieldsToExport); - } - - function setNbLines($nb) - { - $this->nblines = $nb; - } - - function openHandler() - { - if ($this->fileName) - $this->myhandler = @fopen($this->fileName, 'a'); - } - - function releaseHandler() - { - if ($this->myhandler) - fclose($this->myhandler); - } - - function release() - { - $this->releaseHandler(); - } - - function writeHeader() - { - if (!$this->myhandler) - $this->openHandler(); - if ($this->myhandler) + function setNbLines($nb) { - // fwrite($this->myhandler, $somecontent); + $this->nblines = $nb; + } - fwrite($this->myhandler, "ID;APhraseanet\n"); // ID;Pappli - fwrite($this->myhandler, "\n"); - // formats - fwrite($this->myhandler, "P;PGeneral\n"); - fwrite($this->myhandler, "P;P#,##0.00\n"); // P;Pformat_1 (reels) - fwrite($this->myhandler, "P;P#,##0\n"); // P;Pformat_2 (entiers) - fwrite($this->myhandler, "P;P@\n"); // P;Pformat_3 (textes) - fwrite($this->myhandler, "\n"); - // polices - fwrite($this->myhandler, "P;EArial;M200\n"); - fwrite($this->myhandler, "P;EArial;M200\n"); - fwrite($this->myhandler, "P;EArial;M200\n"); - fwrite($this->myhandler, "P;FArial;M200;SB\n"); - fwrite($this->myhandler, "\n"); + function openHandler() + { + if ($this->fileName) + $this->myhandler = @fopen($this->fileName, 'a'); + } + + function releaseHandler() + { + if ($this->myhandler) + fclose($this->myhandler); + } + + function release() + { + $this->releaseHandler(); + } + + function writeHeader() + { + if ( ! $this->myhandler) + $this->openHandler(); + if ($this->myhandler) { + // fwrite($this->myhandler, $somecontent); + + fwrite($this->myhandler, "ID;APhraseanet\n"); // ID;Pappli + fwrite($this->myhandler, "\n"); + // formats + fwrite($this->myhandler, "P;PGeneral\n"); + fwrite($this->myhandler, "P;P#,##0.00\n"); // P;Pformat_1 (reels) + fwrite($this->myhandler, "P;P#,##0\n"); // P;Pformat_2 (entiers) + fwrite($this->myhandler, "P;P@\n"); // P;Pformat_3 (textes) + fwrite($this->myhandler, "\n"); + // polices + fwrite($this->myhandler, "P;EArial;M200\n"); + fwrite($this->myhandler, "P;EArial;M200\n"); + fwrite($this->myhandler, "P;EArial;M200\n"); + fwrite($this->myhandler, "P;FArial;M200;SB\n"); + fwrite($this->myhandler, "\n"); - fwrite($this->myhandler, "B;Y" . ($this->nblines + 1)); ## myhandler, ";X" . $this->nbrows . "\n"); ## myhandler, "\n"); + fwrite($this->myhandler, "B;Y" . ($this->nblines + 1)); ## myhandler, ";X" . $this->nbrows . "\n"); ## myhandler, "\n"); - /* - // largeurs des colonnes - // pour chaque colones, on calcul la largeur - // dans cette classe on defini ttes las col de la meme tailles - for ($cpt = 1; $cpt <= $nbcol; $cpt++) - { - for($t=0;$t < count($tableau);$t++) - $tmpo[$t]= strlen($tableau[$t][$cpt-1]); - $taille=max($tmpo); - // F;Wcoldeb colfin largeur - if (strlen($tableau[0][$cpt-1]) > $taille) - $taille=strlen($tableau[0][$cpt-1]); - if ($taille>50) - $taille=50; - print( "F;W".$cpt." ".$cpt." ".$taille."\n"); + /* + // largeurs des colonnes + // pour chaque colones, on calcul la largeur + // dans cette classe on defini ttes las col de la meme tailles + for ($cpt = 1; $cpt <= $nbcol; $cpt++) + { + for($t=0;$t < count($tableau);$t++) + $tmpo[$t]= strlen($tableau[$t][$cpt-1]); + $taille=max($tmpo); + // F;Wcoldeb colfin largeur + if (strlen($tableau[0][$cpt-1]) > $taille) + $taille=strlen($tableau[0][$cpt-1]); + if ($taille>50) + $taille=50; + print( "F;W".$cpt." ".$cpt." ".$taille."\n"); + } + */ + $taille = 25; + for ($cmpt = 0; $cmpt < $this->nbrows; $cmpt ++ ) + fwrite($this->myhandler, "F;W" . ($cmpt + 1) . " " . ($cmpt + 1) . " " . $taille . "\n"); + + fwrite($this->myhandler, "F;W" . $this->nbrows . " 256 8\n"); // F;Wcoldeb colfin largeur + fwrite($this->myhandler, "\n"); + + + + // on ecris l'en-tete des colonnes (en gras --> SDM4) + for ($cmpt = 1; $cmpt <= $this->nbrows; $cmpt ++ ) { + fwrite($this->myhandler, "F;SDM4;FG0C;" . ($cmpt == 1 ? "Y1;" : "") . "X" . $cmpt . "\n"); + fwrite($this->myhandler, "C;N;K\"" . $this->fieldsToExport[$cmpt - 1] . "\"\n"); + } + fwrite($this->myhandler, "\n"); } - */ - $taille = 25; - for ($cmpt = 0; $cmpt < $this->nbrows; $cmpt++) - fwrite($this->myhandler, "F;W" . ($cmpt + 1) . " " . ($cmpt + 1) . " " . $taille . "\n"); - - fwrite($this->myhandler, "F;W" . $this->nbrows . " 256 8\n"); // F;Wcoldeb colfin largeur - fwrite($this->myhandler, "\n"); - - - - // on ecris l'en-tete des colonnes (en gras --> SDM4) - for ($cmpt = 1; $cmpt <= $this->nbrows; $cmpt++) - { - fwrite($this->myhandler, "F;SDM4;FG0C;" . ($cmpt == 1 ? "Y1;" : "") . "X" . $cmpt . "\n"); - fwrite($this->myhandler, "C;N;K\"" . $this->fieldsToExport[$cmpt - 1] . "\"\n"); - } - fwrite($this->myhandler, "\n"); } - } - function addLine($lineNum, $arrayFields) - { - if (!$this->myhandler) - $this->openHandler(); - if ($this->myhandler) + function addLine($lineNum, $arrayFields) { - // fwrite($this->myhandler, $somecontent); - // parcours des champs par colone - for ($cmpt = 0; $cmpt < $this->nbrows; $cmpt++) - { + if ( ! $this->myhandler) + $this->openHandler(); + if ($this->myhandler) { + // fwrite($this->myhandler, $somecontent); + // parcours des champs par colone + for ($cmpt = 0; $cmpt < $this->nbrows; $cmpt ++ ) { - if (!isset($arrayFields[$cmpt])) - $arrayFields[$cmpt] = ''; - $arrayFields[$cmpt] = str_replace("\n", "\x1B\x20\x3A", $arrayFields[$cmpt]); - // format - fwrite($this->myhandler, "F;P" . $this->row_format[$cmpt] . ";" . $this->format[$cmpt]); - fwrite($this->myhandler, ($cmpt == 0 ? ";Y" . $lineNum : "") . ";X" . ($cmpt + 1) . "\n"); - // valeur - if ($this->row_format[$cmpt] == FORMAT_TEXTE) - fwrite($this->myhandler, "C;N;K\"" . str_replace(';', ';;', $arrayFields[$cmpt]) . "\"\n"); - else - fwrite($this->myhandler, "C;N;K" . $arrayFields[$cmpt] . "\n"); - } - fwrite($this->myhandler, "\n"); + if ( ! isset($arrayFields[$cmpt])) + $arrayFields[$cmpt] = ''; + $arrayFields[$cmpt] = str_replace("\n", "\x1B\x20\x3A", $arrayFields[$cmpt]); + // format + fwrite($this->myhandler, "F;P" . $this->row_format[$cmpt] . ";" . $this->format[$cmpt]); + fwrite($this->myhandler, ($cmpt == 0 ? ";Y" . $lineNum : "") . ";X" . ($cmpt + 1) . "\n"); + // valeur + if ($this->row_format[$cmpt] == FORMAT_TEXTE) + fwrite($this->myhandler, "C;N;K\"" . str_replace(';', ';;', $arrayFields[$cmpt]) . "\"\n"); + else + fwrite($this->myhandler, "C;N;K" . $arrayFields[$cmpt] . "\n"); + } + fwrite($this->myhandler, "\n"); + } } - } - - function writeEnd() - { - fwrite($this->myhandler, "E\n"); - $this->releaseHandler(); - } + function writeEnd() + { + fwrite($this->myhandler, "E\n"); + $this->releaseHandler(); + } } diff --git a/www/admin/database.php b/www/admin/database.php index a88093e4ef..070337711a 100644 --- a/www/admin/database.php +++ b/www/admin/database.php @@ -27,8 +27,8 @@ $parm = $request->get_parms("act", "p0", // id de la base "othcollsel", "coll_id", "base_id" ); -if (!$parm["srt"]) - $parm["srt"] = "col"; +if ( ! $parm["srt"]) + $parm["srt"] = "col"; $sbas_id = (int) $parm['p0']; $databox = databox::get_instance($sbas_id); @@ -38,719 +38,678 @@ phrasea::headers(); $printLogoUploadMsg = ""; $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if ($user->ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) -{ - switch ($parm["act"]) - { - case "SENDLOGOPDF": - if (isset($_FILES['newLogoPdf']) && $_FILES['newLogoPdf']['error'] == UPLOAD_ERR_OK) - { - if ($_FILES['newLogoPdf']['size'] < 65536) - { - $filenameTemp = $_FILES['newLogoPdf']["tmp_name"]; - $system_file = new system_file($_FILES['newLogoPdf']["tmp_name"]); - $appbox->write_databox_pic($databox, $system_file, databox::PIC_PDF); - unlink($_FILES['newLogoPdf']["tmp_name"]); - } - else - { - $printLogoUploadMsg = _('forms::erreur lors de l\'envoi du fichier'); - } - } - else - { - $printLogoUploadMsg = _('forms::erreur lors de l\'envoi du fichier'); - } - break; - case 'MOUNT': - $appbox->get_connection()->beginTransaction(); - try - { - $base_id = collection::mount_collection($sbas_id, $parm['coll_id'], $user); - if (!is_null($parm['othcollsel'])) - { - - $query = new User_Query($appbox); - $total = $query->on_base_ids(array($parm["othcollsel"]))->get_total(); - $n = 0; - while ($n < $total) - { - $results = $query->limit($n, 50)->execute()->get_results(); - foreach ($results as $user) - { - $user->ACL()->duplicate_right_from_bas($parm["othcollsel"], $base_id); +if ($user->ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) { + switch ($parm["act"]) { + case "SENDLOGOPDF": + if (isset($_FILES['newLogoPdf']) && $_FILES['newLogoPdf']['error'] == UPLOAD_ERR_OK) { + if ($_FILES['newLogoPdf']['size'] < 65536) { + $filenameTemp = $_FILES['newLogoPdf']["tmp_name"]; + $system_file = new system_file($_FILES['newLogoPdf']["tmp_name"]); + $appbox->write_databox_pic($databox, $system_file, databox::PIC_PDF); + unlink($_FILES['newLogoPdf']["tmp_name"]); + } else { + $printLogoUploadMsg = _('forms::erreur lors de l\'envoi du fichier'); + } + } else { + $printLogoUploadMsg = _('forms::erreur lors de l\'envoi du fichier'); } - $n+=50; - } - } - $appbox->get_connection()->commit(); - } - catch (Exception $e) - { - $appbox->get_connection()->rollBack(); - } - break; - case 'ACTIVATE': - try - { - $collection = collection::get_from_base_id($parm['base_id']); - $collection->enable($appbox); - } - catch (Exception $e) - { + break; + case 'MOUNT': + $appbox->get_connection()->beginTransaction(); + try { + $base_id = collection::mount_collection($sbas_id, $parm['coll_id'], $user); + if ( ! is_null($parm['othcollsel'])) { - } - break; - } + $query = new User_Query($appbox); + $total = $query->on_base_ids(array($parm["othcollsel"]))->get_total(); + $n = 0; + while ($n < $total) { + $results = $query->limit($n, 50)->execute()->get_results(); + foreach ($results as $user) { + $user->ACL()->duplicate_right_from_bas($parm["othcollsel"], $base_id); + } + $n+=50; + } + } + $appbox->get_connection()->commit(); + } catch (Exception $e) { + $appbox->get_connection()->rollBack(); + } + break; + case 'ACTIVATE': + try { + $collection = collection::get_from_base_id($parm['base_id']); + $collection->enable($appbox); + } catch (Exception $e) { + + } + break; + } } ?> - - - + + + - + - - - - - - -
      -

      - get_serialized_server_info(); ?> -

      -
      -
      - ID : -
      - -
      - : - ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) - { - ?> - - -
      - get_record_amount(); - - - // stats sur la base distante - $out .= "
      "; - $out .= _('admin::base: nombre d\'enregistrements sur la base :') . ' '; - - if ((int) $parm["sta"] < 1) - { - $out .= " (" . _('phraseanet:: details') . ")"; - } - else - { - $unique_keywords = $databox->get_unique_keywords(); - - $out .= ",   "; - $out .= _('admin::base: nombre de mots uniques sur la base : ') . ' ' . $unique_keywords; - - $indexes = $databox->get_index_amount(); - - $out .= ",   "; - $out .= _('admin::base: nombre de mots indexes sur la base') . ' ' . $indexes; - - if ($registry->get('GV_thesaurus')) - { - $thits = $databox->get_thesaurus_hits(); - - $out .= ",   "; - $out .= _('admin::base: nombre de termes de Thesaurus indexes :') . ' ' . $thits; - } - - $out .= " (" . _('admin::base: masquer les details') . ")
      \n"; - - - $trows = $databox->get_record_details($parm['srt']); - - $out .= "\n"; - $out .= ""; - $out .= ""; - - $out .= ""; - - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $totobj = 0; - $totsiz = "0"; // les tailles de fichiers sont calculees avec bcmath - foreach ($trows as $kgrp => $vgrp) - { - // ksort($vgrp); - $midobj = 0; - $midsiz = "0"; - $last_k1 = $last_k2 = null; - foreach ($vgrp as $krow => $vrow) + var __viewname = ""; // global will be updated by refreshContent + function chgViewName() { - if ($last_k1 !== $vrow["coll_id"]) - { - - } - if ($vrow["n"] > 0 || $last_k1 !== $vrow["coll_id"]) - { - $midobj += $vrow["n"]; - if (extension_loaded("bcmath")) - $midsiz = bcadd($midsiz, $vrow["siz"], 0); - else - $midsiz += $vrow["siz"]; - $out .= "\n"; - if ($last_k1 !== $vrow["coll_id"]) + if( (newAlias = prompt(" :", __viewname)) != null) { - if ((int) $vrow["lostcoll"] <= 0) - { - $out .= "\n"; - } - else - { - $out .= ""; - } - $last_k1 = $vrow["coll_id"]; + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"CHGVIEWNAME", sbas_id:, viewname:newAlias}, + success: function(data){ + } + }); } - else - { - $out .= "\n"; - } - if ($last_k2 !== $vrow["name"]) - $out .= "\n"; - else - $out .= "\n"; - $out .= "\n"; - if (extension_loaded("bcmath")) - $mega = bcdiv($vrow["siz"], 1024 * 1024, 5); - else - $mega = $vrow["siz"] / (1024 * 1024); - if (extension_loaded("bcmath")) - $giga = bcdiv($vrow["siz"], 1024 * 1024 * 1024, 5); - else - $giga = $vrow["siz"] / (1024 * 1024 * 1024); - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - } - // $last_k1 = null; } - $totobj += $midobj; - if (extension_loaded("bcmath")) - $totsiz = bcadd($totsiz, $midsiz, 0); - else - $totsiz += $midsiz; - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - if (extension_loaded("bcmath")) - $mega = bcdiv($midsiz, 1024 * 1024, 5); - else - $mega = $midsiz / (1024 * 1024); - if (extension_loaded("bcmath")) - $giga = bcdiv($midsiz, 1024 * 1024 * 1024, 5); - else - $giga = $midsiz / (1024 * 1024 * 1024); - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - } - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; - if (extension_loaded("bcmath")) - $mega = bcdiv($totsiz, 1024 * 1024, 5); - else - $mega = $totsiz / (1024 * 1024); - if (extension_loaded("bcmath")) - $giga = bcdiv($totsiz, 1024 * 1024 * 1024, 5); - else - $giga = $totsiz / (1024 * 1024 * 1024); - $out .= "\n"; - $out .= "\n"; - $out .= "\n"; + function emptyBase() + { + if(confirm("")) + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php?action=EMPTYBASE", + dataType: 'json', + data: { sbas_id: }, + success: function(data){ + alert(data.message); + } + }); + } + } - $out .= "
      "; - if ($parm["srt"] == "col") - $out .= " "; - $out .= _('phraseanet:: collection') . ""; - if ($parm["srt"] == "obj") - $out .= " "; - $out .= _('admin::base: objet') . "" . _('admin::base: nombre') . "" . _('admin::base: poids') . " (Mo)" . _('admin::base: poids') . " (Go)
      " . $vrow["asciiname"] . "" . _('admin::base: enregistrements orphelins') . " " . sprintf("(coll_id=%s)", $vrow["coll_id"]) . "" . ($last_k2 = $vrow["name"]) . " " . $vrow["n"] . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 
      " . _('report:: total') . " " . $midobj . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 

      " . _('report:: total') . " " . $totobj . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 
      "; - } - $out .= "
      "; + function refreshContent() + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"P_BAR_INFO", sbas_id:""}, + success: function(data){ + __viewname = data.viewname; // global + if(data.viewname == '') + $("#viewname").html(""); + else + $("#viewname").html(""+data.viewname+""); + $("#nrecords").text(data.records); + $("#is_indexable").attr('checked', data.indexable); + $("#xml_indexed").text(data.xml_indexed); + $("#thesaurus_indexed").text(data.thesaurus_indexed); + if(data.records > 0) + { + var p; + p = 100*data.xml_indexed/data.records; + $("#xml_indexed_bar").width(Math.round(2*p)); // 0..200px + $("#xml_indexed_percent").text((Math.round(p*100)/100)+" %"); + p = 100*data.thesaurus_indexed/data.records; + $("#thesaurus_indexed_bar").width(Math.round(2*p)); + $("#thesaurus_indexed_percent").text((Math.round(p*100)/100)+" %"); + } + if(data.printLogoURL) + { + $("#printLogo").attr("src", data.printLogoURL); + $("#printLogoDIV_NONE").hide(); + $("#printLogoDIV_OK").show(); + } + else + { + $("#printLogoDIV_OK").hide(); + $("#printLogoDIV_NONE").show(); + } + } + }); + setTimeout("refreshContent();", 6000); + } - print($out); + function deleteBase() + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"P_BAR_INFO", sbas_id: }, + success: function(data){ + if(data.records > 0) + { + alert(""); + } + else + { + if(confirm("")) + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"DELETEBASE", sbas_id: }, + success: function(data){ + if(data.err == 0) // ok + { + parent.$("#TREE_DATABASES").trigger('click'); + parent.reloadTree("bases"); + } + else + { + if(data.errmsg) + alert(data.errmsg); + } + } + }); + } + } + } + }); + } + function clearAllLog() + { + if(confirm("")) + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"CLEARALLLOG", sbas_id: + }, + success: function(data){ + } + }); + } + } + + function mountColl() + { + $('#mount_coll').toggle(); + } + + function activateColl() + { + $('#activate_coll').toggle(); + } + + function umountBase() + { + if(confirm("")) + { + $.ajax({ + type: "POST", + url: "/admin/adminFeedback.php", + dataType: 'json', + data: { action:"UNMOUNTBASE", sbas_id: + }, + success: function(data){ + parent.$("#TREE_DATABASES").trigger('click'); + } + }); + } + } + + function showDetails(sta) + { + document.forms["manageDatabase"].target = ""; + document.forms["manageDatabase"].act.value = ""; + document.forms["manageDatabase"].sta.value = sta; + document.forms["manageDatabase"].submit(); + } + function chgOrd(srt) + { + document.forms["manageDatabase"].target = ""; + document.forms["manageDatabase"].act.value = ""; + document.forms["manageDatabase"].sta.value = "1"; + document.forms["manageDatabase"].srt.value = srt; + document.forms["manageDatabase"].submit(); + } + $(document).ready(function(){ + refreshContent(); + }); + + + + + + +
      +

      +get_serialized_server_info(); ?> +

      +
      +
      + ID : +
      + +
      + : +ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) { ?> - -
      -
      -
      -
      - : - -
      -
      -
      -
      -
      -
      -
      -
      - : - -
      -
      -
      -
      -
      -
      -
      - ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) - { + + -
      - -
      + get_record_amount(); + + + // stats sur la base distante + $out .= "
      "; + $out .= _('admin::base: nombre d\'enregistrements sur la base :') . ' '; + + if ((int) $parm["sta"] < 1) { + $out .= " (" . _('phraseanet:: details') . ")"; + } else { + $unique_keywords = $databox->get_unique_keywords(); + + $out .= ",   "; + $out .= _('admin::base: nombre de mots uniques sur la base : ') . ' ' . $unique_keywords; + + $indexes = $databox->get_index_amount(); + + $out .= ",   "; + $out .= _('admin::base: nombre de mots indexes sur la base') . ' ' . $indexes; + + if ($registry->get('GV_thesaurus')) { + $thits = $databox->get_thesaurus_hits(); + + $out .= ",   "; + $out .= _('admin::base: nombre de termes de Thesaurus indexes :') . ' ' . $thits; + } + + $out .= " (" . _('admin::base: masquer les details') . ")
      \n"; + + + $trows = $databox->get_record_details($parm['srt']); + + $out .= "\n"; + $out .= ""; + $out .= ""; + + $out .= ""; + + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $totobj = 0; + $totsiz = "0"; // les tailles de fichiers sont calculees avec bcmath + foreach ($trows as $kgrp => $vgrp) { + // ksort($vgrp); + $midobj = 0; + $midsiz = "0"; + $last_k1 = $last_k2 = null; + foreach ($vgrp as $krow => $vrow) { + if ($last_k1 !== $vrow["coll_id"]) { + + } + if ($vrow["n"] > 0 || $last_k1 !== $vrow["coll_id"]) { + $midobj += $vrow["n"]; + if (extension_loaded("bcmath")) + $midsiz = bcadd($midsiz, $vrow["siz"], 0); + else + $midsiz += $vrow["siz"]; + $out .= "\n"; + if ($last_k1 !== $vrow["coll_id"]) { + if ((int) $vrow["lostcoll"] <= 0) { + $out .= "\n"; + } else { + $out .= ""; + } + $last_k1 = $vrow["coll_id"]; + } else { + $out .= "\n"; + } + if ($last_k2 !== $vrow["name"]) + $out .= "\n"; + else + $out .= "\n"; + $out .= "\n"; + if (extension_loaded("bcmath")) + $mega = bcdiv($vrow["siz"], 1024 * 1024, 5); + else + $mega = $vrow["siz"] / (1024 * 1024); + if (extension_loaded("bcmath")) + $giga = bcdiv($vrow["siz"], 1024 * 1024 * 1024, 5); + else + $giga = $vrow["siz"] / (1024 * 1024 * 1024); + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + } + // $last_k1 = null; + } + $totobj += $midobj; + if (extension_loaded("bcmath")) + $totsiz = bcadd($totsiz, $midsiz, 0); + else + $totsiz += $midsiz; + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + if (extension_loaded("bcmath")) + $mega = bcdiv($midsiz, 1024 * 1024, 5); + else + $mega = $midsiz / (1024 * 1024); + + if (extension_loaded("bcmath")) + $giga = bcdiv($midsiz, 1024 * 1024 * 1024, 5); + else + $giga = $midsiz / (1024 * 1024 * 1024); + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + } + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + if (extension_loaded("bcmath")) + $mega = bcdiv($totsiz, 1024 * 1024, 5); + else + $mega = $totsiz / (1024 * 1024); + if (extension_loaded("bcmath")) + $giga = bcdiv($totsiz, 1024 * 1024 * 1024, 5); + else + $giga = $totsiz / (1024 * 1024 * 1024); + $out .= "\n"; + $out .= "\n"; + $out .= "\n"; + + $out .= "
      "; + if ($parm["srt"] == "col") + $out .= " "; + $out .= _('phraseanet:: collection') . ""; + if ($parm["srt"] == "obj") + $out .= " "; + $out .= _('admin::base: objet') . "" . _('admin::base: nombre') . "" . _('admin::base: poids') . " (Mo)" . _('admin::base: poids') . " (Go)
      " . $vrow["asciiname"] . "" . _('admin::base: enregistrements orphelins') . " " . sprintf("(coll_id=%s)", $vrow["coll_id"]) . "" . ($last_k2 = $vrow["name"]) . " " . $vrow["n"] . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 
      " . _('report:: total') . " " . $midobj . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 

      " . _('report:: total') . " " . $totobj . "  " . sprintf("%.2f", $mega) . "  " . sprintf("%.2f", $giga) . " 
      "; + } + $out .= "
      "; + + print($out); + ?> + +
      +
      +
      +
      + : + +
      +
      +
      +
      +
      +
      +
      +
      + : + +
      +
      +
      +
      +
      +
      +
      + ACL()->has_right_on_sbas($sbas_id, 'bas_manage')) { + ?> +
      + + - -
      + + +
      -
      - - - -
      -
      +
      + + + +
      +
      - - get_mountable_colls(); + + get_mountable_colls(); - if (count($mountable_colls) > 0) - { - ?> - - -
      - " /> - - - - -
      - +
      +
      + " /> + + + + +
      + diff --git a/www/admin/databases.php b/www/admin/databases.php index 50ce9f87cd..b6ae19cd97 100644 --- a/www/admin/databases.php +++ b/www/admin/databases.php @@ -31,396 +31,339 @@ $Core = bootstrap::getCore(); phrasea::headers(); ?> - - - - - - - - has_post_datas() && $user_obj->is_admin() === true) - { - $parm = $request->get_parms('upgrade'); - if (!is_null($parm['upgrade'])) - { - $checks = phrasea::is_scheduler_started(); - if ($checks !== true) - { - $appbox = appbox::get_instance(\bootstrap::getCore()); - $upgrader = new Setup_Upgrade($appbox); - $advices = $appbox->forceUpgrade($upgrader); + + + + + + + + has_post_datas() && $user_obj->is_admin() === true) { + $parm = $request->get_parms('upgrade'); + if ( ! is_null($parm['upgrade'])) { + $checks = phrasea::is_scheduler_started(); + if ($checks !== true) { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $upgrader = new Setup_Upgrade($appbox); + $advices = $appbox->forceUpgrade($upgrader); - $code = ''; - foreach ($advices as $advice) - { - $code .= $advice['sql'] . '
      '; - } + $code = ''; + foreach ($advices as $advice) { + $code .= $advice['sql'] . '
      '; + } - $code = _('Propositions de modifications des tables') - . '
      ' . $code . '
      '; - ?> -
      -            
      -          
      - -
      - -
      - ' . $code . ''; + ?> +
      +                    
      +                    
      + +
      + +
      + +
      + get_parms('mount_base', 'new_settings', 'new_dbname', 'new_data_template', 'new_hostname', 'new_port', 'new_user', 'new_user', 'new_password', 'new_dbname', 'new_data_template'); + if ( ! $parm['mount_base']) { + if ( ! $parm['new_settings'] && $parm['new_dbname'] && $parm['new_data_template']) { + if (p4string::hasAccent($parm['new_dbname'])) { + $error[] = _('Database name can not contains special characters'); + } + + if (count($error) === 0) { + try { + $configuration = \Alchemy\Phrasea\Core\Configuration::build(); + + $choosenConnexion = $configuration->getPhraseanet()->get('database'); + + $connexion = $configuration->getConnexion($choosenConnexion); + + $hostname = $connexion->get('host'); + $port = $connexion->get('port'); + $user = $connexion->get('user'); + $password = $connexion->get('password'); + + $data_template = new system_file($registry->get('GV_RootPath') . 'lib/conf.d/data_templates/' . $parm['new_data_template'] . '.xml'); + + $connbas = new connection_pdo('databox_creation', $hostname, $port, $user, $password, $parm['new_dbname'], array(), $appbox->get_registry()); + + try { + $base = databox::create($appbox, $connbas, $data_template, $registry); + $base->registerAdmin($user_obj); + $createBase = $sbas_id = $base->get_sbas_id(); + } catch (Exception $e) { + $error[] = $e->getMessage(); + } + } catch (Exception $e) { + $error[] = _('Database does not exists or can not be accessed'); + } + } + } elseif ($parm['new_settings'] && $parm['new_hostname'] && $parm['new_port'] + && $parm['new_user'] && $parm['new_password'] + && $parm['new_dbname'] && $parm['new_data_template']) { + + if (p4string::hasAccent($parm['new_dbname'])) { + $error[] = _('Database name can not contains special characters'); + } + + if (count($error) === 0) { + + try { + $data_template = new system_file($registry->get('GV_RootPath') . 'lib/conf.d/data_templates/' . $parm['new_data_template'] . '.xml'); + $connbas = new connection_pdo('databox_creation', $parm['new_hostname'], $parm['new_port'], $parm['new_user'], $parm['new_password'], $parm['new_dbname'], array(), $appbox->get_registry()); + $base = databox::create($appbox, $connbas, $data_template, $registry); + $base->registerAdmin($user_obj); + $createBase = $sbas_id = $base->get_sbas_id(); + } catch (Exception $e) { + $error[] = $e->getMessage(); + } + } + } + } elseif ($parm['mount_base']) { + if ( ! $parm['new_settings'] && $parm['new_dbname']) { + + if (p4string::hasAccent($parm['new_dbname'])) + $error[] = _('Database name can not contains special characters'); + + if (count($error) === 0) { + try { + $configuration = \Alchemy\Phrasea\Core\Configuration::build(); + + $connexion = $configuration->getConnexion(); + + $hostname = $connexion->get('host'); + $port = $connexion->get('port'); + $user = $connexion->get('user'); + $password = $connexion->get('password'); + + $appbox->get_connection()->beginTransaction(); + $base = databox::mount($appbox, $hostname, $port, $user, $password, $parm['new_dbname'], $registry); + $base->registerAdmin($user_obj); + $mountBase = true; + $appbox->get_connection()->commit(); + } catch (Exception $e) { + $appbox->get_connection()->rollBack(); + $error[] = $e->getMessage(); + } + } + } elseif ($parm['new_settings'] && $parm['new_hostname'] && $parm['new_port'] && $parm['new_user'] + && $parm['new_password'] && $parm['new_dbname']) { + + if (p4string::hasAccent($parm['new_dbname'])) + $error[] = 'No special chars in dbname'; + + if (count($error) === 0) { + try { + $appbox->get_connection()->beginTransaction(); + $base = databox::mount($appbox, $parm['new_hostname'], $parm['new_port'], $parm['new_user'], $parm['new_password'], $parm['new_dbname'], $registry); + $base->registerAdmin($user_obj); + $appbox->get_connection()->commit(); + } catch (Exception $e) { + $appbox->get_connection()->rollBack(); + $error[] = $e->getMessage() . '@' . $e->getFile() . $e->getLine(); + } + } + } + } } - else - { - ?> -
      - get_parms('mount_base', 'new_settings', 'new_dbname', 'new_data_template', 'new_hostname', 'new_port', 'new_user', 'new_user', 'new_password', 'new_dbname', 'new_data_template'); - if (!$parm['mount_base']) - { - if (!$parm['new_settings'] && $parm['new_dbname'] && $parm['new_data_template']) - { - if (p4string::hasAccent($parm['new_dbname'])) - { - $error[] = _('Database name can not contains special characters'); - } - - if (count($error) === 0) - { - try - { - $configuration = \Alchemy\Phrasea\Core\Configuration::build(); - - $choosenConnexion = $configuration->getPhraseanet()->get('database'); - - $connexion = $configuration->getConnexion($choosenConnexion); - - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - - $data_template = new system_file($registry->get('GV_RootPath') . 'lib/conf.d/data_templates/' . $parm['new_data_template'] . '.xml'); - - $connbas = new connection_pdo('databox_creation', $hostname, $port, $user, $password, $parm['new_dbname'], array(), $appbox->get_registry()); - - try - { - $base = databox::create($appbox, $connbas, $data_template, $registry); - $base->registerAdmin($user_obj); - $createBase = $sbas_id = $base->get_sbas_id(); - } - catch (Exception $e) - { - $error[] = $e->getMessage(); - } - } - catch (Exception $e) - { - $error[] = _('Database does not exists or can not be accessed'); - } - } - } - elseif ($parm['new_settings'] && $parm['new_hostname'] && $parm['new_port'] - && $parm['new_user'] && $parm['new_password'] - && $parm['new_dbname'] && $parm['new_data_template']) - { - - if (p4string::hasAccent($parm['new_dbname'])) - { - $error[] = _('Database name can not contains special characters'); - } - - if (count($error) === 0) - { - - try - { - $data_template = new system_file($registry->get('GV_RootPath') . 'lib/conf.d/data_templates/' . $parm['new_data_template'] . '.xml'); - $connbas = new connection_pdo('databox_creation', $parm['new_hostname'], $parm['new_port'], $parm['new_user'], $parm['new_password'], $parm['new_dbname'], array(), $appbox->get_registry()); - $base = databox::create($appbox, $connbas, $data_template, $registry); - $base->registerAdmin($user_obj); - $createBase = $sbas_id = $base->get_sbas_id(); - } - catch (Exception $e) - { - $error[] = $e->getMessage(); - } - } - } - } - elseif ($parm['mount_base']) - { - if (!$parm['new_settings'] && $parm['new_dbname']) - { - - if (p4string::hasAccent($parm['new_dbname'])) - $error[] = _('Database name can not contains special characters'); - - if (count($error) === 0) - { - try - { - $configuration = \Alchemy\Phrasea\Core\Configuration::build(); - - $connexion = $configuration->getConnexion(); - - $hostname = $connexion->get('host'); - $port = $connexion->get('port'); - $user = $connexion->get('user'); - $password = $connexion->get('password'); - - $appbox->get_connection()->beginTransaction(); - $base = databox::mount($appbox, $hostname, $port, $user, $password, $parm['new_dbname'], $registry); - $base->registerAdmin($user_obj); - $mountBase = true; - $appbox->get_connection()->commit(); - } - catch (Exception $e) - { - $appbox->get_connection()->rollBack(); - $error[] = $e->getMessage(); - } - } - } - elseif ($parm['new_settings'] && $parm['new_hostname'] && $parm['new_port'] && $parm['new_user'] - && $parm['new_password'] && $parm['new_dbname']) - { - - if (p4string::hasAccent($parm['new_dbname'])) - $error[] = 'No special chars in dbname'; - - if (count($error) === 0) - { - try - { - $appbox->get_connection()->beginTransaction(); - $base = databox::mount($appbox, $parm['new_hostname'], $parm['new_port'], $parm['new_user'], $parm['new_password'], $parm['new_dbname'], $registry); - $base->registerAdmin($user_obj); - $appbox->get_connection()->commit(); - } - catch (Exception $e) - { - $appbox->get_connection()->rollBack(); - $error[] = $e->getMessage() . '@' . $e->getFile() . $e->getLine(); - } - } - } - } - } - $upgrade_available = false; + $upgrade_available = false; - if ($appbox->upgradeavailable()) - $upgrade_available = true; + if ($appbox->upgradeavailable()) + $upgrade_available = true; - $sbas_ids = array_merge( + $sbas_ids = array_merge( array_keys($user_obj->ACL()->get_granted_sbas(array('bas_manage'))) , array_keys($user_obj->ACL()->get_granted_sbas(array('bas_modify_struct'))) - ); + ); - $hasRightsMountDB = count($sbas_ids) > 0; + $hasRightsMountDB = count($sbas_ids) > 0; - $sbas = array(); - foreach ($sbas_ids as $sbas_id) - { - $version = 'unknown'; - $sbas[$sbas_id] = ' ' . ' (Unreachable server)'; - try - { - $databox = databox::get_instance($sbas_id); - $version = $databox->get_version(); - if ($databox->upgradeavailable()) - $upgrade_available = true; - $sbas[$sbas_id] = '' . phrasea::sbas_names($sbas_id) - . ' (version ' . $version . ') MySQL ' . $databox->get_connection()->server_info(); - } - catch (Exception $e) - { + $sbas = array(); + foreach ($sbas_ids as $sbas_id) { + $version = 'unknown'; + $sbas[$sbas_id] = ' ' . ' (Unreachable server)'; + try { + $databox = databox::get_instance($sbas_id); + $version = $databox->get_version(); + if ($databox->upgradeavailable()) + $upgrade_available = true; + $sbas[$sbas_id] = '' . phrasea::sbas_names($sbas_id) + . ' (version ' . $version . ') MySQL ' . $databox->get_connection()->server_info(); + } catch (Exception $e) { - } - } - ?> - + + + +
      +

      Bases actuelles :

      +
        + 0) { + foreach ($sbas as $k => $v) { + ?> +
      • + + + +
      • + +
      • None
      • - - - - +
      +is_admin() === true) { ?> -
      -

      Bases actuelles :

      -
        - 0) - { - foreach ($sbas as $k => $v) - { - ?> -
      • - - - -
      • - -
      • None
      • - -
      -
      +
      +

      is_admin() === true) - { - ?> - -
      -

      - -
      getVersion()->getNumber() ?>
      - -
      getVersion()->getNumber() ?>
      - -
      - - -
      -
      - -
      -

      -
      -
      -
      - -
      - -
      - -
      -
      - - + + +
      - closedir($handle); +
      +

      +
      +
      +
      + +
      + +
      + +
      +
      + + + +
      +
      + +
      +
      +
      -
      - +
      +

      +
      +
      +
      + +
      + +
      + +
      +
      + + +
      +
      +
      - -
      -
      -
      -

      -
      -
      -
      - -
      - -
      - -
      -
      - - -
      -
      -
      -
      - - + + diff --git a/www/admin/demand.php b/www/admin/demand.php index 89c59fc34e..4131fff4a6 100644 --- a/www/admin/demand.php +++ b/www/admin/demand.php @@ -27,305 +27,276 @@ $usr_id = $session->get_usr_id(); phrasea::headers(); $templates = array(); -if (!is_null($parm['template'])) -{ - foreach ($parm['template'] as $tmp) - { - if (trim($tmp) != '') - { - $tmp = explode('_', $tmp); +if ( ! is_null($parm['template'])) { + foreach ($parm['template'] as $tmp) { + if (trim($tmp) != '') { + $tmp = explode('_', $tmp); - if (count($tmp) == 2) - { - $templates[$tmp[0]] = $tmp[1]; - } + if (count($tmp) == 2) { + $templates[$tmp[0]] = $tmp[1]; + } + } } - } } $deny = $accept = $options = array(); -if (!is_null($parm['deny'])) -{ - foreach ($parm['deny'] as $den) - { - $den = explode('_', $den); - if (count($den) == 2 && !isset($templates[$den[0]])) - { - $deny[$den[0]][$den[1]] = $den[1]; +if ( ! is_null($parm['deny'])) { + foreach ($parm['deny'] as $den) { + $den = explode('_', $den); + if (count($den) == 2 && ! isset($templates[$den[0]])) { + $deny[$den[0]][$den[1]] = $den[1]; + } } - } } -if (!is_null($parm['accept'])) -{ - foreach ($parm['accept'] as $acc) - { - $acc = explode('_', $acc); - if (count($acc) == 2 && !isset($templates[$acc[0]])) - { - $accept[$acc[0]][$acc[1]] = $acc[1]; - $options[$acc[0]][$acc[1]] = array('HD' => false, 'WM' => false); +if ( ! is_null($parm['accept'])) { + foreach ($parm['accept'] as $acc) { + $acc = explode('_', $acc); + if (count($acc) == 2 && ! isset($templates[$acc[0]])) { + $accept[$acc[0]][$acc[1]] = $acc[1]; + $options[$acc[0]][$acc[1]] = array('HD' => false, 'WM' => false); + } } - } } -if (!is_null($parm['accept_hd'])) -{ - foreach ($parm['accept_hd'] as $accHD) - { - $accHD = explode('_', $accHD); - if (count($accHD) == 2 && isset($accept[$accHD[0]]) && isset($options[$accHD[0]][$accHD[1]])) - { - $options[$accHD[0]][$accHD[1]]['HD'] = true; +if ( ! is_null($parm['accept_hd'])) { + foreach ($parm['accept_hd'] as $accHD) { + $accHD = explode('_', $accHD); + if (count($accHD) == 2 && isset($accept[$accHD[0]]) && isset($options[$accHD[0]][$accHD[1]])) { + $options[$accHD[0]][$accHD[1]]['HD'] = true; + } } - } } -if (!is_null($parm['watermark'])) -{ - foreach ($parm['watermark'] as $wm) - { - $wm = explode('_', $wm); - if (count($wm) == 2 && isset($accept[$wm[0]]) && isset($options[$wm[0]][$wm[1]])) - { - $options[$wm[0]][$wm[1]]['WM'] = true; +if ( ! is_null($parm['watermark'])) { + foreach ($parm['watermark'] as $wm) { + $wm = explode('_', $wm); + if (count($wm) == 2 && isset($accept[$wm[0]]) && isset($options[$wm[0]][$wm[1]])) { + $options[$wm[0]][$wm[1]]['WM'] = true; + } } - } } -if (!is_null($templates) || !is_null($parm['deny']) || !is_null($parm['accept'])) -{ - $done = array(); +if ( ! is_null($templates) || ! is_null($parm['deny']) || ! is_null($parm['accept'])) { + $done = array(); - $cache_to_update = array(); + $cache_to_update = array(); - foreach ($templates as $usr => $template_id) - { - $user = User_Adapter::getInstance($usr, $appbox); - $cache_to_update[$usr] = true; + foreach ($templates as $usr => $template_id) { + $user = User_Adapter::getInstance($usr, $appbox); + $cache_to_update[$usr] = true; - $user_template = User_Adapter::getInstance($template_id, $appbox); - $base_ids = array_keys($user_template->ACL()->get_granted_base()); + $user_template = User_Adapter::getInstance($template_id, $appbox); + $base_ids = array_keys($user_template->ACL()->get_granted_base()); - $user->ACL()->apply_model($user_template, $base_ids); + $user->ACL()->apply_model($user_template, $base_ids); - if (!isset($done[$usr])) - $done[$usr] = array(); - foreach ($base_ids as $base_id) - { - $done[$usr][$base_id] = true; - } + if ( ! isset($done[$usr])) + $done[$usr] = array(); + foreach ($base_ids as $base_id) { + $done[$usr][$base_id] = true; + } - $sql = "DELETE FROM demand + $sql = "DELETE FROM demand WHERE usr_id = :usr_id AND (base_id = " . implode(' OR base_id = ', $base_ids) . ")"; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(array(':usr_id' => $usr)); - $stmt->closeCursor(); - } + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(array(':usr_id' => $usr)); + $stmt->closeCursor(); + } - $sql = "UPDATE demand SET en_cours=0, refuser=1, date_modif=now() + $sql = "UPDATE demand SET en_cours=0, refuser=1, date_modif=now() WHERE usr_id = :usr_id AND base_id = :base_id"; - $stmt = $appbox->get_connection()->prepare($sql); - foreach ($deny as $usr => $bases) - { - $cache_to_update[$usr] = true; - foreach ($bases as $bas) - { - $stmt->execute(array(':usr_id' => $usr, ':base_id' => $bas)); - - if (!isset($done[$usr])) - $done[$usr] = array(); - - $done[$usr][$bas] = false; - } - } - $stmt->closeCursor(); - - foreach ($accept as $usr => $bases) - { - $user = User_Adapter::getInstance($usr, $appbox); - $cache_to_update[$usr] = true; - foreach ($bases as $bas) - { - $user->ACL()->give_access_to_sbas(array(phrasea::sbasFromBas($bas))); - - $rights = array( - 'canputinalbum' => '1' - , 'candwnldhd' => ($options[$usr][$bas]['HD'] ? '1' : '0') - , 'nowatermark' => ($options[$usr][$bas]['WM'] ? '0' : '1') - , 'candwnldpreview' => '1' - , 'actif' => '1' - ); - - $user->ACL()->give_access_to_base(array($bas)); - $user->ACL()->update_rights_to_base($bas, $rights); - - if (!isset($done[$usr])) - $done[$usr] = array(); - - $done[$usr][$bas] = true; - - $sql = "DELETE FROM demand WHERE usr_id = :usr_id AND base_id = :base_id"; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(array(':usr_id' => $usr, ':base_id' => $bas)); - $stmt->closeCursor(); - } - } - - foreach ($cache_to_update as $usr_id => $true) - { - $user = User_Adapter::getInstance($usr_id, $appbox); - $user->ACL()->delete_data_from_cache(); - unset($user); - } - foreach ($done as $usr => $bases) - { - $sql = 'SELECT usr_mail FROM usr WHERE usr_id = :usr_id'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(array(':usr_id' => $usr)); - $row = $stmt->fetch(PDO::FETCH_ASSOC); + foreach ($deny as $usr => $bases) { + $cache_to_update[$usr] = true; + foreach ($bases as $bas) { + $stmt->execute(array(':usr_id' => $usr, ':base_id' => $bas)); + + if ( ! isset($done[$usr])) + $done[$usr] = array(); + + $done[$usr][$bas] = false; + } + } $stmt->closeCursor(); - $accept = $deny = ''; + foreach ($accept as $usr => $bases) { + $user = User_Adapter::getInstance($usr, $appbox); + $cache_to_update[$usr] = true; + foreach ($bases as $bas) { + $user->ACL()->give_access_to_sbas(array(phrasea::sbasFromBas($bas))); - if ($row) - { + $rights = array( + 'canputinalbum' => '1' + , 'candwnldhd' => ($options[$usr][$bas]['HD'] ? '1' : '0') + , 'nowatermark' => ($options[$usr][$bas]['WM'] ? '0' : '1') + , 'candwnldpreview' => '1' + , 'actif' => '1' + ); - if (PHPMailer::ValidateAddress($row['usr_mail'])) - { - foreach ($bases as $bas => $isok) - { - if ($isok === true) - $accept .= '
    • ' . phrasea::bas_names($bas) . "
    • \n"; - if ($isok === false) - $deny .= '
    • ' . phrasea::bas_names($bas) . "
    • \n"; + $user->ACL()->give_access_to_base(array($bas)); + $user->ACL()->update_rights_to_base($bas, $rights); + + if ( ! isset($done[$usr])) + $done[$usr] = array(); + + $done[$usr][$bas] = true; + + $sql = "DELETE FROM demand WHERE usr_id = :usr_id AND base_id = :base_id"; + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(array(':usr_id' => $usr, ':base_id' => $bas)); + $stmt->closeCursor(); + } + } + + foreach ($cache_to_update as $usr_id => $true) { + $user = User_Adapter::getInstance($usr_id, $appbox); + $user->ACL()->delete_data_from_cache(); + unset($user); + } + foreach ($done as $usr => $bases) { + $sql = 'SELECT usr_mail FROM usr WHERE usr_id = :usr_id'; + + $stmt = $appbox->get_connection()->prepare($sql); + $stmt->execute(array(':usr_id' => $usr)); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + $accept = $deny = ''; + + if ($row) { + + if (PHPMailer::ValidateAddress($row['usr_mail'])) { + foreach ($bases as $bas => $isok) { + if ($isok === true) + $accept .= '
    • ' . phrasea::bas_names($bas) . "
    • \n"; + if ($isok === false) + $deny .= '
    • ' . phrasea::bas_names($bas) . "
    • \n"; + } + if (($accept != '' || $deny != '')) { + mail::register_confirm($row['usr_mail'], $accept, $deny); + } + } } - if (($accept != '' || $deny != '')) - { - mail::register_confirm($row['usr_mail'], $accept, $deny); - } - } } - } } ?> - - - - - - + + - + function checkAll(that) + { + var bool = true; + var first = true; + $('.'+that+'_checker:not(:disabled)').each(function(){ + // if(!$(this)[0].disabled) + // { + if(first && $(this)[0].checked) + bool = false; + $(this)[0].checked = bool; + first = false; + if(that == 'deny') + { + checkDeny($(this)); + } + if(that == 'accept_hd') + checkAdd(this) + if(that == 'watermark') + checkAdd(this) + if(that == 'accept') + checkRemove(this) + // } + }); + } + + - + -
      + execute(array(':usr_id' => $session->get_usr_id())); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); -foreach ($rs as $row) -{ - $models .= ''; +foreach ($rs as $row) { + $models .= ''; } $sql = "SELECT demand.date_modif,demand.base_id,usr.usr_id , usr.usr_login ,usr.usr_nom,usr.usr_prenom, @@ -372,120 +342,116 @@ $out .= "

      " . _('admin:: demandes en cours') . "

      $out .= "
      "; $out .= "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "
      HDW" . _('admin::compte-utilisateur identifiant') . "" . _('admin::compte-utilisateur societe') . "" . _('admin::compte-utilisateur date d\'inscription') . "" . _('admin::collection') . "
      "; + "" . + "" . + "" . + "HD" . + "W" . + "" . _('admin::compte-utilisateur identifiant') . "" . + "" . _('admin::compte-utilisateur societe') . "" . + "" . _('admin::compte-utilisateur date d\'inscription') . "" . + "" . _('admin::collection') . "" . + "" . + ""; $out .= "
      "; $out .= "
    "; $out .= "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - "" . - ""; + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + "" . + ""; $class = ''; $currentUsr = null; $sql = "SELECT * FROM usr WHERE usr_id = :usr_id"; $stmt = $appbox->get_connection()->prepare($sql); -foreach ($rs as $row) -{ - if ($row['usr_id'] != $currentUsr) - { - if ($currentUsr !== null) - { +foreach ($rs as $row) { + if ($row['usr_id'] != $currentUsr) { + if ($currentUsr !== null) { - $out .= '
    '; - } + $out .= '
'; + } - $currentUsr = $row['usr_id']; - $class = $class == 'g' ? '' : 'g'; + $currentUsr = $row['usr_id']; + $class = $class == 'g' ? '' : 'g'; - $info = ""; - $stmt->execute(array(':usr_id' => $row['usr_id'])); - $rowInfo = $stmt->fetch(PDO::FETCH_ASSOC); - if ($rowInfo) - { - $info .= "
" . _('admin::compte-utilisateur identifiant') . " : " . ($rowInfo["usr_login"]) . "
"; + $info = ""; + $stmt->execute(array(':usr_id' => $row['usr_id'])); + $rowInfo = $stmt->fetch(PDO::FETCH_ASSOC); + if ($rowInfo) { + $info .= "
" . _('admin::compte-utilisateur identifiant') . " : " . ($rowInfo["usr_login"]) . "
"; - $info .= "
" . _('admin::compte-utilisateur nom') . "/" . _('admin::compte-utilisateur prenom') . " : "; - $info .= ( $rowInfo["usr_nom"]) . " "; - $info .= ( $rowInfo["usr_prenom"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur nom') . "/" . _('admin::compte-utilisateur prenom') . " : "; + $info .= ( $rowInfo["usr_nom"]) . " "; + $info .= ( $rowInfo["usr_prenom"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur email') . " : "; - $info .= ( $rowInfo["usr_mail"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur email') . " : "; + $info .= ( $rowInfo["usr_mail"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur telephone') . " : "; - $info .= ( $rowInfo["tel"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur telephone') . " : "; + $info .= ( $rowInfo["tel"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur poste') . " : "; - $info .= ( $rowInfo["fonction"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur poste') . " : "; + $info .= ( $rowInfo["fonction"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur societe') . " : "; - $info .= ( $rowInfo["societe"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur societe') . " : "; + $info .= ( $rowInfo["societe"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur activite') . " : "; - $info .= ( $rowInfo["activite"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur activite') . " : "; + $info .= ( $rowInfo["activite"]); + $info .= "
"; - $info .= "
" . _('admin::compte-utilisateur adresse') . " : "; - $info .= "" . ($rowInfo["adresse"]); - $info .= "
"; + $info .= "
" . _('admin::compte-utilisateur adresse') . " : "; + $info .= "" . ($rowInfo["adresse"]); + $info .= "
"; - $info .= "
"; + $info .= "
"; - $info .= ( $rowInfo["cpostal"]) . " "; + $info .= ( $rowInfo["cpostal"]) . " "; - $info .= ( $rowInfo["ville"]); - $info .= "
" . "
"; - } + $info .= ( $rowInfo["ville"]); + $info .= "
" . "
"; + } - $info = "
" . $info . "
"; + $info = "
" . $info . "
"; - $out .= ''; - $out .= ""; - $out .= " "; - $out .= ""; - $out .= ""; - $out .= " "; - $out .= ""; - $out .= ""; - $out .= " "; - $out .= ""; - $out .= ""; - $out .= " "; - $out .= ""; - $out .= ''; - $out .= '' . ($row["usr_login"]); - $out .= ''; + $out .= ''; + $out .= ""; + $out .= " "; + $out .= ""; + $out .= ""; + $out .= " "; + $out .= ""; + $out .= ""; + $out .= " "; + $out .= ""; + $out .= ""; + $out .= " "; + $out .= ""; + $out .= ''; + $out .= '' . ($row["usr_login"]); + $out .= ''; - $tmp = $row["usr_nom"] . " " . $row["usr_prenom"] . ( $row["societe"] ? " (" . $row["societe"] . ")" : "" ); - $out .= '' . (trim($tmp)) . ''; + $tmp = $row["usr_nom"] . " " . $row["usr_prenom"] . ( $row["societe"] ? " (" . $row["societe"] . ")" : "" ); + $out .= '' . (trim($tmp)) . ''; - $out .= ' ' . _('admin:: appliquer le modele ') . ' '; + $out .= ' ' . _('admin:: appliquer le modele ') . ' '; - $out .= ''; - $out .= '
' . + $out .= ''; + $out .= '"; + $onedetail.=" "; + + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + + $onedetail.="
' . "" . "" . "" . @@ -496,29 +462,29 @@ foreach ($rs as $row) "" . "" . ""; - } + } - $out .= ''; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; + $out .= ''; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; - $out .= ''; + $out .= ''; - $out .= ''; + $out .= ''; - $out .= ''; + $out .= ''; } $stmt->closeCursor(); @@ -539,6 +505,6 @@ $out .= ""; print($out); ?> - - + + diff --git a/www/admin/getinfousr.php b/www/admin/getinfousr.php index 424976c024..c19ee86dcf 100644 --- a/www/admin/getinfousr.php +++ b/www/admin/getinfousr.php @@ -33,36 +33,31 @@ $info .= _('admin::compte-utilisateur identifiant') . " : " . $user->get_login() $info2 .= "
" . _('admin::compte-utilisateur nom') . "/" . _('admin::compte-utilisateur prenom') . " : "; $info2 .= $user->get_display_name(); -if ($user->get_email()) -{ - $info2 .= "
" . _('admin::compte-utilisateur email') . " : " . $user->get_email(); +if ($user->get_email()) { + $info2 .= "
" . _('admin::compte-utilisateur email') . " : " . $user->get_email(); } -if ($user->get_tel()) -{ - $info2 .= "
" . _('admin::compte-utilisateur telephone') . " : " . $user->get_tel(); +if ($user->get_tel()) { + $info2 .= "
" . _('admin::compte-utilisateur telephone') . " : " . $user->get_tel(); } -if ($user->get_job()) -{ - $info2 .= "
" . _('admin::compte-utilisateur poste') . " : " . $user->get_job(); +if ($user->get_job()) { + $info2 .= "
" . _('admin::compte-utilisateur poste') . " : " . $user->get_job(); } -if ($user->get_company()) -{ - $info2 .= "
" . _('admin::compte-utilisateur societe') . " : " . $user->get_company(); +if ($user->get_company()) { + $info2 .= "
" . _('admin::compte-utilisateur societe') . " : " . $user->get_company(); } -if ($user->get_position()) -{ - $info2 .= "
" . _('admin::compte-utilisateur activite') . " : " . $user->get_position(); +if ($user->get_position()) { + $info2 .= "
" . _('admin::compte-utilisateur activite') . " : " . $user->get_position(); } $info2 .= "
" . _('admin::compte-utilisateur adresse') . ""; $info2 .= "
" . $user->get_address() . "
" . $user->get_zipcode() . " " . $user->get_city(); $info2 .= "
"; if ($info2 != "") - $info .= "" . $info2 . ""; + $info .= "" . $info2 . ""; $info = str_replace("

", "
", $info); $info = str_replace("\n", "", $info); $info = str_replace("\r", "", $info); ?> diff --git a/www/admin/global_values.php b/www/admin/global_values.php index 0a83476281..fe6d88e1e6 100644 --- a/www/admin/global_values.php +++ b/www/admin/global_values.php @@ -27,207 +27,192 @@ require(__DIR__ . "/../../lib/conf.d/_GV_template.inc"); $request = http_request::getInstance(); -if ($request->has_post_datas()) -{ - if (setup::create_global_values($appbox->get_registry(), $request->get_post_datas())) - { - return phrasea::redirect('/admin/global_values.php'); - } +if ($request->has_post_datas()) { + if (setup::create_global_values($appbox->get_registry(), $request->get_post_datas())) { + return phrasea::redirect('/admin/global_values.php'); + } } -function getFormTimezone($props=array(), $selected=false) +function getFormTimezone($props = array(), $selected = false) { - $form = ''; + $form .= ''; - return $form; + return $form; } - phrasea::start($Core); ?> - - - - - - - - - + + + -
- Adresse : -
-
- Installation : -
-
- Maintenance : get('GV_maintenance') == true ? "checked='checked'" : ''; ?>/> -
-
- Debug : get('GV_debug') == true ? "checked='checked'" : ''; ?>/> -
- + Adresse : + +
+ Installation : +
+
+ Maintenance : get('GV_maintenance') == true ? "checked='checked'" : ''; ?>/> +
+
+ Debug : get('GV_debug') == true ? "checked='checked'" : ''; ?>/> +
+'; +echo ''; - foreach ($GV as $section) - { - echo '
'; - echo '

' . $section['section'] . '

'; - echo '
    '; - foreach ($section['vars'] as $value) - { +foreach ($GV as $section) { + echo '
    '; + echo '

    ' . $section['section'] . '

    '; + echo '
      '; + foreach ($section['vars'] as $value) { $readonly = false; if (isset($value['readonly']) && $value['readonly'] === true) - $readonly = true; + $readonly = true; $input = ''; $currentValue = null; if ($registry->is_set($value['name'])) - $currentValue = $registry->get($value['name']); + $currentValue = $registry->get($value['name']); elseif (isset($value['default'])) - $currentValue = $value['default']; + $currentValue = $value['default']; - switch ($value['type']) - { + switch ($value['type']) { - case 'boolean': - $input = ' + case 'boolean': + $input = ' '; - break; - case 'string': - $input = ''; - break; - case 'text': - $input = ''; - break; - case 'enum': - $input = ''; - break; - case 'enum_multi': - if (isset($value['available']) && is_array($value['available'])) - { - foreach ($value['available'] as $k => $v) - $input .= '
      '; + break; + case 'string': + $input = ''; + break; + case 'text': + $input = ''; + break; + case 'enum': + $input = ''; + break; + case 'enum_multi': + if (isset($value['available']) && is_array($value['available'])) { + foreach ($value['available'] as $k => $v) + $input .= '
      '; + } else { + echo '

      erreur avec la valeur ' . $value['name'] . '

      '; + } + break; + case 'list': - } - else - { - echo '

      erreur avec la valeur ' . $value['name'] . '

      '; - } - break; - case 'list': - - break; - case 'integer': - $input .= ''; - break; - case 'password': - $input .= ''; - break; - case 'timezone': - if (trim($currentValue) === '') - { - $datetime = new DateTime(); - $currentValue = $datetime->getTimezone()->getName(); - } - $input .= getFormTimezone(array('name' => $value['name'], 'id' => 'id_' . $value['name']), $currentValue); - break; - default: - break; + break; + case 'integer': + $input .= ''; + break; + case 'password': + $input .= ''; + break; + case 'timezone': + if (trim($currentValue) === '') { + $datetime = new DateTime(); + $currentValue = $datetime->getTimezone()->getName(); + } + $input .= getFormTimezone(array('name' => $value['name'], 'id' => 'id_' . $value['name']), $currentValue); + break; + default: + break; } $isnew = $registry->is_set($value['name']); @@ -235,25 +220,23 @@ phrasea::start($Core);
      ' . $input . '
      ' . ($isnew === false ? 'NEW' : '') . '
      '; - if (isset($value['required'])) - { - $rules[$value['name']] = array('required' => $value['required']); - $messages[$value['name']] = array('required' => 'Ce champ est requis !'); + if (isset($value['required'])) { + $rules[$value['name']] = array('required' => $value['required']); + $messages[$value['name']] = array('required' => 'Ce champ est requis !'); } - } - - echo '
    '; - - if (isset($section['javascript'])) - { - echo "
    "; - } - - echo '
    '; } + echo '
'; - $JS = '$(document).ready(function() { + if (isset($section['javascript'])) { + echo "
"; + } + + echo '
'; +} + + +$JS = '$(document).ready(function() { // validate signup form on keyup and submit $("#form").validate({ rules: ' . p4string::jsonencode($rules) . ', @@ -264,12 +247,12 @@ phrasea::start($Core); }); }); '; - ?> - - - +?> + + + diff --git a/www/admin/import.php b/www/admin/import.php index fb456dc899..05339ace21 100644 --- a/www/admin/import.php +++ b/www/admin/import.php @@ -1,5 +1,4 @@ - - - - + - - - + function rloadusr() + { + parent.imp0rloadusr(); + } + + + - count($test1) && count($test2) < 20)) - $separateur = ";"; + // pb sinon qd venant de mac + ini_set("auto_detect_line_endings", true); + if ($FILE = fopen($filename, "r")) { + $test1 = fgetcsv($FILE, 1024, ","); + rewind($FILE); + $test2 = fgetcsv($FILE, 1024, ";"); + rewind($FILE); + if (count($test1) == 1 || ( count($test2) > count($test1) && count($test2) < 20)) + $separateur = ";"; - while ($ARRAY[] = fgetcsv($FILE, 1024, $separateur)) - ; - fclose($FILE); - array_pop($ARRAY); + while ($ARRAY[] = fgetcsv($FILE, 1024, $separateur)); + fclose($FILE); + array_pop($ARRAY); - return $ARRAY; - } - } + return $ARRAY; + } + } + $request = http_request::getInstance(); + $parm = $request->get_parms("act", "modelToAplly", "sr"); - $request = http_request::getInstance(); - $parm = $request->get_parms("act", "modelToAplly", "sr"); + $conn = $appbox->get_connection(); - $conn = $appbox->get_connection(); + $models = null; - $models = null; + if ($parm["act"] == "STEP2" || $parm["act"] == "STEP3") { + $admBasid = array_keys($user->ACL()->get_granted_base(array('manage'))); + $admBasid = implode(', ', $admBasid); - if ($parm["act"] == "STEP2" || $parm["act"] == "STEP3") - { - $admBasid = array_keys($user->ACL()->get_granted_base(array('manage'))); - $admBasid = implode(', ',$admBasid); - - if ($parm["act"] == "STEP2") - { - $sql = "SELECT usr.usr_id,usr.usr_login + if ($parm["act"] == "STEP2") { + $sql = "SELECT usr.usr_id,usr.usr_login FROM usr INNER JOIN basusr ON (basusr.usr_id=usr.usr_id) @@ -119,382 +113,344 @@ phrasea::headers(); AND usr_login not like '(#deleted_%)' GROUP BY usr_id"; - $stmt = $conn->prepare($sql); - $stmt->execute(array(':usr_id' => $usr_id)); - $models = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - } - } - - $equivalenceToMysqlField['civilite'] = 'usr_sexe'; - $equivalenceToMysqlField['gender'] = 'usr_sexe'; - $equivalenceToMysqlField['usr_sexe'] = 'usr_sexe'; - $equivalenceToMysqlField['nom'] = 'usr_nom'; - $equivalenceToMysqlField['name'] = 'usr_nom'; - $equivalenceToMysqlField['last name'] = 'usr_nom'; - $equivalenceToMysqlField['last_name'] = 'usr_nom'; - $equivalenceToMysqlField['usr_nom'] = 'usr_nom'; - $equivalenceToMysqlField['first name'] = 'usr_prenom'; - $equivalenceToMysqlField['first_name'] = 'usr_prenom'; - $equivalenceToMysqlField['prenom'] = 'usr_prenom'; - $equivalenceToMysqlField['usr_prenom'] = 'usr_prenom'; - $equivalenceToMysqlField['identifiant'] = 'usr_login'; - $equivalenceToMysqlField['login'] = 'usr_login'; - $equivalenceToMysqlField['usr_login'] = 'usr_login'; - $equivalenceToMysqlField['usr_password'] = 'usr_password'; - $equivalenceToMysqlField['password'] = 'usr_password'; - $equivalenceToMysqlField['mot de passe'] = 'usr_password'; - $equivalenceToMysqlField['usr_mail'] = 'usr_mail'; - $equivalenceToMysqlField['email'] = 'usr_mail'; - $equivalenceToMysqlField['mail'] = 'usr_mail'; - $equivalenceToMysqlField['adresse'] = 'adresse'; - $equivalenceToMysqlField['adress'] = 'adresse'; - $equivalenceToMysqlField['address'] = 'adresse'; - $equivalenceToMysqlField['ville'] = 'ville'; - $equivalenceToMysqlField['city'] = 'ville'; - $equivalenceToMysqlField['zip'] = 'cpostal'; - $equivalenceToMysqlField['zipcode'] = 'cpostal'; - $equivalenceToMysqlField['zip_code'] = 'cpostal'; - $equivalenceToMysqlField['cpostal'] = 'cpostal'; - $equivalenceToMysqlField['cp'] = 'cpostal'; - $equivalenceToMysqlField['code_postal'] = 'cpostal'; - $equivalenceToMysqlField['tel'] = 'tel'; - $equivalenceToMysqlField['telephone'] = 'tel'; - $equivalenceToMysqlField['phone'] = 'tel'; - $equivalenceToMysqlField['fax'] = 'fax'; - $equivalenceToMysqlField['job'] = 'fonction'; - $equivalenceToMysqlField['fonction'] = 'fonction'; - $equivalenceToMysqlField['function'] = 'fonction'; - $equivalenceToMysqlField['societe'] = 'societe'; - $equivalenceToMysqlField['company'] = 'societe'; - $equivalenceToMysqlField['activity'] = 'activite'; - $equivalenceToMysqlField['activite'] = 'activite'; - $equivalenceToMysqlField['pays'] = 'pays'; - $equivalenceToMysqlField['country'] = 'pays'; - - $equivalenceToMysqlField['ftp_active'] = 'activeFTP'; - $equivalenceToMysqlField['compte_ftp_actif'] = 'activeFTP'; - $equivalenceToMysqlField['ftpactive'] = 'activeFTP'; - $equivalenceToMysqlField['activeftp'] = 'activeFTP'; - $equivalenceToMysqlField['ftp_adress'] = 'addrFTP'; - $equivalenceToMysqlField['adresse_du_serveur_ftp'] = 'addrFTP'; - $equivalenceToMysqlField['addrftp'] = 'addrFTP'; - $equivalenceToMysqlField['ftpaddr'] = 'addrFTP'; - $equivalenceToMysqlField['loginftp'] = 'loginFTP'; - $equivalenceToMysqlField['ftplogin'] = 'loginFTP'; - $equivalenceToMysqlField['ftppwd'] = 'pwdFTP'; - $equivalenceToMysqlField['pwdftp'] = 'pwdFTP'; - $equivalenceToMysqlField['destftp'] = 'destFTP'; - $equivalenceToMysqlField['destination_folder'] = 'destFTP'; - $equivalenceToMysqlField['dossier_de_destination'] = 'destFTP'; - $equivalenceToMysqlField['passive_mode'] = 'passifFTP'; - $equivalenceToMysqlField['mode_passif'] = 'passifFTP'; - $equivalenceToMysqlField['passifftp'] = 'passifFTP'; - $equivalenceToMysqlField['retry'] = 'retryFTP'; - $equivalenceToMysqlField['nombre_de_tentative'] = 'retryFTP'; - $equivalenceToMysqlField['retryftp'] = 'retryFTP'; - $equivalenceToMysqlField['by_default__send'] = 'defaultftpdatasent'; - $equivalenceToMysqlField['by_default_send'] = 'defaultftpdatasent'; - $equivalenceToMysqlField['envoi_par_defaut'] = 'defaultftpdatasent'; - $equivalenceToMysqlField['defaultftpdatasent'] = 'defaultftpdatasent'; - $equivalenceToMysqlField['prefix_creation_folder'] = 'prefixFTPfolder'; - $equivalenceToMysqlField['prefix_de_creation_de_dossier'] = 'prefixFTPfolder'; - $equivalenceToMysqlField['prefixFTPfolder'] = 'prefixFTPfolder'; - - if ($parm["act"] == "STEP2" && (!isset($_FILES['fileusers']) || (isset($_FILES['fileusers']) && $_FILES['fileusers']['error']))) - { - print("
ERROR : " . $_FILES['fileusers']['error'] . "
"); - $parm["act"] = ""; - } - if ($parm["act"] == "STEP3") - { - $nbcreation = 0; - - $ARRAY = unserialize($parm["sr"]); - $nblignes = sizeof($ARRAY); // compte le nombre de ligne - $nbcol = sizeof($ARRAY[0]); // nombre de colonne par ligne - - for ($i = 1; $i < $nblignes; $i++) // pour chaque ligne.... - { - $curUser = NULL; - for ($j = 0; $j < $nbcol; $j++) // affiche colonne par colonne - { - if (!isset($equivalenceToMysqlField[$ARRAY[0][$j]])) - continue; - if ($equivalenceToMysqlField[$ARRAY[0][$j]] == "usr_sexe" && isset($ARRAY[$i][$j])) - { - switch ($ARRAY[$i][$j]) - { - case "Mlle": - case "Mlle.": - case "mlle": - case "Miss": - case "miss": - case "0": - $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 0; - break; - - case "Mme": - case "Madame": - case "Ms": - case "Ms.": - case "1": - $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 1; - break; - - case "M": - case "M.": - case "Mr": - case "Mr.": - case "Monsieur": - case "Mister": - case "2": - $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 2; - break; + $stmt = $conn->prepare($sql); + $stmt->execute(array(':usr_id' => $usr_id)); + $models = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); } - } - else - { - if (isset($ARRAY[$i][$j])) - $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = trim($ARRAY[$i][$j]); - } } + $equivalenceToMysqlField['civilite'] = 'usr_sexe'; + $equivalenceToMysqlField['gender'] = 'usr_sexe'; + $equivalenceToMysqlField['usr_sexe'] = 'usr_sexe'; + $equivalenceToMysqlField['nom'] = 'usr_nom'; + $equivalenceToMysqlField['name'] = 'usr_nom'; + $equivalenceToMysqlField['last name'] = 'usr_nom'; + $equivalenceToMysqlField['last_name'] = 'usr_nom'; + $equivalenceToMysqlField['usr_nom'] = 'usr_nom'; + $equivalenceToMysqlField['first name'] = 'usr_prenom'; + $equivalenceToMysqlField['first_name'] = 'usr_prenom'; + $equivalenceToMysqlField['prenom'] = 'usr_prenom'; + $equivalenceToMysqlField['usr_prenom'] = 'usr_prenom'; + $equivalenceToMysqlField['identifiant'] = 'usr_login'; + $equivalenceToMysqlField['login'] = 'usr_login'; + $equivalenceToMysqlField['usr_login'] = 'usr_login'; + $equivalenceToMysqlField['usr_password'] = 'usr_password'; + $equivalenceToMysqlField['password'] = 'usr_password'; + $equivalenceToMysqlField['mot de passe'] = 'usr_password'; + $equivalenceToMysqlField['usr_mail'] = 'usr_mail'; + $equivalenceToMysqlField['email'] = 'usr_mail'; + $equivalenceToMysqlField['mail'] = 'usr_mail'; + $equivalenceToMysqlField['adresse'] = 'adresse'; + $equivalenceToMysqlField['adress'] = 'adresse'; + $equivalenceToMysqlField['address'] = 'adresse'; + $equivalenceToMysqlField['ville'] = 'ville'; + $equivalenceToMysqlField['city'] = 'ville'; + $equivalenceToMysqlField['zip'] = 'cpostal'; + $equivalenceToMysqlField['zipcode'] = 'cpostal'; + $equivalenceToMysqlField['zip_code'] = 'cpostal'; + $equivalenceToMysqlField['cpostal'] = 'cpostal'; + $equivalenceToMysqlField['cp'] = 'cpostal'; + $equivalenceToMysqlField['code_postal'] = 'cpostal'; + $equivalenceToMysqlField['tel'] = 'tel'; + $equivalenceToMysqlField['telephone'] = 'tel'; + $equivalenceToMysqlField['phone'] = 'tel'; + $equivalenceToMysqlField['fax'] = 'fax'; + $equivalenceToMysqlField['job'] = 'fonction'; + $equivalenceToMysqlField['fonction'] = 'fonction'; + $equivalenceToMysqlField['function'] = 'fonction'; + $equivalenceToMysqlField['societe'] = 'societe'; + $equivalenceToMysqlField['company'] = 'societe'; + $equivalenceToMysqlField['activity'] = 'activite'; + $equivalenceToMysqlField['activite'] = 'activite'; + $equivalenceToMysqlField['pays'] = 'pays'; + $equivalenceToMysqlField['country'] = 'pays'; - # on va cree ici le user et ses droits - # on verifie juste le login et le password - if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== '' && isset($curUser['usr_password']) && trim($curUser['usr_password']) !== "") - { - $loginNotExist = !User_Adapter::get_usr_id_from_login($curUser['usr_login']); + $equivalenceToMysqlField['ftp_active'] = 'activeFTP'; + $equivalenceToMysqlField['compte_ftp_actif'] = 'activeFTP'; + $equivalenceToMysqlField['ftpactive'] = 'activeFTP'; + $equivalenceToMysqlField['activeftp'] = 'activeFTP'; + $equivalenceToMysqlField['ftp_adress'] = 'addrFTP'; + $equivalenceToMysqlField['adresse_du_serveur_ftp'] = 'addrFTP'; + $equivalenceToMysqlField['addrftp'] = 'addrFTP'; + $equivalenceToMysqlField['ftpaddr'] = 'addrFTP'; + $equivalenceToMysqlField['loginftp'] = 'loginFTP'; + $equivalenceToMysqlField['ftplogin'] = 'loginFTP'; + $equivalenceToMysqlField['ftppwd'] = 'pwdFTP'; + $equivalenceToMysqlField['pwdftp'] = 'pwdFTP'; + $equivalenceToMysqlField['destftp'] = 'destFTP'; + $equivalenceToMysqlField['destination_folder'] = 'destFTP'; + $equivalenceToMysqlField['dossier_de_destination'] = 'destFTP'; + $equivalenceToMysqlField['passive_mode'] = 'passifFTP'; + $equivalenceToMysqlField['mode_passif'] = 'passifFTP'; + $equivalenceToMysqlField['passifftp'] = 'passifFTP'; + $equivalenceToMysqlField['retry'] = 'retryFTP'; + $equivalenceToMysqlField['nombre_de_tentative'] = 'retryFTP'; + $equivalenceToMysqlField['retryftp'] = 'retryFTP'; + $equivalenceToMysqlField['by_default__send'] = 'defaultftpdatasent'; + $equivalenceToMysqlField['by_default_send'] = 'defaultftpdatasent'; + $equivalenceToMysqlField['envoi_par_defaut'] = 'defaultftpdatasent'; + $equivalenceToMysqlField['defaultftpdatasent'] = 'defaultftpdatasent'; + $equivalenceToMysqlField['prefix_creation_folder'] = 'prefixFTPfolder'; + $equivalenceToMysqlField['prefix_de_creation_de_dossier'] = 'prefixFTPfolder'; + $equivalenceToMysqlField['prefixFTPfolder'] = 'prefixFTPfolder'; - if ($loginNotExist) - { - $NewUser = User_Adapter::create($appbox, $curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail'], false); - - $newid = $NewUser->get_id(); - - $admBasid = array_keys($user->ACL()->get_granted_base(array('manage'))); - $template_user = User_Adapter::getInstance($parm["modelToAplly"], $appbox); - $NewUser->ACL()->apply_model($template_user, $admBasid); - - $nbcreation++; - } + if ($parm["act"] == "STEP2" && ( ! isset($_FILES['fileusers']) || (isset($_FILES['fileusers']) && $_FILES['fileusers']['error']))) { + print("
ERROR : " . $_FILES['fileusers']['error'] . "
"); + $parm["act"] = ""; } - } - ?> -
-
- users was created. -
-
- + if ($parm["act"] == "STEP3") { + $nbcreation = 0; - Close -
-
+ $ARRAY = unserialize($parm["sr"]); + $nblignes = sizeof($ARRAY); // compte le nombre de ligne + $nbcol = sizeof($ARRAY[0]); // nombre de colonne par ligne + + for ($i = 1; $i < $nblignes; $i ++ ) { // pour chaque ligne.... + $curUser = NULL; + for ($j = 0; $j < $nbcol; $j ++ ) { // affiche colonne par colonne + if ( ! isset($equivalenceToMysqlField[$ARRAY[0][$j]])) + continue; + if ($equivalenceToMysqlField[$ARRAY[0][$j]] == "usr_sexe" && isset($ARRAY[$i][$j])) { + switch ($ARRAY[$i][$j]) { + case "Mlle": + case "Mlle.": + case "mlle": + case "Miss": + case "miss": + case "0": + $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 0; + break; + + case "Mme": + case "Madame": + case "Ms": + case "Ms.": + case "1": + $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 1; + break; + + case "M": + case "M.": + case "Mr": + case "Mr.": + case "Monsieur": + case "Mister": + case "2": + $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = 2; + break; + } + } else { + if (isset($ARRAY[$i][$j])) + $curUser[$equivalenceToMysqlField[$ARRAY[0][$j]]] = trim($ARRAY[$i][$j]); + } + } + + + # on va cree ici le user et ses droits + # on verifie juste le login et le password + if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== '' && isset($curUser['usr_password']) && trim($curUser['usr_password']) !== "") { + $loginNotExist = ! User_Adapter::get_usr_id_from_login($curUser['usr_login']); + + if ($loginNotExist) { + $NewUser = User_Adapter::create($appbox, $curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail'], false); + + $newid = $NewUser->get_id(); + + $admBasid = array_keys($user->ACL()->get_granted_base(array('manage'))); + $template_user = User_Adapter::getInstance($parm["modelToAplly"], $appbox); + $NewUser->ACL()->apply_model($template_user, $admBasid); + + $nbcreation ++; + } + } + } + ?> +
+
+ users was created. +
+
+ + + Close +
+
+ + +
- -
- - Row \"" . $ARRAY[0][$j] . "\" will be ignored"; - } - else - { + } else { if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_login') - $logindefined = true; + $logindefined = true; if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_password') - $pwddefined = true; - } + $pwddefined = true; } - $outTmp = ""; - if (!$logindefined) - $outTmp.= "
- Row \"login\" is missing, script has stopped !"; - if (!$pwddefined) - $outTmp.= "
- Row \"password\" is missing, script has stopped !"; + } + $outTmp = ""; + if ( ! $logindefined) + $outTmp.= "
- Row \"login\" is missing, script has stopped !"; + if ( ! $pwddefined) + $outTmp.= "
- Row \"password\" is missing, script has stopped !"; - if ($out != "") - $out.="\n
"; + if ($out != "") + $out.="\n
"; - if (!$logindefined || !$pwddefined) - $out = $outTmp; - else - { - // On continu les tests !! - // on verifie (pour chacun) que le login n'existe pas deja et aussi que les mots de passe sont pas vides - $nblignes = sizeof($ARRAY); // nombre de ligne - $nbcol = sizeof($ARRAY[0]); // nombre de colonne par ligne + if ( ! $logindefined || ! $pwddefined) + $out = $outTmp; + else { + // On continu les tests !! + // on verifie (pour chacun) que le login n'existe pas deja et aussi que les mots de passe sont pas vides + $nblignes = sizeof($ARRAY); // nombre de ligne + $nbcol = sizeof($ARRAY[0]); // nombre de colonne par ligne - for ($i = 1; $i < $nblignes; $i++) // pour chaque ligne.... - { + for ($i = 1; $i < $nblignes; $i ++ ) { // pour chaque ligne.... $out2 = ""; $hasVerifLogin = false; $hasVerifPwd = false; - for ($j = 0; $j < $nbcol; $j++) // colonne par colonne - { - $ARRAY[$i][$j] = trim($ARRAY[$i][$j]); - if (!isset($equivalenceToMysqlField[$ARRAY[0][$j]])) - continue; - // verif du login - if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_login') - { - $loginToadd = trim($ARRAY[$i][$j]); - if ($loginToadd == "") - $out2.= " login is empty."; - elseif (isset($loginNew[$loginToadd])) - $out2.= " Le login \"" . $loginToadd . "\" is already defined in the file (line " . $loginNew[$loginToadd] . ")."; - else - { - if (User_Adapter::get_usr_id_from_login($loginToadd)) - { - $out2.= " Login \"" . $loginToadd . "\" already exists in database."; - } - else - { - $loginNew[$loginToadd] = ($i + 1); - } + for ($j = 0; $j < $nbcol; $j ++ ) { // colonne par colonne + $ARRAY[$i][$j] = trim($ARRAY[$i][$j]); + if ( ! isset($equivalenceToMysqlField[$ARRAY[0][$j]])) + continue; + // verif du login + if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_login') { + $loginToadd = trim($ARRAY[$i][$j]); + if ($loginToadd == "") + $out2.= " login is empty."; + elseif (isset($loginNew[$loginToadd])) + $out2.= " Le login \"" . $loginToadd . "\" is already defined in the file (line " . $loginNew[$loginToadd] . ")."; + else { + if (User_Adapter::get_usr_id_from_login($loginToadd)) { + $out2.= " Login \"" . $loginToadd . "\" already exists in database."; + } else { + $loginNew[$loginToadd] = ($i + 1); + } + } + $hasVerifLogin = true; } - $hasVerifLogin = true; - } - // verif du pwd - if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_password') - { + // verif du pwd + if (($equivalenceToMysqlField[$ARRAY[0][$j]]) == 'usr_password') { - if (trim($ARRAY[$i][$j]) == "") - { - $out2.= " password is empty ."; + if (trim($ARRAY[$i][$j]) == "") { + $out2.= " password is empty ."; + } + $hasVerifPwd = true; } - $hasVerifPwd = true; - } - if ($hasVerifLogin && $hasVerifPwd) - $j = $nbcol; + if ($hasVerifLogin && $hasVerifPwd) + $j = $nbcol; - if (($j + 1) >= $nbcol) - { - if ($out2 != "") - { - $out .= "
Line " . ( $i + 1) . " :"; - $out .= "$out2
"; + if (($j + 1) >= $nbcol) { + if ($out2 != "") { + $out .= "
Line " . ( $i + 1) . " :"; + $out .= "$out2
"; + } + else + $nbusrToadd ++; } - else - $nbusrToadd++; - } } - } } + } - if ($out != "") - { // on affiche les erreurs - ?> - -
 Warning 
-
- -
- Number of users who's ready to be create : $nbusrToadd"; - /* ------------- ON ALLEGE LE TABLEAU ---------------- */ - for ($i = 1; $i < sizeof($ARRAY); $i++) - for ($j = 0; $j < sizeof($ARRAY[0]); $j++) - if ((isset($ARRAY[$i][$j]) && trim($ARRAY[$i][$j]) == "") || (!isset($equivalenceToMysqlField[$ARRAY[0][$j]]))) - unset($ARRAY[$i][$j]); - /* -------------------------------------------------- */ - ?> -
-
- - - 0 && count($models) > 0) - { - echo "
Select a model to apply on users :"; - echo " "; + if ($out != "") { // on affiche les erreurs ?> -

Cancel      Add users - -
- you need define a model before importing a list of users. -
-
- Close -
- -
- Close + +
 Warning 
+
+ +
+ Number of users who's ready to be create : $nbusrToadd"; + /* ------------- ON ALLEGE LE TABLEAU ---------------- */ + for ($i = 1; $i < sizeof($ARRAY); $i ++ ) + for ($j = 0; $j < sizeof($ARRAY[0]); $j ++ ) + if ((isset($ARRAY[$i][$j]) && trim($ARRAY[$i][$j]) == "") || ( ! isset($equivalenceToMysqlField[$ARRAY[0][$j]]))) + unset($ARRAY[$i][$j]); + /* -------------------------------------------------- */ + ?> +
+ + + + 0 && count($models) > 0) { + echo "
Select a model to apply on users :"; + echo " "; + ?> +

Cancel      Add users + +
+ you need define a model before importing a list of users. +
+
+ Close +
+ +
+ Close - - - -
- Upload a "csv" file CSV for users creation + + + +
+ Upload a "csv" file CSV for users creation -
- you can download an example by clicking here
and his documentation here
-

-
- - User's file : -
-
-
-
- Send this file +
+ you can download an example by clicking here
and his documentation here
+

+ + + User's file : +
+
+
+
+ Send this file -
- +
+ diff --git a/www/admin/import0.php b/www/admin/import0.php index 92a2ca9434..b4e977c858 100644 --- a/www/admin/import0.php +++ b/www/admin/import0.php @@ -1,5 +1,4 @@ get_session(); phrasea::headers(); ?> - - - - - - - - + + + + + diff --git a/www/admin/newcoll.php b/www/admin/newcoll.php index f407c12326..786ff88fe1 100644 --- a/www/admin/newcoll.php +++ b/www/admin/newcoll.php @@ -1,5 +1,4 @@ get_session(); $request = http_request::getInstance(); -$parm = $request->get_parms("act", - "p0", // base_id - "cnm", // si act=NEWCOLL, nom de la collection a creer - "othcollsel", - "ccusrothercoll" +$parm = $request->get_parms("act", "p0", // base_id + "cnm", // si act=NEWCOLL, nom de la collection a creer + "othcollsel", "ccusrothercoll" ); $usr_id = $session->get_usr_id(); @@ -40,141 +37,129 @@ $sbasid = null; $error = false; if (trim($parm["cnm"]) == '' && $parm["act"] == "NEWCOLL") - $error = _('admin:: La collection n\'a pas ete creee : vous devez donner un nom a votre collection'); + $error = _('admin:: La collection n\'a pas ete creee : vous devez donner un nom a votre collection'); $new_collection = null; -if ($parm["act"] == "NEWCOLL" && !$error) -{ +if ($parm["act"] == "NEWCOLL" && ! $error) { - try - { - $databox = $appbox->get_databox((int) $parm['p0']); - $new_collection = collection::create($databox, $appbox, $parm['cnm'], $user); - if ($new_collection && $parm["ccusrothercoll"] == "on" && $parm["othcollsel"] != null) - { - $query = new User_Query($appbox); - $total = $query->on_base_ids(array($parm["othcollsel"]))->get_total(); - $n = 0; - while($n < $total) - { - $results = $query->limit($n, 20)->execute()->get_results(); - foreach($results as $user) - { - $user->ACL()->duplicate_right_from_bas($parm["othcollsel"], $new_collection->get_base_id()); + try { + $databox = $appbox->get_databox((int) $parm['p0']); + $new_collection = collection::create($databox, $appbox, $parm['cnm'], $user); + if ($new_collection && $parm["ccusrothercoll"] == "on" && $parm["othcollsel"] != null) { + $query = new User_Query($appbox); + $total = $query->on_base_ids(array($parm["othcollsel"]))->get_total(); + $n = 0; + while ($n < $total) { + $results = $query->limit($n, 20)->execute()->get_results(); + foreach ($results as $user) { + $user->ACL()->duplicate_right_from_bas($parm["othcollsel"], $new_collection->get_base_id()); + } + $n+=20; + } } - $n+=20; - } + } catch (Exception $e) { + $new_collection = null; } - } - catch (Exception $e) - { - $new_collection = null; - } } ?> - + - - - - - " . _('admin::base:collection: Creer une collection') . ""; - - if ($parm["act"] == "NEWCOLL") - { - $out .= $msg; - } - else - { - $out .= "
"; - $out .= "
"; - $out .= "
"; - } - - if ($error) - $out .= "
" . $error . "
"; - - $out .= " \n"; - $out .= " \n"; - $out .= " \n"; - $out .= "
\n"; - $out .= " " . _('admin::base:collection: Nom de la nouvelle collection : ') . "

\n"; - $out .= "
"; - - $user = User_Adapter::getInstance($usr_id, $appbox); - - $colls = $user->ACL()->get_granted_base(array('canadmin')); - if (count($colls) > 0) - { - $out .= ""; - $out .= ""; - $out .= "" . _('admin::base:collection: Vous pouvez choisir une collection de reference pour donenr des acces ') . " : "; - $out .= ""; - $out .= ""; - } - $out .= "
"; - $out .= "
"; - - $out .= " " . _('boutton::valider') . "\n"; - $out .= " "; - $out .= " " . _('boutton::annuler') . "\n"; - $out .= "
\n"; - $out .= "\n"; - - print($out); - ?> - + + " . _('admin::base:collection: Creer une collection') . ""; + +if ($parm["act"] == "NEWCOLL") { + $out .= $msg; +} else { + $out .= "
"; + $out .= "
"; + $out .= "
"; +} + +if ($error) + $out .= "
" . $error . "
"; + +$out .= " \n"; +$out .= " \n"; +$out .= " \n"; +$out .= "
\n"; +$out .= " " . _('admin::base:collection: Nom de la nouvelle collection : ') . "

\n"; +$out .= "
"; + +$user = User_Adapter::getInstance($usr_id, $appbox); + +$colls = $user->ACL()->get_granted_base(array('canadmin')); +if (count($colls) > 0) { + $out .= ""; + $out .= ""; + $out .= "" . _('admin::base:collection: Vous pouvez choisir une collection de reference pour donenr des acces ') . " : "; + $out .= ""; + $out .= ""; +} +$out .= "
"; +$out .= "
"; + +$out .= " " . _('boutton::valider') . "\n"; +$out .= " "; +$out .= " " . _('boutton::annuler') . "\n"; +$out .= "
\n"; +$out .= "\n"; + +print($out); ?> - - + + diff --git a/www/admin/router.php b/www/admin/router.php index 9e019e4b69..54328871fc 100644 --- a/www/admin/router.php +++ b/www/admin/router.php @@ -20,9 +20,8 @@ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $request = http_request::getInstance(); $parm = $request->get_parms('session'); -if ($parm["session"]) -{ - session_id($parm["session"]); +if ($parm["session"]) { + session_id($parm["session"]); } $app = require __DIR__ . "/../../lib/Alchemy/Phrasea/Application/Admin.php"; diff --git a/www/admin/runscheduler.php b/www/admin/runscheduler.php index 1b28680e4b..6c79c374be 100644 --- a/www/admin/runscheduler.php +++ b/www/admin/runscheduler.php @@ -26,16 +26,14 @@ $parm = $request->get_parms('key'); $scheduler_key = phrasea::scheduler_key(); $good_user = false; -if ($session->is_authenticated()) -{ - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - if ($user->ACL()->has_right('taskmanager')) - $good_user = true; +if ($session->is_authenticated()) { + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); + if ($user->ACL()->has_right('taskmanager')) + $good_user = true; } -if (!$good_user && (trim($scheduler_key) == '' || $scheduler_key !== $parm['key'])) -{ - phrasea::headers(403); +if ( ! $good_user && (trim($scheduler_key) == '' || $scheduler_key !== $parm['key'])) { + phrasea::headers(403); } set_time_limit(0); @@ -44,30 +42,28 @@ ignore_user_abort(true); $system = system_server::get_platform(); -if ($system != "DARWIN" && $system != "WINDOWS" && $system != "LINUX") -{ - phrasea::headers(500); +if ($system != "DARWIN" && $system != "WINDOWS" && $system != "LINUX") { + phrasea::headers(500); } $logdir = p4string::addEndSlash($registry->get('GV_RootPath') . 'logs'); $phpcli = $registry->get('GV_cli'); $nullfile = ''; -switch ($system) -{ - case "DARWIN": - $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; - $nullfile = '/dev/null'; - break; - case "LINUX": - $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; - $nullfile = '/dev/null'; - break; - case "WINDOWS": - case "WINDOWS NT": - $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; - $nullfile = 'NUL'; - break; +switch ($system) { + case "DARWIN": + $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; + $nullfile = '/dev/null'; + break; + case "LINUX": + $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; + $nullfile = '/dev/null'; + break; + case "WINDOWS": + case "WINDOWS NT": + $cmd = $phpcli . ' -f ' . $registry->get('GV_RootPath') . "bin/console scheduler:start"; + $nullfile = 'NUL'; + break; } @@ -78,8 +74,8 @@ switch ($system) //} //else //{ - $descriptors[1] = array("file", $nullfile, "a+"); - $descriptors[2] = array("file", $nullfile, "a+"); +$descriptors[1] = array("file", $nullfile, "a+"); +$descriptors[2] = array("file", $nullfile, "a+"); //} $pipes = null; @@ -87,28 +83,24 @@ $cwd = $registry->get('GV_RootPath') . "bin/"; $proc = proc_open($cmd, $descriptors, $pipes, $cwd, null, array('bypass_shell' => true)); $pid = NULL; -if (is_resource($proc)) -{ - $proc_status = proc_get_status($proc); - if ($proc_status['running']) - $pid = $proc_status['pid']; +if (is_resource($proc)) { + $proc_status = proc_get_status($proc); + if ($proc_status['running']) + $pid = $proc_status['pid']; } -if ($pid !== NULL) -{ - $msg = sprintf("scheduler '%s' started (pid=%s)", $cmd, $pid); - my_syslog(LOG_INFO, $msg); -} -else -{ - @fclose($pipes[1]); - @fclose($pipes[2]); - @proc_close($process); +if ($pid !== NULL) { + $msg = sprintf("scheduler '%s' started (pid=%s)", $cmd, $pid); + my_syslog(LOG_INFO, $msg); +} else { + @fclose($pipes[1]); + @fclose($pipes[2]); + @proc_close($process); - $msg = sprintf("scheduler '%s' failed to start", $cmd); - my_syslog(LOG_INFO, $msg); + $msg = sprintf("scheduler '%s' failed to start", $cmd); + my_syslog(LOG_INFO, $msg); } function my_syslog($level, $msg) { - print($msg . "\n"); + print($msg . "\n"); } diff --git a/www/admin/sessionwhois.php b/www/admin/sessionwhois.php index bcd4625e8d..8b39f17b44 100644 --- a/www/admin/sessionwhois.php +++ b/www/admin/sessionwhois.php @@ -1,5 +1,4 @@ get_session(); ?>
-
-
+
-
$n = 0; -foreach (Session_Handler::get_active_sessions() as $row) -{ - $onedetail = ""; - $onedetail.="
"; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= "
"; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= "' . ($row["date_modif"]) . '' . ($row["date_modif"]) . '' . phrasea::bas_names($row['base_id']) . '' . phrasea::bas_names($row['base_id']) . '
"; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; +foreach (Session_Handler::get_active_sessions() as $row) { + $onedetail = ""; + $onedetail.="
"; - $onedetail.=" "; - $onedetail.="
usr_id : " . $row['usr_id']->get_id() . "
"; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + } + $onedetail.="
"; + $onedetail.=" "; + $onedetail.="
usr_id : " . $row['usr_id']->get_id() . "
"; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.="
" . _('admin::compte-utilisateur nom') . ' : ' . $row['usr_id']->get_display_name() . "
" . _('admin::compte-utilisateur societe') . ' : ' . $row['usr_id']->get_company() . "
" . _('admin::compte-utilisateur telephone') . ' : ' . $row['usr_id']->get_tel() . "
" . _('admin::compte-utilisateur email') . ' : ' . $row['usr_id']->get_email() . "
"; - $onedetail.="
"; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - $onedetail.=" "; - - foreach ($row['usr_id']->ACL()->get_granted_sbas() as $databox) - { - $onedetail.=" "; - $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; - $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.="
" . _('admin::monitor: bases sur lesquelles l\'utilisateur est connecte : ') . "
" . $databox->get_viewname() . "
"; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; $onedetail.=" "; - } - $onedetail.="
" . _('admin::compte-utilisateur nom') . ' : ' . $row['usr_id']->get_display_name() . "
"; - $onedetail.="
" . _('admin::compte-utilisateur societe') . ' : ' . $row['usr_id']->get_company() . "
" . _('admin::compte-utilisateur telephone') . ' : ' . $row['usr_id']->get_tel() . "
" . _('admin::compte-utilisateur email') . ' : ' . $row['usr_id']->get_email() . "
"; + $onedetail.="
" . - $row['platform'] . ' / ' . $row['browser'] . ' - ' . $row['browser_version'] . '
' . ($row['token'] ? _('Session persistente') : '') . - "
"; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; + $onedetail.=" "; - $onedetail.="
" . _('admin::monitor: bases sur lesquelles l\'utilisateur est connecte : ') . "
"; - $onedetail.=""; + foreach ($row['usr_id']->ACL()->get_granted_sbas() as $databox) { + $onedetail.="
" . $databox->get_viewname() . "
"; + $onedetail.="
" . + $row['platform'] . ' / ' . $row['browser'] . ' - ' . $row['browser_version'] . '
' . ($row['token'] ? _('Session persistente') : '') . + "
"; + $onedetail.=""; - $out.=""; + $out.=""; - if ($row["session_id"] == $session->get_ses_id()) - $out.=sprintf("" . $row['usr_id']->get_display_name() . "\n"); - else - $out.=sprintf("" . $row['usr_id']->get_display_name() . "\n"); + if ($row["session_id"] == $session->get_ses_id()) + $out.=sprintf("" . $row['usr_id']->get_display_name() . "\n"); + else + $out.=sprintf("" . $row['usr_id']->get_display_name() . "\n"); - $appRef = array( - '0' => _('admin::monitor: module inconnu') - , '1' => _('admin::monitor: module production') - , '2' => _('admin::monitor: module client') - , '3' => _('admin::monitor: module admin') - , '4' => _('admin::monitor: module report') - , '5' => _('admin::monitor: module thesaurus') - , '6' => _('admin::monitor: module comparateur') - , '7' => _('admin::monitor: module validation') - , '8' => _('admin::monitor: module upload') - ); + $appRef = array( + '0' => _('admin::monitor: module inconnu') + , '1' => _('admin::monitor: module production') + , '2' => _('admin::monitor: module client') + , '3' => _('admin::monitor: module admin') + , '4' => _('admin::monitor: module report') + , '5' => _('admin::monitor: module thesaurus') + , '6' => _('admin::monitor: module comparateur') + , '7' => _('admin::monitor: module validation') + , '8' => _('admin::monitor: module upload') + ); - $row["app"] = unserialize($row["app"]); + $row["app"] = unserialize($row["app"]); - $out.= ""; - foreach ($row["app"] as $app) - { - if (isset($appLaunched[$app])) - $appLaunched[$app]++; - if ($app == '0') - continue; - $out .= ( isset($appRef[$app]) ? $appRef[$app] : $appRef[0]) . '
'; - } - $out .= "\n"; + $out.= ""; + foreach ($row["app"] as $app) { + if (isset($appLaunched[$app])) + $appLaunched[$app] ++; + if ($app == '0') + continue; + $out .= ( isset($appRef[$app]) ? $appRef[$app] : $appRef[0]) . '
'; + } + $out .= "\n"; - $out.=sprintf("" . $row["ip"] . '
' . $row["ip_infos"] . "\n"); - $out.=sprintf("" . phraseadate::getDate($row['created_on']) . "\n"); - $out.=sprintf("" . phraseadate::getPrettyString($row['lastaccess']) . "\n"); + $out.=sprintf("" . $row["ip"] . '
' . $row["ip_infos"] . "\n"); + $out.=sprintf("" . phraseadate::getDate($row['created_on']) . "\n"); + $out.=sprintf("" . phraseadate::getPrettyString($row['lastaccess']) . "\n"); - $out.="\n"; - $n++; + $out.="\n"; + $n ++; } $out.="\n"; @@ -233,17 +229,16 @@ echo ""; echo " "; echo ""; -if ($appLaunched[0] > 0) -{ +if ($appLaunched[0] > 0) { - echo ""; - echo ""; - echo ""; + echo ""; + echo ""; + echo ""; - echo ""; - echo "" . _('admin::monitor: total des utilisateurs uniques : '); - echo " " . $appLaunched[0] . ""; - echo ""; + echo ""; + echo "" . _('admin::monitor: total des utilisateurs uniques : '); + echo " " . $appLaunched[0] . ""; + echo ""; } diff --git a/www/admin/showlogtask.php b/www/admin/showlogtask.php index dc6f69bd0f..4c94256d91 100644 --- a/www/admin/showlogtask.php +++ b/www/admin/showlogtask.php @@ -23,72 +23,65 @@ $request = http_request::getInstance(); $parm = $request->get_parms('fil', 'log', 'id', 'act'); ?> - - - - -

- logfile : - 'log', 'o' => 'stdout', 'e' => 'stderr') as $k => $v) -{ - $cls = ''; - if($k == $parm['log']) - $cls = 'current'; - printf("(%s)\n" - , $cls - , urlencode($parm['fil']) - , urlencode($k) - , urlencode($parm['id']) - , $v); -} -?> -

- get_registry(); - $logdir = p4string::addEndSlash($registry->get('GV_RootPath') . 'logs'); - $logfile = $logdir . $parm['fil']; - if($parm['log']) - $logfile .= '_' . $parm['log']; - if($parm['id']) - $logfile .= '_' . $parm['id']; - $logfile .= '.log'; + + + + +

+ logfile : + 'log', 'o' => 'stdout', 'e' => 'stderr') as $k => $v) { + $cls = ''; + if ($k == $parm['log']) + $cls = 'current'; + printf("(%s)\n" + , $cls + , urlencode($parm['fil']) + , urlencode($k) + , urlencode($parm['id']) + , $v); + } + ?> +

+ get_registry(); + $logdir = p4string::addEndSlash($registry->get('GV_RootPath') . 'logs'); + $logfile = $logdir . $parm['fil']; + if ($parm['log']) + $logfile .= '_' . $parm['log']; + if ($parm['id']) + $logfile .= '_' . $parm['id']; + $logfile .= '.log'; - if(file_exists($logfile)) - { - if($parm['act'] == 'CLR') - { - file_put_contents($logfile, ''); + if (file_exists($logfile)) { + if ($parm['act'] == 'CLR') { + file_put_contents($logfile, ''); - return phrasea::redirect(sprintf("/admin/showlogtask.php?fil=%s&log=%s&id=%s" - , urlencode($parm['fil']) - , urlencode($parm['log']) - , urlencode($parm['id'])) - ); + return phrasea::redirect(sprintf("/admin/showlogtask.php?fil=%s&log=%s&id=%s" + , urlencode($parm['fil']) + , urlencode($parm['log']) + , urlencode($parm['id'])) + ); + } else { + printf("

%s\n", $logfile); + printf(" effacer\n" + , urlencode($parm['fil']) + , urlencode($parm['log']) + , urlencode($parm['id'])); + print("

\n
\n");
+                print(htmlentities(file_get_contents($logfile)));
+                print("
\n"); + } + } else { + printf("

file %s does not exists

\n", $logfile); } - else - { - printf("

%s\n", $logfile); - printf(" effacer\n" - , urlencode($parm['fil']) - , urlencode($parm['log']) - , urlencode($parm['id'])); - print("

\n
\n");
-          print(htmlentities(file_get_contents($logfile)));
-          print("
\n"); - } - } - else - { - printf("

file %s does not exists

\n", $logfile); - } - ?> - + ?> + diff --git a/www/admin/sitestruct.php b/www/admin/sitestruct.php index e2e5f53ed0..b9c2321a68 100644 --- a/www/admin/sitestruct.php +++ b/www/admin/sitestruct.php @@ -1,5 +1,4 @@ get_parms("act", "p0", "p1", 'flush_cache', 'sudo', 'admins', 'email'); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if (!$user->is_admin()) -{ - phrasea::headers(403); +if ( ! $user->is_admin()) { + phrasea::headers(403); } $cache_flushed = false; -if ($parm['flush_cache']) -{ - $Core = \bootstrap::getCore(); - $Core['CacheService']->flushAll(); - $cache_flushed = true; +if ($parm['flush_cache']) { + $Core = \bootstrap::getCore(); + $Core['CacheService']->flushAll(); + $cache_flushed = true; } ?> - - - - - + h1{ + position:relative; + float:left; + width:100%; + } + ul.setup { + position:relative; + float:left; + width:360px; + list-style-type:none; + padding:0 0 0 0px; + margin:5px 0 5px 40px; + border:1px solid #404040; + } + ul.setup table{ + width:100%; + table-layout: fixed; + } + .setup li{ + margin:0px 0; + padding:2px 5px 2px 30px; + background-image:url(/skins/icons/ok.png); + background-repeat:no-repeat; + background-position:5px center; + } + .setup li.non-blocker{ + background-image:url(/skins/icons/alert.png); + } + .setup li.blocker{ + background-image:url(/skins/icons/delete.png); + } + tr.even{ + background-color:#CCCCCC; + } + #flush_button { + width:360px; + margin: 5px 0 5px 40px; + } + - - - - - " ) + .data( "item.autocomplete", item ) + .append( "" + item.name + login + email + "" ) + .appendTo( ul ); + }; + }); + + + +get_usr_id(), $admins)) + if ( ! in_array($session->get_usr_id(), $admins)) $admins[] = $session->get_usr_id(); - if ($admins > 0) - { + if ($admins > 0) { User_Adapter::set_sys_admins($admins); User_Adapter::reset_sys_admins_rights(); - } } +} - if ($cache_flushed) - { +if ($cache_flushed) { ?> -
- -
- -
-

-
- $usr_login) - { -?> -
- -
- - - - -
-

- -
- - -
-
-

-
-

-
-
- ' . $php_constraint->get_name() . ''; - echo '
    '; - ?> -
  • - get_message(); ?> -
  • - '; - } - - $php_constraints = setup::check_writability($registry); - - echo '

    ' . _('setup::Filesystem configuration') . '

    '; - echo '
      '; - foreach($php_constraints as $constraint) - { - ?> -
    • - get_message(); ?> -
    • - '; - - - $php_constraints = setup::check_binaries($registry); - echo '

      ' . _('setup::Executables') . '

      '; - echo '
        '; - foreach($php_constraints as $constraint) - { - ?> -
      • - get_message(); ?> -
      • - '; - - - $php_constraints = setup::check_php_extension(); - echo '

        ' . _('setup::PHP extensions') . '

        '; - echo '
          '; - foreach($php_constraints as $constraint) - { - ?> -
        • - get_message(); ?> -
        • - '; - - $php_constraints = setup::check_cache_server(); - echo '

          ' . _('setup::Serveur de cache') . '

          '; - echo '
            '; - foreach($php_constraints as $constraint) - { - ?> -
          • - get_message(); ?> -
          • - '; - - - ?> -
-
- ' . _('Phrasea Module') . ''; - echo '
    '; - foreach($php_constraints as $constraint) - { - ?> -
  • - get_message(); ?> -
  • +
    + +
    '; - - setup::check_apache(); - setup::check_mod_auth_token(); - setup::check_cache_opcode(); - setup::check_cache_memcache(); - - if ($Core->getCache()->isServer()) - { + } ?> -
    - - -
    - +

    +
    + $usr_login) { + ?> +
    + - -
-
- +
+ + + + + +

+ +
+ + +
+
+

+
+

+
+
+' . $php_constraint->get_name() . ''; + echo '
    '; + ?> +
  • + get_message(); ?> +
  • + '; + } + + $php_constraints = setup::check_writability($registry); + + echo '

    ' . _('setup::Filesystem configuration') . '

    '; + echo '
      '; + foreach ($php_constraints as $constraint) { + ?> +
    • + get_message(); ?> +
    • + '; + + + $php_constraints = setup::check_binaries($registry); + echo '

      ' . _('setup::Executables') . '

      '; + echo '
        '; + foreach ($php_constraints as $constraint) { + ?> +
      • + get_message(); ?> +
      • + '; + + + $php_constraints = setup::check_php_extension(); + echo '

        ' . _('setup::PHP extensions') . '

        '; + echo '
          '; + foreach ($php_constraints as $constraint) { + ?> +
        • + get_message(); ?> +
        • + '; + + $php_constraints = setup::check_cache_server(); + echo '

          ' . _('setup::Serveur de cache') . '

          '; + echo '
            '; + foreach ($php_constraints as $constraint) { + ?> +
          • + get_message(); ?> +
          • + '; + ?> +
+
+ ' . _('Phrasea Module') . ''; + echo '
    '; + foreach ($php_constraints as $constraint) { + ?> +
  • + get_message(); ?> +
  • + '; + + setup::check_apache(); + setup::check_mod_auth_token(); + setup::check_cache_opcode(); + setup::check_cache_memcache(); + + if ($Core->getCache()->isServer()) { + ?> +
    + + +
    + + +
+
+ diff --git a/www/admin/sphinxconf.php b/www/admin/sphinxconf.php index d05c67db9d..4616df8740 100644 --- a/www/admin/sphinxconf.php +++ b/www/admin/sphinxconf.php @@ -1,5 +1,4 @@ get_parms('charset_tables', 'libstemmer'); -if (is_array($parms['charset_tables'])) -{ - $registry->set('sphinx_charset_tables', $parms['charset_tables'], registry::TYPE_ARRAY); +if (is_array($parms['charset_tables'])) { + $registry->set('sphinx_charset_tables', $parms['charset_tables'], registry::TYPE_ARRAY); } -if (is_array($parms['libstemmer'])) -{ - $registry->set('sphinx_user_stemmer', $parms['libstemmer'], registry::TYPE_ARRAY); +if (is_array($parms['libstemmer'])) { + $registry->set('sphinx_user_stemmer', $parms['libstemmer'], registry::TYPE_ARRAY); } $sphinx_conf = new sphinx_configuration(); @@ -35,31 +32,29 @@ $selected_charsets = $registry->get('sphinx_charset_tables'); $selected_libstemmer = $registry->get('sphinx_user_stemmer'); $options = array( - 'charset_tables' => (!is_array($selected_charsets) ? array() : $selected_charsets) - , 'libstemmer' => (!is_array($selected_libstemmer) ? array() : $selected_libstemmer) + 'charset_tables' => ( ! is_array($selected_charsets) ? array() : $selected_charsets) + , 'libstemmer' => ( ! is_array($selected_libstemmer) ? array() : $selected_libstemmer) ); ?>
- get_available_charsets() as $charset => $charset_obj) -{ - echo ""; +foreach ($sphinx_conf->get_available_charsets() as $charset => $charset_obj) { + echo ""; } ?> - - + + - +
diff --git a/www/admin/statbits.php b/www/admin/statbits.php index 2337b1f978..6c54e76a5e 100644 --- a/www/admin/statbits.php +++ b/www/admin/statbits.php @@ -1,5 +1,4 @@ get_session(); $request = http_request::getInstance(); -$parm = $request->get_parms("srt", "ord", - "act", - "p0", // base_id - "bit", - "nam", // name - "searchable", // name - "printable", // name - "dic0", // ccoch delete icon 0 - "dic1", // ccoch delete icon 1 - "labelon", // ccoch delete icon 1 - "labeloff" // ccoch delete icon 1 +$parm = $request->get_parms("srt", "ord", "act", "p0", // base_id + "bit", "nam", // name + "searchable", // name + "printable", // name + "dic0", // ccoch delete icon 0 + "dic1", // ccoch delete icon 1 + "labelon", // ccoch delete icon 1 + "labeloff" // ccoch delete icon 1 ); if (is_null($parm['p0'])) - phrasea::headers(400); + phrasea::headers(400); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if (!$user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) -{ - phrasea::headers(403); +if ( ! $user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) { + phrasea::headers(403); } -$sbas_id = (int)$parm['p0']; +$sbas_id = (int) $parm['p0']; $databox = databox::get_instance($sbas_id); phrasea::headers(); ?> - - - - - - - - $searchable, - 'printable' => $printable, - 'name' => $parm["nam"], - 'labelon' => $parm["labelon"], - 'labeloff' => $parm["labeloff"] - ); - - databox_status::updateStatus($parm['p0'], $parm["bit"], $properties); - - if ($parm["dic0"]) - { - databox_status::deleteIcon($parm['p0'], $parm['bit'], 'off'); - } - if (isset($_FILES['ic0']) && $_FILES['ic0']['name']) - { - try - { - databox_status::updateIcon($parm['p0'], $parm['bit'], 'off', $_FILES['ic0']); - } - catch(Exception_Forbidden $e) - { - $errors[] = _('You do not enough rights to update status'); - } - catch(Exception_InvalidArgument $e) - { - $errors[] = _('Something wrong happend'); - } - catch(Exception_Upload_FileTooBig $e) - { - $errors[] = _('File is too big : 64k max'); - } - catch(Exception_Upload_Error $e) - { - $errors[] = _('Status icon upload failed : upload error'); - } - catch(Exception_Upload_CannotWriteFile $e) - { - $errors[] = _('Status icon upload failed : can not write on disk'); - } - catch(Exception $e) - { - $errors[] = _('An error occured'); - } - } - - - if ($parm["dic1"]) - { - databox_status::deleteIcon($parm['p0'], $parm['bit'], 'on'); - } - if (isset($_FILES['ic1']) && $_FILES['ic1']['name']) - { - try - { - databox_status::updateIcon($parm['p0'], $parm['bit'], 'on', $_FILES['ic1']); - } - catch(Exception_Forbidden $e) - { - $errors[] = _('You do not enough rights to update status'); - } - catch(Exception_InvalidArgument $e) - { - $errors[] = _('Something wrong happend'); - } - catch(Exception_Upload_FileTooBig $e) - { - $errors[] = _('File is too big : 64k max'); - } - catch(Exception_Upload_Error $e) - { - $errors[] = _('Status icon upload failed : upload error'); - } - catch(Exception_Upload_CannotWriteFile $e) - { - $errors[] = _('Status icon upload failed : can not write on disk'); - } - catch(Exception $e) - { - $errors[] = _('An error occured'); - } - } - } - - - - if ($parm["act"] == "ADD" || $parm["act"] == "EDIT") - { - $status = $databox->get_statusbits(); - - $status = isset($status[$parm['bit']]) ? $status[$parm['bit']] : array('name' => '', 'labelon' => '', 'labeloff' => '', 'img_on' => '', 'img_off' => '', 'searchable' => '0', 'printable' => '0') - ?> - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

" />

' : _('admin::status: aucun symlboler')); ?> ' : _('admin::status: aucun symlboler')); ?>
/>
/>
')" value=""/>
- - " /> - " /> -
- - + } + H4 + { + MARGIN-TOP: 0px; + FONT-WEIGHT: normal; + FONT-SIZE: 18px; + MARGIN-BOTTOM: 0px; + MARGIN-LEFT: 5px + } + img.editer, img.adder, img.deleter{ + cursor:pointer; + } + + + ".$error."

"; +if ($parm["act"] == "DELETE") { + databox_status::deleteStatus($parm['p0'], $parm["bit"]); } - $status = $databox->get_statusbits(); +if ($parm["act"] == "APPLY") { + $searchable = ($parm["searchable"] == 'on') ? '1' : '0'; + $printable = ($parm["printable"] == 'on') ? '1' : '0'; + + $properties = array('searchable' => $searchable, + 'printable' => $printable, + 'name' => $parm["nam"], + 'labelon' => $parm["labelon"], + 'labeloff' => $parm["labeloff"] + ); + + databox_status::updateStatus($parm['p0'], $parm["bit"], $properties); + + if ($parm["dic0"]) { + databox_status::deleteIcon($parm['p0'], $parm['bit'], 'off'); + } + if (isset($_FILES['ic0']) && $_FILES['ic0']['name']) { + try { + databox_status::updateIcon($parm['p0'], $parm['bit'], 'off', $_FILES['ic0']); + } catch (Exception_Forbidden $e) { + $errors[] = _('You do not enough rights to update status'); + } catch (Exception_InvalidArgument $e) { + $errors[] = _('Something wrong happend'); + } catch (Exception_Upload_FileTooBig $e) { + $errors[] = _('File is too big : 64k max'); + } catch (Exception_Upload_Error $e) { + $errors[] = _('Status icon upload failed : upload error'); + } catch (Exception_Upload_CannotWriteFile $e) { + $errors[] = _('Status icon upload failed : can not write on disk'); + } catch (Exception $e) { + $errors[] = _('An error occured'); + } + } + + + if ($parm["dic1"]) { + databox_status::deleteIcon($parm['p0'], $parm['bit'], 'on'); + } + if (isset($_FILES['ic1']) && $_FILES['ic1']['name']) { + try { + databox_status::updateIcon($parm['p0'], $parm['bit'], 'on', $_FILES['ic1']); + } catch (Exception_Forbidden $e) { + $errors[] = _('You do not enough rights to update status'); + } catch (Exception_InvalidArgument $e) { + $errors[] = _('Something wrong happend'); + } catch (Exception_Upload_FileTooBig $e) { + $errors[] = _('File is too big : 64k max'); + } catch (Exception_Upload_Error $e) { + $errors[] = _('Status icon upload failed : upload error'); + } catch (Exception_Upload_CannotWriteFile $e) { + $errors[] = _('Status icon upload failed : can not write on disk'); + } catch (Exception $e) { + $errors[] = _('An error occured'); + } + } +} + + + +if ($parm["act"] == "ADD" || $parm["act"] == "EDIT") { + $status = $databox->get_statusbits(); + + $status = isset($status[$parm['bit']]) ? $status[$parm['bit']] : array('name' => '', 'labelon' => '', 'labeloff' => '', 'img_on' => '', 'img_off' => '', 'searchable' => '0', 'printable' => '0') + ?> + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

" />

' : _('admin::status: aucun symlboler')); ?> ' : _('admin::status: aucun symlboler')); ?>
/>
/>
')" value=""/>
+ + " /> + " /> +
+ + + + " . $error . "

"; +} + +$status = $databox->get_statusbits(); ?> -

+

-
- " /> - - -
+
+ " /> + + +
- - - - - - - - - +
-
+ + + + + + + + - "> +for ($bit = 4; $bit < 64; $bit ++ ) { + ?> + "> - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + +
+
-
- - - - -
-
-
- - - - '))document.getElementById('deleter_').submit();"> -
-
-
- - - - -
-
- " : ""; ?> - - " : ""; ?> - - -
+
+ + + + +
+
+
+ + + + '))document.getElementById('deleter_').submit();"> +
+
+
+ + + + +
+ +
+ " : ""; ?> + + " : ""; ?> + + +
diff --git a/www/admin/structure.php b/www/admin/structure.php index 7c146353da..d2c54a416c 100644 --- a/www/admin/structure.php +++ b/www/admin/structure.php @@ -1,5 +1,4 @@ get_session(); $request = http_request::getInstance(); -$parm = $request->get_parms("srt", "ord", - "act", - "p0", // base_id - "str" // si act=CHGSTRUCTURE, structure en xml +$parm = $request->get_parms("srt", "ord", "act", "p0", // base_id + "str" // si act=CHGSTRUCTURE, structure en xml ); $parm['p0'] = (int) $parm['p0']; if ($parm['p0'] <= 0) - phrasea::headers(400); + phrasea::headers(400); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if (!$user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) -{ - phrasea::headers(403); +if ( ! $user->ACL()->has_right_on_sbas($parm['p0'], 'bas_modify_struct')) { + phrasea::headers(403); } phrasea::headers(); ?> - - - - - + + + + + - " . p4string::MakeString(_('admin::base: structure')) . "\n"; - if ($parm["act"] == "CHGSTRUCTURE") - { - $domst = new DOMDocument('1.0', 'UTF-8'); - $domst->preserveWhiteSpace = false; - $domst->formatOutput = true; +$out .= "

" . p4string::MakeString(_('admin::base: structure')) . "

\n"; +if ($parm["act"] == "CHGSTRUCTURE") { + $domst = new DOMDocument('1.0', 'UTF-8'); + $domst->preserveWhiteSpace = false; + $domst->formatOutput = true; - $errors = databox::get_structure_errors($parm["str"]); - if (count($errors) == 0 && $domst->loadXML($parm["str"])) // simplexml_load_string($parm["str"])) - { + $errors = databox::get_structure_errors($parm["str"]); + if (count($errors) == 0 && $domst->loadXML($parm["str"])) { // simplexml_load_string($parm["str"])) $databox = databox::get_instance((int) $parm['p0']); $databox->saveStructure($domst); - } - else - { - $msg .= p4string::MakeString(_('admin::base: xml invalide, les changements ne seront pas appliques')."\n".implode("\n", $errors), 'js') . ""; + } else { + $msg .= p4string::MakeString(_('admin::base: xml invalide, les changements ne seront pas appliques') . "\n" . implode("\n", $errors), 'js') . ""; $loadit = false; $out .= "
" . implode("
", $errors) . "
"; $out .= "
\n"; @@ -101,38 +93,35 @@ phrasea::headers(); $out .= "
\n"; $out .= "
\n"; $out .= "
" . p4string::MakeString(_('boutton::valider')) . "
\n"; - } - unset($domst); } - else - { - $databox = databox::get_instance((int) $parm["p0"]); - $parm["str"] = $databox->get_structure(); - } - if ($loadit) - { + unset($domst); +} else { + $databox = databox::get_instance((int) $parm["p0"]); + $parm["str"] = $databox->get_structure(); +} +if ($loadit) { - $errors = databox::get_structure_errors($parm["str"]); - $out .= "
" . implode("
", $errors) . "
"; - $out .= "\n"; - $out .= " \n"; - $out .= " \n"; - $out .= " \n"; - $out .= "
\n"; - $out .= "
\n"; - $out .= "
\n"; - $out .= "
\n"; - $out .= "
" . p4string::MakeString(_('boutton::valider')) . "
\n"; - } + $errors = databox::get_structure_errors($parm["str"]); + $out .= "
" . implode("
", $errors) . "
"; + $out .= "
\n"; + $out .= " \n"; + $out .= " \n"; + $out .= " \n"; + $out .= "
\n"; + $out .= "
\n"; + $out .= "
\n"; + $out .= "
\n"; + $out .= "
" . p4string::MakeString(_('boutton::valider')) . "
\n"; +} - print($out); - ?> - - + + diff --git a/www/admin/sugval.php b/www/admin/sugval.php index e0c522cdb2..05befa66a7 100644 --- a/www/admin/sugval.php +++ b/www/admin/sugval.php @@ -20,11 +20,9 @@ $appbox = appbox::get_instance($Core); $session = $appbox->get_session(); $request = http_request::getInstance(); -$parm = $request->get_parms("srt", "ord", - "act", - "p0", // base_id - "p1", // coll_id - "str" // si act=CHGSTRUCTURE, structure en xml +$parm = $request->get_parms("srt", "ord", "act", "p0", // base_id + "p1", // coll_id + "str" // si act=CHGSTRUCTURE, structure en xml ); phrasea::headers(); @@ -37,295 +35,293 @@ $coll_id = phrasea::collFromBas($parm['p1']); $databox = databox::get_instance($sbas_id); $collection = collection::get_from_coll_id($databox, $coll_id); -if ($parm["act"] == "CHGSUGVAL") -{ - if ($mdesc = DOMDocument::loadXML($parm["str"])) - { - $collection->set_prefs($mdesc); - } +if ($parm["act"] == "CHGSUGVAL") { + if ($mdesc = DOMDocument::loadXML($parm["str"])) { + $collection->set_prefs($mdesc); + } } $curPrefs = $collection->get_prefs(); ?> - - + + - + - - + - + -
- - - - - - - - -
-

-


+
+ + + + + + + + +
+

+


- + -
 
+
 
- +
- - - - - - - - - - - - - - - - - + - - + - - - - -
- - - " . $collname . "" ?> - - -
- - -
- -
- - - - - - - + - - - - - - - -
- - -
-
- -   - -   - -   - +
- - - + + +" . $collname . "" ?>
- - - - - -
+
+
-
- -
+
+ + + - - -
-
- - " /> - " /> - -
+ - + + + +
+ + + + + + + + + + + + + + + +
+ + +
+
+ +   + +   + +   + + +
+ + + +
+ + + + + +
+
+
+ + + + + + + + + + + + + + + + +
+ + " /> + " /> + +
+ + diff --git a/www/admin/task2.js.php b/www/admin/task2.js.php index 822db2ea28..ab9407860d 100644 --- a/www/admin/task2.js.php +++ b/www/admin/task2.js.php @@ -1,5 +1,4 @@ "; - parms += "&name=" + encodeURIComponent(name); +url = "/admin/adminFeedback.php?action=CHANGETASK"; +parms = "task_id="; +parms += "&name=" + encodeURIComponent(name); // alert(url+"?"+parms); - ret = loadXMLDoc(url, parms, true); +ret = loadXMLDoc(url, parms, true); } function chgActive(ck) { - url = "/admin/adminFeedback.php?action=CHANGETASK"; - parms = "task_id="; - parms += "&active=" + (ck ? "1":"0"); - // alert(url+"?"+parms); - if( (ret = loadXMLDoc(url, parms, true)) ) - { - crashed = ret.documentElement.getAttribute("crashed"); - document.getElementById("idCrashCount").innerHTML = crashed; - document.getElementById("idCrashLine").style.visibility = crashed > 0 ? "visible" : "hidden"; +url = "/admin/adminFeedback.php?action=CHANGETASK"; +parms = "task_id="; +parms += "&active=" + (ck ? "1":"0"); +// alert(url+"?"+parms); +if( (ret = loadXMLDoc(url, parms, true)) ) +{ +crashed = ret.documentElement.getAttribute("crashed"); +document.getElementById("idCrashCount").innerHTML = crashed; +document.getElementById("idCrashLine").style.visibility = crashed > 0 ? "visible" : "hidden"; // if(ret.documentElement.getAttribute("saved") == "1") // return(true); - } +} } function saveXML() { - var xml = document.forms["fxml"].txtareaxml.value; - if(xml) - { - url = "/admin/adminFeedback.php?action=CHANGETASK"; - parms += "?task_id="; - parms += "&xml=" + encodeURIComponent(xml); - // alert(url+"?"+parms); - if( (ret = loadXMLDoc(url, parms, true)) ) - { - if(ret.documentElement.getAttribute("saved") == "1") +var xml = document.forms["fxml"].txtareaxml.value; +if(xml) +{ +url = "/admin/adminFeedback.php?action=CHANGETASK"; +parms += "?task_id="; +parms += "&xml=" + encodeURIComponent(xml); +// alert(url+"?"+parms); +if( (ret = loadXMLDoc(url, parms, true)) ) +{ +if(ret.documentElement.getAttribute("saved") == "1") - return(true); - } - } +return(true); +} +} - return(false); +return(false); } diff --git a/www/admin/task2.php b/www/admin/task2.php index 2cc2a8088f..0ce283f198 100644 --- a/www/admin/task2.php +++ b/www/admin/task2.php @@ -1,4 +1,5 @@ get_parms('act' // NEWTASK or SAVETASK - , "tid" - , 'tcl' // task class - , 'view' // XML ou GRAPHIC + , "tid" + , 'tcl' // task class + , 'view' // XML ou GRAPHIC ); $lng = Session_Handler::get_locale(); @@ -30,62 +31,52 @@ $task_manager = new task_manager($appbox); phrasea::headers(); -if (!$parm['view']) - $parm['view'] = 'GRAPHIC'; +if ( ! $parm['view']) + $parm['view'] = 'GRAPHIC'; $refreshfinder = false; $out = ""; -try -{ - switch ($parm['act']) - { - case 'NEWTASK': // blank task from scratch, NOT saved into sql - $task = task_abstract::create($appbox, $parm['tcl']); - break; - case 'EDITTASK': // existing task - $task = $task_manager->get_task($parm['tid']); - break; - default: - throw new Exception('Unknown action'); - break; - } -} -catch (Exception $e) -{ - phrasea::headers(404); +try { + switch ($parm['act']) { + case 'NEWTASK': // blank task from scratch, NOT saved into sql + $task = task_abstract::create($appbox, $parm['tcl']); + break; + case 'EDITTASK': // existing task + $task = $task_manager->get_task($parm['tid']); + break; + default: + throw new Exception('Unknown action'); + break; + } +} catch (Exception $e) { + phrasea::headers(404); } $zGraphicForm = 'graphicForm'; $hasGraphicMode = false; -if (method_exists($task, 'getGraphicForm')) -{ - $hasGraphicMode = true; - $zGraphicForm = $task->getGraphicForm(); -} -else -{ - $parm['view'] = 'XML'; +if (method_exists($task, 'getGraphicForm')) { + $hasGraphicMode = true; + $zGraphicForm = $task->getGraphicForm(); +} else { + $parm['view'] = 'XML'; } function stripdoublequotes($value) { - return str_replace(array("\r\n", "\r", "\n", "\""), array('', '', '', '\"'), $value); + return str_replace(array("\r\n", "\r", "\n", "\""), array('', '', '', '\"'), $value); } - -if (!$task->getGraphicForm()) -{ - $parm['view'] = 'XML'; +if ( ! $task->getGraphicForm()) { + $parm['view'] = 'XML'; } $core = \bootstrap::getCore(); $twig = $core->getTwig(); -if (!$task->getGraphicForm()) -{ - $parm['view'] = 'XML'; +if ( ! $task->getGraphicForm()) { + $parm['view'] = 'XML'; } echo $twig->render('admin/task.html', array('task' => $task, 'view' => $parm['view'])); diff --git a/www/admin/task2utils.php b/www/admin/task2utils.php index abcba7d51b..f081d2156a 100644 --- a/www/admin/task2utils.php +++ b/www/admin/task2utils.php @@ -21,161 +21,138 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - '__act' - , '__class' // task class - , '__tname' - , '__tactive' - , '__xml' - , '__tid' - , 'txtareaxml' + '__act' + , '__class' // task class + , '__tname' + , '__tactive' + , '__xml' + , '__tid' + , 'txtareaxml' ); phrasea::headers(); - ?> - - - + + get_task($parm['__tid']); + switch ($parm['__act']) { + case 'FORM2XML': + if (method_exists($ztask, 'printInterfaceHTML')) { + if ($ztask->getGraphicForm()) { + $xml = p4string::MakeString($ztask->graphic2xml($parm['__xml']), "js"); + } else { + $xml = p4string::MakeString($parm['__xml'], "js"); + } + ?> + -getGraphicForm()) - { - if (($msg = ($ztask->xml2graphic($parm['txtareaxml'], "parent.document.forms['graphicForm']"))) == "") - { -?> - - - -"; + d.getElementById('divGraph').style.display = "none"; + d.getElementById('divXml').style.display = ""; + d.getElementById('linkviewxml').className = "tabFront"; + d.getElementById('linkviewgraph').className = "tabBack"; + parent.jsTaskObj.currentView = "XML"; + + - -getGraphicForm()) { + if (($msg = ($ztask->xml2graphic($parm['txtareaxml'], "parent.document.forms['graphicForm']"))) == "") { + ?> + + + + + + + + - -graphic2xml($parm['__xml']); + case 'SAVE_GRAPHIC': + $parm['txtareaxml'] = $ztask->graphic2xml($parm['__xml']); - case 'SAVE_XML': - if ((simplexml_load_string($parm['txtareaxml']))) - { - if (method_exists($ztask, 'checkXML')) - { - if ($ztask->checkXML($parm['txtareaxml']) != '') - { - return; + case 'SAVE_XML': + if ((simplexml_load_string($parm['txtareaxml']))) { + if (method_exists($ztask, 'checkXML')) { + if ($ztask->checkXML($parm['txtareaxml']) != '') { + return; + } + } + $task_manager = new task_manager($appbox); + $tid = $parm['__tid']; + $task = $task_manager->get_task($tid); + + $task->set_active($parm['__tactive']); + $task->set_title($parm['__tname']); + $task->set_settings($parm['txtareaxml']); + ?> + + + + get_task($tid); - - $task->set_active($parm['__tactive']); - $task->set_title($parm['__tname']); - $task->set_settings($parm['txtareaxml']); - -?> - - - - - - - + ?> + + + diff --git a/www/admin/taskfacility.php b/www/admin/taskfacility.php index 457c00e246..819b1e3ea6 100644 --- a/www/admin/taskfacility.php +++ b/www/admin/taskfacility.php @@ -21,10 +21,6 @@ $request = http_request::getInstance(); $parm = $request->get_parms('cls', 'taskid'); $cls = 'task_period_' . $parm['cls']; -$registry = registry::get_instance(); -$tskfile = $registry->get('GV_RootPath') . 'lib/classes/task/period/' . $parm['cls'] . '.class.php'; - -// require_once $tskfile; $ztask = new $cls($parm['taskid']); diff --git a/www/admin/taskmanager.php b/www/admin/taskmanager.php index 26cbd5605a..d3ca1bb3be 100644 --- a/www/admin/taskmanager.php +++ b/www/admin/taskmanager.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -25,9 +24,8 @@ $parm = $request->get_parms("act", "tid"); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if(!$user->ACL()->has_right('taskmanager')) -{ - phrasea::headers(403); +if ( ! $user->ACL()->has_right('taskmanager')) { + phrasea::headers(403); } phrasea::headers(); @@ -36,723 +34,713 @@ $registry = $appbox->get_registry(); $task_manager = new task_manager($appbox); $refresh_tasklist = false; -if($parm["act"] == "DELETETASK") -{ - try - { - $task = $task_manager->get_task($parm['tid']); - $task->delete(); - $refresh_tasklist = true; - } - catch(Exception $e) - { +if ($parm["act"] == "DELETETASK") { + try { + $task = $task_manager->get_task($parm['tid']); + $task->delete(); + $refresh_tasklist = true; + } catch (Exception $e) { - } + } } - - - ?> - + - - - - - - - + + - - + }) + + + - + + +

+ +'); ?> + +

+ + + + + + + + + + + + + + + + + + + + + + + +get_tasks($refresh_tasklist) as $task) { + $n ++; + $tid = $task->get_task_id() ?> - + + + + + + + + + + + + + + + + + +
ID!
    TaskManager
  +
+
+
+
+
+
+
get_title()) ?> []
+ +
-

- - '); ?> - -

+
+ - - - - - - - - - - - - - - - - - - - - - - - get_tasks($refresh_tasklist) as $task) + + + - + - - - - - - - - - - - + + + + + + + + + + + - + diff --git a/www/api/index.php b/www/api/index.php index 7837e5cdd7..3cc5e42ee0 100644 --- a/www/api/index.php +++ b/www/api/index.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - require_once __DIR__ . '/../../lib/bootstrap.php'; $app = require __DIR__ . '/../../lib/Alchemy/Phrasea/Application/ApiVersion.php'; diff --git a/www/api/v1/index.php b/www/api/v1/index.php index d3f4b83645..67f12e49d5 100644 --- a/www/api/v1/index.php +++ b/www/api/v1/index.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - require_once __DIR__ . '/../../../lib/bootstrap.php'; $app = require __DIR__ . '/../../../lib/Alchemy/Phrasea/Application/Api.php'; diff --git a/www/client/answer.php b/www/client/answer.php index eeca59bb45..9001d23b54 100644 --- a/www/client/answer.php +++ b/www/client/answer.php @@ -17,77 +17,68 @@ /* @var $Core \Alchemy\Phrasea\Core */ require_once __DIR__ . "/../../lib/bootstrap.php"; -$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(); -$user = $Core->getAuthenticatedUser(); +$user = $Core->getAuthenticatedUser(); -if ( ! isset($parm)) -{ +if ( ! isset($parm)) { - $request = http_request::getInstance(); - $parm = $request->get_parms("mod", "bas" - , "pag" - , "qry", "search_type", "recordtype" - , "qryAdv", 'opAdv', 'status', 'datemin', 'datemax' - , 'dateminfield', 'datemaxfield' - , 'datefield' - , 'sort' - , 'stemme' - , 'infield' - , "nba" - , "regroup" // si rech par doc, regroup ,ou pizza - , "ord" - ); + $request = http_request::getInstance(); + $parm = $request->get_parms("mod", "bas" + , "pag" + , "qry", "search_type", "recordtype" + , "qryAdv", 'opAdv', 'status', 'datemin', 'datemax' + , 'dateminfield', 'datemaxfield' + , 'datefield' + , 'sort' + , 'stemme' + , 'infield' + , "nba" + , "regroup" // si rech par doc, regroup ,ou pizza + , "ord" + ); } -$qry = ''; +$qry = ''; -if (trim($parm['qry']) != '') -{ - $qry .= trim($parm['qry']); +if (trim($parm['qry']) != '') { + $qry .= trim($parm['qry']); } -if (count($parm['opAdv']) > 0 && count($parm['opAdv']) == count($parm['qryAdv'])) -{ - foreach ($parm['opAdv'] as $opId => $op) - { - if (trim($parm['qryAdv'][$opId]) != '') - { - if ($qry == trim($parm['qry'])) - $qry = '(' . trim($parm['qry']) . ')'; - $qry .= ' ' . $op . ' (' . trim($parm['qryAdv'][$opId]) . ')'; +if (count($parm['opAdv']) > 0 && count($parm['opAdv']) == count($parm['qryAdv'])) { + foreach ($parm['opAdv'] as $opId => $op) { + if (trim($parm['qryAdv'][$opId]) != '') { + if ($qry == trim($parm['qry'])) + $qry = '(' . trim($parm['qry']) . ')'; + $qry .= ' ' . $op . ' (' . trim($parm['qryAdv'][$opId]) . ')'; + } } - } } if ($qry == '') - $qry = 'all'; + $qry = 'all'; $parm['qry'] = $qry; $qrySbas = array(); -if (is_null($parm['bas'])) -{ - echo 'vous devez selectionner des collections dans lesquelles chercher'; +if (is_null($parm['bas'])) { + echo 'vous devez selectionner des collections dans lesquelles chercher'; - return; + return; } if ( ! $parm["mod"]) - $parm["mod"] = "3X6"; + $parm["mod"] = "3X6"; $mod = explode("X", $parm["mod"]); -if (count($mod) == 1) -{ - $mod_row = (int) ($mod[0]); - $mod_col = 1; +if (count($mod) == 1) { + $mod_row = (int) ($mod[0]); + $mod_col = 1; +} else { + $mod_row = (int) ($mod[0]); + $mod_col = (int) ($mod[1]); } -else -{ - $mod_row = (int) ($mod[0]); - $mod_col = (int) ($mod[1]); -} -$mod_xy = $mod_col * $mod_row; +$mod_xy = $mod_col * $mod_row; $tbases = array(); @@ -96,39 +87,33 @@ $options = new searchEngine_options(); $parm['bas'] = is_array($parm['bas']) ? $parm['bas'] : array_keys($user->ACL()->get_granted_base()); /* @var $user \User_Adapter */ -if ($user->ACL()->has_right('modifyrecord')) -{ - $options->set_business_fields(array()); +if ($user->ACL()->has_right('modifyrecord')) { + $options->set_business_fields(array()); - $BF = array(); + $BF = array(); - foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) - { - if (count($parm['bas']) === 0 || in_array($collection->get_base_id(), $parm['bas'])) - { - $BF[] = $collection->get_base_id(); + foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) { + if (count($parm['bas']) === 0 || in_array($collection->get_base_id(), $parm['bas'])) { + $BF[] = $collection->get_base_id(); + } } - } - $options->set_business_fields($BF); -} -else -{ - $options->set_business_fields(array()); + $options->set_business_fields($BF); +} else { + $options->set_business_fields(array()); } $options->set_bases($parm['bas'], $user->ACL()); if ( ! is_array($parm['infield'])) - $parm['infield'] = array(); + $parm['infield'] = array(); -foreach ($parm['infield'] as $offset => $value) -{ - if (trim($value) === '') - unset($parm['infield'][$offset]); +foreach ($parm['infield'] as $offset => $value) { + if (trim($value) === '') + unset($parm['infield'][$offset]); } $options->set_fields($parm['infield']); if ( ! is_array($parm['status'])) - $parm['status'] = array(); + $parm['status'] = array(); $options->set_status($parm['status']); $options->set_search_type($parm['search_type']); $options->set_record_type($parm['recordtype']); @@ -139,9 +124,9 @@ $options->set_sort($parm['sort'], $parm['ord']); $options->set_use_stemming($parm['stemme']); if ($parm['ord'] === NULL) - $parm['ord'] = PHRASEA_ORDER_DESC; + $parm['ord'] = PHRASEA_ORDER_DESC; else - $parm['ord'] = (int) $parm['ord']; + $parm['ord'] = (int) $parm['ord']; $form = serialize($options); @@ -151,11 +136,10 @@ $search_engine = new searchEngine_adapter($registry); $search_engine->set_options($options); -if ($parm['pag'] < 1) -{ - $search_engine->set_is_first_page(true); - $search_engine->reset_cache(); - $parm['pag'] = 1; +if ($parm['pag'] < 1) { + $search_engine->set_is_first_page(true); + $search_engine->reset_cache(); + $parm['pag'] = 1; } $result = $search_engine->query_per_page($parm['qry'], (int) $parm["pag"], $perPage); @@ -171,22 +155,20 @@ $page = $result->get_current_page(); $ACL = $user->ACL(); -if ($registry->get('GV_thesaurus')) -{ - ?> - - - $("#history").empty().append("' . str_replace('"', '\"', $history) . '")'; $nbanswers = $result->get_count_available_results(); -$longueur = strlen($parm['qry']); +$longueur = strlen($parm['qry']); $qrys = '
' . _('client::answers: rapport de questions par bases') . '
'; foreach ($qrySbas as $sbas => $qryBas) - $qrys .= '
' . phrasea::sbas_names($sbas) . '
' . $qryBas . '
'; + $qrys .= '
' . phrasea::sbas_names($sbas) . '
' . $qryBas . '
'; -$txt = "" . substr($parm['qry'], 0, 36) . ($longueur > 36 ? "..." : "") . "" . sprintf(_('client::answers: %d reponses'), (int) $nbanswers) . "  "; +$txt = "" . substr($parm['qry'], 0, 36) . ($longueur > 36 ? "..." : "") . "" . sprintf(_('client::answers: %d reponses'), (int) $nbanswers) . "  "; ?> get_total_pages(); -$pages = ''; -$ecart = 3; -$max = (2 * $ecart) + 3; +$pages = ''; +$ecart = 3; +$max = (2 * $ecart) + 3; -if ($npages > $max) -{ - for ($p = 1; $p <= $npages; $p ++ ) - { - if ($p == $page) - $pages .= '' . ($p) . ''; - elseif (( $p >= ($page - $ecart) ) && ( ($p - 1) <= ($page + $ecart) )) - $pages .= '' . ($p) . ''; - elseif (($page < ($ecart + 2)) && ($p < ($max - $ecart + 2) )) // si je suis dans les premieres pages ... - $pages .= '' . ($p) . ''; - elseif (($page >= ($npages - $ecart - 2)) && ($p >= ($npages - (2 * $ecart) - 2) )) // si je suis dans les dernieres pages ... - $pages .= '' . ($p) . ''; - elseif ($p == ($npages - 1)) // c"est la derniere - $pages .= '...' . ($p) . ''; - elseif ($p == 0) // c"est la premiere - $pages .= '' . ($p) . '...'; +if ($npages > $max) { + for ($p = 1; $p <= $npages; $p ++ ) { + if ($p == $page) + $pages .= '' . ($p) . ''; + elseif (( $p >= ($page - $ecart) ) && ( ($p - 1) <= ($page + $ecart) )) + $pages .= '' . ($p) . ''; + elseif (($page < ($ecart + 2)) && ($p < ($max - $ecart + 2) )) // si je suis dans les premieres pages ... + $pages .= '' . ($p) . ''; + elseif (($page >= ($npages - $ecart - 2)) && ($p >= ($npages - (2 * $ecart) - 2) )) // si je suis dans les dernieres pages ... + $pages .= '' . ($p) . ''; + elseif ($p == ($npages - 1)) // c"est la derniere + $pages .= '...' . ($p) . ''; + elseif ($p == 0) // c"est la premiere + $pages .= '' . ($p) . '...'; - if (($p == $page) - || ( ( $p >= ($page - $ecart) ) && ( $p <= ($page + $ecart) )) - || ( ($page < ($ecart + 2)) && ($p < ($max - $ecart + 2) ) ) - || ( ($page >= ($npages - $ecart - 2)) && ($p >= ($npages - (2 * $ecart) - 2) ) ) - || ( $p == 0) - ) - $pages .= ' - '; - } + if (($p == $page) + || ( ( $p >= ($page - $ecart) ) && ( $p <= ($page + $ecart) )) + || ( ($page < ($ecart + 2)) && ($p < ($max - $ecart + 2) ) ) + || ( ($page >= ($npages - $ecart - 2)) && ($p >= ($npages - (2 * $ecart) - 2) ) ) + || ( $p == 0) + ) + $pages .= ' - '; + } } -else -{ - for ($p = 1; $p <= $npages; $p ++ ) - { - if ($p == $page) - $pages .= '' . ($p) . ''; - else - $pages .= '' . ($p) . ''; - if ($p < $npages) - $pages .= ' - '; - } +else { + for ($p = 1; $p <= $npages; $p ++ ) { + if ($p == $page) + $pages .= '' . ($p) . ''; + else + $pages .= '' . ($p) . ''; + if ($p < $npages) + $pages .= ' - '; + } } $string2 = $pages . ''; ?> get_datas(); $i = 0; -if (count($result->get_datas()) > 0) -{ - ?>
ID!
    TaskManager
get_datas()) > 0) { + ?>
getTwig(); - foreach ($result->get_datas() as $record) - { - /* @var $record record_adapter */ - $base_id = $record->get_base_id(); - $sbas_id = $record->get_sbas_id(); + foreach ($result->get_datas() as $record) { + /* @var $record record_adapter */ + $base_id = $record->get_base_id(); + $sbas_id = $record->get_sbas_id(); - $thumbnail = $record->get_thumbnail(); + $thumbnail = $record->get_thumbnail(); - $docType = $record->get_type(); + $docType = $record->get_type(); - $title = $record->get_title(); + $title = $record->get_title(); - try - { - $record->get_subdef('document'); - $light_info = $twig->render('common/technical_datas.twig', array('record' => $record)); - } - catch (\Exception $e) - { - $light_info = ''; - } - $caption = $twig->render('common/caption.html', array('view' => 'answer', 'record' => $record)); + try { + $record->get_subdef('document'); + $light_info = $twig->render('common/technical_datas.twig', array('record' => $record)); + } catch (\Exception $e) { + $light_info = ''; + } + $caption = $twig->render('common/caption.html', array('view' => 'answer', 'record' => $record)); - if ($i == 0) - { - ?> - - + + + +


-
+
'; $status .= $record->get_status_icons(); @@ -378,133 +335,117 @@ if (count($result->get_datas()) > 0) echo $status; - $isVideo = ($docType == 'video'); - $isAudio = ($docType == 'audio'); - $isImage = ($docType == 'image'); + $isVideo = ($docType == 'video'); + $isAudio = ($docType == 'audio'); + $isImage = ($docType == 'image'); $isDocument = ($docType == 'document'); $sd = $record->get_subdefs(); - $isImage = false; + $isImage = false; $isDocument = false; - if ( ! $isVideo && ! $isAudio) - { - $isImage = true; + if ( ! $isVideo && ! $isAudio) { + $isImage = true; } - ?> - -
get_formated_duration(); - if ($duration != '') - echo '
' . $duration . '
'; - } - if ($isAudio) - { - $duration = $record->get_formated_duration(); - if ($duration != '') - echo '
' . $duration . '
'; - } - - $onclick = ""; - - if ($record->is_grouping()) - { - $onclick = 'openPreview(\'REG\',0,\'' . $sbas_id . '_' . $record->get_record_id() . '\');'; - } - else - { - $onclick = 'openPreview(\'RESULT\',' . $record->get_number() . ');'; - } - - if ($mod_col == '1') - $pic_roll = '/prod/tooltip/preview/' . $record->get_sbas_id() . '/' . $record->get_record_id() . '/'; - else - $pic_roll = '/prod/tooltip/caption/' . $record->get_sbas_id() . '/' . $record->get_record_id() . '/answer/'; - - $pic_roll = str_replace(array('&', '"'), array('&', '"'), $pic_roll); - ?> -
-
-
' . collection::getLogo($record->get_base_id()); - $minilogos .= '
'; - $sbas_id = $record->get_sbas_id(); - echo $minilogos; - - if ( - $ACL->has_right_on_base($record->get_base_id(), 'candwnldpreview') || - $ACL->has_right_on_base($record->get_base_id(), 'candwnldhd') || - $ACL->has_right_on_base($record->get_base_id(), 'cancmd') - ) - { - ?>
-
- has_right_on_base($record->get_base_id(), "canputinalbum")) - { - ?>
-
- get_preview()->is_physically_present()) - { - ?> -
 
- -
get_formated_duration(); + if ($duration != '') + echo '
' . $duration . '
'; + } + if ($isAudio) { + $duration = $record->get_formated_duration(); + if ($duration != '') + echo '
' . $duration . '
'; } - ?>
' . $light_info) ?>
- -
+
+
+
' . collection::getLogo($record->get_base_id()); + $minilogos .= '
'; + $sbas_id = $record->get_sbas_id(); + echo $minilogos; + + if ( + $ACL->has_right_on_base($record->get_base_id(), 'candwnldpreview') || + $ACL->has_right_on_base($record->get_base_id(), 'candwnldhd') || + $ACL->has_right_on_base($record->get_base_id(), 'cancmd') + ) { + ?>
+
+ has_right_on_base($record->get_base_id(), "canputinalbum")) { + ?>
+
+ get_preview()->is_physically_present()) { + ?> +
 
+
' . $light_info) ?>
+ + +
ACL(); $out = null; -if ($Request->get("act") == "DELIMG" && $Request->get("p0") != "") -{ - $repository = $em->getRepository('\Entities\BasketElement'); - /* @var $repository \Repositories\BasketElementRepository */ - $basket_element = $repository->findUserElement($Request->get('p0'), $user); - $em->remove($basket_element); - $em->flush(); +if ($Request->get("act") == "DELIMG" && $Request->get("p0") != "") { + $repository = $em->getRepository('\Entities\BasketElement'); + /* @var $repository \Repositories\BasketElementRepository */ + $basket_element = $repository->findUserElement($Request->get('p0'), $user); + $em->remove($basket_element); + $em->flush(); } -if ($Request->get('act') == "ADDIMG" && ($Request->get("p0") != "" && $Request->get("p0") != null)) -{ - $repository = $em->getRepository('\Entities\Basket'); - /* @var $repository \Repositories\BasketRepository */ - $basket = $repository->findUserBasket($Request->get('courChuId'), $user, true); +if ($Request->get('act') == "ADDIMG" && ($Request->get("p0") != "" && $Request->get("p0") != null)) { + $repository = $em->getRepository('\Entities\Basket'); + /* @var $repository \Repositories\BasketRepository */ + $basket = $repository->findUserBasket($Request->get('courChuId'), $user, true); - $sbas_id = $Request->get('sbas'); - $record = new record_adapter($sbas_id, $Request->get('p0')); + $sbas_id = $Request->get('sbas'); + $record = new record_adapter($sbas_id, $Request->get('p0')); - $BasketElement = new \Entities\BasketElement(); - $BasketElement->setRecord($record); - $BasketElement->setBasket($basket); - $basket->addBasketElement($BasketElement); + $BasketElement = new \Entities\BasketElement(); + $BasketElement->setRecord($record); + $BasketElement->setBasket($basket); + $basket->addBasketElement($BasketElement); - $em->persist($BasketElement); - $em->merge($basket); + $em->persist($BasketElement); + $em->merge($basket); - $em->flush(); + $em->flush(); } -if ($Request->get('act') == "DELCHU" && ($Request->get("p0") != "" && $Request->get("p0") != null)) -{ - $repository = $em->getRepository('\Entities\Basket'); - /* @var $repository \Repositories\BasketRepository */ - $basket = $repository->findUserBasket($Request->get('courChuId'), $user, true); +if ($Request->get('act') == "DELCHU" && ($Request->get("p0") != "" && $Request->get("p0") != null)) { + $repository = $em->getRepository('\Entities\Basket'); + /* @var $repository \Repositories\BasketRepository */ + $basket = $repository->findUserBasket($Request->get('courChuId'), $user, true); - $em->remove($basket); - $em->flush(); - unset($basket); + $em->remove($basket); + $em->flush(); + unset($basket); } $courChuId = $Request->get('courChuId'); -if ($Request->get('act') == "NEWCHU" && ($Request->get("p0") != "" && $Request->get("p0") != null)) -{ - $basket = new \Entities\Basket(); - $basket->setName($Request->get('p0')); - $basket->setOwner($user); +if ($Request->get('act') == "NEWCHU" && ($Request->get("p0") != "" && $Request->get("p0") != null)) { + $basket = new \Entities\Basket(); + $basket->setName($Request->get('p0')); + $basket->setOwner($user); - $em->persist($basket); - $em->flush(); + $em->persist($basket); + $em->flush(); - $courChuId = $basket->getId(); + $courChuId = $basket->getId(); } $repository = $em->getRepository('\Entities\Basket'); @@ -92,44 +88,39 @@ $out .= '" id="qry" style="width:245px;"> -
- - get('GV_client_coll_ckbox') === 'popup') - { - // liste des collections : popup - ?> -
- - - - get_databoxes()) > 0); - $options = ''; - - - - foreach ($user->ACL()->get_granted_sbas() as $databox) - { - if ($showbases) - { - $options .= ''; - $allbcol = array(); - $n_allbcol = 0; - if (count($databox->get_collections()) > 0) - { - $options .= ''; - } - foreach ($user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll) - { - $allbcol[] = $coll->get_base_id(); - $n_allbcol++; - - echo ''; - - $options .= ''; - - $allbases[] = $coll->get_base_id(); - } - if ($n_allbcol > 1) - { - $options .= ''; - } - } - if ($showbases) - { - $options .= "\n"; - } - } - echo ''; - ?> -
- -
- - get('GV_defaultQuery_type') == 0 ? $sel1 = " checked='checked'" : $sel2 = " checked='checked'") - ?> - - id="search_type_docs" name="search_type" /> - id="search_type_group" name="search_type" /> - -
-
- -
-
-
- - - - - -
- get('GV_client_coll_ckbox') == 'checkbox') - { - ?> - - - - get('GV_thesaurus')) - { - ?> - actives" onclick="chgOng(4);"> - - - - - - -
-
-
- get('GV_client_coll_ckbox') == 'checkbox') - { - ?> -
-
-
- - -
- -
-
-
+
+
+ + ACL()->get_granted_sbas() as $databox) - { - if ($registry->get('GV_view_bas_and_coll')) - { -?> -
-
-
- - - -
-get_statusbits(); - - $sbFilters = ''; - $dateFilters = $fieldsFilters = ''; - foreach ($status as $bit => $datas) - { - $imgoff = ''; - $imgon = ''; - if(!$datas['searchable']) - continue; - if ($datas['img_off']) - $imgoff = ''; - - if ($datas['img_on']) - $imgoff = ''; - - $labeloff = $datas['labeloff']; - $labelon = $datas['labelon']; - - $sbFilters .= '
' . - '
' . - '' . - '' . - '' . - '' . - '
' . - '' . - '' . - '' . - '' . - '' . - '
' . - '
'; - } - - $sxe = $databox->get_sxml_structure(); - if ($sxe) - { - $dateFilters = $fieldsFilters = ''; - if ($sxe->description) - { - foreach ($sxe->description->children() as $f => $field) - { - if ($field['type'] == 'date' && $field['searchclient'] == '1') - { - $dateFilters .= '
' . - '' . - '' . - '
' . - $f . '
' . _('phraseanet::time:: de') . - '' . - _('phraseanet::time:: a') . - '
' . - '' . - ' ' . - '' . - '
' . - '
'; - } - elseif ($field['type'] != 'date') - { - $fieldsFilters .= ''; - } - } - if ($dateFilters != '' || $sbFilters != '' || $fieldsFilters != '') - { - echo '
' . _('client::recherche: filter sur') . '
' . - '
 
'; - } - } - } - ?> -
- -
ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll) - { - $s = "checked"; - echo '
'; - } - ?>
get('GV_view_bas_and_coll')) - echo '
'; - } - ?> -
-
-
- - get('GV_thesaurus')) - { - ?> - -
-
-
- -
-
-
- -
-
-
-
- - - - -
-
- - -
- - get('GV_client_render_topics') == 'popups') - echo queries::dropdown_topics(); - elseif ($registry->get('GV_client_render_topics') == 'tree') - echo queries::tree_topics(); - ?> - -
-
- - -
-
-
-
- -
-
- -
-
- +
-
-
-
- -
-
-
-
-
-
-
-
-
-
-
-
-
-
    -
  • -
  • -
  • -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
- -
+
+
+
+
+ " id="qry" style="width:245px;"> +
+ +get('GV_client_coll_ckbox') === 'popup') { + // liste des collections : popup + ?> +
+ + + + get_databoxes()) > 0); + $options = ''; + + + + foreach ($user->ACL()->get_granted_sbas() as $databox) { + if ($showbases) { + $options .= ''; + $allbcol = array(); + $n_allbcol = 0; + if (count($databox->get_collections()) > 0) { + $options .= ''; + } + foreach ($user->ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll) { + $allbcol[] = $coll->get_base_id(); + $n_allbcol ++; + + echo ''; + + $options .= ''; + + $allbases[] = $coll->get_base_id(); + } + if ($n_allbcol > 1) { + $options .= ''; + } + } + if ($showbases) { + $options .= "\n"; + } + } + echo ''; + ?> +
+ +
+ + get('GV_defaultQuery_type') == 0 ? $sel1 = " checked='checked'" : $sel2 = " checked='checked'") + ?> + + id="search_type_docs" name="search_type" /> + id="search_type_group" name="search_type" /> + +
+
+ +
+
+
+ + + + + +
+get('GV_client_coll_ckbox') == 'checkbox') { + ?> + + + + get('GV_thesaurus')) { + ?> + actives" onclick="chgOng(4);"> + + + + + + +
+
+
+ get('GV_client_coll_ckbox') == 'checkbox') { + ?> +
+
+
+ + +
+ +
+
+
+ ACL()->get_granted_sbas() as $databox) { + if ($registry->get('GV_view_bas_and_coll')) { + ?> +
+
+
+ + + +
+ get_statusbits(); + + $sbFilters = ''; + $dateFilters = $fieldsFilters = ''; + foreach ($status as $bit => $datas) { + $imgoff = ''; + $imgon = ''; + if ( ! $datas['searchable']) + continue; + if ($datas['img_off']) + $imgoff = ''; + + if ($datas['img_on']) + $imgoff = ''; + + $labeloff = $datas['labeloff']; + $labelon = $datas['labelon']; + + $sbFilters .= '
' . + '' . + '' . + '' . + '' . + '' . + '
' . + '' . + '' . + '' . + '' . + '' . + '
' . + '
'; + } + + $sxe = $databox->get_sxml_structure(); + if ($sxe) { + $dateFilters = $fieldsFilters = ''; + if ($sxe->description) { + foreach ($sxe->description->children() as $f => $field) { + if ($field['type'] == 'date' && $field['searchclient'] == '1') { + $dateFilters .= '
' . + '' . + '' . + '
' . + $f . '
' . _('phraseanet::time:: de') . + '' . + _('phraseanet::time:: a') . + '
' . + '' . + ' ' . + '' . + '
' . + '
'; + } elseif ($field['type'] != 'date') { + $fieldsFilters .= ''; + } + } + if ($dateFilters != '' || $sbFilters != '' || $fieldsFilters != '') { + echo '
' . _('client::recherche: filter sur') . '
' . + '
 
'; + } + } + } + ?> +
+ +
ACL()->get_granted_base(array(), array($databox->get_sbas_id())) as $coll) { + $s = "checked"; + echo '
'; + } + ?>
get('GV_view_bas_and_coll')) + echo '
'; + } + ?> +
+
+
+ + get('GV_thesaurus')) { + ?> + +
+
+
+ +
+
+
+ +
+
+
+
+ + + + +
+
+ + +
+ + get('GV_client_render_topics') == 'popups') + echo queries::dropdown_topics(); + elseif ($registry->get('GV_client_render_topics') == 'tree') + echo queries::tree_topics(); + ?> + +
+
+ + +
- - - - - -
- -
- - - - - - + + + - get('GV_bitly_user')) !== '' && trim($registry->get('GV_bitly_key')) !== '') - { - $request = new http_request(); - ?> +get('GV_bitly_user')) !== '' && trim($registry->get('GV_bitly_key')) !== '') { + $request = new http_request(); + ?> - - + get('GV_googleAnalytics')) != '') - { - ?> - - - +get('GV_googleAnalytics')) != '') { ?> - + + + + diff --git a/www/include/cguUtils.php b/www/include/cguUtils.php index 23a7533ce9..18f8364795 100644 --- a/www/include/cguUtils.php +++ b/www/include/cguUtils.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -27,48 +26,42 @@ $parm = $request->get_parms("action", "usr", "cgus", "date", "bas", "col"); $tab = null; -if ($parm['action'] == 'PRINT') -{ - $inscriptions = giveMeBases(); +if ($parm['action'] == 'PRINT') { + $inscriptions = giveMeBases(); - phrasea::headers(); -?> - - - + + + $baseInsc) { + if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript'] && $sbasId == $parm['bas']) {// il y a des coll ou s'inscrire ! + $pot = false; + if ($baseInsc['CGU']) { + //je pr�sente la base + echo '

' . phrasea::sbas_names($sbasId) . '

'; + $pot = '

' . str_replace(array("\r\n", "\n", "\n"), "
", (string) $baseInsc['CGU']) . '

'; + } + $found = false; + foreach ($baseInsc['CollsCGU'] as $collId => $collDesc) { + if ($parm['col'] == $collId) { + echo '

' . str_replace(array("\r\n", "\n", "\n"), "
", (string) $collDesc['CGU']) . '

'; + $found = true; + } + } } - - - - $baseInsc) - { - if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript'] && $sbasId == $parm['bas'])// il y a des coll ou s'inscrire ! - { - $pot = false; - if ($baseInsc['CGU']) - { - //je pr�sente la base - echo '

' . phrasea::sbas_names($sbasId) . '

'; - $pot = '

' . str_replace(array("\r\n", "\n", "\n"), "
", (string) $baseInsc['CGU']) . '

'; - } - $found = false; - foreach ($baseInsc['CollsCGU'] as $collId => $collDesc) - { - if ($parm['col'] == $collId) - { - echo '

' . str_replace(array("\r\n", "\n", "\n"), "
", (string) $collDesc['CGU']) . '

'; - $found = true; - } - } } - } - if (!$found) - echo $pot; -?> - - + + get_parms("app"); -if (!$session->is_authenticated()) -{ - return; +if ( ! $session->is_authenticated()) { + return; } $session->set_event_module($parm['app'], false); diff --git a/www/include/download.php b/www/include/download.php index c8d0db4c63..bf876ca4fa 100644 --- a/www/include/download.php +++ b/www/include/download.php @@ -33,23 +33,22 @@ $parm = $request->get_parms("lst", "obj", "ssttid", "type", "businessfields"); $download = new set_export($parm['lst'], $parm['ssttid']); if ($parm["type"] == "title") - $titre = true; + $titre = true; else - $titre=false; + $titre = false; $list = $download->prepare_export($parm['obj'], $titre, $parm['businessfields']); $exportname = "Export_" . date("Y-n-d") . '_' . mt_rand(100, 999); -if ($parm["ssttid"] != "") -{ - $em = $Core->getEntityManager(); - $repository = $em->getRepository('\Entities\Basket'); +if ($parm["ssttid"] != "") { + $em = $Core->getEntityManager(); + $repository = $em->getRepository('\Entities\Basket'); - /* @var $repository \Repositories\BasketRepository */ + /* @var $repository \Repositories\BasketRepository */ - $basket = $repository->findUserBasket($Request->get('ssttid'), $Core->getAuthenticatedUser(), false); - $exportname = str_replace(' ', '_', $basket->getName()) . "_" . date("Y-n-d"); + $basket = $repository->findUserBasket($Request->get('ssttid'), $Core->getAuthenticatedUser(), false); + $exportname = str_replace(' ', '_', $basket->getName()) . "_" . date("Y-n-d"); } $list['export_name'] = $exportname . '.zip'; @@ -58,22 +57,21 @@ $endDate = new DateTime('+3 hours'); $url = random::getUrlToken(\random::TYPE_DOWNLOAD, $session->get_usr_id(), $endDate, serialize($list)); -if ($url) -{ +if ($url) { - $params = array( - 'lst' => $parm['lst'], - 'downloader' => $session->get_usr_id(), - 'subdefs' => $parm['obj'], - 'from_basket' => $parm["ssttid"], - 'export_file' => $exportname - ); + $params = array( + 'lst' => $parm['lst'], + 'downloader' => $session->get_usr_id(), + 'subdefs' => $parm['obj'], + 'from_basket' => $parm["ssttid"], + 'export_file' => $exportname + ); - $events_mngr = eventsmanager_broker::getInstance($appbox, $Core); - $events_mngr->trigger('__DOWNLOAD__', $params); + $events_mngr = eventsmanager_broker::getInstance($appbox, $Core); + $events_mngr->trigger('__DOWNLOAD__', $params); - return phrasea::redirect('/download/' . $url); + return phrasea::redirect('/download/' . $url); } phrasea::headers(500); diff --git a/www/include/download_anonymous.php b/www/include/download_anonymous.php index 94b128ca66..730c4adda1 100644 --- a/www/include/download_anonymous.php +++ b/www/include/download_anonymous.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -24,32 +23,27 @@ $request = http_request::getInstance(); $parm = $request->get_parms('token', 'get', 'type'); ob_start(null, 0); -try -{ - $datas = ((random::helloToken($parm['token']))); +try { + $datas = ((random::helloToken($parm['token']))); +} catch (Exception_NotFound $e) { + phrasea::headers(204); } -catch(Exception_NotFound $e) -{ - phrasea::headers(204); -} -if (!is_string($datas['datas'])) - phrasea::headers(204); +if ( ! is_string($datas['datas'])) + phrasea::headers(204); -if (($list = @unserialize($datas['datas'])) == false) -{ - phrasea::headers(500); +if (($list = @unserialize($datas['datas'])) == false) { + phrasea::headers(500); } $registry = registry::get_instance(); $zipFile = $registry->get('GV_RootPath') . 'tmp/download/' . $datas['value'] . '.zip'; -if (isset($parm['get']) && $parm['get'] == '1') -{ - $response = set_export::stream_file($zipFile, $list['export_name'], 'application/zip'); - $response->send(); - set_export::log_download($list, $parm['type'], true, (isset($list['email']) ? $list['email'] : '')); +if (isset($parm['get']) && $parm['get'] == '1') { + $response = set_export::stream_file($zipFile, $list['export_name'], 'application/zip'); + $response->send(); + set_export::log_download($list, $parm['type'], true, (isset($list['email']) ? $list['email'] : '')); - return; + return; } $files = $list['files']; @@ -58,151 +52,141 @@ $files = $list['files']; $zip_done = $zip_building = false; -if (isset($list['complete'])) -{ - if ($list['complete'] == true) - $zip_done = true; - else - $zip_building = true; +if (isset($list['complete'])) { + if ($list['complete'] == true) + $zip_done = true; + else + $zip_building = true; } phrasea::headers(); ?> - - <?php echo _('phraseanet:: Telechargement de documents'); ?> anonyme - - - - - - - -
-

+ + <?php echo _('phraseanet:: Telechargement de documents'); ?> anonyme + + + + + + + +
+

-

-
+if ( ! $zip_done) { + ?> +

+
+ +

', ''); ?>

+ +
+

+ + + + + + + + + + + + + + + + 10 ? 10 : $time); ?> -

', ''); ?>

- -
-

-
() $v) { + echo $v['label'] . '
'; + $size += $v['size']; } - else - { + ?>
- - - - - - - - +
- - () - - $v) - { - echo $v['label'] . '
'; - $size += $v['size']; - } ?> - - - + + + + + + - $time = round($total_size / (1024 * 1024 * 3)); - $time = $time < 1 ? 2 : ($time > 10 ? 10 : $time); - ?> - - - - - - - - +
- - -
- -
-
- + + +
+
+ diff --git a/www/include/download_prepare.exe.php b/www/include/download_prepare.exe.php index a7a9df929b..c503346fe3 100644 --- a/www/include/download_prepare.exe.php +++ b/www/include/download_prepare.exe.php @@ -24,20 +24,16 @@ $request = http_request::getInstance(); $parm = $request->get_parms('token'); $token = (string) ($parm["token"]); -try -{ -$datas = ((random::helloToken($token))); +try { + $datas = ((random::helloToken($token))); +} catch (Exception_NotFound $e) { + die('0'); } -catch(Exception_NotFound $e) -{ - die('0'); -} -if (!is_string($datas['datas'])) - die('0'); +if ( ! is_string($datas['datas'])) + die('0'); -if (($list = @unserialize($datas['datas'])) == false) -{ - die('0'); +if (($list = @unserialize($datas['datas'])) == false) { + die('0'); } set_time_limit(0); diff --git a/www/include/download_prepare.php b/www/include/download_prepare.php index 8f7366a8f4..5bc669e6cb 100644 --- a/www/include/download_prepare.php +++ b/www/include/download_prepare.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -24,32 +23,25 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms('token', 'get', 'type'); -try -{ - $datas = ((random::helloToken($parm['token']))); -} -catch (Exception_NotFound $e) -{ - phrasea::headers(204); +try { + $datas = ((random::helloToken($parm['token']))); +} catch (Exception_NotFound $e) { + phrasea::headers(204); } -if (!is_string($datas['datas'])) - phrasea::headers(204); +if ( ! is_string($datas['datas'])) + phrasea::headers(204); -if (($list = @unserialize($datas['datas'])) == false) -{ - phrasea::headers(500); +if (($list = @unserialize($datas['datas'])) == false) { + phrasea::headers(500); } -try -{ - $appbox = appbox::get_instance(\bootstrap::getCore()); - $auth = new Session_Authentication_Token($appbox, $parm['token']); - $session->authenticate($auth); -} -catch (Exception $e) -{ - phrasea::headers(204); +try { + $appbox = appbox::get_instance(\bootstrap::getCore()); + $auth = new Session_Authentication_Token($appbox, $parm['token']); + $session->authenticate($auth); +} catch (Exception $e) { + phrasea::headers(204); } $gatekeeper = gatekeeper::getInstance($Core); @@ -62,206 +54,191 @@ $zip_done = $zip_building = false; $export_name = $list['export_name']; -if ($n_files == 1) -{ - $u_file = $list['files']; - $u_file = array_pop($u_file); - $export_name = $u_file["export_name"]; - $u_file = array_pop($u_file['subdefs']); - $unique_file = true; - $export_name .= $u_file["ajout"] . '.' . $u_file["exportExt"]; - $zipFile = p4string::addEndSlash($u_file['path']) . $u_file['file']; - $mime = $u_file['mime']; - $zip_done = true; -} -else -{ - $zipFile = $registry->get('GV_RootPath') . 'tmp/download/' . $datas['value'] . '.zip'; - $mime = 'application/zip'; +if ($n_files == 1) { + $u_file = $list['files']; + $u_file = array_pop($u_file); + $export_name = $u_file["export_name"]; + $u_file = array_pop($u_file['subdefs']); + $unique_file = true; + $export_name .= $u_file["ajout"] . '.' . $u_file["exportExt"]; + $zipFile = p4string::addEndSlash($u_file['path']) . $u_file['file']; + $mime = $u_file['mime']; + $zip_done = true; +} else { + $zipFile = $registry->get('GV_RootPath') . 'tmp/download/' . $datas['value'] . '.zip'; + $mime = 'application/zip'; } $files = $list['files']; -if (isset($parm['get']) && $parm['get'] == '1') -{ - $response = set_export::stream_file($zipFile, $export_name, $mime); - $response->send(); - set_export::log_download($list, $parm['type']); +if (isset($parm['get']) && $parm['get'] == '1') { + $response = set_export::stream_file($zipFile, $export_name, $mime); + $response->send(); + set_export::log_download($list, $parm['type']); - return; + return; } -if (isset($list['complete'])) -{ - if ($list['complete'] == true) - $zip_done = true; - else - $zip_building = true; +if (isset($list['complete'])) { + if ($list['complete'] == true) + $zip_done = true; + else + $zip_building = true; } phrasea::headers(); ?> - - <?php echo _('phraseanet:: Telechargement de documents'); ?> - - - - - - - -
-

-
-

-
-
- -
-

', ''); ?>

-
-
-

- - - - - - - - - - - - - - - - - - - 10 ? 10 : $time); - ?> -
() $v) - { - echo $v['label'] . '
'; - $size += $v['size']; - } - ?>
get_thumbnail(); - - if ($thumbnail->is_paysage()) - { - $w = 140; - $h = round($w / ($thumbnail->get_width() / $thumbnail->get_height())); - } - else - { - $h = 105; - $w = round($h * ($thumbnail->get_width() / $thumbnail->get_height())); - } - - echo ''; - ?>
- + + +
+

+
+

+
+
+ +
+

', ''); ?>

+
+
+

+ + + + + + + + + + - $.post("/include/download_prepare.exe.php", { - token: "" - }, function(data){ - if(data == '1') - { - $('#wait').hide(); - $('#ready').show(); - get_file(); - } +$total_size = 0; +foreach ($files as $file) { + $size = 0; + ?> + + + + + + + + 10 ? 10 : $time); + ?> +
() $v) { + echo $v['label'] . '
'; + $size += $v['size']; + } + ?>
get_thumbnail(); - return; - }); - + if ($thumbnail->is_paysage()) { + $w = 140; + $h = round($w / ($thumbnail->get_width() / $thumbnail->get_height())); + } else { + $h = 105; + $w = round($h * ($thumbnail->get_width() / $thumbnail->get_height())); + } - get_file(); - - setTimeout("document.location.href = document.location.href",000); - get_url() . '"/>'; + ?>
+ -
+ }); + + -
- + + - + -
-
- +
+
+ diff --git a/www/include/error.php b/www/include/error.php index eeddafcffd..0be2f96945 100644 --- a/www/include/error.php +++ b/www/include/error.php @@ -20,105 +20,101 @@ $locales = \Alchemy\Phrasea\Core::getAvailableLanguages(); $current_locale = \Session_Handler::get_locale(); -if (!$current_locale) -{ - foreach ($locales as $code => $locale) - { - if ($request->getLocale() == $locale) - { - $current_locale = $locale; - break; +if ( ! $current_locale) { + foreach ($locales as $code => $locale) { + if ($request->getLocale() == $locale) { + $current_locale = $locale; + break; + } } - } - if (!$current_locale) - $current_locale = 'fr_FR'; + if ( ! $current_locale) + $current_locale = 'fr_FR'; } phrasea::use_i18n($current_locale); $request = http_request::getInstance(); -switch ($request->get_code()) -{ - case '204': - $title = '204 NO Content'; - $desc = '

' . _('error:204::Le contenu que vous demandez n\'existe pas ou a expire') . '

'; - break; - case '400': - $title = '400 Bad Request'; - $desc = '

' . _('error:400::La requete que vous faites ne peut etre traitee car les parametres necessaire a son traitement, sont mauvais ou manquants.') . '

'; - break; - case '403': - $title = '403 Forbidden'; - $desc = '

' . _('error:403::Vous avez demande une page a laquelle vous n\'avez pas acces.') . '

+switch ($request->get_code()) { + case '204': + $title = '204 NO Content'; + $desc = '

' . _('error:204::Le contenu que vous demandez n\'existe pas ou a expire') . '

'; + break; + case '400': + $title = '400 Bad Request'; + $desc = '

' . _('error:400::La requete que vous faites ne peut etre traitee car les parametres necessaire a son traitement, sont mauvais ou manquants.') . '

'; + break; + case '403': + $title = '403 Forbidden'; + $desc = '

' . _('error:403::Vous avez demande une page a laquelle vous n\'avez pas acces.') . '

' . _('error:403::Soit vous n\'avez pas les droits, soit vous avez ete deconnecte.') . '

'; - break; - case '404': - $title = '404 Not Found'; - $desc = '

' . _('error:404::Vous avez demande une page qui n\'existe pas ou plus') . '

'; - break; - case '500': - $title = '500 Internal Server Error'; - $desc = '

' . _('error:500::Erreur interne du serveur') . '

+ break; + case '404': + $title = '404 Not Found'; + $desc = '

' . _('error:404::Vous avez demande une page qui n\'existe pas ou plus') . '

'; + break; + case '500': + $title = '500 Internal Server Error'; + $desc = '

' . _('error:500::Erreur interne du serveur') . '

' . _('error:500::Une erreur interne est survenue. Ceci se produit lorsque la connetion a la base de donnee a ete interrompue ou lorsqu\'un module rencontre un probleme.') . '

' . _('error:500::Si ce probleme persiste, contactez l\'administrateur du serveur') . '

'; - break; - default: - $title = 'Unknown Error'; - $desc = ''; - break; + break; + default: + $title = 'Unknown Error'; + $desc = ''; + break; } ?> - - - <?php echo $title; ?> - - - -

- + + + <?php echo $title; ?> + + + +

+ - + --> - + diff --git a/www/include/geonames.feedback.php b/www/include/geonames.feedback.php index bac4b3fa5c..46c68c2855 100644 --- a/www/include/geonames.feedback.php +++ b/www/include/geonames.feedback.php @@ -23,15 +23,14 @@ $parm = $request->get_parms('action', 'city'); $action = $parm['action']; -switch ($action) -{ - case 'FIND': - $geoname = new geonames(); - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); +switch ($action) { + case 'FIND': + $geoname = new geonames(); + $core = \bootstrap::getCore(); + $twig = $core->getTwig(); - $output = $twig->render('geonames/city_list.twig', array('geonames' => $geoname->find_city($parm['city']))); - break; + $output = $twig->render('geonames/city_list.twig', array('geonames' => $geoname->find_city($parm['city']))); + break; } diff --git a/www/include/multiexports.php b/www/include/multiexports.php index 11afdd24cb..fa85142096 100644 --- a/www/include/multiexports.php +++ b/www/include/multiexports.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -29,15 +28,14 @@ $parm = $request->get_parms("lst", "SSTTID", "story"); $gatekeeper = gatekeeper::getInstance($Core); $gatekeeper->require_session(); -if ($registry->get('GV_needAuth2DL') && $user->is_guest()) -{ - ?> - - get('GV_needAuth2DL') && $user->is_guest()) { + ?> + + getTwig(); echo $twig->render('common/dialog_export.twig', array( - 'download' => $download, - 'ssttid' => $parm['SSTTID'], - 'lst' => $download->serialize_list(), - 'user' => $user, + 'download' => $download, + 'ssttid' => $parm['SSTTID'], + 'lst' => $download->serialize_list(), + 'user' => $user, 'default_export_title' => $registry->get('GV_default_export_title'), - 'choose_export_title' => $registry->get('GV_choose_export_title') + 'choose_export_title' => $registry->get('GV_choose_export_title') )); diff --git a/www/include/overview.php b/www/include/overview.php index 9a76b62ff1..7863fb16d4 100644 --- a/www/include/overview.php +++ b/www/include/overview.php @@ -17,7 +17,7 @@ */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; -$app = require __DIR__ .'/../../lib/Alchemy/Phrasea/Application/Overview.php'; +$app = require __DIR__ . '/../../lib/Alchemy/Phrasea/Application/Overview.php'; $app->run(); diff --git a/www/include/sendmailpage.php b/www/include/sendmailpage.php index 9fd157a274..f57cb04e5d 100644 --- a/www/include/sendmailpage.php +++ b/www/include/sendmailpage.php @@ -35,21 +35,20 @@ $events_mngr = \eventsmanager_broker::getInstance(\appbox::get_instance($Core), $user = $Core->getAuthenticatedUser(); -$from = array('name' => $user->get_display_name(), 'email' => $user->get_email()); +$from = array('name' => $user->get_display_name(), 'email' => $user->get_email()); $titre = $Request->get("type") == "title" ? : false; $exportname = "Export_" . date("Y-n-d") . '_' . mt_rand(100, 999); -if ($Request->get("ssttid", "") != "") -{ - $em = $Core->getEntityManager(); - $repository = $em->getRepository('\Entities\Basket'); +if ($Request->get("ssttid", "") != "") { + $em = $Core->getEntityManager(); + $repository = $em->getRepository('\Entities\Basket'); - /* @var $repository \Repositories\BasketRepository */ - $Basket = $repository->findUserBasket($Request->get('ssttid'), $Core->getAuthenticatedUser(), false); + /* @var $repository \Repositories\BasketRepository */ + $Basket = $repository->findUserBasket($Request->get('ssttid'), $Core->getAuthenticatedUser(), false); - $exportname = str_replace(' ', '_', $Basket->getName()) . "_" . date("Y-n-d"); + $exportname = str_replace(' ', '_', $Basket->getName()) . "_" . date("Y-n-d"); } $download = new set_export($Request->get('lst', ''), $Request->get('ssttid', '')); @@ -69,83 +68,70 @@ $dest = array(); $mails = explode(';', $Request->get("destmail", '')); -foreach ($mails as $email) -{ - if (filter_var($email, FILTER_VALIDATE_EMAIL)) - { - $dest[] = $email; - } - else - { - $params = array( - 'usr_id' => $Core->getAuthenticatedUser()->get_id() - , 'lst' => $Request->get('lst', '') - , 'ssttid' => $Request->get('ssttid') - , 'dest' => $email - , 'reason' => \eventsmanager_notify_downloadmailfail::MAIL_NO_VALID - ); +foreach ($mails as $email) { + if (filter_var($email, FILTER_VALIDATE_EMAIL)) { + $dest[] = $email; + } else { + $params = array( + 'usr_id' => $Core->getAuthenticatedUser()->get_id() + , 'lst' => $Request->get('lst', '') + , 'ssttid' => $Request->get('ssttid') + , 'dest' => $email + , 'reason' => \eventsmanager_notify_downloadmailfail::MAIL_NO_VALID + ); - $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); - } + $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); + } } //got some emails -if (count($dest) > 0 && $token) -{ - $reading_confirm_to = false; +if (count($dest) > 0 && $token) { + $reading_confirm_to = false; - if ($Request->get('reading_confirm') == '1') - { - $reading_confirm_to = $user->get_email(); - } - - //BUILDING ZIP - - $zipFile = $registry->get('GV_RootPath') . 'tmp/download/' . $token . '.zip'; - set_export::build_zip($token, $list, $zipFile); - - $res = $dest; - - $url = $registry->get('GV_ServerName') . 'mail-export/' . $token . '/'; - - foreach ($dest as $key => $email) - { - if (($result = mail::send_documents(trim($email), $url, $from, $endate_obj, $Request->get("textmail"), $reading_confirm_to)) === true) - { - unset($res[$key]); + if ($Request->get('reading_confirm') == '1') { + $reading_confirm_to = $user->get_email(); } - } - //some email fails - if (count($res) > 0) - { - foreach ($res as $email) - { - $params = array( - 'usr_id' => $Core->getAuthenticatedUser()->get_id() - , 'lst' => $Request->get('lst') - , 'ssttid' => $Request->get('ssttid') - , 'dest' => $email - , 'reason' => \eventsmanager_notify_downloadmailfail::MAIL_FAIL - ); + //BUILDING ZIP - $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); + $zipFile = $registry->get('GV_RootPath') . 'tmp/download/' . $token . '.zip'; + set_export::build_zip($token, $list, $zipFile); + + $res = $dest; + + $url = $registry->get('GV_ServerName') . 'mail-export/' . $token . '/'; + + foreach ($dest as $key => $email) { + if (($result = mail::send_documents(trim($email), $url, $from, $endate_obj, $Request->get("textmail"), $reading_confirm_to)) === true) { + unset($res[$key]); + } } - } -} -elseif(!$token && count($dest) > 0) -{ - foreach ($res as $email) - { - $params = array( - 'usr_id' => $Core->getAuthenticatedUser()->get_id() - , 'lst' => $Request->get('lst') - , 'ssttid' => $Request->get('ssttid') - , 'dest' => $email - , 'reason' => 0 - ); - $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); + //some email fails + if (count($res) > 0) { + foreach ($res as $email) { + $params = array( + 'usr_id' => $Core->getAuthenticatedUser()->get_id() + , 'lst' => $Request->get('lst') + , 'ssttid' => $Request->get('ssttid') + , 'dest' => $email + , 'reason' => \eventsmanager_notify_downloadmailfail::MAIL_FAIL + ); + + $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); + } + } +} elseif ( ! $token && count($dest) > 0) { + foreach ($res as $email) { + $params = array( + 'usr_id' => $Core->getAuthenticatedUser()->get_id() + , 'lst' => $Request->get('lst') + , 'ssttid' => $Request->get('ssttid') + , 'dest' => $email + , 'reason' => 0 + ); + + $events_mngr->trigger('__EXPORT_MAIL_FAIL__', $params); } } diff --git a/www/include/updses.php b/www/include/updses.php index 5876d03fcc..a66e72a9ef 100644 --- a/www/include/updses.php +++ b/www/include/updses.php @@ -23,35 +23,28 @@ $em = $Core->getEntityManager(); $appbox = appbox::get_instance($Core); $session = $appbox->get_session(); $session->close_storage(); -$ret = array('status' => 'unknown', 'message' => false); +$ret = array('status' => 'unknown', 'message' => false); $request = http_request::getInstance(); $parm = $request->get_parms('usr', 'app'); -if ($session->is_authenticated()) -{ - $usr_id = $session->get_usr_id(); - if ($usr_id != $parm['usr']) //i logged with another user - { +if ($session->is_authenticated()) { + $usr_id = $session->get_usr_id(); + if ($usr_id != $parm['usr']) { //i logged with another user + $ret['status'] = 'disconnected'; + die(p4string::jsonencode($ret)); + } +} else { $ret['status'] = 'disconnected'; die(p4string::jsonencode($ret)); - } -} -else -{ - $ret['status'] = 'disconnected'; - die(p4string::jsonencode($ret)); } $user = $Core->getAuthenticatedUser(); -try -{ - $conn = $appbox->get_connection(); -} -catch (Exception $e) -{ - return p4string::jsonencode($ret); +try { + $conn = $appbox->get_connection(); +} catch (Exception $e) { + return p4string::jsonencode($ret); } $ret['apps'] = 1; @@ -78,26 +71,22 @@ $repository = $em->getRepository('\Entities\Basket'); /* @var $repository \Repositories\BasketRepository */ $baskets = $repository->findUnreadActiveByUser($user); -foreach ($baskets as $basket) -{ - $ret['changed'][] = $basket->getId(); +foreach ($baskets as $basket) { + $ret['changed'][] = $basket->getId(); } -if (in_array($session->get_session_prefs('message'), array('1', null))) -{ - $registry = $appbox->get_registry(); - if ($registry->get('GV_maintenance')) - { +if (in_array($session->get_session_prefs('message'), array('1', null))) { + $registry = $appbox->get_registry(); + if ($registry->get('GV_maintenance')) { - $ret['message'] .= '
' . _('The application is going down for maintenance, please logout.') . '
'; - } + $ret['message'] .= '
' . _('The application is going down for maintenance, please logout.') . '
'; + } - if ($registry->get('GV_message_on')) - { + if ($registry->get('GV_message_on')) { - $ret['message'] .= '
' . strip_tags($registry->get('GV_message')) . '
'; - } + $ret['message'] .= '
' . strip_tags($registry->get('GV_message')) . '
'; + } } echo p4string::jsonencode($ret); diff --git a/www/index.php b/www/index.php index 46a48af2ff..97979ccaeb 100644 --- a/www/index.php +++ b/www/index.php @@ -15,8 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - - require_once __DIR__ . "/../lib/bootstrap.php"; $app = require __DIR__ . '/../lib/Alchemy/Phrasea/Application/Root.php'; diff --git a/www/login/account.php b/www/login/account.php index d525a5f94a..3c837bbff3 100644 --- a/www/login/account.php +++ b/www/login/account.php @@ -23,9 +23,9 @@ require_once($appbox->get_registry()->get('GV_RootPath') . 'lib/classes/deprecat $request = http_request::getInstance(); $parm = $request->get_parms("form_gender", "form_lastname", "form_firstname", "form_job", "form_company" - , "form_function", "form_activity", "form_phone", "form_fax", "form_address", "form_zip", "form_geonameid" - , "form_destFTP", "form_defaultdataFTP", "form_prefixFTPfolder", "notice", "form_bases", "mail_notifications", "request_notifications", 'demand', 'notifications' - , "form_activeFTP", "form_addrFTP", "form_loginFTP", "form_pwdFTP", "form_passifFTP", "form_retryFTP"); + , "form_function", "form_activity", "form_phone", "form_fax", "form_address", "form_zip", "form_geonameid" + , "form_destFTP", "form_defaultdataFTP", "form_prefixFTPfolder", "notice", "form_bases", "mail_notifications", "request_notifications", 'demand', 'notifications' + , "form_activeFTP", "form_addrFTP", "form_loginFTP", "form_pwdFTP", "form_passifFTP", "form_retryFTP"); $lng = Session_Handler::get_locale(); @@ -36,762 +36,740 @@ $usr_id = $user->get_id(); $gatekeeper = gatekeeper::getInstance($Core); $gatekeeper->require_session(); -if ($user->is_guest()) -{ - phrasea::headers(403); +if ($user->is_guest()) { + phrasea::headers(403); } phrasea::headers(); appbox_register::clean_old_requests($appbox); -if ($request->has_post_datas()) -{ - $accountFields = array( - 'form_gender', - 'form_firstname', - 'form_lastname', - 'form_address', - 'form_zip', - 'form_phone', - 'form_fax', - 'form_function', - 'form_company', - 'form_activity', - 'form_geonameid', - 'form_addrFTP', - 'form_loginFTP', - 'form_pwdFTP', - 'form_destFTP', - 'form_prefixFTPfolder' - ); +if ($request->has_post_datas()) { + $accountFields = array( + 'form_gender', + 'form_firstname', + 'form_lastname', + 'form_address', + 'form_zip', + 'form_phone', + 'form_fax', + 'form_function', + 'form_company', + 'form_activity', + 'form_geonameid', + 'form_addrFTP', + 'form_loginFTP', + 'form_pwdFTP', + 'form_destFTP', + 'form_prefixFTPfolder' + ); - $demandFields = array( - 'demand' - ); + $demandFields = array( + 'demand' + ); - $parm['notice'] = 'account-update-bad'; + $parm['notice'] = 'account-update-bad'; - if (count(array_diff($demandFields, array_keys($request->get_post_datas()))) == 0) - { - $register = new appbox_register($appbox); + if (count(array_diff($demandFields, array_keys($request->get_post_datas()))) == 0) { + $register = new appbox_register($appbox); - foreach ($parm["demand"] as $unebase) - { - try - { - $register->add_request($user, collection::get_from_base_id($unebase)); - $parm['notice'] = 'demand-ok'; - } - catch (Exception $e) - { + foreach ($parm["demand"] as $unebase) { + try { + $register->add_request($user, collection::get_from_base_id($unebase)); + $parm['notice'] = 'demand-ok'; + } catch (Exception $e) { - } + } + } } - } - if (count(array_diff($accountFields, array_keys($request->get_post_datas()))) == 0) - { + if (count(array_diff($accountFields, array_keys($request->get_post_datas()))) == 0) { - $defaultDatas = 0; - if ($parm["form_defaultdataFTP"]) - { - if (in_array('document', $parm["form_defaultdataFTP"])) - $defaultDatas += 4; - if (in_array('preview', $parm["form_defaultdataFTP"])) - $defaultDatas += 2; - if (in_array('caption', $parm["form_defaultdataFTP"])) - $defaultDatas += 1; - } - try - { - $appbox->get_connection()->beginTransaction(); - $user->set_gender($parm["form_gender"]) - ->set_firstname($parm["form_firstname"]) - ->set_lastname($parm["form_lastname"]) - ->set_address($parm["form_address"]) - ->set_zip($parm["form_zip"]) - ->set_tel($parm["form_phone"]) - ->set_fax($parm["form_fax"]) - ->set_job($parm["form_activity"]) - ->set_company($parm["form_company"]) - ->set_position($parm["form_function"]) - ->set_geonameid($parm["form_geonameid"]) - ->set_mail_notifications(($parm["mail_notifications"] == '1')) - ->set_activeftp($parm["form_activeFTP"]) - ->set_ftp_address($parm["form_addrFTP"]) - ->set_ftp_login($parm["form_loginFTP"]) - ->set_ftp_password($parm["form_pwdFTP"]) - ->set_ftp_passif($parm["form_passifFTP"]) - ->set_ftp_dir($parm["form_destFTP"]) - ->set_ftp_dir_prefix($parm["form_prefixFTPfolder"]) - ->set_defaultftpdatas($defaultDatas); + $defaultDatas = 0; + if ($parm["form_defaultdataFTP"]) { + if (in_array('document', $parm["form_defaultdataFTP"])) + $defaultDatas += 4; + if (in_array('preview', $parm["form_defaultdataFTP"])) + $defaultDatas += 2; + if (in_array('caption', $parm["form_defaultdataFTP"])) + $defaultDatas += 1; + } + try { + $appbox->get_connection()->beginTransaction(); + $user->set_gender($parm["form_gender"]) + ->set_firstname($parm["form_firstname"]) + ->set_lastname($parm["form_lastname"]) + ->set_address($parm["form_address"]) + ->set_zip($parm["form_zip"]) + ->set_tel($parm["form_phone"]) + ->set_fax($parm["form_fax"]) + ->set_job($parm["form_activity"]) + ->set_company($parm["form_company"]) + ->set_position($parm["form_function"]) + ->set_geonameid($parm["form_geonameid"]) + ->set_mail_notifications(($parm["mail_notifications"] == '1')) + ->set_activeftp($parm["form_activeFTP"]) + ->set_ftp_address($parm["form_addrFTP"]) + ->set_ftp_login($parm["form_loginFTP"]) + ->set_ftp_password($parm["form_pwdFTP"]) + ->set_ftp_passif($parm["form_passifFTP"]) + ->set_ftp_dir($parm["form_destFTP"]) + ->set_ftp_dir_prefix($parm["form_prefixFTPfolder"]) + ->set_defaultftpdatas($defaultDatas); - $appbox->get_connection()->commit(); + $appbox->get_connection()->commit(); - $parm['notice'] = 'account-update-ok'; + $parm['notice'] = 'account-update-ok'; + } catch (Exception $e) { + $appbox->get_connection()->rollBack(); + } } - catch (Exception $e) - { - $appbox->get_connection()->rollBack(); - } - } } -if ($request->has_post_datas()) -{ - $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); - $notifications = $evt_mngr->list_notifications_available($appbox->get_session()->get_usr_id()); +if ($request->has_post_datas()) { + $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); + $notifications = $evt_mngr->list_notifications_available($appbox->get_session()->get_usr_id()); - $datas = array(); + $datas = array(); - foreach ($notifications as $notification => $nots) - { - foreach ($nots as $notification) - { - $current_notif = $user->getPrefs('notification_' . $notification['id']); + foreach ($notifications as $notification => $nots) { + foreach ($nots as $notification) { + $current_notif = $user->getPrefs('notification_' . $notification['id']); - if (!is_null($parm['notifications']) && isset($parm['notifications'][$notification['id']])) - $datas[$notification['id']] = '1'; - else - $datas[$notification['id']] = '0'; + if ( ! is_null($parm['notifications']) && isset($parm['notifications'][$notification['id']])) + $datas[$notification['id']] = '1'; + else + $datas[$notification['id']] = '0'; + } } - } - foreach ($datas as $k => $v) - { - $user->setPrefs('notification_' . $k, $v); - } + foreach ($datas as $k => $v) { + $user->setPrefs('notification_' . $k, $v); + } } $geonames = new geonames(); $user = User_Adapter::getInstance($appbox->get_session()->get_usr_id(), $appbox); ?> - - <?php echo $appbox->get_registry()->get('GV_homeTitle') ?> <?php echo _('login:: Mon compte') ?> - - - - - + + + - - - -
-
- - - - - -
get_registry()->get('GV_homeTitle') ?> - -
-
-
-
-
- -
    -
  • -
  • -
  • -
  • -
  • -
- -
- - - - - -
- - -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - list_notifications_available($appbox->get_session()->get_usr_id()); - - foreach ($notifications as $notification_group => $nots) - { - ?> - - - - - - - - - '); + $(".url_callback").die(); + $(".save_callback").live("click", function(){ + var callback = $("input[name=oauth_callback]").val(); + var app_id = $("input[name=app_id]").val(); + var $this = $(this); + var option = { + type:"POST", + url : "/api/oauthv2/applications/oauth_callback", + dataType: 'json', + data :{app_id : app_id, callback : callback}, + success : function(data){ + if(data.success == true) + $(".url_callback_input").empty().append(callback); + else + $(".url_callback_input").empty().append(cur_value); + $this.hide(); + $(".url_callback").live("mouseover mouseout", $url_callback_event); + } } - ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + $.ajax(option); + }); + }); - - - - - - - - - -
get_login() ?>
- -
- -
- -
-
- get_email() ?> -
Notification par email
- getPrefs('notification_' . $notification['id']) == '0' ? '' : 'checked'; ?> value="1"/> -
- -
- -
- -
-
- -
- -
- -
- -
- -
-
- get_activeftp() ? "checked" : "") ?> name="form_activeFTP" id="form_activeFTP"> -
-
;"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- -
- -
- -
- -
- get_ftp_passif() == "1" ? "checked" : "") ?> name="form_passifFTP" id="form_passifFTP"/> -
- -
- get_defaultftpdatas() >> 2) & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="document" id="form_defaultSendDocument"> - get_defaultftpdatas() >> 1) & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="preview" id="form_defaultSendPreview"> - get_defaultftpdatas() & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="caption" id="form_defaultSendCaption"> -
-
-
-
- -
-
-
-
- - - -
- - -
- - -
- - -
- - - - -
- - - - - - - - - - - - - - - - - - get_session()->get_my_sessions() as $row) - { - ?> - - - - - - - - + } + $.ajax(option); + }); + + $("#form_create input[name=type]").live("click", function(){ + if($(this).val() == "desktop") + $("#form_create .callback td").hide().find("input").val(''); + else + $("#form_create .callback td").show(); + }); + + $(".app-btn").live("click", function(){ + + if (!$(this).hasClass("authorize")) + { + var revoke = 1; + var button_class = "authorize"; + var old_class ="revoke"; + var string = ""; + } + + if ($(this).hasClass("authorize")) + { + var revoke = 0; + var button_class = "revoke"; + var old_class ="authorize"; + var string = ""; + } + + var acc_id = $(this).attr("value"); + var current = $(this); + var opts = { + type:"POST", + url : '/api/oauthv2/applications/revoke_access/', + dataType: 'json', + data : { + account_id : acc_id, + revoke : revoke + }, + success : function(data){ + if(data.ok) + { + div = current.closest("div"); + current.removeClass(old_class).addClass(button_class); + current.attr("value", acc_id); + current.empty().append(string); + } + } + } + $.ajax(opts); + }); + + + $("#app_dev, #app_dev_new, #app_dev_create, a.dev_back").live("click", function(e){ + e.preventDefault(); + target = $(this).attr("href"); + var opts = { + type:"GET", + url : target, + dataType: 'html', + success : function(data){ + $(".ui-tabs-panel:visible").empty().append(data); + } + } + $.ajax(opts); + }); + + + $(".delete_app").die().live("click", function(){ + var id = $(this).closest("li").attr('id').split("_");; + var app_id = id[1]; + var $this= $(this); + $("body").append("

"+trans.confirm_delete+" ?

") + $("#confirm_delete").dialog({ + resizable: false, + autoOpen :true, + title: "", + draggable: false, + width:340, + modal: true, + buttons: [{ + id: "ybutton", + text: trans.yes, + click: function() { + var opts = { + type:"DELETE", + url : '/api/oauthv2/applications/'+ app_id, + dataType: 'json', + data : {}, + success : function(data){ + if(data.success == true) + { + $this.closest("li").remove(); + $("#confirm_delete").dialog("close"); + } + } + } + $.ajax(opts); + } + }, + { + id: "nbutton", + text: trans.no, + click: function() { + $( this ).dialog( "close" ); + } + }], + close : function() { + $( this ).remove(); + } + }); + }); + + }); + + + + +
+
+
- Mes session -
- - - Date de connexion - - Dernier access - - IP - - Browser - - ecran - - Session persistante -
- get_session()->get_ses_id() != $row['session_id']) - { - ?> - - - - - - - - - - - - - - - -
+ + + - - -
get_registry()->get('GV_homeTitle') ?> + +
+
- - -
+
+
+
+ +
    +
  • +
  • +
  • +
  • +
  • +
+ +
+ + + + + +
+ + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +list_notifications_available($appbox->get_session()->get_usr_id()); + +foreach ($notifications as $notification_group => $nots) { + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
get_login() ?>
+ +
+ +
+ +
+
+get_email() ?> +
Notification par email
+ getPrefs('notification_' . $notification['id']) == '0' ? '' : 'checked'; ?> value="1"/> +
+ +
+ +
+ +
+
+ +
+ +
+ +
+ +
+ +
+
+ get_activeftp() ? "checked" : "") ?> name="form_activeFTP" id="form_activeFTP"> +
+
;"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+ +
+ get_ftp_passif() == "1" ? "checked" : "") ?> name="form_passifFTP" id="form_passifFTP"/> +
+ +
+ get_defaultftpdatas() >> 2) & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="document" id="form_defaultSendDocument"> + get_defaultftpdatas() >> 1) & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="preview" id="form_defaultSendPreview"> + get_defaultftpdatas() & 1) == 1 ? "checked" : "") ?> name="form_defaultdataFTP[]" value="caption" id="form_defaultSendCaption"> +
+
+
+
+ +
+
+
+
+ + + +
+ + +
+ + +
+ + +
+ + + + +
+ + + + + + + + + + + + + + + + + +get_session()->get_my_sessions() as $row) { + ?> + + + + + + + + + + + +
+ Mes session +
+ + + Date de connexion + + Dernier access + + IP + + Browser + + ecran + + Session persistante +
+ get_session()->get_ses_id() != $row['session_id']) { + ?> + + + + + + + + + + + + + + + +
+
+ + +
+ + +
+
+ + +
+
+
+
© Copyright Alchemy 2005-
-
- - -
-
-
© Copyright Alchemy 2005-
-
-
- + diff --git a/www/login/authenticate.php b/www/login/authenticate.php index e759405697..8a696b1fed 100644 --- a/www/login/authenticate.php +++ b/www/login/authenticate.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -24,121 +23,87 @@ $session = $appbox->get_session(); $registry = $appbox->get_registry(); if ($registry->get('GV_captchas') - && trim($registry->get('GV_captcha_private_key')) !== '' - && trim($registry->get('GV_captcha_public_key')) !== '') - include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php'); + && trim($registry->get('GV_captcha_private_key')) !== '' + && trim($registry->get('GV_captcha_public_key')) !== '') + include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php'); $request = http_request::getInstance(); -$parm = $request->get_parms('redirect','login', 'pwd', 'nolog', 'recaptcha_response_field', 'remember', 'recaptcha_challenge_field'); +$parm = $request->get_parms('redirect', 'login', 'pwd', 'nolog', 'recaptcha_response_field', 'remember', 'recaptcha_challenge_field'); $is_guest = false; -if (!is_null($parm['nolog']) && phrasea::guest_allowed()) -{ - $is_guest = true; +if ( ! is_null($parm['nolog']) && phrasea::guest_allowed()) { + $is_guest = true; } -if ((!is_null($parm['login']) && !is_null($parm['pwd'])) || $is_guest) -{ - if (file_exists($registry->get('GV_RootPath') . 'config/personnalisation/prelog.class.php')) - { - include($registry->get('GV_RootPath') . 'config/personnalisation/prelog.class.php'); - $prelog = new prelog($parm['login'], $parm['pwd']); - } - - try - { - - if ($is_guest) - { - $auth = new Session_Authentication_Guest($appbox); +if (( ! is_null($parm['login']) && ! is_null($parm['pwd'])) || $is_guest) { + if (file_exists($registry->get('GV_RootPath') . 'config/personnalisation/prelog.class.php')) { + include($registry->get('GV_RootPath') . 'config/personnalisation/prelog.class.php'); + $prelog = new prelog($parm['login'], $parm['pwd']); } - else - { - $captcha = false; - if ($registry->get('GV_captchas') - && trim($registry->get('GV_captcha_private_key')) !== '' - && trim($registry->get('GV_captcha_public_key')) !== '' - && !is_null($parm["recaptcha_challenge_field"]) - && !is_null($parm["recaptcha_response_field"])) - { - $checkCaptcha = recaptcha_check_answer($registry->get('GV_captcha_private_key'), $_SERVER["REMOTE_ADDR"], $parm["recaptcha_challenge_field"], $parm["recaptcha_response_field"]); + try { - if ($checkCaptcha->is_valid) - { - $captcha = true; + if ($is_guest) { + $auth = new Session_Authentication_Guest($appbox); + } else { + $captcha = false; + + if ($registry->get('GV_captchas') + && trim($registry->get('GV_captcha_private_key')) !== '' + && trim($registry->get('GV_captcha_public_key')) !== '' + && ! is_null($parm["recaptcha_challenge_field"]) + && ! is_null($parm["recaptcha_response_field"])) { + $checkCaptcha = recaptcha_check_answer($registry->get('GV_captcha_private_key'), $_SERVER["REMOTE_ADDR"], $parm["recaptcha_challenge_field"], $parm["recaptcha_response_field"]); + + if ($checkCaptcha->is_valid) { + $captcha = true; + } + } + + $auth = new Session_Authentication_Native($appbox, $parm['login'], $parm['pwd']); + $auth->set_captcha_challenge($captcha); } - } + $session->authenticate($auth); + } catch (Exception_Session_StorageClosed $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=session"); + } catch (Exception_Session_RequireCaptcha $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=captcha"); + } catch (Exception_Unauthorized $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=auth"); + } catch (Exception_Session_MailLocked $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=mailNotConfirm&usr=" . $e->get_usr_id()); + } catch (Exception_Session_WrongToken $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=token"); + } catch (Exception_InternalServerError $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=session"); + } catch (Exception_ServiceUnavailable $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=maintenance"); + } catch (Exception_Session_BadSalinity $e) { + $date = new DateTime('5 minutes'); + $usr_id = User_Adapter::get_usr_id_from_login($parm['login']); + $url = random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $date); - $auth = new Session_Authentication_Native($appbox, $parm['login'], $parm['pwd']); - $auth->set_captcha_challenge($captcha); + $url = '/login/forgotpwd.php?token=' . $url . '&salt=1'; + + return phrasea::redirect($url); + } catch (\Exception $e) { + return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=" . $e->getMessage() . $e->getFile() . $e->getLine()); } - $session->authenticate($auth); - } - catch (Exception_Session_StorageClosed $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=session"); - } - catch (Exception_Session_RequireCaptcha $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=captcha"); - } - catch (Exception_Unauthorized $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=auth"); - } - catch (Exception_Session_MailLocked $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=mailNotConfirm&usr=" . $e->get_usr_id()); - } - catch (Exception_Session_WrongToken $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=token"); - } - catch (Exception_InternalServerError $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=session"); - } - catch (Exception_ServiceUnavailable $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=maintenance"); - } - catch (Exception_Session_BadSalinity $e) - { - $date = new DateTime('5 minutes'); - $usr_id = User_Adapter::get_usr_id_from_login($parm['login']); - $url = random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $date); - $url = '/login/forgotpwd.php?token=' . $url . '&salt=1'; + $browser = Browser::getInstance(); - return phrasea::redirect($url); - } - catch (\Exception $e) - { - return phrasea::redirect("/login/?redirect=" . $parm['redirect'] . "&error=".$e->getMessage().$e->getFile().$e->getLine() ); - } - - $browser = Browser::getInstance(); - - if (!$browser->isNewGeneration()) - $app = 'client'; + if ( ! $browser->isNewGeneration()) + $app = 'client'; - if ($browser->isMobile()) - { - return phrasea::redirect("/lightbox/"); - } - elseif($parm['redirect']) - { - return phrasea::redirect($parm['redirect']); - } - else - { - return phrasea::redirect('/prod'); - } -} -else -{ - return phrasea::redirect("/login/"); + if ($browser->isMobile()) { + return phrasea::redirect("/lightbox/"); + } elseif ($parm['redirect']) { + return phrasea::redirect($parm['redirect']); + } else { + return phrasea::redirect('/prod'); + } +} else { + return phrasea::redirect("/login/"); } diff --git a/www/login/forgotpwd.php b/www/login/forgotpwd.php index a0a9bc824e..6452b2f282 100644 --- a/www/login/forgotpwd.php +++ b/www/login/forgotpwd.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -27,275 +26,250 @@ $parm = $request->get_parms('salt', 'error', 'sent', 'token', 'form_password', ' $needed = array(); -if (isset($parm["mail"]) && trim($parm["mail"]) != "") -{ - if (!PHPMailer::ValidateAddress($parm['mail'])) - { - return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); - } - - try - { - $usr_id = User_Adapter::get_usr_id_from_email($parm['mail']); - $user = User_Adapter::getInstance($usr_id, $appbox); - } - catch(Exception $e) - { - return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); - } - - $date = new DateTime('1 day'); - $url = random::getUrlToken(\random::TYPE_PASSWORD, $user->get_id(), $date); - - if ($url !== false) - { - $url = $registry->get('GV_ServerName') . 'login/forgotpwd.php?token=' . $url; - if (mail::forgot_passord($parm['mail'], $user->get_login(), $url) === true) - { - return phrasea::redirect('/login/forgotpwd.php?sent=ok'); +if (isset($parm["mail"]) && trim($parm["mail"]) != "") { + if ( ! PHPMailer::ValidateAddress($parm['mail'])) { + return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); } - else - { - return phrasea::redirect('/login/forgotpwd.php?error=mailserver'); - } - } - return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); + try { + $usr_id = User_Adapter::get_usr_id_from_email($parm['mail']); + $user = User_Adapter::getInstance($usr_id, $appbox); + } catch (Exception $e) { + return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); + } + + $date = new DateTime('1 day'); + $url = random::getUrlToken(\random::TYPE_PASSWORD, $user->get_id(), $date); + + if ($url !== false) { + $url = $registry->get('GV_ServerName') . 'login/forgotpwd.php?token=' . $url; + if (mail::forgot_passord($parm['mail'], $user->get_login(), $url) === true) { + return phrasea::redirect('/login/forgotpwd.php?sent=ok'); + } else { + return phrasea::redirect('/login/forgotpwd.php?error=mailserver'); + } + } + + return phrasea::redirect('/login/forgotpwd.php?error=noaccount'); } -if (isset($parm['token']) && isset($parm['form_password']) && isset($parm['form_password_confirm'])) -{ - if ($parm['form_password'] !== $parm['form_password_confirm']) - $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); - elseif (strlen(trim($parm['form_password'])) < 5) - $needed['form_password'] = _('forms::la valeur donnee est trop courte'); - elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) - $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); +if (isset($parm['token']) && isset($parm['form_password']) && isset($parm['form_password_confirm'])) { + if ($parm['form_password'] !== $parm['form_password_confirm']) + $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); + elseif (strlen(trim($parm['form_password'])) < 5) + $needed['form_password'] = _('forms::la valeur donnee est trop courte'); + elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) + $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); - if (count($needed) == 0) - { + if (count($needed) == 0) { - try - { - $datas = random::helloToken($parm['token']); - $user = User_Adapter::getInstance($datas['usr_id'], $appbox); - $user->set_password($parm['form_password_confirm']); - random::removeToken($parm['token']); + try { + $datas = random::helloToken($parm['token']); + $user = User_Adapter::getInstance($datas['usr_id'], $appbox); + $user->set_password($parm['form_password_confirm']); + random::removeToken($parm['token']); - return phrasea::redirect('/login/index.php?confirm=password-update-ok'); + return phrasea::redirect('/login/index.php?confirm=password-update-ok'); + } catch (Exception_NotFound $e) { + + } } - catch(Exception_NotFound $e) - { - - } - } } phrasea::headers(); ?> - - - - <?php echo _('admin::compte-utilisateur changer mon mot de passe'); ?> - - -
-
- - - - - -
get('GV_homeTitle') ?>
-
-
-
-
- -
-
+ + + + <?php echo _('admin::compte-utilisateur changer mon mot de passe'); ?> + + +
+
+ + + + + +
get('GV_homeTitle') ?>
+
+
+
+
+ +
+
- - - +if ($parm['token'] !== null) { + try { + random::helloToken($parm['token']); + $tokenize = true; + ?> + + + - + }); + - -
-
- -
- -
- - - - - - - - - - - - - - - - -
-
- -
-
-
- -
-
 
-
-
-
+ +
+
+ +
+ + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+ +
+
 
+
+
+
+
+
+
+ +
+ +
+
+
+ +
+
+ + + + +
+ + + '; + + if ($parm['error'] !== null) { + switch ($parm['error']) { + case 'mailserver': + echo '
' . _('phraseanet::erreur: Echec du serveur mail') . '
'; + break; + case 'noaccount': + echo '
' . _('phraseanet::erreur: Le compte n\'a pas ete trouve') . '
'; + break; + case 'mail': + echo '
' . _('phraseanet::erreur: Echec du serveur mail') . '
'; + break; + case 'token': + echo '
' . _('phraseanet::erreur: l\'url n\'est plus valide') . '
'; + break; + } + } + if ($parm['sent'] !== null) { + switch ($parm['sent']) { + case 'ok': + echo '
' . _('phraseanet:: Un email vient de vous etre envoye') . '
'; + break; + } + } + ?> + +
+ +
+
+ +
+
+ +
+
+ + +
+ +
-
-
- -
- -
-
-
- -
-
- - - - -
- -'; - - if ($parm['error'] !== null) - { - switch ($parm['error']) - { - case 'mailserver': - echo '
' . _('phraseanet::erreur: Echec du serveur mail') . '
'; - break; - case 'noaccount': - echo '
' . _('phraseanet::erreur: Le compte n\'a pas ete trouve') . '
'; - break; - case 'mail': - echo '
' . _('phraseanet::erreur: Echec du serveur mail') . '
'; - break; - case 'token': - echo '
' . _('phraseanet::erreur: l\'url n\'est plus valide') . '
'; - break; - } - } - if ($parm['sent'] !== null) - { - switch ($parm['sent']) - { - case 'ok': - echo '
' . _('phraseanet:: Un email vient de vous etre envoye') . '
'; - break; - } - } -?> - -
- -
-
- -
-
- -
-
- - -
- - +
+
+
© Copyright Alchemy 2005-
- -
-
© Copyright Alchemy 2005-
-
-
- + diff --git a/www/login/index.php b/www/login/index.php index 0c09bdb9e9..a7c21274ab 100644 --- a/www/login/index.php +++ b/www/login/index.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -24,32 +23,27 @@ $registry = $appbox->get_registry(); require_once($registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php'); if ($registry->get('GV_captchas') && trim($registry->get('GV_captcha_private_key')) !== '' && trim($registry->get('GV_captcha_public_key')) !== '') - include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php'); + include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php'); $request = http_request::getInstance(); $parm = $request->get_parms('lng', 'error', 'confirm', 'badlog', 'postlog', 'usr', 'redirect', 'logged_out'); -if ($parm['postlog']) -{ - $session->set_postlog(true); +if ($parm['postlog']) { + $session->set_postlog(true); - return phrasea::redirect("/login/index.php?redirect=" . $parm['redirect']); + return phrasea::redirect("/login/index.php?redirect=" . $parm['redirect']); } -if (!$session->isset_postlog() && $session->is_authenticated() && $parm['error'] != 'no-connection') -{ - $parm['redirect'] = trim($parm['redirect']) == '' ? '/prod' : $parm['redirect']; +if ( ! $session->isset_postlog() && $session->is_authenticated() && $parm['error'] != 'no-connection') { + $parm['redirect'] = trim($parm['redirect']) == '' ? '/prod' : $parm['redirect']; - return phrasea::redirect($parm['redirect']); + return phrasea::redirect($parm['redirect']); } -try -{ - $conn = $appbox->get_connection(); -} -catch (Exception $e) -{ - $parm['error'] = 'no-connection'; +try { + $conn = $appbox->get_connection(); +} catch (Exception $e) { + $parm['error'] = 'no-connection'; } phrasea::headers(); @@ -60,67 +54,62 @@ $client = Browser::getInstance(); $errorWarning = $confirmWarning = ''; if ($registry->get('GV_maintenance')) - $parm['error'] = 'maintenance'; + $parm['error'] = 'maintenance'; -if ($parm['error'] !== null) -{ - switch ($parm['error']) - { - case 'auth': - $errorWarning = '
' . _('login::erreur: Erreur d\'authentification') . '
'; - break; - case 'captcha': - $errorWarning = '
' . _('login::erreur: Erreur de captcha') . '
'; - break; - case 'mailNotConfirm' : - $errorWarning = '
' . _('login::erreur: Vous n\'avez pas confirme votre email') . '
'; - if (ctype_digit($parm['usr'])) - $errorWarning .= ''; - break; - case 'no-base' : - $errorWarning = '
' . _('login::erreur: Aucune base n\'est actuellment accessible') . '
'; - break; - case 'no-connection': - $errorWarning = '
' . _('login::erreur: No available connection - Please contact sys-admin') . '
'; - break; - case 'maintenance': - $errorWarning = '
' . _('login::erreur: maintenance en cours, merci de nous excuser pour la gene occasionee') . '
'; - break; - } +if ($parm['error'] !== null) { + switch ($parm['error']) { + case 'auth': + $errorWarning = '
' . _('login::erreur: Erreur d\'authentification') . '
'; + break; + case 'captcha': + $errorWarning = '
' . _('login::erreur: Erreur de captcha') . '
'; + break; + case 'mailNotConfirm' : + $errorWarning = '
' . _('login::erreur: Vous n\'avez pas confirme votre email') . '
'; + if (ctype_digit($parm['usr'])) + $errorWarning .= ''; + break; + case 'no-base' : + $errorWarning = '
' . _('login::erreur: Aucune base n\'est actuellment accessible') . '
'; + break; + case 'no-connection': + $errorWarning = '
' . _('login::erreur: No available connection - Please contact sys-admin') . '
'; + break; + case 'maintenance': + $errorWarning = '
' . _('login::erreur: maintenance en cours, merci de nous excuser pour la gene occasionee') . '
'; + break; + } } -if ($parm['confirm'] !== null) -{ - switch ($parm['confirm']) - { - case 'ok': - $confirmWarning = '
' . _('login::register: sujet email : confirmation de votre adresse email') . '
'; - break; - case 'already': - $confirmWarning = '
' . _('login::notification: cette email est deja confirmee') . '
'; - break; - case 'mail-sent': - $confirmWarning = '
' . _('login::notification: demande de confirmation par mail envoyee') . '
'; - break; - case 'register-ok': - $confirmWarning = '
' . _('login::notification: votre email est desormais confirme') . '
'; - break; - case 'register-ok-wait': - $confirmWarning = '
' . _('login::notification: votre email est desormais confirme') . '
'; - $confirmWarning .= '
' . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . '
'; - break; - case 'password-update-ok': - $confirmWarning = '
' . _('login::notification: Mise a jour du mot de passe avec succes') . '
'; - break; - } +if ($parm['confirm'] !== null) { + switch ($parm['confirm']) { + case 'ok': + $confirmWarning = '
' . _('login::register: sujet email : confirmation de votre adresse email') . '
'; + break; + case 'already': + $confirmWarning = '
' . _('login::notification: cette email est deja confirmee') . '
'; + break; + case 'mail-sent': + $confirmWarning = '
' . _('login::notification: demande de confirmation par mail envoyee') . '
'; + break; + case 'register-ok': + $confirmWarning = '
' . _('login::notification: votre email est desormais confirme') . '
'; + break; + case 'register-ok-wait': + $confirmWarning = '
' . _('login::notification: votre email est desormais confirme') . '
'; + $confirmWarning .= '
' . _('login::register : vous serez avertis par email lorsque vos demandes seront traitees') . '
'; + break; + case 'password-update-ok': + $confirmWarning = '
' . _('login::notification: Mise a jour du mot de passe avec succes') . '
'; + break; + } } $captchaSys = ''; -if (!$registry->get('GV_maintenance') - && $registry->get('GV_captchas') - && trim($registry->get('GV_captcha_private_key')) !== '' - && trim($registry->get('GV_captcha_public_key')) !== '' - && $parm['error'] == 'captcha') -{ - $captchaSys = '
+if ( ! $registry->get('GV_maintenance') + && $registry->get('GV_captchas') + && trim($registry->get('GV_captcha_private_key')) !== '' + && trim($registry->get('GV_captcha_public_key')) !== '' + && $parm['error'] == 'captcha') { + $captchaSys = '
@@ -134,18 +123,18 @@ $public_feeds = Feed_Collection::load_public_feeds($appbox); $feeds = array_merge(array($public_feeds->get_aggregate()), $public_feeds->get_feeds()); //$twig = new supertwig(array('Escaper' => false)); - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); +$core = \bootstrap::getCore(); +$twig = $core->getTwig(); - echo $twig->render('login/index.twig', array( - 'module_name' => _('Accueil'), - 'confirmWarning' => $confirmWarning, - 'errorWarning' => $errorWarning, - 'redirect' => $parm['redirect'], - 'logged_out' => $parm['logged_out'], - 'captcha_system' => $captchaSys, - 'login' => new login(), - 'feeds' => $feeds, - 'sso' => new sso(), - 'display_layout' => $registry->get('GV_home_publi') - )); +echo $twig->render('login/index.twig', array( + 'module_name' => _('Accueil'), + 'confirmWarning' => $confirmWarning, + 'errorWarning' => $errorWarning, + 'redirect' => $parm['redirect'], + 'logged_out' => $parm['logged_out'], + 'captcha_system' => $captchaSys, + 'login' => new login(), + 'feeds' => $feeds, + 'sso' => new sso(), + 'display_layout' => $registry->get('GV_home_publi') +)); diff --git a/www/login/logout.php b/www/login/logout.php index 2a9e3ae007..6c060f638e 100644 --- a/www/login/logout.php +++ b/www/login/logout.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -23,18 +22,14 @@ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $request = http_request::getInstance(); $parm = $request->get_parms("app"); -try -{ - $appbox = appbox::get_instance($Core); - $session = $appbox->get_session(); +try { + $appbox = appbox::get_instance($Core); + $session = $appbox->get_session(); - $session->logout(); - $session->remove_cookies(); - -} -catch (Exception $e) -{ + $session->logout(); + $session->remove_cookies(); +} catch (Exception $e) { } -return phrasea::redirect("/login/?redirect=/" . $parm["app"]."&logged_out=user"); +return phrasea::redirect("/login/?redirect=/" . $parm["app"] . "&logged_out=user"); diff --git a/www/login/register-confirm.php b/www/login/register-confirm.php index 4ab460e1d3..3807390b43 100644 --- a/www/login/register-confirm.php +++ b/www/login/register-confirm.php @@ -15,55 +15,46 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; -$appbox = appbox::get_instance($Core); +$appbox = appbox::get_instance($Core); $request = http_request::getInstance(); -$parm = $request->get_parms('code'); +$parm = $request->get_parms('code'); -try -{ - $datas = random::helloToken($parm['code']); -} -catch (Exception_NotFound $e) -{ - return phrasea::redirect('/login/?redirect=/prod&error=TokenNotFound'); +try { + $datas = random::helloToken($parm['code']); +} catch (Exception_NotFound $e) { + return phrasea::redirect('/login/?redirect=/prod&error=TokenNotFound'); } $usr_id = $datas['usr_id']; $user = User_Adapter::getInstance($usr_id, $appbox); -if (!$user->get_mail_locked()) -{ - return phrasea::redirect('/login?redirect=prod&confirm=already'); +if ( ! $user->get_mail_locked()) { + return phrasea::redirect('/login?redirect=prod&confirm=already'); } $user->set_mail_locked(false); random::removeToken($parm['code']); -if (PHPMailer::ValidateAddress($user->get_email())) -{ - if (count($user->ACL()->get_granted_base()) > 0) - { - mail::mail_confirm_registered($user->get_email()); - } - $user->set_mail_locked(false); - random::removeToken($parm['code']); - - if (PHPMailer::ValidateAddress($user->get_email())) - { - $appbox_register = new appbox_register($appbox); - $list = $appbox_register->get_collection_awaiting_for_user($user); - $others = ''; - foreach ($list as $collection) - { - $others .= '
  • ' . $collection->get_name() . "
  • \n"; +if (PHPMailer::ValidateAddress($user->get_email())) { + if (count($user->ACL()->get_granted_base()) > 0) { + mail::mail_confirm_registered($user->get_email()); } + $user->set_mail_locked(false); + random::removeToken($parm['code']); - mail::mail_confirm_unregistered($user->get_email(), $others); - } + if (PHPMailer::ValidateAddress($user->get_email())) { + $appbox_register = new appbox_register($appbox); + $list = $appbox_register->get_collection_awaiting_for_user($user); + $others = ''; + foreach ($list as $collection) { + $others .= '
  • ' . $collection->get_name() . "
  • \n"; + } + + mail::mail_confirm_unregistered($user->get_email(), $others); + } } return phrasea::redirect('/login?redirect=/prod&confirm=ok'); diff --git a/www/login/register.php b/www/login/register.php index 07719d1424..738c794b61 100644 --- a/www/login/register.php +++ b/www/login/register.php @@ -17,8 +17,8 @@ /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; -$appbox = appbox::get_instance($Core); -$session = $appbox->get_session(); +$appbox = appbox::get_instance($Core); +$session = $appbox->get_session(); $registry = $appbox->get_registry(); require($registry->get('GV_RootPath') . 'lib/classes/deprecated/countries.php'); @@ -26,9 +26,8 @@ require_once($registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.ap $register_enabled = login::register_enabled(); -if (!$register_enabled) -{ - return phrasea::redirect('/login/index.php?no-register-available'); +if ( ! $register_enabled) { + return phrasea::redirect('/login/index.php?no-register-available'); } @@ -43,30 +42,30 @@ $needed = array(); * @todo ameliorer this shit */ $arrayVerif = array("form_login" => true, - "form_password" => true, - "form_password_confirm" => true, - "form_gender" => true, - "form_lastname" => true, - "form_firstname" => true, - "form_email" => true, - "form_job" => true, - "form_company" => true, - "form_activity" => true, - "form_phone" => true, - "form_fax" => true, - "form_address" => true, - "form_zip" => true, - "form_geonameid" => true, - "demand" => true); + "form_password" => true, + "form_password_confirm" => true, + "form_gender" => true, + "form_lastname" => true, + "form_firstname" => true, + "form_email" => true, + "form_job" => true, + "form_company" => true, + "form_activity" => true, + "form_phone" => true, + "form_fax" => true, + "form_address" => true, + "form_zip" => true, + "form_geonameid" => true, + "demand" => true); if (is_file($registry->get('GV_RootPath') . 'config/register-fields.php')) - include($registry->get('GV_RootPath') . 'config/register-fields.php'); + include($registry->get('GV_RootPath') . 'config/register-fields.php'); -$arrayVerif['form_login'] = true; -$arrayVerif['form_password'] = true; +$arrayVerif['form_login'] = true; +$arrayVerif['form_password'] = true; $arrayVerif['form_password_confirm'] = true; -$arrayVerif['demand'] = true; -$arrayVerif['form_email'] = true; +$arrayVerif['demand'] = true; +$arrayVerif['form_email'] = true; $lstreceiver = array(); @@ -75,596 +74,571 @@ $parm = $request->get_parms("form_login", "form_password", "form_city", "form_pa /** * @todo transactionner cette page */ -if ($request->has_post_datas()) -{ +if ($request->has_post_datas()) { - $needed = array_diff_key($arrayVerif, $request->get_post_datas()); + $needed = array_diff_key($arrayVerif, $request->get_post_datas()); - if (sizeof($needed) === 0 || (sizeof($needed) === 1 && isset($needed['form_login']) && $needed['form_login'] === true)) - { + if (sizeof($needed) === 0 || (sizeof($needed) === 1 && isset($needed['form_login']) && $needed['form_login'] === true)) { - foreach ($parm as $field => $value) - { - if (is_string($value) && isset($arrayVerif[$field]) && $arrayVerif[$field] === true) - { - if (trim($value) == '') - $needed[$field] = _('forms::ce champ est requis'); - } + foreach ($parm as $field => $value) { + if (is_string($value) && isset($arrayVerif[$field]) && $arrayVerif[$field] === true) { + if (trim($value) == '') + $needed[$field] = _('forms::ce champ est requis'); + } + } + + // 1 - on verifie les password + if ($parm['form_password'] !== $parm['form_password_confirm']) + $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); + elseif (strlen(trim($parm['form_password'])) < 8) + $needed['form_password'] = _('forms::la valeur donnee est trop courte'); + elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) + $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); + + //2 - on verifie que lemail a lair correcte si elle est requise + if (trim($parm['form_email']) != '' && ! PHPMailer::ValidateAddress($parm['form_email'])) + $needed['form_email'] = _('forms::l\'email semble invalide'); + + //on verifie le login + if (strlen($parm['form_login']) < 5) + $needed['form_login'] = _('forms::la valeur donnee est trop courte'); + + if (sizeof($needed) === 1 && isset($needed['form_login']) && $needed['form_login'] === true) { + unset($needed['form_login']); + $parm['form_login'] = $parm['form_email']; + } + + $usr_mail = mb_strtolower(trim($parm['form_email'])); + + $usr_id = User_Adapter::get_usr_id_from_email($usr_mail); + + if ($usr_id && $usr_mail !== '') + $needed['form_email'] = _('forms::un utilisateur utilisant cette adresse email existe deja'); + + $usr_id = User_Adapter::get_usr_id_from_login($parm['form_login']); + + if ($usr_id) + $needed['form_login'] = _('forms::un utilisateur utilisant ce login existe deja'); + + if ( ! isset($parm['demand']) || sizeof($parm['demand']) === 0) + $needed['demandes'] = true; + + //4 on verifieles demandes + //5 on insere l'utilisateur + + $inscriptions = giveMeBases(); + $inscOK = array(); + + if (sizeof($needed) === 0) { + + $newUsrEmail = (trim($parm['form_email']) != '') ? $parm['form_email'] : false; + + foreach ($appbox->get_databoxes() as $databox) { + $mailsBas = array(); + + $mailColl = array(); + $parm['demand'] = array_unique($parm['demand']); + foreach ($databox->get_collections() as $collection) { + if ( ! in_array($collection->get_base_id(), $parm['demand'])) + continue; + + $sbas_id = $databox->get_sbas_id(); + if (isset($inscriptions[$sbas_id]) && $inscriptions[$sbas_id]['inscript'] === true && (isset($inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()]) || isset($inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]))) + $inscOK[$collection->get_base_id()] = true; + } + } + + try { + + $user = User_Adapter::create($appbox, $parm['form_login'], $parm["form_password"], $parm["form_email"], false); + + $user->set_gender($parm['form_gender']) + ->set_firstname($parm['form_firstname']) + ->set_lastname($parm['form_lastname']) + ->set_address($parm['form_address']) + ->set_zip($parm['form_zip']) + ->set_tel($parm['form_phone']) + ->set_fax($parm['form_fax']) + ->set_job($parm['form_job']) + ->set_company($parm['form_company']) + ->set_position($parm['form_activity']) + ->set_geonameid($parm['form_geonameid']); + + $newid = $user->get_id(); + + $demandOK = array(); + + if ($registry->get('GV_autoregister')) { + $template_user_id = User_Adapter::get_usr_id_from_login('autoregister'); + + $template_user = User_Adapter::getInstance($template_user_id, appbox::get_instance($Core)); + + $base_ids = array(); + + foreach ($inscOK as $base_id => $done) { + $base_ids[] = $base_id; + } + + $user->ACL()->apply_model($template_user, $base_ids); + } + + $autoReg = $user->ACL()->get_granted_base(); + + $appbox_register = new appbox_register($appbox); + + foreach ($parm['demand'] as $base_id) { + if ( ! $inscOK[$base_id] || $user->ACL()->has_access_to_base($base_id)) { + continue; + } + $collection = collection::get_from_base_id($base_id); + $appbox_register->add_request($user, $collection); + unset($collection); + $demandOK[$base_id] = true; + } + + $event_mngr = eventsmanager_broker::getInstance($appbox, $Core); + + $params = array( + 'demand' => $demandOK + , 'autoregister' => $autoReg + , 'usr_id' => $newid + ); + + $event_mngr->trigger('__REGISTER_AUTOREGISTER__', $params); + $event_mngr->trigger('__REGISTER_APPROVAL__', $params); + + + if ($newUsrEmail) { + $user->set_mail_locked(true); + + return phrasea::redirect('/login/sendmail-confirm.php?usr_id=' . $newid); + } + + if (count($autoReg) > 0 || count($demandOK) > 0) { + if (count($autoReg) > 0) { + return phrasea::redirect('/login/index.php?confirm=register-ok'); + } else { + return phrasea::redirect('/login/index.php?confirm=register-ok-wait'); + } + } + } catch (Exception $e) { + + } + } } - - // 1 - on verifie les password - if ($parm['form_password'] !== $parm['form_password_confirm']) - $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); - elseif (strlen(trim($parm['form_password'])) < 8) - $needed['form_password'] = _('forms::la valeur donnee est trop courte'); - elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) - $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); - - //2 - on verifie que lemail a lair correcte si elle est requise - if (trim($parm['form_email']) != '' && !PHPMailer::ValidateAddress($parm['form_email'])) - $needed['form_email'] = _('forms::l\'email semble invalide'); - - //on verifie le login - if (strlen($parm['form_login']) < 5) - $needed['form_login'] = _('forms::la valeur donnee est trop courte'); - - if (sizeof($needed) === 1 && isset($needed['form_login']) && $needed['form_login'] === true) - { - unset($needed['form_login']); - $parm['form_login'] = $parm['form_email']; - } - - $usr_mail = mb_strtolower(trim($parm['form_email'])); - - $usr_id = User_Adapter::get_usr_id_from_email($usr_mail); - - if ($usr_id && $usr_mail !== '') - $needed['form_email'] = _('forms::un utilisateur utilisant cette adresse email existe deja'); - - $usr_id = User_Adapter::get_usr_id_from_login($parm['form_login']); - - if ($usr_id) - $needed['form_login'] = _('forms::un utilisateur utilisant ce login existe deja'); - - if (!isset($parm['demand']) || sizeof($parm['demand']) === 0) - $needed['demandes'] = true; - - //4 on verifieles demandes - //5 on insere l'utilisateur - - $inscriptions = giveMeBases(); - $inscOK = array(); - - if (sizeof($needed) === 0) - { - - $newUsrEmail = (trim($parm['form_email']) != '') ? $parm['form_email'] : false; - - foreach ($appbox->get_databoxes() as $databox) - { - $mailsBas = array(); - - $mailColl = array(); - $parm['demand'] = array_unique($parm['demand']); - foreach ($databox->get_collections() as $collection) - { - if (!in_array($collection->get_base_id(), $parm['demand'])) - continue; - - $sbas_id = $databox->get_sbas_id(); - if (isset($inscriptions[$sbas_id]) && $inscriptions[$sbas_id]['inscript'] === true && (isset($inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()]) || isset($inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]))) - $inscOK[$collection->get_base_id()] = true; - } - } - - try - { - - $user = User_Adapter::create($appbox, $parm['form_login'], $parm["form_password"], $parm["form_email"], false); - - $user->set_gender($parm['form_gender']) - ->set_firstname($parm['form_firstname']) - ->set_lastname($parm['form_lastname']) - ->set_address($parm['form_address']) - ->set_zip($parm['form_zip']) - ->set_tel($parm['form_phone']) - ->set_fax($parm['form_fax']) - ->set_job($parm['form_job']) - ->set_company($parm['form_company']) - ->set_position($parm['form_activity']) - ->set_geonameid($parm['form_geonameid']); - - $newid = $user->get_id(); - - $demandOK = array(); - - if ($registry->get('GV_autoregister')) - { - $template_user_id = User_Adapter::get_usr_id_from_login('autoregister'); - - $template_user = User_Adapter::getInstance($template_user_id, appbox::get_instance($Core)); - - $base_ids = array(); - - foreach ($inscOK as $base_id => $done) - { - $base_ids[] = $base_id; - } - - $user->ACL()->apply_model($template_user, $base_ids); - } - - $autoReg = $user->ACL()->get_granted_base(); - - $appbox_register = new appbox_register($appbox); - - foreach ($parm['demand'] as $base_id) - { - if (!$inscOK[$base_id] || $user->ACL()->has_access_to_base($base_id)) - { - continue; - } - $collection = collection::get_from_base_id($base_id); - $appbox_register->add_request($user, $collection); - unset($collection); - $demandOK[$base_id] = true; - } - - $event_mngr = eventsmanager_broker::getInstance($appbox, $Core); - - $params = array( - 'demand' => $demandOK - , 'autoregister' => $autoReg - , 'usr_id' => $newid - ); - - $event_mngr->trigger('__REGISTER_AUTOREGISTER__', $params); - $event_mngr->trigger('__REGISTER_APPROVAL__', $params); - - - if ($newUsrEmail) - { - $user->set_mail_locked(true); - - return phrasea::redirect('/login/sendmail-confirm.php?usr_id=' . $newid); - } - - if (count($autoReg) > 0 || count($demandOK) > 0) - { - if (count($autoReg) > 0) - { - return phrasea::redirect('/login/index.php?confirm=register-ok'); - } - else - { - return phrasea::redirect('/login/index.php?confirm=register-ok-wait'); - } - } - } - catch (Exception $e) - { - - } - } - } } phrasea::headers(); ?> - - - - - <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('login:: register') ?> - - + - - - - -
    -
    - - - - - - -
    get('GV_homeTitle') ?> - - - - - -
    -
    -
    -
    - - - - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    -
    - - - " class="input_element" name="form_login"> - - -
    -
    - - - " class="input_element password" name="form_password" id="form_password" /> - - -
    - -
    -
     
    -
    -
    -
    -
    -
    - - - " class="input_element" name="form_password_confirm"> - - -
    -
    - - -
    -
    -
    -
    - - - " class="input_element" name="form_email"> - - -
     
    - - - " value="name_from_id($parm["form_geonameid"]) ?>" class="input_element geoname_field" name="form_geonameid"> - - -
    - : - - value="0"> - value="1"> - value="2"> - - -
    - - - " class="input_element" name="form_lastname"> - - -
    - - - " class="input_element" name="form_firstname"> - - -
    - - - " class="input_element" name="form_job"> - - -
    - - - " class="input_element" name="form_activity"> - - -
    - - - " class="input_element" name="form_phone"> - - -
    - - - " class="input_element" name="form_fax"> - - -
    - - - " class="input_element" name="form_company"> - - -
    - - - " class="input_element" name="form_address"> - - -
    - - - " class="input_element" name="form_zip"> - - -
    -
    -
    - - -get('GV_autoselectDB')) -{ - ?> -
    - ", + "too-short": "", + "very-weak": "", + "weak": "", + "good": "", + "strong": "" } - ?> -
    -
    -
    + $("#register").validate( + { + rules: { + + }, + messages: { + + }, + errorPlacement: function(error, element) { + error.prependTo( element.parent().next() ); + } + } + ); + + $('#form_email').rules("add",{email:true}); + + $('#form_login').rules("add",{ + minlength: 5 + }); + + $('#form_password').rules("add",{password: "#form_login"}); + $('#form_password_confirm').rules("add",{equalTo: "#form_password"}); + + + $("#form_password").valid(); + + initialize_geoname_field($('#form_geonameid')); + }); + + + + + + +
    +
    + + + + + + +
    get('GV_homeTitle') ?> - + + + + +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + " class="input_element" name="form_login"> + + +
    +
    + + + " class="input_element password" name="form_password" id="form_password" /> + + +
    + +
    +
     
    +
    +
    +
    +
    +
    + + + " class="input_element" name="form_password_confirm"> + + +
    +
    + + +
    +
    +
    +
    + + + " class="input_element" name="form_email"> + + +
     
    + + + " value="name_from_id($parm["form_geonameid"]) ?>" class="input_element geoname_field" name="form_geonameid"> + + +
    + : + + value="0"> + value="1"> + value="2"> + + +
    + + + " class="input_element" name="form_lastname"> + + +
    + + + " class="input_element" name="form_firstname"> + + +
    + + + " class="input_element" name="form_job"> + + +
    + + + " class="input_element" name="form_activity"> + + +
    + + + " class="input_element" name="form_phone"> + + +
    + + + " class="input_element" name="form_fax"> + + +
    + + + " class="input_element" name="form_company"> + + +
    + + + " class="input_element" name="form_address"> + + +
    + + + " class="input_element" name="form_zip"> + + +
    +
    +
    get('GV_autoselectDB')) { + ?> +
    + +
    +
    + +
    + + + -
    +
    -get('GV_autoselectDB')) -{ - ?> -
    - - -
    - + get('GV_autoselectDB')) { + ?> +
    + + +
    + +
    +
    © Copyright Alchemy 2005-
    +
    -
    © Copyright Alchemy 2005-
    -
    -
    - + $('.tab').hover(function(){ + $(this).addClass('active'); + }, function(){ + $(this).removeClass('active'); + }); + - + diff --git a/www/login/reset-email.php b/www/login/reset-email.php index 39b6d2ce09..1d20372eea 100644 --- a/www/login/reset-email.php +++ b/www/login/reset-email.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -26,85 +25,78 @@ $request = http_request::getInstance(); $parm = $request->get_parms('token'); $updated = $error = false; -if (!is_null($parm['token'])) -{ - try - { - $datas = random::helloToken($parm['token']); +if ( ! is_null($parm['token'])) { + try { + $datas = random::helloToken($parm['token']); - $new_mail = $datas['datas']; - $usr_id = $datas['usr_id']; - $user = User_Adapter::getInstance($usr_id, $appbox); + $new_mail = $datas['datas']; + $usr_id = $datas['usr_id']; + $user = User_Adapter::getInstance($usr_id, $appbox); - $user->set_email($new_mail); + $user->set_email($new_mail); - random::removeToken($parm['token']); + random::removeToken($parm['token']); - phrasea::headers(); - ?> - - <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('admin::compte-utilisateur changer mon mot de passe') ?> + phrasea::headers(); + ?> + + <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('admin::compte-utilisateur changer mon mot de passe') ?> - - - - - -
    -
    - - - - -
    get('GV_homeTitle') ?>
    -
    -
    -
    + + + + + +
    +
    + + + + +
    get('GV_homeTitle') ?>
    +
    +
    +
    -
    - -
    -
    -
    - - -
    + +
    +
    +
    + + + + + <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('admin::compte-utilisateur changer mon mot de passe') ?> - return; - } - catch (Exception $e) - { + + + + + +
    +
    + + + + +
    get('GV_homeTitle') ?>
    +
    +
    +
    - ?> - - <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('admin::compte-utilisateur changer mon mot de passe') ?> - - - - - - -
    -
    - - - - -
    get('GV_homeTitle') ?>
    -
    -
    -
    - -
    getMessage() ?>
    -
    -
    -
    - - - getMessage() ?>
    +
    +
    +
    + + + require_session(); $usr_id = $session->get_usr_id(); $user = User_Adapter::getInstance($usr_id, $appbox); -if ($user->is_guest()) -{ - return; +if ($user->is_guest()) { + return; } $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); $parm = $request->get_parms('form_password', 'form_email', 'form_email_confirm'); -if (isset($parm['form_password']) && isset($parm['form_email']) && isset($parm['form_email_confirm'])) -{ - $nonce = $user->get_nonce(); - $login = $user->get_login(); +if (isset($parm['form_password']) && isset($parm['form_email']) && isset($parm['form_email_confirm'])) { + $nonce = $user->get_nonce(); + $login = $user->get_login(); - try - { - $auth = new Session_Authentication_Native($appbox, $login, $parm["form_password"]); - $auth->challenge_password(); + try { + $auth = new Session_Authentication_Native($appbox, $login, $parm["form_password"]); + $auth->challenge_password(); - if (str_replace(array("\r\n", "\r", "\n", "\t"), '_', trim($parm['form_email'])) == $parm['form_email_confirm']) - { - if (PHPMailer::ValidateAddress($parm['form_email'])) - { - if (mail::reset_email($parm['form_email'], $session->get_usr_id()) === true) - $updated = true; + if (str_replace(array("\r\n", "\r", "\n", "\t"), '_', trim($parm['form_email'])) == $parm['form_email_confirm']) { + if (PHPMailer::ValidateAddress($parm['form_email'])) { + if (mail::reset_email($parm['form_email'], $session->get_usr_id()) === true) + $updated = true; + else + $error = _('phraseanet::erreur: echec du serveur de mail'); + } + else + $error = _('forms::l\'email semble invalide'); + } else - $error = _('phraseanet::erreur: echec du serveur de mail'); - } - else - $error = _('forms::l\'email semble invalide'); + $error = _('forms::les emails ne correspondent pas'); + } catch (Exception $e) { + $error = _('admin::compte-utilisateur:ftp: Le mot de passe est errone'); } - else - $error = _('forms::les emails ne correspondent pas'); - } - catch (Exception $e) - { - $error = _('admin::compte-utilisateur:ftp: Le mot de passe est errone'); - } } phrasea::headers(); ?> - <?php echo $registry->get('GV_homeTitle') ?> - <?php echo _('admin::compte-utilisateur changer mon mot de passe') ?> - - - - + + }, + errorPlacement: function(error, element) { + error.prependTo( element.parent().next() ); + } + } + ); + }); + -
    -
    - - - - -
    get('GV_homeTitle') ?>
    -
    -
    -
    -
    -
    -
    - -
    - -
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - - +
    +
    +
    get_login() ?>
    + + +
    get('GV_homeTitle') ?>
    - - -
    -
    -
    -
    -
    - +
    +
    +
    +
    +
    + +
    + -
    +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    get_login() ?>
    + + +
    +
    +
    +
    +
    + +
    +
    -
    diff --git a/www/login/reset-password.php b/www/login/reset-password.php index b18af3e452..40aa1a14c2 100644 --- a/www/login/reset-password.php +++ b/www/login/reset-password.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -31,43 +30,37 @@ $gatekeeper = gatekeeper::getInstance($Core); $gatekeeper->require_session(); $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); -if ($user->is_guest()) -{ - phrasea::headers(403); +if ($user->is_guest()) { + phrasea::headers(403); } $needed = array(); $updated = $error = false; -if (!is_null($parm['form_old_password']) && !is_null($parm['form_password']) && !is_null($parm['form_password_confirm'])) -{ - $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); +if ( ! is_null($parm['form_old_password']) && ! is_null($parm['form_password']) && ! is_null($parm['form_password_confirm'])) { + $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); - // 1 - on verifie les password - if ($parm['form_password'] !== $parm['form_password_confirm']) - $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); - elseif (strlen(trim($parm['form_password'])) < 5) - $needed['form_password'] = _('forms::la valeur donnee est trop courte'); - elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) - $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); + // 1 - on verifie les password + if ($parm['form_password'] !== $parm['form_password_confirm']) + $needed['form_password'] = $needed['form_password_confirm'] = _('forms::les mots de passe ne correspondent pas'); + elseif (strlen(trim($parm['form_password'])) < 5) + $needed['form_password'] = _('forms::la valeur donnee est trop courte'); + elseif (trim($parm['form_password']) != str_replace(array("\r\n", "\n", "\r", "\t", " "), "_", $parm['form_password'])) + $needed['form_password'] = _('forms::la valeur donnee contient des caracteres invalides'); - if (count($needed) == 0) - { - try - { - $auth = new Session_Authentication_Native($appbox, $user->get_login(), $parm['form_old_password']); - $auth->challenge_password(); - $user->set_password($parm['form_password_confirm']); + if (count($needed) == 0) { + try { + $auth = new Session_Authentication_Native($appbox, $user->get_login(), $parm['form_old_password']); + $auth->challenge_password(); + $user->set_password($parm['form_password_confirm']); - return phrasea::redirect('/login/account.php?notice=password-update-ok'); + return phrasea::redirect('/login/account.php?notice=password-update-ok'); + } catch (Exception $e) { + $error = true; + $needed['form_old_password'] = _('admin::compte-utilisateur:ftp: Le mot de passe est errone'); + } } - catch (Exception $e) - { - $error = true; - $needed['form_old_password'] = _('admin::compte-utilisateur:ftp: Le mot de passe est errone'); - } - } } $user = User_Adapter::getInstance($session->get_usr_id(), $appbox); @@ -78,133 +71,132 @@ phrasea::headers(); - - - - - + + }); + -
    -
    - - - - -
    get('GV_homeTitle') ?>
    -
    -
    -
    - -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - - -
    get_login() ?>
    - -
    -
    -
    -
     
    -
    -
    -
    -
    -
    - - -
    -
    - ' . _('admin::compte-utilisateur A propos de la securite des mots de passe :') . '
    '; - echo '
    ' . _('admin::compte-utilisateur Les mots de passe doivent etre clairement distincts du login et contenir au moins deux types parmis les caracteres suivants :') . '
    '; - echo '
      '; - echo '
    • ' . _('admin::compte-utilisateur::securite caracteres speciaux') . '
    • '; - echo '
    • ' . _('admin::compte-utilisateur::securite caracteres majuscules') . '
    • '; - echo '
    • ' . _('admin::compte-utilisateur::securite caracteres minuscules') . '
    • '; - echo '
    • ' . _('admin::compte-utilisateur::securite caracteres numeriques') . '
    • '; - echo '
    '; - ?> +
    +
    + + + + +
    get('GV_homeTitle') ?>
    +
    +
    +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    get_login() ?>
    + +
    +
    +
    +
     
    +
    +
    +
    +
    +
    + + +
    +
    +' . _('admin::compte-utilisateur A propos de la securite des mots de passe :') . '
    '; +echo '
    ' . _('admin::compte-utilisateur Les mots de passe doivent etre clairement distincts du login et contenir au moins deux types parmis les caracteres suivants :') . '
    '; +echo '
      '; +echo '
    • ' . _('admin::compte-utilisateur::securite caracteres speciaux') . '
    • '; +echo '
    • ' . _('admin::compte-utilisateur::securite caracteres majuscules') . '
    • '; +echo '
    • ' . _('admin::compte-utilisateur::securite caracteres minuscules') . '
    • '; +echo '
    • ' . _('admin::compte-utilisateur::securite caracteres numeriques') . '
    • '; +echo '
    '; +?> +
    +
    -
    -
    diff --git a/www/login/sendmail-confirm.php b/www/login/sendmail-confirm.php index a7607c6b1d..88b59fbbf0 100644 --- a/www/login/sendmail-confirm.php +++ b/www/login/sendmail-confirm.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -24,17 +23,14 @@ $parm = $request->get_parms('usr_id'); $appbox = appbox::get_instance($Core); $confirm = ''; -try -{ - $user = User_Adapter::getInstance($parm['usr_id'], $appbox); - $usr_id = $user->get_id(); - $email = $user->get_email(); +try { + $user = User_Adapter::getInstance($parm['usr_id'], $appbox); + $usr_id = $user->get_id(); + $email = $user->get_email(); - if (mail::mail_confirmation($email, $usr_id) === true) - $confirm = 'mail-sent'; -} -catch (Exception $e) -{ + if (mail::mail_confirmation($email, $usr_id) === true) + $confirm = 'mail-sent'; +} catch (Exception $e) { } return phrasea::redirect('/login/index.php?confirm=' . $confirm); diff --git a/www/prod/chgstatus.php b/www/prod/chgstatus.php index aace071bb8..4a8a4f6a59 100644 --- a/www/prod/chgstatus.php +++ b/www/prod/chgstatus.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance(\bootstrap::getCore()); @@ -25,115 +24,102 @@ $user = $Core->getAuthenticatedUser(); $request = http_request::getInstance(); $parm = $request->get_parms( - "act" - , "lst" - , "mska" - , "msko" - , "chg_status_son" - , 'dlgW' - , 'dlgH' + "act" + , "lst" + , "mska" + , "msko" + , "chg_status_son" + , 'dlgW' + , 'dlgH' ); ?> - - - - - + + - -get_usr_id(), $appbox)->ACL(); + + get_usr_id(), $appbox)->ACL(); - if ($parm["act"] == "WORK") - { - if ($parm["chg_status_son"] == "1") - { - $lst = explode(";", $parm["lst"]); - foreach ($lst as $basrec) - { - $basrec = explode('_', $basrec); - $record = new record_adapter($basrec[0], $basrec[1]); + if ($parm["act"] == "WORK") { + if ($parm["chg_status_son"] == "1") { + $lst = explode(";", $parm["lst"]); + foreach ($lst as $basrec) { + $basrec = explode('_', $basrec); + $record = new record_adapter($basrec[0], $basrec[1]); - if ($record->is_grouping()) - { - foreach ($record->get_children() as $oneson) - { - if (!$ACL->has_right_on_base($oneson->get_base_id(), 'chgstatus')) - continue; - if ($parm["lst"] != "" && $parm["lst"] != null) - $parm["lst"].=","; - $parm["lst"] .= ';' . $oneson->get_sbas_id() . '_' . $oneson->get_record_id(); - } + if ($record->is_grouping()) { + foreach ($record->get_children() as $oneson) { + if ( ! $ACL->has_right_on_base($oneson->get_base_id(), 'chgstatus')) + continue; + if ($parm["lst"] != "" && $parm["lst"] != null) + $parm["lst"].=","; + $parm["lst"] .= ';' . $oneson->get_sbas_id() . '_' . $oneson->get_record_id(); + } + } + } + } + + $mska = $msko = null; + + $sbA = explode(';', $parm["mska"]); + $sbO = explode(';', $parm["msko"]); + + foreach ($sbA as $sbAnd) { + $sbAnd = explode('_', $sbAnd); + $mska[$sbAnd[0]] = $sbAnd[1]; + } + foreach ($sbO as $sbOr) { + $sbOr = explode('_', $sbOr); + $msko[$sbOr[0]] = $sbOr[1]; + } + + $lst = explode(";", $parm["lst"]); + $maj = 0; + foreach ($lst as $basrec) { + $basrec = explode('_', $basrec); + if (count($basrec) !== 2) + continue; + + try { + $record = new record_adapter($basrec[0], $basrec[1]); + $base_id = $record->get_base_id(); + if (isset($mska[$basrec[0]]) && isset($msko[$basrec[0]])) { + $record = new record_adapter($basrec[0], $basrec[1]); + $status = $record->get_status(); + $status = databox_status::operation_and($status, $mska[$basrec[0]]); + $status = databox_status::operation_or($status, $msko[$basrec[0]]); + $record->set_binary_status($status); + + $session->get_logger($record->get_databox()) + ->log($record, Session_Logger::EVENT_STATUS, '', ''); + + $maj ++; + unset($record); + } + } catch (Exception $e) { + + } + } + ?> +
    +
    + +
    + get_base_id(); - if (isset($mska[$basrec[0]]) && isset($msko[$basrec[0]])) - { - $record = new record_adapter($basrec[0], $basrec[1]); - $status = $record->get_status(); - $status = databox_status::operation_and($status, $mska[$basrec[0]]); - $status = databox_status::operation_or($status, $msko[$basrec[0]]); - $record->set_binary_status($status); - - $session->get_logger($record->get_databox()) - ->log($record, Session_Logger::EVENT_STATUS, '', ''); - - $maj++; - unset($record); - } - } - catch (Exception $e) - { - - } - } -?> -
    -
    - -
    - - + ?> + diff --git a/www/prod/chgtype.php b/www/prod/chgtype.php index 76788eba96..7ab7ac969b 100644 --- a/www/prod/chgtype.php +++ b/www/prod/chgtype.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -26,44 +25,37 @@ $parm = $request->get_parms("ACT", "typelst"); $user = $Core->getAuthenticatedUser(); -if ($parm['ACT'] == 'SEND') -{ - $lst = $parm['typelst']; +if ($parm['ACT'] == 'SEND') { + $lst = $parm['typelst']; - $lst = explode(';', $lst); - foreach ($lst as $el) - { - if (strlen($el) > 0) - { - $el = explode('=', $el); - if (strpos($el[0], 'img') !== false) - { - $basrec = explode('_', substr($el[0], 3)); - try - { - $record = new record_adapter($basrec[0], $basrec[1]); - $record->set_type($el[1]); - unset($record); - } - catch (Exception $e) - { + $lst = explode(';', $lst); + foreach ($lst as $el) { + if (strlen($el) > 0) { + $el = explode('=', $el); + if (strpos($el[0], 'img') !== false) { + $basrec = explode('_', substr($el[0], 3)); + try { + $record = new record_adapter($basrec[0], $basrec[1]); + $record->set_type($el[1]); + unset($record); + } catch (Exception $e) { + } + } } - } } - } -?> - - - - - -'; - echo '', _('boutton::fermer'), ''; - echo '
    '; -?> - - - + + + + + + '; + echo '', _('boutton::fermer'), ''; + echo '
    '; + ?> + + + getEntityManager(); +$em = $Core->getEntityManager(); -$appbox = appbox::get_instance($Core); -$session = $appbox->get_session(); +$appbox = appbox::get_instance($Core); +$session = $appbox->get_session(); phrasea::headers(); $request = http_request::getInstance(); -$parm = $request->get_parms("act", "lst", "SSTTID", "story"); +$parm = $request->get_parms("act", "lst", "SSTTID", "story"); -$user = $Core->getAuthenticatedUser(); +$user = $Core->getAuthenticatedUser(); ?> - - - + + + - + + + + getRepository('\Entities\Basket'); + /* @var $repository \Repositories\BasketRepository */ + + $Basket = $repository->findUserBasket($Request->get('SSTTID'), $Core->getAuthenticatedUser(), false); + + foreach ($Basket->getElements() as $basket_element) { + /* @var $basket_element \Entities\BasketElement */ + $record = $basket_element->getRecord(); + $parm['lst'][] = $record->get_serialize_key(); } - } - - function validChgType() - { - var els = getElementsByClass('sbasSelect','select'); - var X = els.length; - - var out = ''; - for(var i=0;i!=X;i++) - { - var gal = false; - if(els[i].options[els[i].selectedIndex].value != '0') - { - gal = true; - } - - var imgs = getElementsByClass('select'+els[i].id.substr(6),'select'); - var Y = imgs.length; - for(var j=0;j!=Y;j++) - { - if(gal) - out += imgs[j].id+'='+els[i].options[els[i].selectedIndex].value+";"; - else - out += imgs[j].id+'='+imgs[j].options[imgs[j].selectedIndex].value+";"; - } - - } - document.getElementById('typelst').value = out; - document.forms.formtypedoc.submit(); - } - - - - function doChgStat(do_it) - { - if(do_it) - { - var sbases = document.getElementsByName('presa'); - var A = sbases.length; - - for(var h=0;h!=A;h++) - { - calcHex(sbases[h].id.substring(4)); - } - - if(document.getElementById("cc_chg_stat_son")) - document.forms.formstatus.chg_status_son.value = document.getElementById("cc_chg_stat_son").getAttribute('status'); - - var sbOr = document.getElementsByName('preso'); - var sbAnd = document.getElementsByName('presa'); - - var X = sbOr.length; - var Y = sbAnd.length; - - var outOr=''; - var outAnd=''; - - for(var i=0;i!=X;i++) - { - outOr += outOr!=''?';':''; - outOr += sbOr[i].id.substring(4)+'_'+sbOr[i].value; - } - for(var j=0;j!=Y;j++) - { - outAnd += outAnd!=''?';':''; - outAnd += sbAnd[j].id.substring(4)+'_'+sbAnd[j].value; - } - document.getElementById('MSKA').value = outAnd; - document.getElementById('MSKO').value = outOr; - document.formstatus.submit(); - } - else - parent.hideDwnl(); - } - - var majImg=new Array(); - - function calcHex(sbas) - { - var t_and = new Array(); - var t_or = new Array(); - for(bit=0; bit<64; bit++) - { - t_and[bit] = bit<4 ? 1 : 0; // on peut clear tous les bits non nommes, sauf les 4 premiers reserves - t_or[bit] = 0; - } - var c = document.getElementsByName("cca"+sbas); - var bit; - var status; - - for(i=0; i coche - ccoch.setAttribute('status', "1"); - document.getElementById("linkoff_"+sbas+'_'+bit).setAttribute('status', "0"); - self.setTimeout("document.getElementById('cc_on_"+sbas+"_"+bit+"').src = '/skins/icons/ccoch1.gif'", 10); - self.setTimeout("document.getElementById('cc_off_"+sbas+"_"+bit+"').src = '/skins/icons/ccoch0.gif'", 10); - break; - case "1": // coche -> decoche - case "2": // grise -> decoche - ccoch.setAttribute('status', "0"); - document.getElementById("linkoff_"+sbas+'_'+bit).setAttribute('status', "1"); - self.setTimeout("document.getElementById('cc_on_"+sbas+"_"+bit+"').src = '/skins/icons/ccoch0.gif'", 10); - self.setTimeout("document.getElementById('cc_off_"+sbas+"_"+bit+"').src = '/skins/icons/ccoch1.gif'", 10); - break; - } - calcHex(sbas); - } - function evt_clk_stat_inv(ccoch) - { - evt_clk_stat(document.getElementById("linkon_"+ccoch.getAttribute('sbas')+'_'+ ccoch.getAttribute('bit') ) ); - } - - - function chksonstatus(obj) - { - if(obj.getAttribute('status')=="1") - { - obj.setAttribute('status', "0"); - obj.src = "/skins/icons/ccoch0.gif"; - } - else - { - obj.setAttribute('status', "1"); - obj.src = "/skins/icons/ccoch1.gif"; - } - - return false; - } - - - - - - getRepository('\Entities\Basket'); - /* @var $repository \Repositories\BasketRepository */ - - $Basket = $repository->findUserBasket($Request->get('SSTTID'), $Core->getAuthenticatedUser(), false); - - foreach ($Basket->getElements() as $basket_element) - { - /* @var $basket_element \Entities\BasketElement */ - $record = $basket_element->getRecord(); - $parm['lst'][] = $record->get_serialize_key(); + $parm['lst'] = implode(';', $parm['lst']); } - $parm['lst'] = implode(';', $parm['lst']); - } - if ($parm['story']) - { - $repository = $em->getRepository('\Entities\StoryWZ'); + if ($parm['story']) { + $repository = $em->getRepository('\Entities\StoryWZ'); - $Story = $repository->findByUserAndId($Core->getAuthenticatedUser(), $parm['story']); + $Story = $repository->findByUserAndId($Core->getAuthenticatedUser(), $parm['story']); - $parm['lst'] = explode(';', $parm['lst']); - $parm['lst'][] = $Story->getRecord()->get_serialize_key(); - $parm['lst'] = implode(';', $parm['lst']); - } - - $lst = liste::filter(explode(';', $parm['lst'])); - - foreach ($lst as $basrec) - { - if ($basrec && count($basrec) == 2) - { - $sbasid = $basrec[0]; - if (!isset($ndocs[$sbasid])) - $ndocs[$sbasid] = 0; - $ndocs[$sbasid]++; + $parm['lst'] = explode(';', $parm['lst']); + $parm['lst'][] = $Story->getRecord()->get_serialize_key(); + $parm['lst'] = implode(';', $parm['lst']); } - } - $types = null; + $lst = liste::filter(explode(';', $parm['lst'])); - $dstatus = databox_status::getDisplayStatus(); + foreach ($lst as $basrec) { + if ($basrec && count($basrec) == 2) { + $sbasid = $basrec[0]; + if ( ! isset($ndocs[$sbasid])) + $ndocs[$sbasid] = 0; + $ndocs[$sbasid] ++; + } + } - foreach ($lst as $onebasrec) - { - if ($onebasrec != '') - { - // on va regarder le nb de sustitution - $basrec = explode('_', $onebasrec); - if (count($basrec) !== 2) - continue; - $sbasid = $basrec[0]; - $record = new record_adapter($basrec[0], $basrec[1]); + $types = null; + + $dstatus = databox_status::getDisplayStatus(); + + foreach ($lst as $onebasrec) { + if ($onebasrec != '') { + // on va regarder le nb de sustitution + $basrec = explode('_', $onebasrec); + if (count($basrec) !== 2) + continue; + $sbasid = $basrec[0]; + $record = new record_adapter($basrec[0], $basrec[1]); - // on verifie que on a le droits de changer les status sur les collections des documents droppe + // on verifie que on a le droits de changer les status sur les collections des documents droppe - if (!isset($sbasSet[$sbasid])) - { - $types[$sbasid] = null; - $tmp_lst[$sbasid] = ''; + if ( ! isset($sbasSet[$sbasid])) { + $types[$sbasid] = null; + $tmp_lst[$sbasid] = ''; - $sbasSet[$sbasid] = true; - $tbits[$sbasid] = isset($dstatus[$sbasid]) ? $dstatus[$sbasid] : array(); - foreach ($tbits[$sbasid] as $bit => $values) - $tbits[$sbasid][$bit]['nset'] = 0; - $nrecs[$sbasid] = 0; + $sbasSet[$sbasid] = true; + $tbits[$sbasid] = isset($dstatus[$sbasid]) ? $dstatus[$sbasid] : array(); + foreach ($tbits[$sbasid] as $bit => $values) + $tbits[$sbasid][$bit]['nset'] = 0; + $nrecs[$sbasid] = 0; - $nbgrouping[$sbasid] = 0; - } + $nbgrouping[$sbasid] = 0; + } // if (!isset($types[$sbasid][$basrec[2]])) // $types[$sbasid][$basrec[2]] = null; - $types[$sbasid][$record->get_type()][] = $basrec[0] . '_' . $basrec[1]; + $types[$sbasid][$record->get_type()][] = $basrec[0] . '_' . $basrec[1]; - if ($record->is_grouping()) - { - $nbgrouping[$sbasid]++; - } - - $nrecs[$sbasid]++; - - $sta = strrev($record->get_status()); - foreach ($tbits[$sbasid] as $bit => $values) - $tbits[$sbasid][$bit]["nset"] += substr($sta, $bit, 1) != "0" ? 1 : 0; - - $tmp_lst[$sbasid] = ($tmp_lst[$sbasid] != '' ? ';' : '') . $basrec[1]; - } - } - ?> - -
    -
    - -
      -
    • -
    • -
    - -
    -
    - is_grouping()) { + $nbgrouping[$sbasid] ++; } - else - $ndocsum = 0; - foreach ($sbasSet as $sbasid => $truth) - { - echo "

    " . phrasea::sbas_names($sbasid) . "

    "; + $nrecs[$sbasid] ++; - if ($nrecs[$sbasid] == 0 && $nbgrouping[$sbasid] > 0) - echo '
    ', sprintf(_('prod::status: edition de status de %d regroupements'), $nbgrouping[$sbasid]), '
    '; - if ($nrecs[$sbasid] > 0 && $nbgrouping[$sbasid] == 0) - echo '
    ', sprintf(_('prod::status: edition de status de %d documents'), $nrecs[$sbasid]), '
    '; + $sta = strrev($record->get_status()); + foreach ($tbits[$sbasid] as $bit => $values) + $tbits[$sbasid][$bit]["nset"] += substr($sta, $bit, 1) != "0" ? 1 : 0; - foreach ($tbits[$sbasid] as $bit => $values) - $tbits[$sbasid][$bit]["status"] = $values["nset"] == 0 ? 0 : ($values["nset"] == $nrecs[$sbasid] ? 1 : 2); + $tmp_lst[$sbasid] = ($tmp_lst[$sbasid] != '' ? ';' : '') . $basrec[1]; + } + } + ?> + +
    +
    - $nsb[$sbasid] = count($tbits[$sbasid]); +
      +
    • +
    • +
    - if ($nsb[$sbasid] > 19) - echo "
    "; - else - echo "
    "; +
    + +"; +if ($sbasSet !== null) { + foreach ($nrecs as $rec) + $nrecsum += $rec; + if ($ndocs != null) { + foreach ($ndocs as $doc) + $ndocsum += $doc; + } + else + $ndocsum = 0; - foreach ($tbits[$sbasid] as $bit => $values) - { + foreach ($sbasSet as $sbasid => $truth) { + echo "

    " . phrasea::sbas_names($sbasid) . "

    "; + + if ($nrecs[$sbasid] == 0 && $nbgrouping[$sbasid] > 0) + echo '
    ', sprintf(_('prod::status: edition de status de %d regroupements'), $nbgrouping[$sbasid]), '
    '; + if ($nrecs[$sbasid] > 0 && $nbgrouping[$sbasid] == 0) + echo '
    ', sprintf(_('prod::status: edition de status de %d documents'), $nrecs[$sbasid]), '
    '; + + foreach ($tbits[$sbasid] as $bit => $values) + $tbits[$sbasid][$bit]["status"] = $values["nset"] == 0 ? 0 : ($values["nset"] == $nrecs[$sbasid] ? 1 : 2); + + $nsb[$sbasid] = count($tbits[$sbasid]); + + if ($nsb[$sbasid] > 19) + echo "
    "; + else + echo "
    "; + + echo "
    "; + + foreach ($tbits[$sbasid] as $bit => $values) { // if($tbits[$sbasid][$bit]["name"]!==null) // { - if (!isset($ndefined[$sbasid])) - $ndefined[$sbasid] = 0; - $ndefined[$sbasid]++; - $inverse = ($values["status"] == "2" ? "2" : ($values["status"] == "0" ? "1" : "0")); - echo "" . - "" . - "" . - ""; + if ( ! isset($ndefined[$sbasid])) + $ndefined[$sbasid] = 0; + $ndefined[$sbasid] ++; + $inverse = ($values["status"] == "2" ? "2" : ($values["status"] == "0" ? "1" : "0")); + echo "" . + "" . + "" . + ""; // } - } - ?> - - + } + ?> + + -
    " . - "" . - ""; - if ($values['img_off']) - echo ' '; - echo $values["labeloff"] . "" . - "" . - "" . - ""; - if ($values['img_on']) - echo ' '; - echo $values["labelon"] . "" . - "
    " . + "" . + ""; + if ($values['img_off']) + echo ' '; + echo $values["labeloff"] . "" . + "" . + "" . + ""; + if ($values['img_on']) + echo ' '; + echo $values["labelon"] . "" . + "
    -
    - 0 ? _('prod::status: remettre a zero les status non nommes') : _('prod::status: remetter a zero tous les status'); + + + 0 ? _('prod::status: remettre a zero les status non nommes') : _('prod::status: remetter a zero tous les status'); - if ($ndefined[$sbasid] == 0) - echo _('prod::status: aucun status n\'est defini sur cette base') . "
    \n"; + if ($ndefined[$sbasid] == 0) + echo _('prod::status: aucun status n\'est defini sur cette base') . "
    \n"; - echo "
    "; + echo "
    "; - if ($nbgrouping[$sbasid] > 0) - { - ?> -
    - - - - - -
    - - - -
    - 0) { + ?> +
    + + + + + +
    + + + +
    + + } elseif ($ndocs !== null) { + foreach ($ndocs as $doc) + $ndocsum += $doc; + } else { + //j'ai pas du comprendre quelque chose + } + ?> - - - - - - " /> -
    - - -
    - -
    -
    -
    -
    - $typeBR) - { - if (!$first) - echo '
    '; - $first = false; - echo '
    ' . phrasea::sbas_names($sbas_id) . "
    "; - - $arryEnum = array('document', 'flash', 'audio', 'video', 'image'); - - $selectGal = '


    '; - echo $selectGal; - unset($selectGal); + + + + + + " /> +
    + + +
    + +
    +
    +
    +
    + $typeBR) { + if ( ! $first) + echo '
    '; + $first = false; + echo '
    ' . phrasea::sbas_names($sbas_id) . "
    "; - foreach ($typeBR as $type => $BR) - { - echo '
    '; - foreach ($BR as $rec) - { - $rec2 = explode('_', $rec); - if (sizeof($rec2) == 2) - { - $sbas_id = $rec2[0]; - $record = new record_adapter($sbas_id, $rec2[1]); + $arryEnum = array('document', 'flash', 'audio', 'video', 'image'); - $dis = ''; - $class = 'select' . $sbas_id; + $selectGal = '


    '; - $select = ''; + foreach ($arryEnum as $option) { + $sel = ''; + if (trim($option) == $type) $sel = 'selected="selected"'; - $select .= ''; - } - $select .= ''; - - echo '
    Record ' . $rec2[1] . "
    "; - $thumbnail = $record->get_thumbnail(); - echo '
    '; - echo '
    ' . $select . '
    '; - flush(); - } + $select .= ''; } - echo '
    '; - } - } - ?> - - -
    - - -
    - -
    -
    + $select .= ''; - + echo '
    Record ' . $rec2[1] . "
    "; + $thumbnail = $record->get_thumbnail(); + echo '
    '; + echo '
    ' . $select . '
    '; + flush(); + } + } + echo '
    '; + } +} +?> + + +
    + + +
    + +
    +
    + + diff --git a/www/prod/prodFeedBack.php b/www/prod/prodFeedBack.php index 3c10fc256c..e54f7e3e87 100644 --- a/www/prod/prodFeedBack.php +++ b/www/prod/prodFeedBack.php @@ -16,9 +16,9 @@ * @link www.phraseanet.com */ /* @var $Core \Alchemy\Phrasea\Core */ -$Core = require_once __DIR__ . "/../../lib/bootstrap.php"; -$appbox = appbox::get_instance($Core); -$session = $appbox->get_session(); +$Core = require_once __DIR__ . "/../../lib/bootstrap.php"; +$appbox = appbox::get_instance($Core); +$session = $appbox->get_session(); $registry = $appbox->get_registry(); $user = $Core->getAuthenticatedUser(); @@ -26,330 +26,296 @@ $user = $Core->getAuthenticatedUser(); $output = ''; $request = http_request::getInstance(); -$parm = $request->get_parms('action'); +$parm = $request->get_parms('action'); $action = $parm['action']; -switch ($action) -{ - case 'search': - $engine = new searchEngine_adapter_sphinx_engine(); +switch ($action) { + case 'search': + $engine = new searchEngine_adapter_sphinx_engine(); - $parm = $request->get_parms("bas", "term" - , "stemme" - , "search_type", "recordtype", "status", "fields", "datemin", "datemax", "datefield"); + $parm = $request->get_parms("bas", "term" + , "stemme" + , "search_type", "recordtype", "status", "fields", "datemin", "datemax", "datefield"); - $options = new searchEngine_options(); + $options = new searchEngine_options(); - $parm['bas'] = is_array($parm['bas']) ? $parm['bas'] : array_keys($user->ACL()->get_granted_base()); + $parm['bas'] = is_array($parm['bas']) ? $parm['bas'] : array_keys($user->ACL()->get_granted_base()); - /* @var $user \User_Adapter */ - if ($user->ACL()->has_right('modifyrecord')) - { - $options->set_business_fields(array()); + /* @var $user \User_Adapter */ + if ($user->ACL()->has_right('modifyrecord')) { + $options->set_business_fields(array()); - $BF = array(); + $BF = array(); - foreach ($user->ACL()->get_granted_base(array('canmodifrecord')) as $collection) - { - if (count($params['bases']) === 0 || in_array($collection->get_base_id(), $params['bases'])) - { - $BF[] = $collection->get_base_id(); + 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_business_fields($BF); - } - else - { - $options->set_business_fields(array()); - } - $options->set_bases($parm['bas'], $user->ACL()); - if ( !! is_array($parm['fields'])) - $parm['fields'] = array(); - $options->set_fields($parm['fields']); - if ( ! is_array($parm['status'])) - $parm['status'] = array(); - $options->set_status($parm['status']); - $options->set_search_type($parm['search_type']); - $options->set_record_type($parm['recordtype']); - $options->set_min_date($parm['datemin']); - $options->set_max_date($parm['datemax']); - $options->set_date_fields(explode('|', $parm['datefield'])); - $options->set_use_stemming($parm['stemme']); + $options->set_bases($parm['bas'], $user->ACL()); + if ( ! ! is_array($parm['fields'])) + $parm['fields'] = array(); + $options->set_fields($parm['fields']); + if ( ! is_array($parm['status'])) + $parm['status'] = array(); + $options->set_status($parm['status']); + $options->set_search_type($parm['search_type']); + $options->set_record_type($parm['recordtype']); + $options->set_min_date($parm['datemin']); + $options->set_max_date($parm['datemax']); + $options->set_date_fields(explode('|', $parm['datefield'])); + $options->set_use_stemming($parm['stemme']); - $engine->set_options($options); - $result = $engine->results($parm['term'], 0, 1); - $res = $engine->get_suggestions($session, true); - $output = p4string::jsonencode($res); + $engine->set_options($options); + $result = $engine->results($parm['term'], 0, 1); + $res = $engine->get_suggestions($session, true); + $output = p4string::jsonencode($res); - break; + break; - case 'CSS': - require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); - $parm = $request->get_parms('color'); - $output = $user->setPrefs('css', $parm['color']); - break; + case 'CSS': + require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); + $parm = $request->get_parms('color'); + $output = $user->setPrefs('css', $parm['color']); + break; - case 'SAVETEMPPREF': - $parm = $request->get_parms('prop', 'value'); - $session->set_session_prefs($parm['prop'], $parm['value']); - $output = 1; - break; + case 'SAVETEMPPREF': + $parm = $request->get_parms('prop', 'value'); + $session->set_session_prefs($parm['prop'], $parm['value']); + $output = 1; + break; - case 'DELETE': - require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); - $parm = $request->get_parms('lst'); - $output = whatCanIDelete($parm['lst']); - break; - case 'DODELETE': - require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); - $parm = $request->get_parms('lst', 'del_children'); - $output = deleteRecord($parm['lst'], $parm['del_children']); - break; + case 'DELETE': + require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); + $parm = $request->get_parms('lst'); + $output = whatCanIDelete($parm['lst']); + break; + case 'DODELETE': + require ($registry->get('GV_RootPath') . 'lib/classes/deprecated/prodUtils.php'); + $parm = $request->get_parms('lst', 'del_children'); + $output = deleteRecord($parm['lst'], $parm['del_children']); + break; - case 'READ_NOTIFICATIONS': - try - { - $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); - $parm = $request->get_parms('notifications'); - $output = $evt_mngr->read(explode('_', $parm['notifications']), $session->get_usr_id()); - $output = p4string::jsonencode(array('error' => false, 'message' => '')); - } - catch (Exception $e) - { - $output = p4string::jsonencode(array('error' => true, 'message' => $e->getMessage())); - } - break; - case 'NOTIFICATIONS_FULL': - $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); - $parm = $request->get_parms('page'); - $output = $evt_mngr->get_json_notifications($parm['page']); - break; + case 'READ_NOTIFICATIONS': + try { + $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); + $parm = $request->get_parms('notifications'); + $output = $evt_mngr->read(explode('_', $parm['notifications']), $session->get_usr_id()); + $output = p4string::jsonencode(array('error' => false, 'message' => '')); + } catch (Exception $e) { + $output = p4string::jsonencode(array('error' => true, 'message' => $e->getMessage())); + } + break; + case 'NOTIFICATIONS_FULL': + $evt_mngr = eventsmanager_broker::getInstance($appbox, $Core); + $parm = $request->get_parms('page'); + $output = $evt_mngr->get_json_notifications($parm['page']); + break; - case 'VIDEOTOKEN': - $parm = $request->get_parms( ! 'sbas_id', 'record_id'); - $sbas_id = (int) $parm['sbas_id']; - $record = new record_adapter($sbas_id, $parm['record_id']); + case 'VIDEOTOKEN': + $parm = $request->get_parms( ! 'sbas_id', 'record_id'); + $sbas_id = (int) $parm['sbas_id']; + $record = new record_adapter($sbas_id, $parm['record_id']); - $output = p4string::jsonencode(array('url' => $record->get_preview()->renew_url())); - break; + $output = p4string::jsonencode(array('url' => $record->get_preview()->renew_url())); + break; - case 'ANSWERTRAIN': - $parm = $request->get_parms('pos', 'record_id', 'options_serial', 'query'); + case 'ANSWERTRAIN': + $parm = $request->get_parms('pos', 'record_id', 'options_serial', 'query'); - $search_engine = null; - if (($options = unserialize($parm['options_serial'])) !== false) - { - $search_engine = new searchEngine_adapter($registry); - $search_engine->set_options($options); - } + $search_engine = null; + if (($options = unserialize($parm['options_serial'])) !== false) { + $search_engine = new searchEngine_adapter($registry); + $search_engine->set_options($options); + } - $record = new record_preview('RESULT', $parm['pos'], '', '', $search_engine, $parm['query']); - $records = $record->get_train($parm['pos'], $parm['query'], $search_engine); - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); - $output = p4string::jsonencode( - array('current' => - $twig->render( - 'prod/preview/result_train.html', array( - 'records' => $records - , 'selected' => $parm['pos']) - ) - ) - ); - break; + $record = new record_preview('RESULT', $parm['pos'], '', '', $search_engine, $parm['query']); + $records = $record->get_train($parm['pos'], $parm['query'], $search_engine); + $core = \bootstrap::getCore(); + $twig = $core->getTwig(); + $output = p4string::jsonencode( + array('current' => + $twig->render( + 'prod/preview/result_train.html', array( + 'records' => $records + , 'selected' => $parm['pos']) + ) + ) + ); + break; - case 'REGTRAIN': - $parm = $request->get_parms('cont', 'pos'); - $record = new record_preview('REG', $parm['pos'], $parm['cont']); - $output = $twig->render('prod/preview/reg_train.html', array('container_records' => $record->get_container()->get_children(), - 'record' => $record)); - break; + case 'REGTRAIN': + $parm = $request->get_parms('cont', 'pos'); + $record = new record_preview('REG', $parm['pos'], $parm['cont']); + $output = $twig->render('prod/preview/reg_train.html', array('container_records' => $record->get_container()->get_children(), + 'record' => $record)); + break; - case 'GET_ORDERMANAGER': - try - { - $parm = $request->get_parms('sort', 'page'); - $orders = new set_ordermanager($parm['sort'], $parm['page']); + case 'GET_ORDERMANAGER': + try { + $parm = $request->get_parms('sort', 'page'); + $orders = new set_ordermanager($parm['sort'], $parm['page']); - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); + $core = \bootstrap::getCore(); + $twig = $core->getTwig(); - $render = $twig->render('prod/orders/order_box.twig', array('ordermanager' => $orders)); - $ret = array('error' => false, 'datas' => $render); - } - catch (Exception $e) - { - $ret = array('error' => true, 'datas' => $e->getMessage()); - } + $render = $twig->render('prod/orders/order_box.twig', array('ordermanager' => $orders)); + $ret = array('error' => false, 'datas' => $render); + } catch (Exception $e) { + $ret = array('error' => true, 'datas' => $e->getMessage()); + } - $output = p4string::jsonencode($ret); - break; + $output = p4string::jsonencode($ret); + break; - case 'GET_ORDER': - try - { - $parm = $request->get_parms('order_id'); - $order = new set_order($parm['order_id']); + case 'GET_ORDER': + try { + $parm = $request->get_parms('order_id'); + $order = new set_order($parm['order_id']); - $core = \bootstrap::getCore(); - $twig = $core->getTwig(); + $core = \bootstrap::getCore(); + $twig = $core->getTwig(); - $render = $twig->render('prod/orders/order_item.twig', array('order' => $order)); - $ret = array('error' => false, 'datas' => $render); - } - catch (Exception $e) - { - $ret = array('error' => true, 'datas' => $e->getMessage()); - } + $render = $twig->render('prod/orders/order_item.twig', array('order' => $order)); + $ret = array('error' => false, 'datas' => $render); + } catch (Exception $e) { + $ret = array('error' => true, 'datas' => $e->getMessage()); + } - $output = p4string::jsonencode($ret); - break; + $output = p4string::jsonencode($ret); + break; - case 'SEND_ORDER': - try - { - $parm = $request->get_parms('order_id', 'elements', 'force'); - $order = new set_order($parm['order_id']); - $order->send_elements($parm['elements'], $parm['force']); - $ret = array('error' => false, 'datas' => ''); - } - catch (Exception $e) - { - $ret = array('error' => true, 'datas' => $e->getMessage()); - } + case 'SEND_ORDER': + try { + $parm = $request->get_parms('order_id', 'elements', 'force'); + $order = new set_order($parm['order_id']); + $order->send_elements($parm['elements'], $parm['force']); + $ret = array('error' => false, 'datas' => ''); + } catch (Exception $e) { + $ret = array('error' => true, 'datas' => $e->getMessage()); + } - $output = p4string::jsonencode($ret); - break; + $output = p4string::jsonencode($ret); + break; - case 'DENY_ORDER': - try - { - $parm = $request->get_parms('order_id', 'elements'); - $order = new set_order($parm['order_id']); - $order->deny_elements($parm['elements']); - $ret = array('error' => false, 'datas' => ''); - } - catch (Exception $e) - { - $ret = array('error' => true, 'datas' => $e->getMessage()); - } + case 'DENY_ORDER': + try { + $parm = $request->get_parms('order_id', 'elements'); + $order = new set_order($parm['order_id']); + $order->deny_elements($parm['elements']); + $ret = array('error' => false, 'datas' => ''); + } catch (Exception $e) { + $ret = array('error' => true, 'datas' => $e->getMessage()); + } - $output = p4string::jsonencode($ret); - break; + $output = p4string::jsonencode($ret); + break; - case "ORDER": - $parm = $request->get_parms('lst', 'ssttid', 'use', 'deadline'); - $order = new set_exportorder($parm['lst'], $parm['ssttid']); + case "ORDER": + $parm = $request->get_parms('lst', 'ssttid', 'use', 'deadline'); + $order = new set_exportorder($parm['lst'], $parm['ssttid']); - if ($order->order_available_elements($session->get_usr_id(), $parm['use'], $parm['deadline'])) - { - $ret = array('error' => false, 'message' => _('les enregistrements ont ete correctement commandes')); - } - else - { - $ret = array('error' => true, 'message' => _('Erreur lors de la commande des enregistrements')); - } + if ($order->order_available_elements($session->get_usr_id(), $parm['use'], $parm['deadline'])) { + $ret = array('error' => false, 'message' => _('les enregistrements ont ete correctement commandes')); + } else { + $ret = array('error' => true, 'message' => _('Erreur lors de la commande des enregistrements')); + } - $output = p4string::jsonencode($ret); + $output = p4string::jsonencode($ret); - break; - case "FTP_EXPORT": + break; + case "FTP_EXPORT": - $request = http_request::getInstance(); - $parm = $request->get_parms( - "addr" // addr du srv ftp - , "login" // login ftp - , "pwd" // pwd ftp - , "passif" // mode passif ou non - , "nbretry" // nb retry - , "ssl" // nb retry - , "obj" // les types d'obj a exporter - , "destfolder"// le folder de destination - , "usr_dest" // le mail dudestinataire ftp - , "lst" // la liste des objets - , "ssttid" - , "sendermail" - , "namecaract" - , "NAMMKDFOLD" - , "logfile" - , "businessfields" - ); - - $download = new set_exportftp($parm['lst'], $parm['ssttid']); - - if (count($download->get_display_ftp()) == 0) - { - $output = p4string::jsonencode(array('error' => true, 'message' => _('Les documents ne peuvent etre envoyes par FTP'))); - } - else - { - try - { - $download->prepare_export($parm['obj'], false, $parm['businessfields']); - $download->export_ftp( - $parm['usr_dest'] - , $parm['addr'] - , $parm['login'] - , $parm['pwd'] - , $parm['ssl'] - , $parm['nbretry'] - , $parm['passif'] - , $parm['destfolder'] - , $parm['NAMMKDFOLD'] - , $parm['logfile'] + $request = http_request::getInstance(); + $parm = $request->get_parms( + "addr" // addr du srv ftp + , "login" // login ftp + , "pwd" // pwd ftp + , "passif" // mode passif ou non + , "nbretry" // nb retry + , "ssl" // nb retry + , "obj" // les types d'obj a exporter + , "destfolder"// le folder de destination + , "usr_dest" // le mail dudestinataire ftp + , "lst" // la liste des objets + , "ssttid" + , "sendermail" + , "namecaract" + , "NAMMKDFOLD" + , "logfile" + , "businessfields" ); - $out = array( - 'error' => false - , 'message' => _('Export enregistre dans la file dattente') + $download = new set_exportftp($parm['lst'], $parm['ssttid']); + + if (count($download->get_display_ftp()) == 0) { + $output = p4string::jsonencode(array('error' => true, 'message' => _('Les documents ne peuvent etre envoyes par FTP'))); + } else { + try { + $download->prepare_export($parm['obj'], false, $parm['businessfields']); + $download->export_ftp( + $parm['usr_dest'] + , $parm['addr'] + , $parm['login'] + , $parm['pwd'] + , $parm['ssl'] + , $parm['nbretry'] + , $parm['passif'] + , $parm['destfolder'] + , $parm['NAMMKDFOLD'] + , $parm['logfile'] + ); + + $out = array( + 'error' => false + , 'message' => _('Export enregistre dans la file dattente') + ); + + $output = p4string::jsonencode($out); + } catch (Exception $e) { + $output = p4string::jsonencode(array('error' => true, 'message' => $e->getMessage())); + } + } + break; + case "FTP_TEST": + + $request = http_request::getInstance(); + $parm = $request->get_parms( + "addr" // addr du srv ftp + , "login" // login ftp + , "pwd" // pwd ftp + , "ssl" // nb retry ); - $output = p4string::jsonencode($out); - } - catch (Exception $e) - { - $output = p4string::jsonencode(array('error' => true, 'message' => $e->getMessage())); - } - } - break; - case "FTP_TEST": + $ssl = $parm['ssl'] == '1'; - $request = http_request::getInstance(); - $parm = $request->get_parms( - "addr" // addr du srv ftp - , "login" // login ftp - , "pwd" // pwd ftp - , "ssl" // nb retry - ); + try { + $ftp_client = new ftpclient($parm['addr'], 21, 90, $ssl = false); + $ftp_client->login($parm['login'], $parm['pwd']); + $ftp_client->close(); + $output = _('Connection au FTP avec succes'); + } catch (Exception $e) { + $output = sprintf(_('Erreur lors de la connection au FTP : %s'), $e->getMessage()); + } - $ssl = $parm['ssl'] == '1'; - - try - { - $ftp_client = new ftpclient($parm['addr'], 21, 90, $ssl = false); - $ftp_client->login($parm['login'], $parm['pwd']); - $ftp_client->close(); - $output = _('Connection au FTP avec succes'); - } - catch (Exception $e) - { - $output = sprintf(_('Erreur lors de la connection au FTP : %s'), $e->getMessage()); - } - - break; + break; } echo $output; diff --git a/www/prod/publish.php b/www/prod/publish.php index 55da404848..0eb3b68ddb 100644 --- a/www/prod/publish.php +++ b/www/prod/publish.php @@ -18,20 +18,14 @@ require_once __DIR__ . "/../../lib/bootstrap.php"; $message = ''; -try -{ - $pub = new action_publish(http_request::getInstance()); +try { + $pub = new action_publish(http_request::getInstance()); +} catch (Exception $e) { + $message = $e->getMessage(); } -catch (Exception $e) -{ - $message = $e->getMessage(); -} -try -{ - $pub->render($message); -} -catch (Exception $e) -{ - echo $e->getMessage(); +try { + $pub->render($message); +} catch (Exception $e) { + echo $e->getMessage(); } ?> diff --git a/www/prod/share.php b/www/prod/share.php index c891e46b12..973076b1cf 100644 --- a/www/prod/share.php +++ b/www/prod/share.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(); @@ -31,129 +30,120 @@ $right = false; ?> - - - - + + + + - - + }); + + - -
    -
    + +
    +
    -
    +
    + ACL()->has_right_on_sbas($sbas_id, 'bas_chupub') + && $user->ACL()->has_access_to_subdef($record, 'preview')); + + if ( ! $right) + exit('ERROR
    '); + + + $sha256 = $record->get_sha256(); + $type = $record->get_type(); + + $url = ''; + + $url = $record->get_preview()->get_permalink()->get_url(); + + $embed = ''; + + if ($url != '') { + switch ($type) { + case 'video': + $embed = '' . + '' . + '' . + '' . + '' . + '' . + '' . + ''; + break; + case 'document': + $embed = '' . + '' . + '' . + '' . + '' . + ''; + break; + case 'audio': + $embed = '' . + '' . + '' . + '' . + '' . + ''; + break; + case 'image': + default: + $embed = ''; + break; + } + } + ?> +
    + +
    +
    URL :
    ACL()->has_right_on_sbas($sbas_id, 'bas_chupub') - && $user->ACL()->has_access_to_subdef($record, 'preview')); - -if (!$right) - exit('ERROR
    '); +if ($url != '') { + ?> + + +
    + +
    Embed :
    + + + +
    + +
    -$sha256 = $record->get_sha256(); -$type = $record->get_type(); - -$url = ''; - -$url = $record->get_preview()->get_permalink()->get_url() ; - -$embed = ''; - -if ($url != '') -{ - switch ($type) - { - case 'video': - $embed = '' . - '' . - '' . - '' . - '' . - '' . - '' . - ''; - break; - case 'document': - $embed = '' . - '' . - '' . - '' . - '' . - ''; - break; - case 'audio': - $embed = '' . - '' . - '' . - '' . - '' . - ''; - break; - case 'image': - default: - $embed = ''; - break; - } -} -?> -
    -
    -
    -
    URL :
    - - - -
    - -
    Embed :
    - - - -
    - -
    - - -
    - -
    -
    -
    - + diff --git a/www/report/ajax_chart.php b/www/report/ajax_chart.php index 3e4991c523..1e13ef5e5f 100644 --- a/www/report/ajax_chart.php +++ b/www/report/ajax_chart.php @@ -26,9 +26,9 @@ $id = $parm['id']; $dashboard = new module_report_dashboard($Core->getAuthenticatedUser()->get_id()); $var = array( - 'rs' => $dashboard->dashboard['activity_day'][$id], - 'legendDay' => $dashboard->legendDay, - "sbas_id" => $id, + 'rs' => $dashboard->dashboard['activity_day'][$id], + 'legendDay' => $dashboard->legendDay, + "sbas_id" => $id, 'ajax_chart' => true ); diff --git a/www/report/ajax_info_dashboard.php b/www/report/ajax_info_dashboard.php index ba074076d5..726c555d84 100644 --- a/www/report/ajax_info_dashboard.php +++ b/www/report/ajax_info_dashboard.php @@ -15,43 +15,38 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $user = $Core->getAuthenticatedUser(); -if (!$user->ACL()->has_right('report')) - phrasea::headers(403); +if ( ! $user->ACL()->has_right('report')) + phrasea::headers(403); $sbasid = isset($_POST['sbasid']) ? $_POST['sbasid'] : null; $dmin = isset($_POST['dmin']) ? $_POST['dmin'] : false; $dmax = isset($_POST['dmax']) ? $_POST['dmax'] : false; ///////Construct dashboard -try -{ - $dashboard = new module_report_dashboard($user, $sbasid); +try { + $dashboard = new module_report_dashboard($user, $sbasid); - if ($dmin && $dmax) - { - $dashboard->setDate($dmin, $dmax); - } + if ($dmin && $dmax) { + $dashboard->setDate($dmin, $dmax); + } - $dashboard->execute(); -} -catch (Exception $e) -{ - echo 'Exception reçue : ', $e->getMessage(), "\n"; + $dashboard->execute(); +} catch (Exception $e) { + echo 'Exception reçue : ', $e->getMessage(), "\n"; } $twig = $Core->getTwig(); $html = $twig->render( - "report/ajax_dashboard_content_child.twig", array( + "report/ajax_dashboard_content_child.twig", array( 'dashboard' => $dashboard - ) + ) ); $t = array('html' => $html); diff --git a/www/report/ajax_liste_base.php b/www/report/ajax_liste_base.php index 3d5d507c00..154cd3f09a 100644 --- a/www/report/ajax_liste_base.php +++ b/www/report/ajax_liste_base.php @@ -19,30 +19,30 @@ require_once __DIR__ . "/../../lib/bootstrap.php"; $request = http_request::getInstance(); $parm = $request->get_parms( - "dmin" - , "dmax" - , "baslst" - , "popbases" - , "tbl" - , "precise" - , "preciseWord" - , "preciseUser" - , "page" - , "limit" - , "fonction" - , "pays" - , "societe" - , "activite" - , "on" + "dmin" + , "dmax" + , "baslst" + , "popbases" + , "tbl" + , "precise" + , "preciseWord" + , "preciseUser" + , "page" + , "limit" + , "fonction" + , "pays" + , "societe" + , "activite" + , "on" ); extract($parm); /* Initialise les dates par defaults min au 1er jour du mois courant et max a la date courante */ if ($parm['dmin'] == "") - $parm['dmin'] = "01-" . date("m") . "-" . date("Y"); + $parm['dmin'] = "01-" . date("m") . "-" . date("Y"); if ($parm['dmax'] == "") - $parm['dmax'] = date("d") . "-" . date("m") . "-" . date("Y"); + $parm['dmax'] = date("d") . "-" . date("m") . "-" . date("Y"); $td = explode("-", $parm['dmin']); $parm['dmin'] = date('Y-m-d H:i:s', mktime(0, 0, 0, $td[1], $td[0], $td[2])); @@ -56,18 +56,16 @@ $popbases = array_fill_keys($popbases, 0); $liste = ''; $i = 0; $id_sbas = ""; -foreach ($popbases as $key => $val) -{ - $exp = explode("_", $key); - if ($exp[0] != $id_sbas && $i != 0) - { - $selection[$id_sbas]['liste'] = $liste; - $liste = ''; - } - $selection[$exp[0]][] = $exp[1]; - $liste .= ( empty($liste) ? '' : ',') . $exp[1]; - $id_sbas = $exp[0]; - $i++; +foreach ($popbases as $key => $val) { + $exp = explode("_", $key); + if ($exp[0] != $id_sbas && $i != 0) { + $selection[$id_sbas]['liste'] = $liste; + $liste = ''; + } + $selection[$exp[0]][] = $exp[1]; + $liste .= ( empty($liste) ? '' : ',') . $exp[1]; + $id_sbas = $exp[0]; + $i ++; } //fill the last entry $selection[$id_sbas]['liste'] = $liste; @@ -78,4 +76,4 @@ $registry = registry::get_instance(); $core = \bootstrap::getCore(); $twig = $core->getTwig(); -echo $twig->render('liste_base.twig', array('selection' => $selection, 'param' => $parm)); +echo $twig->render('liste_base.twig', array('selection' => $selection, 'param' => $parm)); diff --git a/www/report/ajax_table_content.php b/www/report/ajax_table_content.php index 481dba74f2..ad421ed8fc 100644 --- a/www/report/ajax_table_content.php +++ b/www/report/ajax_table_content.php @@ -90,692 +90,649 @@ $conf_info_usr = array( function getFilterField($param) { - $filter_column = explode(' ', $param['filter_column']); - $column = $filter_column[0]; + $filter_column = explode(' ', $param['filter_column']); + $column = $filter_column[0]; - return $column; + return $column; } function doOrder($obj, $param) { - (!empty($param['order']) && !empty($param['champ'])) ? $obj->setOrder($param['champ'], $param['order']) : ""; + ( ! empty($param['order']) && ! empty($param['champ'])) ? $obj->setOrder($param['champ'], $param['order']) : ""; } function doLimit($obj, $param) { - (!empty($param['page']) && !empty($param['limit'])) ? $obj->setLimit($param['page'], $param['limit']) : ""; + ( ! empty($param['page']) && ! empty($param['limit'])) ? $obj->setLimit($param['page'], $param['limit']) : ""; } function doFilter($obj, $param, $twig) { - $cor = $obj->getTransQueryString(); - $currentfilter = unserializeFilter($param['liste_filter']); - $filter = new module_report_filter($currentfilter, $cor); + $cor = $obj->getTransQueryString(); + $currentfilter = unserializeFilter($param['liste_filter']); + $filter = new module_report_filter($currentfilter, $cor); - if (!empty($param['filter_column'])) - { - $field = getFilterField($param); - $value = $param['filter_value']; + if ( ! empty($param['filter_column'])) { + $field = getFilterField($param); + $value = $param['filter_value']; - if ($param['liste'] == "on") - { - $tab = $obj->colFilter($field); - displayColValue($tab, $field, $twig); + if ($param['liste'] == "on") { + $tab = $obj->colFilter($field); + displayColValue($tab, $field, $twig); + } + + if ($field == $value) + $filter->removeFilter($field); + else + $filter->addFilter($field, '=', $value); } - if ($field == $value) - $filter->removeFilter($field); - else - $filter->addFilter($field, '=', $value); - } - - return $filter; + return $filter; } function passFilter($filter, $obj) { - $tab_filter = $filter->getTabFilter(); - $obj->setFilter($tab_filter); + $tab_filter = $filter->getTabFilter(); + $obj->setFilter($tab_filter); } function doPreff($conf, $param) { - $pref = module_report::getPreff($param['sbasid']); - foreach ($pref as $key => $field) - $conf_pref[$field] = array($field, 0, 0, 0, 0); - $conf = array_merge($conf, $conf_pref); - - return $conf; -} - -function doReport($obj, $param, $conf, $twig, $what = false) -{ - $conf = doUserConf($conf, $param); - displayListColumn($conf, $param, $twig); - doOrder($obj, $param); - - $filter = doFilter($obj, $param, $twig); - passFilter($filter, $obj); - $posting_filter = $filter->getPostingFilter(); - $active_column = $filter->getActiveColumn(); - - if ($param['precise'] == 1) - $dl->addfilter('xml', 'LIKE', $param['word']); - elseif ($param['precise'] == 2) - $dl->addfilter('record_id', '=', $param['word']); - - groupBy($obj, $param, $twig); - doLimit($obj, $param); - - if (!$what) - $tab = $obj->buildTab($conf); - else - $tab = $obj->buildTab($conf, $what, $param['tbl']); - - return (array('rs' => $tab, 'filter' => $posting_filter, 'column' => $active_column)); -} - -function doHtml($report, $param, $twig, $template, $type = false) -{ - $var = array( - 'result' => (isset($report['rs'])) ? $report['rs'] : $report, - 'report' => $report, - 'currentfilter' => isset($report['filter']) ? $report['filter'] : "", - 'param' => $param, - 'is_infouser' => false, - 'is_nav' => false, - 'is_groupby' => false, - 'is_plot' => false, - 'meta' => true - ); - - if ($type) - { - switch ($type) - { - case "user" : - $var['is_infouser'] = true; - break; - case "nav" : - $var['is_nav'] = true; - break; - case "group" : - $var['is_groupby'] = true; - break; - case "plot" : - $var['is_plot'] = true; - break; - } - } - - return ($twig->render($template, $var)); -} - -function sendReport($html, $report = false, $title = false, $display_nav = false) -{ - if ($report) - { - $t = array( - 'rs' => $html, - 'next' => intval($report['rs']['next_page']), //Number of the next page - 'prev' => intval($report['rs']['previous_page']), //Number of the previoous page - 'page' => intval($report['rs']['page']), //The current page - 'limit' => $report['rs']['nb_record'] - ); - } - else - { - $t = array( - 'rs' => $html, - 'display_nav' => $display_nav, - 'title' => $title - ); - } - echo json_encode($t); -} - -function getBasId($param) -{ - try - { - $record = new record_adapter($param['sbasid'], $param['rid']); - - return $record->get_base_id(); - } - catch (Exception $e) - { - - } - - return false; -} - -function unserializeFilter($serialized_filter) -{ - $tab_filter = array(); - if (!empty($serialized_filter)) - { - $tab_filter = @unserialize(urldecode($serialized_filter)); - } - - return $tab_filter; -} - -function doUserConf($conf, $param) -{ - $registry = registry::get_instance(); - if ($registry->get('GV_anonymousReport') == true) - { - if (isset($conf['user'])) - unset($conf['user']); - if (isset($conf['ip'])) - unset($conf['ip']); - } - - if (!empty($param['list_column'])) - { - $new_conf = array(); - $new_conf = $conf; - $x = explode(",", $param['list_column']); - - foreach ($conf as $key => $value) - { - if (!in_array($key, $x)) - unset($new_conf[$key]); - } - - return $new_conf; - } - else + $pref = module_report::getPreff($param['sbasid']); + foreach ($pref as $key => $field) + $conf_pref[$field] = array($field, 0, 0, 0, 0); + $conf = array_merge($conf, $conf_pref); return $conf; } +function doReport($obj, $param, $conf, $twig, $what = false) +{ + $conf = doUserConf($conf, $param); + displayListColumn($conf, $param, $twig); + doOrder($obj, $param); + + $filter = doFilter($obj, $param, $twig); + passFilter($filter, $obj); + $posting_filter = $filter->getPostingFilter(); + $active_column = $filter->getActiveColumn(); + + if ($param['precise'] == 1) + $dl->addfilter('xml', 'LIKE', $param['word']); + elseif ($param['precise'] == 2) + $dl->addfilter('record_id', '=', $param['word']); + + groupBy($obj, $param, $twig); + doLimit($obj, $param); + + if ( ! $what) + $tab = $obj->buildTab($conf); + else + $tab = $obj->buildTab($conf, $what, $param['tbl']); + + return (array('rs' => $tab, 'filter' => $posting_filter, 'column' => $active_column)); +} + +function doHtml($report, $param, $twig, $template, $type = false) +{ + $var = array( + 'result' => (isset($report['rs'])) ? $report['rs'] : $report, + 'report' => $report, + 'currentfilter' => isset($report['filter']) ? $report['filter'] : "", + 'param' => $param, + 'is_infouser' => false, + 'is_nav' => false, + 'is_groupby' => false, + 'is_plot' => false, + 'meta' => true + ); + + if ($type) { + switch ($type) { + case "user" : + $var['is_infouser'] = true; + break; + case "nav" : + $var['is_nav'] = true; + break; + case "group" : + $var['is_groupby'] = true; + break; + case "plot" : + $var['is_plot'] = true; + break; + } + } + + return ($twig->render($template, $var)); +} + +function sendReport($html, $report = false, $title = false, $display_nav = false) +{ + if ($report) { + $t = array( + 'rs' => $html, + 'next' => intval($report['rs']['next_page']), //Number of the next page + 'prev' => intval($report['rs']['previous_page']), //Number of the previoous page + 'page' => intval($report['rs']['page']), //The current page + 'limit' => $report['rs']['nb_record'] + ); + } else { + $t = array( + 'rs' => $html, + 'display_nav' => $display_nav, + 'title' => $title + ); + } + echo json_encode($t); +} + +function getBasId($param) +{ + try { + $record = new record_adapter($param['sbasid'], $param['rid']); + + return $record->get_base_id(); + } catch (Exception $e) { + + } + + return false; +} + +function unserializeFilter($serialized_filter) +{ + $tab_filter = array(); + if ( ! empty($serialized_filter)) { + $tab_filter = @unserialize(urldecode($serialized_filter)); + } + + return $tab_filter; +} + +function doUserConf($conf, $param) +{ + $registry = registry::get_instance(); + if ($registry->get('GV_anonymousReport') == true) { + if (isset($conf['user'])) + unset($conf['user']); + if (isset($conf['ip'])) + unset($conf['ip']); + } + + if ( ! empty($param['list_column'])) { + $new_conf = array(); + $new_conf = $conf; + $x = explode(",", $param['list_column']); + + foreach ($conf as $key => $value) { + if ( ! in_array($key, $x)) + unset($new_conf[$key]); + } + + return $new_conf; + } + else + return $conf; +} + function displayListColumn($conf, $param, $twig) { - if ($param['conf'] == "on") - { - $html = $twig->render('report/listColumn.twig', array( - 'conf' => $conf, - 'param' => $param, + if ($param['conf'] == "on") { + $html = $twig->render('report/listColumn.twig', array( + 'conf' => $conf, + 'param' => $param, )); - $t = array('liste' => $html, "title" => _("configuration")); - echo json_encode($t); - exit(); - } + $t = array('liste' => $html, "title" => _("configuration")); + echo json_encode($t); + exit(); + } } function groupBy($obj, $param, $twig, $on = false) { - //Contains the name of the column where the group by is applied - (!empty($param['groupby']) ? $groupby = explode(' ', $param['groupby']) : $groupby = false); - //If users ask for group by, display the good array, result is encoded in Json , exit the function. - if ($groupby) - { - $report = $obj->buildTab(false, $groupby[0], $on); - $html = doHtml($report, $param, $twig, 'report/report.twig', 'group'); - $title = "Groupement des resultats sur le champ " . $report['display'][$report['allChamps'][0]]['title']; - sendReport($html, false, $title); - exit(); - } + //Contains the name of the column where the group by is applied + ( ! empty($param['groupby']) ? $groupby = explode(' ', $param['groupby']) : $groupby = false); + //If users ask for group by, display the good array, result is encoded in Json , exit the function. + if ($groupby) { + $report = $obj->buildTab(false, $groupby[0], $on); + $html = doHtml($report, $param, $twig, 'report/report.twig', 'group'); + $title = "Groupement des resultats sur le champ " . $report['display'][$report['allChamps'][0]]['title']; + sendReport($html, false, $title); + exit(); + } } function displayColValue($tab, $column, $twig, $on = false) { - $test = $twig->render('report/colFilter.twig', array( - 'result' => $tab, - 'field' => $column - )); - $t = array('diag' => $test, "title" => sprintf(_("filtrer les resultats sur la colonne %s"), $column)); - echo json_encode($t); - exit(); + $test = $twig->render('report/colFilter.twig', array( + 'result' => $tab, + 'field' => $column + )); + $t = array('diag' => $test, "title" => sprintf(_("filtrer les resultats sur la colonne %s"), $column)); + echo json_encode($t); + exit(); } function getHistory($obj, $param, $twig, $conf, $dl = false, $title) { - $filter = doFilter($obj, $param, $twig); + $filter = doFilter($obj, $param, $twig); - if (!empty($param['user']) && empty($param['on'])) - $filter->addfilter('usrid', '=', $param['user']); - elseif (!empty($param['on']) && !empty($param['user'])) - $filter->addfilter($param['on'], '=', $param['user']); - if ($dl) - $filter->addfilter("(log_docs.final = 'document'", "OR", "log_docs.final = 'preview')"); + if ( ! empty($param['user']) && empty($param['on'])) + $filter->addfilter('usrid', '=', $param['user']); + elseif ( ! empty($param['on']) && ! empty($param['user'])) + $filter->addfilter($param['on'], '=', $param['user']); + if ($dl) + $filter->addfilter("(log_docs.final = 'document'", "OR", "log_docs.final = 'preview')"); - passFilter($filter, $obj); - $obj->setOrder('ddate', 'DESC'); + passFilter($filter, $obj); + $obj->setOrder('ddate', 'DESC'); - $report = $obj->buildTab($conf); + $report = $obj->buildTab($conf); - $report['title'] = $title; - $report['config'] = 0; + $report['title'] = $title; + $report['config'] = 0; - $html = doHtml($report, $param, $twig, 'report.twig'); - $request = $obj->req; + $html = doHtml($report, $param, $twig, 'report.twig'); + $request = $obj->req; - return(array('html' => $html, 'req' => $request)); + return(array('html' => $html, 'req' => $request)); } - ################################################ACTION FUNCTIONS####################################################### function cnx($param, $twig) { - $cnx = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('phraseanet::utilisateurs'), 1, 1, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1), - 'ip' => array(_('report:: IP'), 1, 0, 0, 0), - 'appli' => array(_('report:: modules'), 1, 0, 0, 0) - ); - $report = doReport($cnx, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html, $report); + $cnx = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array(_('phraseanet::utilisateurs'), 1, 1, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1), + 'ip' => array(_('report:: IP'), 1, 0, 0, 0), + 'appli' => array(_('report:: modules'), 1, 0, 0, 0) + ); + $report = doReport($cnx, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html, $report); } - /* generate all the html string to display all the valid download in
    , the result is encoded in json */ function gen($param, $twig) { - $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('report:: utilisateurs'), 1, 1, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1), - 'record_id' => array(_('report:: record id'), 1, 1, 1, 1), - 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), - 'coll_id' => array(_('report:: collections'), 1, 0, 1, 1) - ); - //$conf = doPreff($conf, $param); - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html, $report); + $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array(_('report:: utilisateurs'), 1, 1, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1), + 'record_id' => array(_('report:: record id'), 1, 1, 1, 1), + 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), + 'coll_id' => array(_('report:: collections'), 1, 0, 1, 1) + ); + //$conf = doPreff($conf, $param); + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html, $report); } - /* generate all the html string to display all the valid question in
    , the result is encoded in json */ function ask($param, $twig) { - $ask = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('report:: utilisateur'), 1, 1, 1, 1), - 'search' => array(_('report:: question'), 1, 0, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1) - ); - $report = doReport($ask, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html, $report); + $ask = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array(_('report:: utilisateur'), 1, 1, 1, 1), + 'search' => array(_('report:: question'), 1, 0, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1) + ); + $report = doReport($ask, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html, $report); } - /* generate the html code to display the download by doc (records or string in xml description), the result is encoded in json */ function doc($param, $twig) { - $conf = array( - 'telechargement' => array(_('report:: telechargements'), 1, 0, 0, 0), - 'record_id' => array(_('report:: record id'), 1, 1, 1, 0), - 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), - 'file' => array(_('report:: fichier'), 1, 0, 0, 1), - 'mime' => array(_('report:: type'), 1, 0, 1, 1), - 'size' => array(_('report:: taille'), 1, 0, 1, 1) - ); - $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = doPreff($conf, $param); - $report = doReport($dl, $param, $conf, $twig, 'record_id'); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html, $report); + $conf = array( + 'telechargement' => array(_('report:: telechargements'), 1, 0, 0, 0), + 'record_id' => array(_('report:: record id'), 1, 1, 1, 0), + 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), + 'file' => array(_('report:: fichier'), 1, 0, 0, 1), + 'mime' => array(_('report:: type'), 1, 0, 1, 1), + 'size' => array(_('report:: taille'), 1, 0, 1, 1) + ); + $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = doPreff($conf, $param); + $report = doReport($dl, $param, $conf, $twig, 'record_id'); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html, $report); } - /* generate the html string to display the result from different report (see below) in
    , the result is encoded in json */ function cnxb($param, $twig) { - $nav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_nav = array('nav' => array(_('report:: navigateur'), 0, 1, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_combo = array('combo' => array(_('report:: navigateurs et plateforme'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_os = array('os' => array(_('report:: plateforme'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_res = array('res' => array(_('report:: resolution'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_mod = array('appli' => array(_('report:: module'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $report = array( - 'nav' => $nav->buildTabNav($conf_nav), - 'os' => $nav->buildTabOs($conf_os), - 'res' => $nav->buildTabRes($conf_res), - 'mod' => $nav->buildTabModule($conf_mod), - 'combo' => $nav->buildTabCombo($conf_combo) - ); - $html = doHtml($report, $param, $twig, 'report/report.twig', 'nav'); - sendReport($html); + $nav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_nav = array('nav' => array(_('report:: navigateur'), 0, 1, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_combo = array('combo' => array(_('report:: navigateurs et plateforme'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_os = array('os' => array(_('report:: plateforme'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_res = array('res' => array(_('report:: resolution'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_mod = array('appli' => array(_('report:: module'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $report = array( + 'nav' => $nav->buildTabNav($conf_nav), + 'os' => $nav->buildTabOs($conf_os), + 'res' => $nav->buildTabRes($conf_res), + 'mod' => $nav->buildTabModule($conf_mod), + 'combo' => $nav->buildTabCombo($conf_combo) + ); + $html = doHtml($report, $param, $twig, 'report/report.twig', 'nav'); + sendReport($html); } - /* generate the html string to display the number of connexion by user in
    , the result is encoded in json */ function cnxu($param, $twig) { - $conf = array( - $param['on'] => array("", 0, 0, 0, 0), - 'connexion' => array(_('report::Connexions'), 0, 0, 0, 0) - ); - $connex = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - doLimit($connex, $param); - $report = $connex->getConnexionBase(false, $param['on']); + $conf = array( + $param['on'] => array("", 0, 0, 0, 0), + 'connexion' => array(_('report::Connexions'), 0, 0, 0, 0) + ); + $connex = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + doLimit($connex, $param); + $report = $connex->getConnexionBase(false, $param['on']); - isset($report['display']['user']) ? $report['display']['user']['title'] = _('phraseanet::utilisateurs') : ""; - isset($report['display']['user']) ? $report['display']['user']['bound'] = 1 : ""; + isset($report['display']['user']) ? $report['display']['user']['title'] = _('phraseanet::utilisateurs') : ""; + isset($report['display']['user']) ? $report['display']['user']['bound'] = 1 : ""; - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html); } - /* generate all the html string to display the top 20 question by databox in
    , the result is encoded in json */ function bestOf($param, $twig) { - $conf = array( - 'search' => array(_('report:: question'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'search' => array(_('report:: question'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $activity->setLimit(1, $param['limit']); - $activity->nb_top = $param['limit']; + $activity->setLimit(1, $param['limit']); + $activity->nb_top = $param['limit']; - $report = $activity->getTopQuestion($conf); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html); + $report = $activity->getTopQuestion($conf); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html); } - /* generate all the html string to display all the resot of questions
    , the result is encoded in json */ function noBestOf($param, $twig) { - $conf = array('search' => array(_('report:: question'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - doLimit($activity, $param); - $report = $activity->getTopQuestion($conf, true); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html); + $conf = array('search' => array(_('report:: question'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + doLimit($activity, $param); + $report = $activity->getTopQuestion($conf, true); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html); } - /* generate all the html string to display the users connexions activity by hour in
    , the result is encoded in json */ function tableSiteActivityPerHours($param, $twig) { - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $report = $activity->getActivityPerHours(); - $html = doHtml($report, $param, $twig, 'report/report.twig', 'plot'); - sendReport($html); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $report = $activity->getActivityPerHours(); + $html = doHtml($report, $param, $twig, 'report/report.twig', 'plot'); + sendReport($html); } - /* generate all the html string to display all number of download day by day in
    , the result is encoded in json */ function day($param, $twig) { - $conf = array('ddate' => array(_('report:: jour'), 0, 0, 0, 0), - 'total' => array(_('report:: total des telechargements'), 0, 0, 0, 0), - 'preview' => array(_('report:: preview'), 0, 0, 0, 0), - 'document' => array(_('report:: document original'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $activiy->list_coll_id = $param['collection']; - doLimit($activity, $param); - $report = $activity->getDownloadByBaseByDay($conf); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html); + $conf = array('ddate' => array(_('report:: jour'), 0, 0, 0, 0), + 'total' => array(_('report:: total des telechargements'), 0, 0, 0, 0), + 'preview' => array(_('report:: preview'), 0, 0, 0, 0), + 'document' => array(_('report:: document original'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $activiy->list_coll_id = $param['collection']; + doLimit($activity, $param); + $report = $activity->getDownloadByBaseByDay($conf); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html); } - /* generate all the html string to display all the details of download user by user in
    , the result is encoded in json */ function usr($param, $twig) { - $conf = array('user' => array(_('report:: utilisateur'), 0, 1, 0, 0), - 'nbdoc' => array(_('report:: nombre de documents'), 0, 0, 0, 0), - 'poiddoc' => array(_('report:: poids des documents'), 0, 0, 0, 0), - 'nbprev' => array(_('report:: nombre de preview'), 0, 0, 0, 0), - 'poidprev' => array(_('report:: poids des previews'), 0, 0, 0, 0) - ); + $conf = array('user' => array(_('report:: utilisateur'), 0, 1, 0, 0), + 'nbdoc' => array(_('report:: nombre de documents'), 0, 0, 0, 0), + 'poiddoc' => array(_('report:: poids des documents'), 0, 0, 0, 0), + 'nbprev' => array(_('report:: nombre de preview'), 0, 0, 0, 0), + 'poidprev' => array(_('report:: poids des previews'), 0, 0, 0, 0) + ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - doLimit($activity, $param); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + doLimit($activity, $param); - empty($param['on']) ? $on = "user" : $on = $param['on']; //by default always report on user + empty($param['on']) ? $on = "user" : $on = $param['on']; //by default always report on user - $report = $activity->getDetailDownload($conf, $on); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html); + $report = $activity->getDetailDownload($conf, $on); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html); } - /* Display basic informations about an user */ function infoUsr($param, $twig, $conf) { - $registry = registry::get_instance(); - if ($registry->get('GV_anonymousReport') == true) - { - $conf = array( - $param['on'] => array($param['on'], 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) - ); - } + $registry = registry::get_instance(); + if ($registry->get('GV_anonymousReport') == true) { + $conf = array( + $param['on'] => array($param['on'], 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) + ); + } - empty($param['on']) ? $param['on'] = false : ""; + empty($param['on']) ? $param['on'] = false : ""; - $request = ""; - $params = array(); - $html = ""; - $html_info = ""; - $is_dl = false; + $request = ""; + $params = array(); + $html = ""; + $html_info = ""; + $is_dl = false; - if ($param['from'] == 'CNXU' || $param['from'] == 'CNX') - { - $histo = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_cnx']; - $title = _("report:: historique des connexions"); - } - elseif ($param['from'] == "USR" || $param['from'] == "GEN") - { - $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_dl']; - $is_dl = true; - $title = _("report:: historique des telechargements"); - } - elseif ($param['from'] == "ASK") - { - $histo = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_ask']; - $title = _("report:: historique des questions"); - } + if ($param['from'] == 'CNXU' || $param['from'] == 'CNX') { + $histo = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_cnx']; + $title = _("report:: historique des connexions"); + } elseif ($param['from'] == "USR" || $param['from'] == "GEN") { + $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_dl']; + $is_dl = true; + $title = _("report:: historique des telechargements"); + } elseif ($param['from'] == "ASK") { + $histo = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_ask']; + $title = _("report:: historique des questions"); + } - if (isset($histo)) - { - $rs = getHistory($histo, $param, $twig, $conf_array, $is_dl, $title); - $html = $rs['html']; - $request = $rs['req']; - $params = $rs['params']; - } + if (isset($histo)) { + $rs = getHistory($histo, $param, $twig, $conf_array, $is_dl, $title); + $html = $rs['html']; + $request = $rs['req']; + $params = $rs['params']; + } - $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $report = $info->buildTabGrpInfo($request, $params, $param['user'], $conf['conf'], $param['on']); - $report['periode'] = ""; //delete the periode - if ($registry->get('GV_anonymousReport') == false) - { - $html_info .= doHtml($report, $param, $twig, 'report/report.twig'); - (empty($param['on']) && isset($report['result'])) ? $title = $report['result'][0]['identifiant'] : $title = $param['user']; - } - else - $title = $param['user']; + $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $report = $info->buildTabGrpInfo($request, $params, $param['user'], $conf['conf'], $param['on']); + $report['periode'] = ""; //delete the periode + if ($registry->get('GV_anonymousReport') == false) { + $html_info .= doHtml($report, $param, $twig, 'report/report.twig'); + (empty($param['on']) && isset($report['result'])) ? $title = $report['result'][0]['identifiant'] : $title = $param['user']; + } + else + $title = $param['user']; - sendReport($html_info . $html, false, $title); + sendReport($html_info . $html, false, $title); } - /* Display some basics informations about a Document */ function what($param, $twig) { - $registry = registry::get_instance(); + $registry = registry::get_instance(); - $config = array( - 'photo' => array(_('report:: document'), 0, 0, 0, 0), - 'record_id' => array(_('report:: record id'), 0, 0, 0, 0), - 'date' => array(_('report:: date'), 0, 0, 0, 0), - 'type' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), - 'titre' => array(_('report:: titre'), 0, 0, 0, 0), - 'taille' => array(_('report:: poids'), 0, 0, 0, 0) - ); - $config_dl = array( - 'ddate' => array(_('report:: date'), 0, 0, 0, 0), - 'user' => array(_('report:: utilisateurs'), 0, 0, 0, 0), - 'final' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), - 'coll_id' => array(_('report:: collections'), 0, 0, 0, 0), - 'comment' => array(_('report:: commentaire'), 0, 0, 0, 0) - ); - - $config_dl = doUserConf($config_dl, $param); - - $html = ""; - $basid = getBasId($param); - - $what = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - - $report = $what->buildTabUserWhat($basid, $param['rid'], $config); - $report['periode'] = ""; - - if ($param['from'] == 'TOOL') - $report['title'] = ""; - - $title = $report['result'][0]["titre"]; - - $html = doHtml($report, $param, $twig, 'report/info.twig'); - - if ($param['from'] == 'TOOL') - sendReport($html); - - if ($param['from'] != 'DASH') - { - $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - - $filter = doFilter($histo, $param, $twig); - if (!empty($param['rid'])) - $filter->addfilter('record_id', '=', $param['rid']); - - passFilter($filter, $histo); - $histo->setOrder('ddate', 'DESC'); - - $report = $histo->buildTab($config_dl); - $report['title'] = _("report:: historique des telechargements"); - $report['config'] = 0; - $html .= doHtml($report, $param, $twig, 'report/report.twig'); - } - - if ($registry->get('GV_anonymousReport') == false && $param['from'] != 'DOC' && $param['from'] != 'DASH' && $param['from'] != "GEN") - { - $conf = array( - 'identifiant' => array(_('report:: identifiant'), 0, 0, 0, 0), - 'nom' => array(_('report:: nom'), 0, 0, 0, 0), - 'mail' => array(_('report:: email'), 0, 0, 0, 0), - 'adresse' => array(_('report:: adresse'), 0, 0, 0, 0), - 'tel' => array(_('report:: telephone'), 0, 0, 0, 0) + $config = array( + 'photo' => array(_('report:: document'), 0, 0, 0, 0), + 'record_id' => array(_('report:: record id'), 0, 0, 0, 0), + 'date' => array(_('report:: date'), 0, 0, 0, 0), + 'type' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), + 'titre' => array(_('report:: titre'), 0, 0, 0, 0), + 'taille' => array(_('report:: poids'), 0, 0, 0, 0) + ); + $config_dl = array( + 'ddate' => array(_('report:: date'), 0, 0, 0, 0), + 'user' => array(_('report:: utilisateurs'), 0, 0, 0, 0), + 'final' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), + 'coll_id' => array(_('report:: collections'), 0, 0, 0, 0), + 'comment' => array(_('report:: commentaire'), 0, 0, 0, 0) ); - $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $report = $info->buildTabGrpInfo(false, array(), $param['user'], $conf, false); + $config_dl = doUserConf($config_dl, $param); + + $html = ""; + $basid = getBasId($param); + + $what = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + + $report = $what->buildTabUserWhat($basid, $param['rid'], $config); $report['periode'] = ""; - $report['config'] = 0; - $report['title'] = _('report:: utilisateur'); - $html .= doHtml($report, $param, $twig, 'report/report.twig'); - } - sendReport($html, false, $title); + if ($param['from'] == 'TOOL') + $report['title'] = ""; + + $title = $report['result'][0]["titre"]; + + $html = doHtml($report, $param, $twig, 'report/info.twig'); + + if ($param['from'] == 'TOOL') + sendReport($html); + + if ($param['from'] != 'DASH') { + $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + + $filter = doFilter($histo, $param, $twig); + if ( ! empty($param['rid'])) + $filter->addfilter('record_id', '=', $param['rid']); + + passFilter($filter, $histo); + $histo->setOrder('ddate', 'DESC'); + + $report = $histo->buildTab($config_dl); + $report['title'] = _("report:: historique des telechargements"); + $report['config'] = 0; + $html .= doHtml($report, $param, $twig, 'report/report.twig'); + } + + if ($registry->get('GV_anonymousReport') == false && $param['from'] != 'DOC' && $param['from'] != 'DASH' && $param['from'] != "GEN") { + $conf = array( + 'identifiant' => array(_('report:: identifiant'), 0, 0, 0, 0), + 'nom' => array(_('report:: nom'), 0, 0, 0, 0), + 'mail' => array(_('report:: email'), 0, 0, 0, 0), + 'adresse' => array(_('report:: adresse'), 0, 0, 0, 0), + 'tel' => array(_('report:: telephone'), 0, 0, 0, 0) + ); + $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $report = $info->buildTabGrpInfo(false, array(), $param['user'], $conf, false); + + $report['periode'] = ""; + $report['config'] = 0; + $report['title'] = _('report:: utilisateur'); + + $html .= doHtml($report, $param, $twig, 'report/report.twig'); + } + sendReport($html, false, $title); } - /* Display image when click in the dashboard */ function infoNav($param, $twig) { - $conf = array( - 'version' => array(_('report::version '), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) - ); - $infonav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $report = $infonav->buildTabInfoNav($conf, $param['user']); - $html = doHtml($report, $param, $twig, 'report/report.twig'); - sendReport($html, false, $param['user']); + $conf = array( + 'version' => array(_('report::version '), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) + ); + $infonav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $report = $infonav->buildTabInfoNav($conf, $param['user']); + $html = doHtml($report, $param, $twig, 'report/report.twig'); + sendReport($html, false, $param['user']); } - ################################################SWITCH ACTIONS############################################################## -switch ($param['tbl']) -{ - case "CNX": - cnx($param, $twig); - break; +switch ($param['tbl']) { + case "CNX": + cnx($param, $twig); + break; - case "CNXU": - cnxu($param, $twig); - break; + case "CNXU": + cnxu($param, $twig); + break; - case "CNXB": - cnxb($param, $twig); - break; + case "CNXB": + cnxb($param, $twig); + break; - case "GEN": - gen($param, $twig); - break; + case "GEN": + gen($param, $twig); + break; - case "DAY": - day($param, $twig); - break; + case "DAY": + day($param, $twig); + break; - case "DOC": - doc($param, $twig); - break; + case "DOC": + doc($param, $twig); + break; - case "BESTOF": - bestOf($param, $twig); - break; + case "BESTOF": + bestOf($param, $twig); + break; - case "NOBESTOF": - noBestOf($param, $twig); - break; + case "NOBESTOF": + noBestOf($param, $twig); + break; - case "SITEACTIVITY": - tableSiteActivityPerHours($param, $twig); - break; + case "SITEACTIVITY": + tableSiteActivityPerHours($param, $twig); + break; - case "USR": - usr($param, $twig); - break; + case "USR": + usr($param, $twig); + break; - case "ASK": - ask($param, $twig); - break; + case "ASK": + ask($param, $twig); + break; - case "infouser": - infoUsr($param, $twig, $conf_info_usr); - break; + case "infouser": + infoUsr($param, $twig, $conf_info_usr); + break; - case "what": - what($param, $twig); - break; + case "what": + what($param, $twig); + break; - case "infonav": - infoNav($param, $twig); - break; + case "infonav": + infoNav($param, $twig); + break; } ?> diff --git a/www/report/export_csv.php b/www/report/export_csv.php index 7ad3a4d7bf..b0a63cfc62 100644 --- a/www/report/export_csv.php +++ b/www/report/export_csv.php @@ -22,11 +22,10 @@ $parm = $request->get_parms('name', 'csv'); function trimUltime($str) { - $str = preg_replace('/[ \t\r\f]+/', '', $str); + $str = preg_replace('/[ \t\r\f]+/', '', $str); - return $str; + return $str; } - $parm['name'] ? $name = '_' . $parm['name'] : $name = ""; $name = preg_replace('/\s+/', '_', $name); $filename = mb_strtolower('report' . $name . '_' . date('dmY') . '.csv'); @@ -34,9 +33,8 @@ $filename = mb_strtolower('report' . $name . '_' . date('dmY') . '.csv'); $content = ""; -if ($parm['csv']) -{ - $content = trimUltime($parm['csv']); - set_export::stream_data($content, $filename, "text/csv"); +if ($parm['csv']) { + $content = trimUltime($parm['csv']); + set_export::stream_data($content, $filename, "text/csv"); } ?> diff --git a/www/report/index.php b/www/report/index.php index 21a94b0e4e..daa067c018 100644 --- a/www/report/index.php +++ b/www/report/index.php @@ -15,7 +15,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -33,15 +32,15 @@ $dashboard->execute(); $var = array( - 'ajax_dash' => true, - 'dashboard' => $dashboard, - 'home_title' => $registry->get('GV_homeTitle'), - 'module' => "report", + 'ajax_dash' => true, + 'dashboard' => $dashboard, + 'home_title' => $registry->get('GV_homeTitle'), + 'module' => "report", "module_name" => "Report", - 'anonymous' => $registry->get('GV_anonymousReport'), - 'g_anal' => $registry->get('GV_googleAnalytics'), - 'ajax' => false, - 'ajax_chart' => false + 'anonymous' => $registry->get('GV_anonymousReport'), + 'g_anal' => $registry->get('GV_googleAnalytics'), + 'ajax' => false, + 'ajax_chart' => false ); $twig = $Core->getTwig(); diff --git a/www/report/report.php b/www/report/report.php index ee5593dc9d..996d00e5a6 100644 --- a/www/report/report.php +++ b/www/report/report.php @@ -21,31 +21,31 @@ $request = http_request::getInstance(); $registry = registry::get_instance(); $parm = $request->get_parms( - "dmin" - , "dmax" - , "baslst" - , "popbases" - , "tbl" - , "precise" - , "preciseWord" - , "preciseUser" - , "page" - , "limit" - , "fonction" - , "pays" - , "societe" - , "activite" - , "on" - , "docwhat" + "dmin" + , "dmax" + , "baslst" + , "popbases" + , "tbl" + , "precise" + , "preciseWord" + , "preciseUser" + , "page" + , "limit" + , "fonction" + , "pays" + , "societe" + , "activite" + , "on" + , "docwhat" ); extract($parm); /* Initialise les dates par defaults min au 1er jour du mois courant et max a la date courante */ if ($parm['dmin'] == "") - $parm['dmin'] = "01-" . date("m") . "-" . date("Y"); + $parm['dmin'] = "01-" . date("m") . "-" . date("Y"); if ($parm['dmax'] == "") - $parm['dmax'] = date("d") . "-" . date("m") . "-" . date("Y"); + $parm['dmax'] = date("d") . "-" . date("m") . "-" . date("Y"); $td = explode("-", $parm['dmin']); $parm['dmin'] = date('Y-m-d H:i:s', mktime(0, 0, 0, $td[1], $td[0], $td[2])); @@ -59,18 +59,16 @@ $popbases = array_fill_keys($popbases, 0); $liste = ''; $i = 0; $id_sbas = ""; -foreach ($popbases as $key => $val) -{ - $exp = explode("_", $key); - if ($exp[0] != $id_sbas && $i != 0) - { - $selection[$id_sbas]['liste'] = $liste; - $liste = ''; - } - $selection[$exp[0]][] = $exp[1]; - $liste .= ( empty($liste) ? '' : ',') . $exp[1]; - $id_sbas = $exp[0]; - $i++; +foreach ($popbases as $key => $val) { + $exp = explode("_", $key); + if ($exp[0] != $id_sbas && $i != 0) { + $selection[$id_sbas]['liste'] = $liste; + $liste = ''; + } + $selection[$exp[0]][] = $exp[1]; + $liste .= ( empty($liste) ? '' : ',') . $exp[1]; + $id_sbas = $exp[0]; + $i ++; } //fill the last entry $selection[$id_sbas]['liste'] = $liste; @@ -79,11 +77,11 @@ $core = \bootstrap::getCore(); $twig = $core->getTwig(); echo $twig->render( - 'report/ajax_report_content.twig', array( + 'report/ajax_report_content.twig', array( 'selection' => $selection, - 'param' => $parm, + 'param' => $parm, 'anonymous' => $registry->get('GV_anonymousReport'), - 'ajax' => true - ) + 'ajax' => true + ) ); diff --git a/www/report/tab.php b/www/report/tab.php index eadecb3099..2e03612fb8 100644 --- a/www/report/tab.php +++ b/www/report/tab.php @@ -22,33 +22,33 @@ require_once __DIR__ . "/../../lib/bootstrap.php"; $request = http_request::getInstance(); $param = $request->get_parms( - "dmin", // date minimal of the reporting - "dmax", // date maximal of the reporting - "page", // current page of the reporting - "limit", // numbers of result by page displayed in the reporting - "tbl", // action requested - "collection", // list of collection which concerns the reporting - "user", // id of user which concern the reporting - "precise", // 1 = precision on content of the doc we're lookin for; 2 = precison on id of the document we're looking for - "order", // order result of the reporting - "champ", // precise the field we want order - "word", // precise the word we're lookin for in our documents - "sbasid", // the report relates to this base iD - "rid", // precise the id of the document we are looking for - "filter_column", // name of the colonne we want applied the filter - "filter_value", // value of the filter - "liste", // default = off, if on, apply the new filter - "liste_filter", // memorize the current(s) applied filters - "conf", // default = off, if on, apply the new configuration - "list_column", // contain the list of the column the user wants to see - "groupby", // name of the column that the user wants group - "societe", // the name of the selectionned firm - "fonction", // the name of the selectionned function - "activite", // the name of the selectionned activity - "pays", // the name of the selectionned country - "on", // this field contain the name of the column the user wants display the download by - "top", // this field contains the number of the top questions he wants to see - "from", "printcsv", "docwhat" + "dmin", // date minimal of the reporting + "dmax", // date maximal of the reporting + "page", // current page of the reporting + "limit", // numbers of result by page displayed in the reporting + "tbl", // action requested + "collection", // list of collection which concerns the reporting + "user", // id of user which concern the reporting + "precise", // 1 = precision on content of the doc we're lookin for; 2 = precison on id of the document we're looking for + "order", // order result of the reporting + "champ", // precise the field we want order + "word", // precise the word we're lookin for in our documents + "sbasid", // the report relates to this base iD + "rid", // precise the id of the document we are looking for + "filter_column", // name of the colonne we want applied the filter + "filter_value", // value of the filter + "liste", // default = off, if on, apply the new filter + "liste_filter", // memorize the current(s) applied filters + "conf", // default = off, if on, apply the new configuration + "list_column", // contain the list of the column the user wants to see + "groupby", // name of the column that the user wants group + "societe", // the name of the selectionned firm + "fonction", // the name of the selectionned function + "activite", // the name of the selectionned activity + "pays", // the name of the selectionned country + "on", // this field contain the name of the column the user wants display the download by + "top", // this field contains the number of the top questions he wants to see + "from", "printcsv", "docwhat" ); $core = \bootstrap::getCore(); @@ -90,1054 +90,946 @@ $conf_info_usr = array( function getFilterField($param) { - $filter_column = explode(' ', $param['filter_column']); - $column = $filter_column[0]; + $filter_column = explode(' ', $param['filter_column']); + $column = $filter_column[0]; - return $column; + return $column; } function doOrder($obj, $param) { - (!empty($param['order']) && !empty($param['champ'])) ? $obj->setOrder($param['champ'], $param['order']) : ""; + ( ! empty($param['order']) && ! empty($param['champ'])) ? $obj->setOrder($param['champ'], $param['order']) : ""; } function doLimit($obj, $param) { - if ($obj->getEnableLimit()) - (!empty($param['page']) && !empty($param['limit'])) ? $obj->setLimit($param['page'], $param['limit']) : $obj->setLimit(false, false); + if ($obj->getEnableLimit()) + ( ! empty($param['page']) && ! empty($param['limit'])) ? $obj->setLimit($param['page'], $param['limit']) : $obj->setLimit(false, false); } function doFilter($obj, $param, $twig) { - $cor = $obj->getTransQueryString(); - $currentfilter = unserializeFilter($param['liste_filter']); + $cor = $obj->getTransQueryString(); + $currentfilter = unserializeFilter($param['liste_filter']); - $filter = new module_report_filter($currentfilter, $cor); + $filter = new module_report_filter($currentfilter, $cor); - if (!empty($param['filter_column'])) - { - $field = getFilterField($param); - $value = $param['filter_value']; + if ( ! empty($param['filter_column'])) { + $field = getFilterField($param); + $value = $param['filter_value']; - if ($param['liste'] == "on") - { - $tab = $obj->colFilter($field); - displayColValue($tab, $field, $twig); + if ($param['liste'] == "on") { + $tab = $obj->colFilter($field); + displayColValue($tab, $field, $twig); + } + + if ($field == $value) + $filter->removeFilter($field); + else + $filter->addFilter($field, '=', $value); } - if ($field == $value) - $filter->removeFilter($field); - else - $filter->addFilter($field, '=', $value); - } - - return $filter; + return $filter; } function doPreff($conf, $param) { - $conf_pref = array(); - $pref = module_report::getPreff($param['sbasid']); - foreach ($pref as $key => $field) - $conf_pref[$field] = array($field, 0, 0, 0, 0); - $conf = array_merge($conf, $conf_pref); - - return $conf; -} - -function doReport($obj, $param, $conf, $twig, $what = false) -{ - $registry = registry::get_instance(); - if ($registry->get('GV_anonymousReport') == true) - { - if (isset($conf['user'])) - unset($conf['user']); - if (isset($conf['ip'])) - unset($conf['ip']); - } - //save initial conf - $base_conf = $conf; - //format conf according user preferences - $conf = doUserConf($conf, $param); - //display content of a table column when user click on it - displayListColumn($base_conf, $param, $twig); - //set order - doOrder($obj, $param); - - //return a filter object - $filter = doFilter($obj, $param, $twig); - - //set new request filter if user asking for them - if ($param['precise'] == 1) - $filter->addFilter('xml', 'LIKE', $param['word']); - elseif ($param['precise'] == 2) - $filter->addFilter('record_id', '=', $param['word']); - - $tab_filter = $filter->getTabFilter(); //display filter in array - $posting_filter = $filter->getPostingFilter(); //display filter in string to render it - $active_column = $filter->getActiveColumn(); //get the column where a filter is applied - //set filter to current obj - $obj->setFilter($tab_filter); - $obj->setActiveColumn($active_column); - $obj->setPostingFilter($posting_filter); - - - // display a new arraywhere results are group - groupBy($obj, $param, $twig); - //set Limit - doLimit($obj, $param); - - //time to build our report - if (!$what) - $report = $obj->buildReport($conf); - else - $report = $obj->buildReport($conf, $what, $param['tbl']); - - return $report; -} - -function doHtml($report, $param, $twig, $template, $type = false) -{ - $var = array( - 'result' => isset($report['report']) ? $report['report'] : $report, - 'param' => $param, - 'is_infouser' => false, - 'is_nav' => false, - 'is_groupby' => false, - 'is_plot' => false, - 'is_doc' => false - ); - - if ($type) - { - switch ($type) - { - case "user" : - $var['is_infouser'] = true; - break; - case "nav" : - $var['is_nav'] = true; - break; - case "group" : - $var['is_groupby'] = true; - break; - case "plot" : - $var['is_plot'] = true; - break; - case "doc" : - $var['is_doc'] = true; - break; - } - } - - return ($twig->render($template, $var)); -} - -function doCsv($obj, $param, $conf, $twig) -{ - $scv = ""; - //disable limit - $obj->setHasLimit(false); - $obj->setPrettyString(false); - //construct new report - doReport($obj, $param, $conf, $twig); - - //get resulst - $result_csv = $obj->getResult(); - - $display = $obj->getDisplay(); - - //convert array to csv string format - try - { - $csv = format::arr_to_csv($result_csv, $display); - } - catch (Exception $e) - { - $csv = false; - } - - return $csv; -} - -function sendReport($html, $report = false, $title = false, $display_nav = false) -{ - if ($report) - { - $t = array( - 'rs' => $html, - 'display_nav' => $report['display_nav'], // do we display the prev and next button ? - 'next' => $report['next_page'], //Number of the next page - 'prev' => $report['previous_page'], //Number of the previoous page - 'page' => $report['page'], //The current page - 'filter' => ((sizeof($report['filter']) > 0) ? serialize($report['filter']) : ""), //the serialized filters - 'col' => $report['active_column'], //all the columns where a filter is applied - 'limit' => $report['nb_record'] - ); - } - else - { - $t = array( - 'rs' => $html, - 'display_nav' => $display_nav, - 'title' => $title - ); - } - echo p4string::jsonencode($t); -} - -function sendCsv($csv) -{ - $t = array('rs' => $csv); - echo p4string::jsonencode($t); -} - -function getBasId($param) -{ - try - { - $record = new record_adapter($param['sbasid'], $param['rid']); - - return $record->get_base_id(); - } - catch (Exception $e) - { - - } - - return false; -} - -function unserializeFilter($serialized_filter) -{ - $tab_filter = array(); - if (!empty($serialized_filter)) - { - $tab_filter = @unserialize(urldecode($serialized_filter)); - } - - return $tab_filter; -} - -function doUserConf($conf, $param) -{ - if (!empty($param['list_column'])) - { - $new_conf = array(); - $new_conf = $conf; - $x = explode(",", $param['list_column']); - - foreach ($conf as $key => $value) - { - if (!in_array($key, $x)) - unset($new_conf[$key]); - } - - return $new_conf; - } - else + $conf_pref = array(); + $pref = module_report::getPreff($param['sbasid']); + foreach ($pref as $key => $field) + $conf_pref[$field] = array($field, 0, 0, 0, 0); + $conf = array_merge($conf, $conf_pref); return $conf; } +function doReport($obj, $param, $conf, $twig, $what = false) +{ + $registry = registry::get_instance(); + if ($registry->get('GV_anonymousReport') == true) { + if (isset($conf['user'])) + unset($conf['user']); + if (isset($conf['ip'])) + unset($conf['ip']); + } + //save initial conf + $base_conf = $conf; + //format conf according user preferences + $conf = doUserConf($conf, $param); + //display content of a table column when user click on it + displayListColumn($base_conf, $param, $twig); + //set order + doOrder($obj, $param); + + //return a filter object + $filter = doFilter($obj, $param, $twig); + + //set new request filter if user asking for them + if ($param['precise'] == 1) + $filter->addFilter('xml', 'LIKE', $param['word']); + elseif ($param['precise'] == 2) + $filter->addFilter('record_id', '=', $param['word']); + + $tab_filter = $filter->getTabFilter(); //display filter in array + $posting_filter = $filter->getPostingFilter(); //display filter in string to render it + $active_column = $filter->getActiveColumn(); //get the column where a filter is applied + //set filter to current obj + $obj->setFilter($tab_filter); + $obj->setActiveColumn($active_column); + $obj->setPostingFilter($posting_filter); + + + // display a new arraywhere results are group + groupBy($obj, $param, $twig); + //set Limit + doLimit($obj, $param); + + //time to build our report + if ( ! $what) + $report = $obj->buildReport($conf); + else + $report = $obj->buildReport($conf, $what, $param['tbl']); + + return $report; +} + +function doHtml($report, $param, $twig, $template, $type = false) +{ + $var = array( + 'result' => isset($report['report']) ? $report['report'] : $report, + 'param' => $param, + 'is_infouser' => false, + 'is_nav' => false, + 'is_groupby' => false, + 'is_plot' => false, + 'is_doc' => false + ); + + if ($type) { + switch ($type) { + case "user" : + $var['is_infouser'] = true; + break; + case "nav" : + $var['is_nav'] = true; + break; + case "group" : + $var['is_groupby'] = true; + break; + case "plot" : + $var['is_plot'] = true; + break; + case "doc" : + $var['is_doc'] = true; + break; + } + } + + return ($twig->render($template, $var)); +} + +function doCsv($obj, $param, $conf, $twig) +{ + $scv = ""; + //disable limit + $obj->setHasLimit(false); + $obj->setPrettyString(false); + //construct new report + doReport($obj, $param, $conf, $twig); + + //get resulst + $result_csv = $obj->getResult(); + + $display = $obj->getDisplay(); + + //convert array to csv string format + try { + $csv = format::arr_to_csv($result_csv, $display); + } catch (Exception $e) { + $csv = false; + } + + return $csv; +} + +function sendReport($html, $report = false, $title = false, $display_nav = false) +{ + if ($report) { + $t = array( + 'rs' => $html, + 'display_nav' => $report['display_nav'], // do we display the prev and next button ? + 'next' => $report['next_page'], //Number of the next page + 'prev' => $report['previous_page'], //Number of the previoous page + 'page' => $report['page'], //The current page + 'filter' => ((sizeof($report['filter']) > 0) ? serialize($report['filter']) : ""), //the serialized filters + 'col' => $report['active_column'], //all the columns where a filter is applied + 'limit' => $report['nb_record'] + ); + } else { + $t = array( + 'rs' => $html, + 'display_nav' => $display_nav, + 'title' => $title + ); + } + echo p4string::jsonencode($t); +} + +function sendCsv($csv) +{ + $t = array('rs' => $csv); + echo p4string::jsonencode($t); +} + +function getBasId($param) +{ + try { + $record = new record_adapter($param['sbasid'], $param['rid']); + + return $record->get_base_id(); + } catch (Exception $e) { + + } + + return false; +} + +function unserializeFilter($serialized_filter) +{ + $tab_filter = array(); + if ( ! empty($serialized_filter)) { + $tab_filter = @unserialize(urldecode($serialized_filter)); + } + + return $tab_filter; +} + +function doUserConf($conf, $param) +{ + if ( ! empty($param['list_column'])) { + $new_conf = array(); + $new_conf = $conf; + $x = explode(",", $param['list_column']); + + foreach ($conf as $key => $value) { + if ( ! in_array($key, $x)) + unset($new_conf[$key]); + } + + return $new_conf; + } + else + return $conf; +} + function displayListColumn($conf, $param, $twig) { - if ($param['conf'] == "on") - { - $html = $twig->render('report/listColumn.twig', array( - 'conf' => $conf, - 'param' => $param + if ($param['conf'] == "on") { + $html = $twig->render('report/listColumn.twig', array( + 'conf' => $conf, + 'param' => $param )); - $t = array('liste' => $html, "title" => _("configuration")); - echo p4string::jsonencode($t); - exit(); - } + $t = array('liste' => $html, "title" => _("configuration")); + echo p4string::jsonencode($t); + exit(); + } } function groupBy($obj, $param, $twig, $on = false) { - //Contains the name of the column where the group by is applied - (!empty($param['groupby']) ? $groupby = explode(' ', $param['groupby']) : $groupby = false); - //If users ask for group by, display the good array, result is encoded in Json , exit the function. - if ($groupby) - { - $obj->setConfig(false); - $report = $obj->buildReport(false, $groupby[0], $on); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'group'); - $title = "Groupement des resultats sur le champ " . $report['display'][$report['allChamps'][0]]['title']; - sendReport($html, false, $title); - exit(); - } + //Contains the name of the column where the group by is applied + ( ! empty($param['groupby']) ? $groupby = explode(' ', $param['groupby']) : $groupby = false); + //If users ask for group by, display the good array, result is encoded in Json , exit the function. + if ($groupby) { + $obj->setConfig(false); + $report = $obj->buildReport(false, $groupby[0], $on); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'group'); + $title = "Groupement des resultats sur le champ " . $report['display'][$report['allChamps'][0]]['title']; + sendReport($html, false, $title); + exit(); + } } function displayColValue($tab, $column, $twig, $on = false) { - $test = $twig->render('report/colFilter.twig', array( - 'result' => $tab, - 'field' => $column - )); - $t = array('diag' => $test, "title" => sprintf(_("filtrer les resultats sur la colonne %s"), $column)); - echo p4string::jsonencode($t); - exit(); + $test = $twig->render('report/colFilter.twig', array( + 'result' => $tab, + 'field' => $column + )); + $t = array('diag' => $test, "title" => sprintf(_("filtrer les resultats sur la colonne %s"), $column)); + echo p4string::jsonencode($t); + exit(); } function getHistory($obj, $param, $twig, $conf, $dl = false, $title) { - $filter = doFilter($obj, $param, $twig); + $filter = doFilter($obj, $param, $twig); - if (!empty($param['user']) && empty($param['on'])) - $filter->addfilter('usrid', '=', $param['user']); - elseif (!empty($param['on']) && !empty($param['user'])) - $filter->addfilter($param['on'], '=', $param['user']); - if ($dl) - { - $obj->setIsInformative(true); - } - $tab_filter = $filter->getTabFilter(); - $obj->setFilter($tab_filter); + if ( ! empty($param['user']) && empty($param['on'])) + $filter->addfilter('usrid', '=', $param['user']); + elseif ( ! empty($param['on']) && ! empty($param['user'])) + $filter->addfilter($param['on'], '=', $param['user']); + if ($dl) { + $obj->setIsInformative(true); + } + $tab_filter = $filter->getTabFilter(); + $obj->setFilter($tab_filter); - $obj->setOrder('ddate', 'DESC'); - $obj->setConfig(false); - $obj->setTitle($title); - $obj->setHasLimit(false); + $obj->setOrder('ddate', 'DESC'); + $obj->setConfig(false); + $obj->setTitle($title); + $obj->setHasLimit(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($obj, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = $obj->buildReport($conf); - } + if ($param['printcsv'] == "on") { + $csv = doCsv($obj, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = $obj->buildReport($conf); + } - if ($dl) - { - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', "user"); - } - else - { - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - } - $request = $obj->getReq(); + if ($dl) { + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', "user"); + } else { + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + } + $request = $obj->getReq(); - return(array('html' => $html, 'req' => $request, 'params' => $obj->getParams())); + return(array('html' => $html, 'req' => $request, 'params' => $obj->getParams())); } - ################################################ACTION FUNCTIONS####################################################### function cnx($param, $twig) { - $cnx = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $cnx = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('phraseanet::utilisateurs'), 1, 1, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1), - 'ip' => array(_('report:: IP'), 1, 0, 0, 0), - 'appli' => array(_('report:: modules'), 1, 0, 0, 0), - 'fonction' => array(_('report::fonction'), 1, 1, 1, 1), - 'activite' => array(_('report::activite'), 1, 1, 1, 1), - 'pays' => array(_('report::pays'), 1, 1, 1, 1), - 'societe' => array(_('report::societe'), 1, 1, 1, 1) - ); + $conf = array( + 'user' => array(_('phraseanet::utilisateurs'), 1, 1, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1), + 'ip' => array(_('report:: IP'), 1, 0, 0, 0), + 'appli' => array(_('report:: modules'), 1, 0, 0, 0), + 'fonction' => array(_('report::fonction'), 1, 1, 1, 1), + 'activite' => array(_('report::activite'), 1, 1, 1, 1), + 'pays' => array(_('report::pays'), 1, 1, 1, 1), + 'societe' => array(_('report::societe'), 1, 1, 1, 1) + ); - if ($param['printcsv'] == "on") - { - $csv = doCsv($cnx, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($cnx, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + if ($param['printcsv'] == "on") { + $csv = doCsv($cnx, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($cnx, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } - /* generate all the html string to display all the valid download in
    , the result is encoded in json */ function gen($param, $twig) { - $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('report:: utilisateurs'), 1, 1, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1), - 'record_id' => array(_('report:: record id'), 1, 1, 1, 1), - 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), - 'coll_id' => array(_('report:: collections'), 1, 0, 1, 1), - 'comment' => array(_('report:: commentaire'), 1, 0, 0, 0), - 'fonction' => array(_('report:: fonction'), 1, 1, 1, 1), - 'activite' => array(_('report:: activite'), 1, 1, 1, 1), - 'pays' => array(_('report:: pays'), 1, 1, 1, 1), - 'societe' => array(_('report:: societe'), 1, 1, 1, 1) - ); - $conf = doPreff($conf, $param); + $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array(_('report:: utilisateurs'), 1, 1, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1), + 'record_id' => array(_('report:: record id'), 1, 1, 1, 1), + 'final' => array(_('phrseanet:: sous definition'), 1, 0, 1, 1), + 'coll_id' => array(_('report:: collections'), 1, 0, 1, 1), + 'comment' => array(_('report:: commentaire'), 1, 0, 0, 0), + 'fonction' => array(_('report:: fonction'), 1, 1, 1, 1), + 'activite' => array(_('report:: activite'), 1, 1, 1, 1), + 'pays' => array(_('report:: pays'), 1, 1, 1, 1), + 'societe' => array(_('report:: societe'), 1, 1, 1, 1) + ); + $conf = doPreff($conf, $param); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } - /* generate all the html string to display all the valid question in
    , the result is encoded in json */ function ask($param, $twig) { - $ask = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'user' => array(_('report:: utilisateur'), 1, 1, 1, 1), - 'search' => array(_('report:: question'), 1, 0, 1, 1), - 'ddate' => array(_('report:: date'), 1, 0, 1, 1), - 'fonction' => array(_('report:: fonction'), 1, 1, 1, 1), - 'activite' => array(_('report:: activite'), 1, 1, 1, 1), - 'pays' => array(_('report:: pays'), 1, 1, 1, 1), - 'societe' => array(_('report:: societe'), 1, 1, 1, 1) - ); + $ask = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array(_('report:: utilisateur'), 1, 1, 1, 1), + 'search' => array(_('report:: question'), 1, 0, 1, 1), + 'ddate' => array(_('report:: date'), 1, 0, 1, 1), + 'fonction' => array(_('report:: fonction'), 1, 1, 1, 1), + 'activite' => array(_('report:: activite'), 1, 1, 1, 1), + 'pays' => array(_('report:: pays'), 1, 1, 1, 1), + 'societe' => array(_('report:: societe'), 1, 1, 1, 1) + ); - if ($param['printcsv'] == "on") - { - $csv = doCsv($ask, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($ask, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + if ($param['printcsv'] == "on") { + $csv = doCsv($ask, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($ask, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } - /* generate the html code to display the download by doc (records or string in xml description), the result is encoded in json */ function doc($param, $twig) { - $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf = array( - 'telechargement' => array(_('report:: telechargements'), 1, 0, 0, 0), - 'record_id' => array(_('report:: record id'), 1, 1, 1, 0), - 'final' => array(_('phraseanet:: sous definition'), 1, 0, 1, 1), - 'file' => array(_('report:: fichier'), 1, 0, 0, 1), - 'mime' => array(_('report:: type'), 1, 0, 1, 1), - 'size' => array(_('report:: taille'), 1, 0, 1, 1) - ); - $conf = doPreff($conf, $param); + $dl = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'telechargement' => array(_('report:: telechargements'), 1, 0, 0, 0), + 'record_id' => array(_('report:: record id'), 1, 1, 1, 0), + 'final' => array(_('phraseanet:: sous definition'), 1, 0, 1, 1), + 'file' => array(_('report:: fichier'), 1, 0, 0, 1), + 'mime' => array(_('report:: type'), 1, 0, 1, 1), + 'size' => array(_('report:: taille'), 1, 0, 1, 1) + ); + $conf = doPreff($conf, $param); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig, 'record_id'); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'doc'); - sendReport($html, $report); - } + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig, 'record_id'); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'doc'); + sendReport($html, $report); + } } - /* generate the html string to display the result from different report (see below) in
    , the result is encoded in json */ function cnxb($param, $twig) { - $nav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_nav = array('nav' => array(_('report:: navigateur'), 0, 1, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_combo = array('combo' => array(_('report:: navigateurs et plateforme'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_os = array('os' => array(_('report:: plateforme'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_res = array('res' => array(_('report:: resolution'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - $conf_mod = array('appli' => array(_('report:: module'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) - ); - - $report = array( - 'nav' => $nav->buildTabNav($conf_nav), - 'os' => $nav->buildTabOs($conf_os), - 'res' => $nav->buildTabRes($conf_res), - 'mod' => $nav->buildTabModule($conf_mod), - 'combo' => $nav->buildTabCombo($conf_combo) - ); - - if ($param['printcsv'] == "on") - { - $csv = array( - 'nav' => format::arr_to_csv($report['nav']['result'], $conf_nav), - 'os' => format::arr_to_csv($report['os']['result'], $conf_os), - 'res' => format::arr_to_csv($report['res']['result'], $conf_res), - 'mod' => format::arr_to_csv($report['mod']['result'], $conf_mod), - 'combo' => format::arr_to_csv($report['combo']['result'], $conf_combo) + $nav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_nav = array('nav' => array(_('report:: navigateur'), 0, 1, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_combo = array('combo' => array(_('report:: navigateurs et plateforme'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_os = array('os' => array(_('report:: plateforme'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_res = array('res' => array(_('report:: resolution'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) + ); + $conf_mod = array('appli' => array(_('report:: module'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'pourcent' => array(_('report:: pourcentage'), 0, 0, 0, 0) ); - sendCsv($csv); - } - else - { - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'nav'); - sendReport($html); - } -} + $report = array( + 'nav' => $nav->buildTabNav($conf_nav), + 'os' => $nav->buildTabOs($conf_os), + 'res' => $nav->buildTabRes($conf_res), + 'mod' => $nav->buildTabModule($conf_mod), + 'combo' => $nav->buildTabCombo($conf_combo) + ); + if ($param['printcsv'] == "on") { + $csv = array( + 'nav' => format::arr_to_csv($report['nav']['result'], $conf_nav), + 'os' => format::arr_to_csv($report['os']['result'], $conf_os), + 'res' => format::arr_to_csv($report['res']['result'], $conf_res), + 'mod' => format::arr_to_csv($report['mod']['result'], $conf_mod), + 'combo' => format::arr_to_csv($report['combo']['result'], $conf_combo) + ); + + sendCsv($csv); + } else { + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'nav'); + sendReport($html); + } +} /* generate the html string to display the number of connexion by user in
    , the result is encoded in json */ function cnxu($param, $twig) { - $connex = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $connex->setConfig(false); - $connex->setBound("user", true); - doLimit($connex, $param); + $connex = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $connex->setConfig(false); + $connex->setBound("user", true); + doLimit($connex, $param); - if ($param['printcsv'] == "on") - { - $connex->setHasLimit(false); - $report_csv = $connex->getConnexionBase(false, $param['on']); - $result_csv = $connex->getResult(); - $display = $connex->getDisplay(); - $csv = format::arr_to_csv($result_csv, $display); - sendCsv($csv); - } - else - { - $report = $connex->getConnexionBase(false, $param['on']); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $connex->setHasLimit(false); + $report_csv = $connex->getConnexionBase(false, $param['on']); + $result_csv = $connex->getResult(); + $display = $connex->getDisplay(); + $csv = format::arr_to_csv($result_csv, $display); + sendCsv($csv); + } else { + $report = $connex->getConnexionBase(false, $param['on']); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html); + } } - /* generate all the html string to display the top 20 question by databox in
    , the result is encoded in json */ function bestOf($param, $twig) { - $conf = array( - 'search' => array(_('report:: question'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'search' => array(_('report:: question'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $activity->setLimit(1, $param['limit']); - $activity->setTop(20); - $activity->setConfig(false); + $activity->setLimit(1, $param['limit']); + $activity->setTop(20); + $activity->setConfig(false); - if ($param['printcsv'] == "on") - { - $activity->setHasLimit(false); - $report_csv = $activity->getTopQuestion($conf); - $result_csv = $activity->getResult(); - $display = $activity->getDisplay(); - $csv = format::arr_to_csv($result_csv, $display); - sendCsv($csv); - } - else - { - $report = $activity->getTopQuestion($conf); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $activity->setHasLimit(false); + $report_csv = $activity->getTopQuestion($conf); + $result_csv = $activity->getResult(); + $display = $activity->getDisplay(); + $csv = format::arr_to_csv($result_csv, $display); + sendCsv($csv); + } else { + $report = $activity->getTopQuestion($conf); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html); + } } - /* generate all the html string to display all the resot of questions
    , the result is encoded in json */ function noBestOf($param, $twig) { - $conf = array('search' => array(_('report:: question'), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), - 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $activity->setConfig(false); - doLimit($activity, $param); + $conf = array('search' => array(_('report:: question'), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0), + 'nb_rep' => array(_('report:: nombre de reponses'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $activity->setConfig(false); + doLimit($activity, $param); - if ($param['printcsv'] == "on") - { - $activity->setHasLimit(false); - $report_csv = $activity->getTopQuestion($conf, true); - $result_csv = $activity->getResult(); - $display = $activity->getDisplay(); - $csv = format::arr_to_csv($result_csv, $display); - sendCsv($csv); - } - else - { - $report = $activity->getTopQuestion($conf, true); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $activity->setHasLimit(false); + $report_csv = $activity->getTopQuestion($conf, true); + $result_csv = $activity->getResult(); + $display = $activity->getDisplay(); + $csv = format::arr_to_csv($result_csv, $display); + sendCsv($csv); + } else { + $report = $activity->getTopQuestion($conf, true); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html); + } } - /* generate all the html string to display the users connexions activity by hour in
    , the result is encoded in json */ function tableSiteActivityPerHours($param, $twig) { - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $activity->setConfig(false); - $report = $activity->getActivityPerHours(); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $activity->setConfig(false); + $report = $activity->getActivityPerHours(); - if ($param['printcsv'] == "on") - { - $display = $activity->getDisplay(); - $result = $activity->getResult(); - $csv = format::arr_to_csv($result, $display); - sendCsv($csv); - } - else - { - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'plot'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $display = $activity->getDisplay(); + $result = $activity->getResult(); + $csv = format::arr_to_csv($result, $display); + sendCsv($csv); + } else { + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig', 'plot'); + sendReport($html); + } } - /* generate all the html string to display all number of download day by day in
    , the result is encoded in json */ function day($param, $twig) { - $conf = array('ddate' => array(_('report:: jour'), 0, 0, 0, 0), - 'total' => array(_('report:: total des telechargements'), 0, 0, 0, 0), - 'preview' => array(_('report:: preview'), 0, 0, 0, 0), - 'document' => array(_('report:: document original'), 0, 0, 0, 0) - ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - doLimit($activity, $param); - $activity->setConfig(false); + $conf = array('ddate' => array(_('report:: jour'), 0, 0, 0, 0), + 'total' => array(_('report:: total des telechargements'), 0, 0, 0, 0), + 'preview' => array(_('report:: preview'), 0, 0, 0, 0), + 'document' => array(_('report:: document original'), 0, 0, 0, 0) + ); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + doLimit($activity, $param); + $activity->setConfig(false); - if ($param['printcsv'] == "on") - { - $activity->setHasLimit(false); - $report_csv = $activity->getDownloadByBaseByDay($conf); - $result_csv = $activity->getResult(); - $display = $activity->getDisplay(); - $csv = format::arr_to_csv($result_csv, $display); - sendCsv($csv); - } - else - { - $report = $activity->getDownloadByBaseByDay($conf); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $activity->setHasLimit(false); + $report_csv = $activity->getDownloadByBaseByDay($conf); + $result_csv = $activity->getResult(); + $display = $activity->getDisplay(); + $csv = format::arr_to_csv($result_csv, $display); + sendCsv($csv); + } else { + $report = $activity->getDownloadByBaseByDay($conf); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html); + } } - /* generate all the html string to display all the details of download user by user in
    , the result is encoded in json */ function usr($param, $twig) { - $conf = array('user' => array(_('report:: utilisateur'), 0, 1, 0, 0), - 'nbdoc' => array(_('report:: nombre de documents'), 0, 0, 0, 0), - 'poiddoc' => array(_('report:: poids des documents'), 0, 0, 0, 0), - 'nbprev' => array(_('report:: nombre de preview'), 0, 0, 0, 0), - 'poidprev' => array(_('report:: poids des previews'), 0, 0, 0, 0) - ); + $conf = array('user' => array(_('report:: utilisateur'), 0, 1, 0, 0), + 'nbdoc' => array(_('report:: nombre de documents'), 0, 0, 0, 0), + 'poiddoc' => array(_('report:: poids des documents'), 0, 0, 0, 0), + 'nbprev' => array(_('report:: nombre de preview'), 0, 0, 0, 0), + 'poidprev' => array(_('report:: poids des previews'), 0, 0, 0, 0) + ); - $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - doLimit($activity, $param); - $activity->setConfig(false); + $activity = new module_report_activity($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + doLimit($activity, $param); + $activity->setConfig(false); - if ($param['printcsv'] == "on") - { - $activity->setHasLimit(false); - $report_csv = $activity->getDetailDownload($conf, $param['on']); - $result_csv = $activity->getResult(); - $display = $activity->getDisplay(); - $csv = format::arr_to_csv($result_csv, $display); - sendCsv($csv); - } - else - { - $report = $activity->getDetailDownload($conf, $param['on']); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html); - } + if ($param['printcsv'] == "on") { + $activity->setHasLimit(false); + $report_csv = $activity->getDetailDownload($conf, $param['on']); + $result_csv = $activity->getResult(); + $display = $activity->getDisplay(); + $csv = format::arr_to_csv($result_csv, $display); + sendCsv($csv); + } else { + $report = $activity->getDetailDownload($conf, $param['on']); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html); + } } - /* Display basic informations about an user */ function infoUsr($param, $twig, $conf) { - $registry = registry::get_instance(); - if ($registry->get('GV_anonymousReport') == true) - { - $conf['conf'] = array( - $param['on'] => array($param['on'], 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) - ); - } + $registry = registry::get_instance(); + if ($registry->get('GV_anonymousReport') == true) { + $conf['conf'] = array( + $param['on'] => array($param['on'], 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) + ); + } - $request = ""; - $params = array(); - $html = ""; - $html_info = ""; - $is_dl = false; + $request = ""; + $params = array(); + $html = ""; + $html_info = ""; + $is_dl = false; - if ($param['from'] == 'CNXU' || $param['from'] == 'CNX') - { - $histo = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_cnx']; - $title = _("report:: historique des connexions"); - } - elseif ($param['from'] == "USR" || $param['from'] == "GEN") - { - $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_dl']; - $is_dl = true; - $title = _("report:: historique des telechargements"); - } - elseif ($param['from'] == "ASK") - { - $histo = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $conf_array = $conf['config_ask']; - $title = _("report:: historique des questions"); - } + if ($param['from'] == 'CNXU' || $param['from'] == 'CNX') { + $histo = new module_report_connexion($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_cnx']; + $title = _("report:: historique des connexions"); + } elseif ($param['from'] == "USR" || $param['from'] == "GEN") { + $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_dl']; + $is_dl = true; + $title = _("report:: historique des telechargements"); + } elseif ($param['from'] == "ASK") { + $histo = new module_report_question($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf_array = $conf['config_ask']; + $title = _("report:: historique des questions"); + } - if (isset($histo)) - { - $rs = getHistory($histo, $param, $twig, $conf_array, $is_dl, $title); - $html = $rs['html']; - $request = $rs['req']; - $params = $rs['params']; - } + if (isset($histo)) { + $rs = getHistory($histo, $param, $twig, $conf_array, $is_dl, $title); + $html = $rs['html']; + $request = $rs['req']; + $params = $rs['params']; + } - $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $info->setPeriode(""); - $info->setCsv(false); - $report = $info->buildTabGrpInfo($request, $params, $param['user'], $conf['conf'], $param['on']); - if ($registry->get('GV_anonymousReport') == false) - { - $html_info .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - (empty($param['on']) && isset($report['result'])) ? $title = $report['result'][0]['identifiant'] : $title = $param['user']; - } - else - $title = $param['user']; + $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $info->setPeriode(""); + $info->setCsv(false); + $report = $info->buildTabGrpInfo($request, $params, $param['user'], $conf['conf'], $param['on']); + if ($registry->get('GV_anonymousReport') == false) { + $html_info .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + (empty($param['on']) && isset($report['result'])) ? $title = $report['result'][0]['identifiant'] : $title = $param['user']; + } + else + $title = $param['user']; - sendReport($html_info . $html, false, $title); + sendReport($html_info . $html, false, $title); } - /* Display some basics informations about a Document */ function what($param, $twig) { - $registry = registry::get_instance(); - $config = array( - 'photo' => array(_('report:: document'), 0, 0, 0, 0), - 'record_id' => array(_('report:: record id'), 0, 0, 0, 0), - 'date' => array(_('report:: date'), 0, 0, 0, 0), - 'type' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), - 'titre' => array(_('report:: titre'), 0, 0, 0, 0), - 'taille' => array(_('report:: poids'), 0, 0, 0, 0) - ); - $config_dl = array( - 'ddate' => array(_('report:: date'), 0, 0, 0, 0), - 'user' => array(_('report:: utilisateurs'), 0, 0, 0, 0), - 'final' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), - 'coll_id' => array(_('report:: collections'), 0, 0, 0, 0), - 'comment' => array(_('report:: commentaire'), 0, 0, 0, 0), - 'fonction' => array(_('report:: fonction'), 0, 0, 0, 0), - 'activite' => array(_('report:: activite'), 0, 0, 0, 0), - 'pays' => array(_('report:: pays'), 0, 0, 0, 0), - 'societe' => array(_('report:: societe'), 0, 0, 0, 0) - ); - - $config_dl = doUserConf($config_dl, $param); - - $html = ""; - $basid = getBasId($param); - - $what = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $what->setPeriode(""); - $what->setCsv(false); - $what->setPrint(false); - $report = $what->buildTabUserWhat($basid, $param['rid'], $config); - $title = $what->getTitle(); - - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - - if ($param['from'] == 'TOOL') - { - $what->setTitle(""); - sendReport($html, false, $title); - - return false; - } - elseif ($param['from'] != 'DASH' && $param['from'] != "PUSHDOC") - { - $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - - $filter = doFilter($histo, $param, $twig); - if (!empty($param['rid'])) - $filter->addfilter('record_id', '=', $param['rid']); - - $tab_filter = $filter->getTabFilter(); - $histo->setFilter($tab_filter); - $histo->setOrder('ddate', 'DESC'); - $histo->setTitle(_("report:: historique des telechargements")); - $histo->setConfig(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($histo, $param, $config_dl, $twig); - sendCsv($csv); - } - else - { - $report = $histo->buildReport($config_dl); - $html .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, false, $title); - } - } - elseif ($registry->get('GV_anonymousReport') == false && $param['from'] != 'DOC' && $param['from'] != 'DASH' && $param['from'] != "GEN" && $param['from'] != "PUSHDOC") - { - $conf = array( - 'identifiant' => array(_('report:: identifiant'), 0, 0, 0, 0), - 'nom' => array(_('report:: nom'), 0, 0, 0, 0), - 'mail' => array(_('report:: email'), 0, 0, 0, 0), - 'adresse' => array(_('report:: adresse'), 0, 0, 0, 0), - 'tel' => array(_('report:: telephone'), 0, 0, 0, 0) + $registry = registry::get_instance(); + $config = array( + 'photo' => array(_('report:: document'), 0, 0, 0, 0), + 'record_id' => array(_('report:: record id'), 0, 0, 0, 0), + 'date' => array(_('report:: date'), 0, 0, 0, 0), + 'type' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), + 'titre' => array(_('report:: titre'), 0, 0, 0, 0), + 'taille' => array(_('report:: poids'), 0, 0, 0, 0) + ); + $config_dl = array( + 'ddate' => array(_('report:: date'), 0, 0, 0, 0), + 'user' => array(_('report:: utilisateurs'), 0, 0, 0, 0), + 'final' => array(_('phrseanet:: sous definition'), 0, 0, 0, 0), + 'coll_id' => array(_('report:: collections'), 0, 0, 0, 0), + 'comment' => array(_('report:: commentaire'), 0, 0, 0, 0), + 'fonction' => array(_('report:: fonction'), 0, 0, 0, 0), + 'activite' => array(_('report:: activite'), 0, 0, 0, 0), + 'pays' => array(_('report:: pays'), 0, 0, 0, 0), + 'societe' => array(_('report:: societe'), 0, 0, 0, 0) ); - $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $info->setPeriode(""); - $info->setConfig(false); - $info->setTitle(_('report:: utilisateur')); - if ($param['printcsv'] == "on") - { - $csv = doCsv($info, $param, $conf, $twig); - sendCsv($csv); + $config_dl = doUserConf($config_dl, $param); + + $html = ""; + $basid = getBasId($param); + + $what = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $what->setPeriode(""); + $what->setCsv(false); + $what->setPrint(false); + $report = $what->buildTabUserWhat($basid, $param['rid'], $config); + $title = $what->getTitle(); + + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + + if ($param['from'] == 'TOOL') { + $what->setTitle(""); + sendReport($html, false, $title); + + return false; + } elseif ($param['from'] != 'DASH' && $param['from'] != "PUSHDOC") { + $histo = new module_report_download($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + + $filter = doFilter($histo, $param, $twig); + if ( ! empty($param['rid'])) + $filter->addfilter('record_id', '=', $param['rid']); + + $tab_filter = $filter->getTabFilter(); + $histo->setFilter($tab_filter); + $histo->setOrder('ddate', 'DESC'); + $histo->setTitle(_("report:: historique des telechargements")); + $histo->setConfig(false); + if ($param['printcsv'] == "on") { + $csv = doCsv($histo, $param, $config_dl, $twig); + sendCsv($csv); + } else { + $report = $histo->buildReport($config_dl); + $html .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, false, $title); + } + } elseif ($registry->get('GV_anonymousReport') == false && $param['from'] != 'DOC' && $param['from'] != 'DASH' && $param['from'] != "GEN" && $param['from'] != "PUSHDOC") { + $conf = array( + 'identifiant' => array(_('report:: identifiant'), 0, 0, 0, 0), + 'nom' => array(_('report:: nom'), 0, 0, 0, 0), + 'mail' => array(_('report:: email'), 0, 0, 0, 0), + 'adresse' => array(_('report:: adresse'), 0, 0, 0, 0), + 'tel' => array(_('report:: telephone'), 0, 0, 0, 0) + ); + $info = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $info->setPeriode(""); + $info->setConfig(false); + $info->setTitle(_('report:: utilisateur')); + + if ($param['printcsv'] == "on") { + $csv = doCsv($info, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = $info->buildTabGrpInfo(false, array(), $param['user'], $conf, false); + $html .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, false, $title); + } } else - { - $report = $info->buildTabGrpInfo(false, array(), $param['user'], $conf, false); - $html .= doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, false, $title); - } - } - else - sendReport($html, false, $title); + sendReport($html, false, $title); } - /* Display informations about navigators */ function infoNav($param, $twig) { - $conf = array( - 'version' => array(_('report::version '), 0, 0, 0, 0), - 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) - ); - $infonav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $infonav->setCsv(false); - $infonav->setConfig(false); - $report = $infonav->buildTabInfoNav($conf, $param['user']); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, false, $param['user']); + $conf = array( + 'version' => array(_('report::version '), 0, 0, 0, 0), + 'nb' => array(_('report:: nombre'), 0, 0, 0, 0) + ); + $infonav = new module_report_nav($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $infonav->setCsv(false); + $infonav->setConfig(false); + $report = $infonav->buildTabInfoNav($conf, $param['user']); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, false, $param['user']); } function pushDoc($param, $twig) { - $conf = array( - 'user' => array("", 1, 0, 1, 1), - 'getter' => array("Destinataire", 1, 0, 1, 1), - 'date' => array("", 1, 0, 1, 1), - 'record_id' => array("", 1, 1, 1, 1), - 'file' => array("", 1, 0, 1, 1), - 'mime' => array("", 1, 0, 1, 1), - 'size' => array("", 1, 0, 1, 1) - ); - $dl = new module_report_push($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array("", 1, 0, 1, 1), + 'getter' => array("Destinataire", 1, 0, 1, 1), + 'date' => array("", 1, 0, 1, 1), + 'record_id' => array("", 1, 1, 1, 1), + 'file' => array("", 1, 0, 1, 1), + 'mime' => array("", 1, 0, 1, 1), + 'size' => array("", 1, 0, 1, 1) + ); + $dl = new module_report_push($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $dl->setConfig(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + $dl->setConfig(false); + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } function addDoc($param, $twig) { - $conf = array( - 'user' => array("", 1, 0, 1, 1), - 'date' => array("", 1, 0, 1, 1), - 'record_id' => array("", 1, 1, 1, 1), - 'file' => array("", 1, 0, 1, 1), - 'mime' => array("", 1, 0, 1, 1), - 'size' => array("", 1, 0, 1, 1) - ); - $dl = new module_report_add($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array("", 1, 0, 1, 1), + 'date' => array("", 1, 0, 1, 1), + 'record_id' => array("", 1, 1, 1, 1), + 'file' => array("", 1, 0, 1, 1), + 'mime' => array("", 1, 0, 1, 1), + 'size' => array("", 1, 0, 1, 1) + ); + $dl = new module_report_add($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $dl->setConfig(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + $dl->setConfig(false); + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } function ediDoc($param, $twig) { - $conf = array( - 'user' => array("", 1, 0, 1, 1), - 'date' => array("", 1, 0, 1, 1), - 'record_id' => array("", 1, 1, 1, 1), - 'file' => array("", 1, 0, 1, 1), - 'mime' => array("", 1, 0, 1, 1), - 'size' => array("", 1, 0, 1, 1) - ); - $dl = new module_report_edit($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array("", 1, 0, 1, 1), + 'date' => array("", 1, 0, 1, 1), + 'record_id' => array("", 1, 1, 1, 1), + 'file' => array("", 1, 0, 1, 1), + 'mime' => array("", 1, 0, 1, 1), + 'size' => array("", 1, 0, 1, 1) + ); + $dl = new module_report_edit($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $dl->setConfig(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + $dl->setConfig(false); + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } function validDoc($param, $twig) { - $conf = array( - 'user' => array("", 1, 0, 1, 1), - 'getter' => array("Destinataire", 1, 0, 1, 1), - 'date' => array("", 1, 0, 1, 1), - 'record_id' => array("", 1, 1, 1, 1), - 'file' => array("", 1, 0, 1, 1), - 'mime' => array("", 1, 0, 1, 1), - 'size' => array("", 1, 0, 1, 1) - ); - $dl = new module_report_validate($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); + $conf = array( + 'user' => array("", 1, 0, 1, 1), + 'getter' => array("Destinataire", 1, 0, 1, 1), + 'date' => array("", 1, 0, 1, 1), + 'record_id' => array("", 1, 1, 1, 1), + 'file' => array("", 1, 0, 1, 1), + 'mime' => array("", 1, 0, 1, 1), + 'size' => array("", 1, 0, 1, 1) + ); + $dl = new module_report_validate($param['dmin'], $param['dmax'], $param['sbasid'], $param['collection']); - $dl->setConfig(false); - if ($param['printcsv'] == "on") - { - $csv = doCsv($dl, $param, $conf, $twig); - sendCsv($csv); - } - else - { - $report = doReport($dl, $param, $conf, $twig); - $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); - sendReport($html, $report); - } + $dl->setConfig(false); + if ($param['printcsv'] == "on") { + $csv = doCsv($dl, $param, $conf, $twig); + sendCsv($csv); + } else { + $report = doReport($dl, $param, $conf, $twig); + $html = doHtml($report, $param, $twig, 'report/ajax_data_content.twig'); + sendReport($html, $report); + } } function whichDoc($param, $twig) { - switch ($param['docwhat']) - { - case "ADDDOC": - addDoc($param, $twig); - break; + switch ($param['docwhat']) { + case "ADDDOC": + addDoc($param, $twig); + break; - case "EDIDOC": - ediDoc($param, $twig); - break; + case "EDIDOC": + ediDoc($param, $twig); + break; - case "PUSHDOC": - pushDoc($param, $twig); - break; - case "VALIDATEDOC" : - validDoc($param, $twig); - break; - } + case "PUSHDOC": + pushDoc($param, $twig); + break; + case "VALIDATEDOC" : + validDoc($param, $twig); + break; + } } - ################################################SWITCH ACTIONS############################################################## -switch ($param['tbl']) -{ - case "CNX": - cnx($param, $twig); - break; +switch ($param['tbl']) { + case "CNX": + cnx($param, $twig); + break; - case "CNXU": - cnxu($param, $twig); - break; + case "CNXU": + cnxu($param, $twig); + break; - case "CNXB": - cnxb($param, $twig); - break; + case "CNXB": + cnxb($param, $twig); + break; - case "GEN": - gen($param, $twig); - break; + case "GEN": + gen($param, $twig); + break; - case "DAY": - day($param, $twig); - break; + case "DAY": + day($param, $twig); + break; - case "DOC": - doc($param, $twig); - break; + case "DOC": + doc($param, $twig); + break; - case "BESTOF": - bestOf($param, $twig); - break; + case "BESTOF": + bestOf($param, $twig); + break; - case "NOBESTOF": - noBestOf($param, $twig); - break; + case "NOBESTOF": + noBestOf($param, $twig); + break; - case "SITEACTIVITY": - tableSiteActivityPerHours($param, $twig); - break; + case "SITEACTIVITY": + tableSiteActivityPerHours($param, $twig); + break; - case "USR": - usr($param, $twig); - break; + case "USR": + usr($param, $twig); + break; - case "ASK": - ask($param, $twig); - break; + case "ASK": + ask($param, $twig); + break; - case "infouser": - infoUsr($param, $twig, $conf_info_usr); - break; + case "infouser": + infoUsr($param, $twig, $conf_info_usr); + break; - case "what": - what($param, $twig); - break; + case "what": + what($param, $twig); + break; - case "infonav": - infoNav($param, $twig); - break; + case "infonav": + infoNav($param, $twig); + break; - case "WDOC": - whichDoc($param, $twig); - break; + case "WDOC": + whichDoc($param, $twig); + break; } ?> diff --git a/www/setup/index.php b/www/setup/index.php index 6f06505026..37d48afe9e 100644 --- a/www/setup/index.php +++ b/www/setup/index.php @@ -1,7 +1,7 @@ - - -
    french : Vous devez activer le mod_rewrite de votre serveur web
    -
    english : You must activate mod_rewrite on your web server
    - + + +
    french : Vous devez activer le mod_rewrite de votre serveur web
    +
    english : You must activate mod_rewrite on your web server
    + diff --git a/www/thesaurus2/accept.php b/www/thesaurus2/accept.php index 107726e9d1..e644ac4c8d 100644 --- a/www/thesaurus2/accept.php +++ b/www/thesaurus2/accept.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -27,286 +26,268 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "src" - , "tgt" - , "dlg" + "bid" + , "piv" + , "src" + , "tgt" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - <?php echo p4string::MakeString(_('thesaurus:: accepter...')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: accepter...')) ?> - - - - - + - - + } + + + \n"); - $dom = xmlhttp($url); +if ($parm["bid"] !== null) { + $url = "thesaurus2/xmlhttp/getterm.x.php"; + $url .= "?bid=" . urlencode($parm["bid"]); + $url .= "&piv=" . urlencode($parm["piv"]); + $url .= "&sortsy=0"; + $url .= "&id=" . urlencode($parm["src"]); + $url .= "&typ=CT"; + $url .= "¬s=1"; + //print("URL='$url'
    \n"); + $dom = xmlhttp($url); - if ((int) ($dom->documentElement->getAttribute('found')) == 0) - { -?> -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    - -getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; - $nts = $dom->getElementsByTagName("ts_list")->item(0)->getAttribute("nts"); + if ((int) ($dom->documentElement->getAttribute('found')) == 0) { + ?> +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + + getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; + $nts = $dom->getElementsByTagName("ts_list")->item(0)->getAttribute("nts"); - if (($cfield = $dom->getElementsByTagName("cfield")->item(0))) - { - if ($cfield->getAttribute("delbranch")) - $cfield = '*'; - else - $cfield = $cfield->getAttribute("field"); - } - else - { - $cfield = NULL; - } - // { - // if( ($cfield_tbranch = $cfield->getAttribute("tbranch")) ) - // { - // } - // } + if (($cfield = $dom->getElementsByTagName("cfield")->item(0))) { + if ($cfield->getAttribute("delbranch")) + $cfield = '*'; + else + $cfield = $cfield->getAttribute("field"); + } + else { + $cfield = NULL; + } + // { + // if( ($cfield_tbranch = $cfield->getAttribute("tbranch")) ) + // { + // } + // } // print("cfield='$cfield'
    \n"); // print($fullpath); - $url = "thesaurus2/xmlhttp/getterm.x.php"; - $url .= "?bid=" . urlencode($parm["bid"]); - $url .= "&piv=" . urlencode($parm["piv"]); - $url .= "&sortsy=0"; - $url .= "&id=" . urlencode($parm["tgt"]); - $url .= "&typ=TH"; - if ($cfield) - $url .= "&acf=" . urlencode($cfield); - $url .= "¬s=1"; + $url = "thesaurus2/xmlhttp/getterm.x.php"; + $url .= "?bid=" . urlencode($parm["bid"]); + $url .= "&piv=" . urlencode($parm["piv"]); + $url .= "&sortsy=0"; + $url .= "&id=" . urlencode($parm["tgt"]); + $url .= "&typ=TH"; + if ($cfield) + $url .= "&acf=" . urlencode($cfield); + $url .= "¬s=1"; - // print("URL='$url'
    \n"); - // print($url. "
    \n"); - $dom = xmlhttp($url); + // print("URL='$url'
    \n"); + // print($url. "
    \n"); + $dom = xmlhttp($url); - if ((int) ($dom->documentElement->getAttribute('found')) == 0) - { - // on n'a pas trouve le node de destination (il a ete deplace par qqun d'autre) -?> -
    -
    -
    -
    - -
    -
    - -
    -
    -
    -
    -
    - -saveXML()); + if ((int) ($dom->documentElement->getAttribute('found')) == 0) { + // on n'a pas trouve le node de destination (il a ete deplace par qqun d'autre) + ?> +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + + saveXML()); - $fullpath_tgt = $dom->getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; + $fullpath_tgt = $dom->getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; - $acceptable = 0 + $dom->getElementsByTagName("cfield")->item(0)->getAttribute("acceptable"); + $acceptable = 0 + $dom->getElementsByTagName("cfield")->item(0)->getAttribute("acceptable"); - // print("acceptable=$acceptable
    \n"); - if ($acceptable) - { -?> -
    -
    + // print("acceptable=$acceptable
    \n"); + if ($acceptable) { + ?> +
    +
    -
    - "> - "> - "> - "> - "> -

    ' . $fullpath_src . '



    '); - print("
      " . p4string::MakeString(_('thesaurus:: comme terme specifique'))); - print("   "); - print(""); - // print("

    \n"); - printf(p4string::MakeString(_('thesaurus:: comme synonyme de %s'), "html"), "

    \n

    " . $fullpath_tgt . "


    \n"); - } - else - { - printf("

    " . $fullpath_src . "



    \n"); - print(p4string::MakeString(_('thesaurus:: Accepter la branche comme'), "html") . '
    '); - print(" " . p4string::MakeString(_('thesaurus:: comme terme specifique'))); - printf("

    \n

    " . $fullpath_tgt . "



    \n"); - print("\n"); - } - // print($fullpath); -?> -
    -
    - -        - -
    -
    - -
    -
    -
    -
    -
    " . $cfield . "

    ") ?> -
    -
    -
    -
    -
    -
    -
    - - - - +
    + "> + "> + "> + "> + "> +

    ' . $fullpath_src . '



    '); + print("
      " . p4string::MakeString(_('thesaurus:: comme terme specifique'))); + print("   "); + print(""); + // print("

    \n"); + printf(p4string::MakeString(_('thesaurus:: comme synonyme de %s'), "html"), "

    \n

    " . $fullpath_tgt . "


    \n"); + } else { + printf("

    " . $fullpath_src . "



    \n"); + print(p4string::MakeString(_('thesaurus:: Accepter la branche comme'), "html") . '
    '); + print(" " . p4string::MakeString(_('thesaurus:: comme terme specifique'))); + printf("

    \n

    " . $fullpath_tgt . "



    \n"); + print("\n"); + } + // print($fullpath); + ?> +
    +
    + +        + +
    +
    + +
    +
    +
    +
    +
    " . $cfield . "

    ") ?> +
    +
    +
    +
    +
    +
    +
    + + + + diff --git a/www/thesaurus2/export_text.php b/www/thesaurus2/export_text.php index df6710d03f..cfdb078474 100644 --- a/www/thesaurus2/export_text.php +++ b/www/thesaurus2/export_text.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -26,92 +25,80 @@ phrasea::headers(200, true); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "typ" - , "dlg" - , "osl" - , "iln" - , "ilg" - , "hit" - , "smp" + "bid" + , "piv" + , "id" + , "typ" + , "dlg" + , "osl" + , "iln" + , "ilg" + , "hit" + , "smp" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - <?php echo p4string::MakeString(_('thesaurus:: export au format texte')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: export au format texte')) ?> - + - - - + + + get_dom_thesaurus(); + } else { + $domth = $databox->get_dom_cterms(); + } + + if ($domth) { + $sql = "SELECT value, SUM(1) as hits FROM thit GROUP BY value"; + + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($rs as $rowbas2) { + $thits[str_replace('d', '.', $rowbas2["value"])] = $rowbas2["hits"]; + } + + $xpathth = new DOMXPath($domth); + printf("
    \n", $parm["smp"] ? 9 : 12);
    +            if ($parm["id"] == "T")
    +                $q = "/thesaurus";
    +            elseif ($parm["id"] == "C")
    +                $q = "/cterms";
    +            else
    +                $q = "//te[@id='" . $parm["id"] . "']";
    +            export0($xpathth->query($q)->item(0));
    +            print("
    \n"); + } + } catch (Exception $e) { - if ($parm["typ"] == "TH") - { - $domth = $databox->get_dom_thesaurus(); } - else - { - $domth = $databox->get_dom_cterms(); - } - - if ($domth) - { - $sql = "SELECT value, SUM(1) as hits FROM thit GROUP BY value"; - - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $rowbas2) - { - $thits[str_replace('d', '.', $rowbas2["value"])] = $rowbas2["hits"]; - } - - $xpathth = new DOMXPath($domth); - printf("
    \n", $parm["smp"] ? 9 : 12);
    -      if ($parm["id"] == "T")
    -        $q = "/thesaurus";
    -      elseif ($parm["id"] == "C")
    -        $q = "/cterms";
    -      else
    -        $q = "//te[@id='" . $parm["id"] . "']";
    -      export0($xpathth->query($q)->item(0));
    -      print("
    \n"); - } - } - catch (Exception $e) - { - - } } @@ -120,173 +107,155 @@ $tnodes = NULL; function printTNodes() { - global $tnodes; - global $thits; - global $parm; + global $tnodes; + global $thits; + global $parm; - $numlig = ($parm["iln"] == "1"); - $hits = ($parm["hit"] == "1"); - $ilg = ($parm["ilg"] == "1"); - $oneline = ($parm["osl"] == "1"); + $numlig = ($parm["iln"] == "1"); + $hits = ($parm["hit"] == "1"); + $ilg = ($parm["ilg"] == "1"); + $oneline = ($parm["osl"] == "1"); - $ilig = 1; + $ilig = 1; - foreach ($tnodes as $node) - { - $tabs = str_repeat("\t", $node["depth"]); - switch ($node["type"]) - { - case "ROOT": - if ($numlig) - print($ilig++ . "\t"); - if ($hits && !$oneline) - print("\t"); - print($tabs . $node["name"] . "\n"); - break; - case "TRASH": - if ($numlig) - print($ilig++ . "\t"); - if ($hits && !$oneline) - print("\t"); - print($tabs . "{TRASH}\n"); - break; - case "FIELD": - if ($numlig) - print($ilig++ . "\t"); - if ($hits && !$oneline) - print("\t"); - print($tabs . $node["name"] . "\n"); - break; - case "TERM": - $isyn = 0; - if ($oneline) - { - if ($numlig) - print($ilig++ . "\t"); - print($tabs); - $isyn = 0; - foreach ($node["syns"] as $syn) - { - if ($isyn > 0) - print(" ; "); - print($syn["v"]); - if ($ilg) - print(" [" . $syn["lng"] . "]"); - if ($hits) - print(" [" . $syn["hits"] . "]"); - $isyn++; - } - print("\n"); + foreach ($tnodes as $node) { + $tabs = str_repeat("\t", $node["depth"]); + switch ($node["type"]) { + case "ROOT": + if ($numlig) + print($ilig ++ . "\t"); + if ($hits && ! $oneline) + print("\t"); + print($tabs . $node["name"] . "\n"); + break; + case "TRASH": + if ($numlig) + print($ilig ++ . "\t"); + if ($hits && ! $oneline) + print("\t"); + print($tabs . "{TRASH}\n"); + break; + case "FIELD": + if ($numlig) + print($ilig ++ . "\t"); + if ($hits && ! $oneline) + print("\t"); + print($tabs . $node["name"] . "\n"); + break; + case "TERM": + $isyn = 0; + if ($oneline) { + if ($numlig) + print($ilig ++ . "\t"); + print($tabs); + $isyn = 0; + foreach ($node["syns"] as $syn) { + if ($isyn > 0) + print(" ; "); + print($syn["v"]); + if ($ilg) + print(" [" . $syn["lng"] . "]"); + if ($hits) + print(" [" . $syn["hits"] . "]"); + $isyn ++; + } + print("\n"); + } + else { + $isyn = 0; + foreach ($node["syns"] as $syn) { + if ($numlig) + print($ilig ++ . "\t"); + if ($hits) + print( $syn["hits"] . "\t"); + print($tabs); + if ($isyn > 0) + print("; "); + print($syn["v"]); + if ($ilg) + print(" [" . $syn["lng"] . "]"); + print("\n"); + $isyn ++; + } + } + break; } - else - { - $isyn = 0; - foreach ($node["syns"] as $syn) - { + if ( ! $oneline) { if ($numlig) - print($ilig++ . "\t"); - if ($hits) - print( $syn["hits"] . "\t"); - print($tabs); - if ($isyn > 0) - print("; "); - print($syn["v"]); - if ($ilg) - print(" [" . $syn["lng"] . "]"); + print($ilig ++ . "\t"); print("\n"); - $isyn++; - } } - break; } - if (!$oneline) - { - if ($numlig) - print($ilig++ . "\t"); - print("\n"); - } - } } function exportNode(&$node, $depth) { - global $thits; - global $tnodes; - if ($node->nodeType == XML_ELEMENT_NODE) - { - if (($nname = $node->nodeName) == "thesaurus" || $nname == "cterms") - { - $tnodes[] = array("type" => "ROOT", "depth" => $depth, "name" => $nname, "cdate" => $node->getAttribute("creation_date"), "mdate" => $node->getAttribute("modification_date")); - } - elseif (($fld = $node->getAttribute("field"))) - { - if ($node->getAttribute("delbranch")) - $tnodes[] = array("type" => "TRASH", "depth" => $depth, "name" => $fld); - else - $tnodes[] = array("type" => "FIELD", "depth" => $depth, "name" => $fld); - } - else - { - $tsy = array(); - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "sy") - { - $id = $n->getAttribute("id"); - if (array_key_exists($id . '.', $thits)) - $hits = 0 + $thits[$id . '.']; - else - $hits = 0; - - $tsy[] = array("v" => $n->getAttribute("v"), "lng" => $n->getAttribute("lng"), "hits" => $hits); + global $thits; + global $tnodes; + if ($node->nodeType == XML_ELEMENT_NODE) { + if (($nname = $node->nodeName) == "thesaurus" || $nname == "cterms") { + $tnodes[] = array("type" => "ROOT", "depth" => $depth, "name" => $nname, "cdate" => $node->getAttribute("creation_date"), "mdate" => $node->getAttribute("modification_date")); + } elseif (($fld = $node->getAttribute("field"))) { + if ($node->getAttribute("delbranch")) + $tnodes[] = array("type" => "TRASH", "depth" => $depth, "name" => $fld); + else + $tnodes[] = array("type" => "FIELD", "depth" => $depth, "name" => $fld); + } + else { + $tsy = array(); + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "sy") { + $id = $n->getAttribute("id"); + if (array_key_exists($id . '.', $thits)) + $hits = 0 + $thits[$id . '.']; + else + $hits = 0; + + $tsy[] = array("v" => $n->getAttribute("v"), "lng" => $n->getAttribute("lng"), "hits" => $hits); + } + } + $tnodes[] = array("type" => "TERM", "depth" => $depth, "syns" => $tsy); } - } - $tnodes[] = array("type" => "TERM", "depth" => $depth, "syns" => $tsy); } - } } function export0($znode) { - global $tnodes; - $tnodes = array(); + global $tnodes; + $tnodes = array(); - $nodes = array(); - $depth = 0; + $nodes = array(); + $depth = 0; - for ($node = $znode->parentNode; $node; $node = $node->parentNode) - { - if ($node->nodeType == XML_ELEMENT_NODE) - $nodes[] = $node; - } - $nodes = array_reverse($nodes); + for ($node = $znode->parentNode; $node; $node = $node->parentNode) { + if ($node->nodeType == XML_ELEMENT_NODE) + $nodes[] = $node; + } + $nodes = array_reverse($nodes); - foreach ($nodes as $depth => $node) - { - // print( exportNode($node, $depth) ); - exportNode($node, $depth); - } + foreach ($nodes as $depth => $node) { + // print( exportNode($node, $depth) ); + exportNode($node, $depth); + } - export($znode, count($nodes)); + export($znode, count($nodes)); - printTNodes(); + printTNodes(); } -function export($node, $depth=0) +function export($node, $depth = 0) { - global $tnodes; - if ($node->nodeType == XML_ELEMENT_NODE) - { - // print( exportNode($node, $depth) ); - exportNode($node, $depth); - } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "te") - export($n, $depth + 1); - } + global $tnodes; + if ($node->nodeType == XML_ELEMENT_NODE) { + // print( exportNode($node, $depth) ); + exportNode($node, $depth); + } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "te") + export($n, $depth + 1); + } } ?> - + diff --git a/www/thesaurus2/export_text_dlg.php b/www/thesaurus2/export_text_dlg.php index 4f7ffee188..98215688bf 100644 --- a/www/thesaurus2/export_text_dlg.php +++ b/www/thesaurus2/export_text_dlg.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,173 +22,170 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "typ" - , "dlg" + "bid" + , "piv" + , "id" + , "typ" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - <?php echo p4string::MakeString(_('thesaurus:: export au format texte')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: export au format texte')) ?> - - - - + { + url += "&obr="; + } + */ + // alert(url); + document.getElementById("ifrsample").src = url; + } + + +
    -
    -
    - " > - " > - " > - " > - " > - - - - - - - - - - + + + +
    -
    - - -
    -
    -
    - +
    + + " > + " > + " > + " > + " > + + + + + + + + + + - - - -
    +
    + + +
    +
    +
    + -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    -
    -
    - -     - - +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    + +
    +
    +
    + +     + +
    - + diff --git a/www/thesaurus2/export_topics.php b/www/thesaurus2/export_topics.php index a225e44563..5da518be06 100644 --- a/www/thesaurus2/export_topics.php +++ b/www/thesaurus2/export_topics.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -25,281 +24,250 @@ $registry = $appbox->get_registry(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "typ" - , "dlg" - , 'obr' // liste des branches ouvertes - , 'ofm' // 'toscreen' ; 'tofiles' - , 'srt' // trie - , 'sth' // recherche 'thesaurus' - , 'sand' // full query, with 'and's - , 'obrf' // opened br format + "bid" + , "piv" + , "id" + , "typ" + , "dlg" + , 'obr' // liste des branches ouvertes + , 'ofm' // 'toscreen' ; 'tofiles' + , 'srt' // trie + , 'sth' // recherche 'thesaurus' + , 'sand' // full query, with 'and's + , 'obrf' // opened br format ); -if ($parm['ofm'] == 'toscreen') -{ - //header('Content-type: text/xml'); - //header('Content-Disposition: attachment; filename="topics.xml"'); +if ($parm['ofm'] == 'toscreen') { + //header('Content-type: text/xml'); + //header('Content-Disposition: attachment; filename="topics.xml"'); } $lng = Session_Handler::get_locale(); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } $obr = explode(';', $parm['obr']); $t_lng = array(); -if ($parm['ofm'] == 'tofiles') -{ - $t = User_Adapter::avLanguages(); - foreach ($t as $lng_code => $lng) - $t_lng[] = $lng_code; -} -else -{ - $t_lng[] = $parm['piv']; +if ($parm['ofm'] == 'tofiles') { + $t = User_Adapter::avLanguages(); + foreach ($t as $lng_code => $lng) + $t_lng[] = $lng_code; +} else { + $t_lng[] = $parm['piv']; } -switch ($parm['obrf']) -{ - case 'from_itf_closable': - $default_display = 'closed'; - $opened_display = 'opened'; - break; - case 'from_itf_static': - $default_display = 'closed'; - $opened_display = 'static'; - break; - case 'all_opened_closable': - $default_display = 'opened'; - $opened_display = ''; - break; - case 'all_opened_static': - $default_display = 'static'; - $opened_display = ''; - break; - case 'all_closed': - $default_display = 'closed'; - $opened_display = ''; - break; +switch ($parm['obrf']) { + case 'from_itf_closable': + $default_display = 'closed'; + $opened_display = 'opened'; + break; + case 'from_itf_static': + $default_display = 'closed'; + $opened_display = 'static'; + break; + case 'all_opened_closable': + $default_display = 'opened'; + $opened_display = ''; + break; + case 'all_opened_static': + $default_display = 'static'; + $opened_display = ''; + break; + case 'all_closed': + $default_display = 'closed'; + $opened_display = ''; + break; } $now = date('YmdHis'); ?> - - <?php echo p4string::MakeString(_('thesaurus:: export en topics')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: export en topics')) ?> - + - + - - - -
    + + + +
    get_dom_thesaurus(); - } - else - { - $domth = $databox->get_dom_cterms(); - } - - if ($domth) - { - $xpathth = new DOMXPath($domth); - if ($parm["id"] == "T") - $q = "/thesaurus"; - elseif ($parm["id"] == "C") - $q = "/cterms"; - else - $q = "//te[@id='" . $parm["id"] . "']"; - - if ($parm['ofm'] == 'toscreen') - printf("
    \n");
    -      foreach ($t_lng as $lng)
    -      {
    -        $dom = new DOMDocument("1.0", "UTF-8");
    -        $dom->standalone = true;
    -        $dom->preserveWhiteSpace = false;
    -        $dom->formatOutput = true;
    -        $root = $dom->appendChild($dom->createElementNS('www.phraseanet.com', 'phraseanet:topics'));
    -
    -        $root->appendChild($dom->createComment(sprintf(_('thesaurus:: fichier genere le %s'), $now)));
    -
    -        $root->appendChild($dom->createElement('display'))
    -                ->appendChild($dom->createElement('defaultview'))
    -                ->appendChild($dom->createTextNode($default_display));
    -
    -        export0($xpathth->query($q)->item(0), $dom, $root, $lng);
    -
    -        if ($parm['ofm'] == 'toscreen')
    -        {
    -          print(str_replace(array('&', '<', '>'), array('&', '<', '>'), $dom->saveXML()));
    +if ($parm["typ"] == "TH" || $parm["typ"] == "CT") {
    +    $loaded = false;
    +    try {
    +        $databox = databox::get_instance((int) $parm['bid']);
    +        if ($parm["typ"] == "TH") {
    +            $domth = $databox->get_dom_thesaurus();
    +        } else {
    +            $domth = $databox->get_dom_cterms();
             }
    -        elseif ($parm['ofm'] == 'tofiles')
    -        {
    -          $fname = 'topics_' . $lng . '.xml';
     
    -          @rename($registry->get('GV_RootPath') . 'config/topics/' . $fname, $registry->get('GV_RootPath') . 'config/topics/topics_' . $lng . '_BKP_' . $now . '.xml');
    +        if ($domth) {
    +            $xpathth = new DOMXPath($domth);
    +            if ($parm["id"] == "T")
    +                $q = "/thesaurus";
    +            elseif ($parm["id"] == "C")
    +                $q = "/cterms";
    +            else
    +                $q = "//te[@id='" . $parm["id"] . "']";
     
    -          if ($dom->save($registry->get('GV_RootPath') . 'config/topics/' . $fname))
    -            echo p4string::MakeString(sprintf(_('thesaurus:: fichier genere : %s'), $fname));
    -          else
    -            echo p4string::MakeString(_('thesaurus:: erreur lors de l\'enregsitrement du fichier'));
    -          print("

    \n"); + if ($parm['ofm'] == 'toscreen') + printf("
    \n");
    +            foreach ($t_lng as $lng) {
    +                $dom = new DOMDocument("1.0", "UTF-8");
    +                $dom->standalone = true;
    +                $dom->preserveWhiteSpace = false;
    +                $dom->formatOutput = true;
    +                $root = $dom->appendChild($dom->createElementNS('www.phraseanet.com', 'phraseanet:topics'));
    +
    +                $root->appendChild($dom->createComment(sprintf(_('thesaurus:: fichier genere le %s'), $now)));
    +
    +                $root->appendChild($dom->createElement('display'))
    +                    ->appendChild($dom->createElement('defaultview'))
    +                    ->appendChild($dom->createTextNode($default_display));
    +
    +                export0($xpathth->query($q)->item(0), $dom, $root, $lng);
    +
    +                if ($parm['ofm'] == 'toscreen') {
    +                    print(str_replace(array('&', '<', '>'), array('&', '<', '>'), $dom->saveXML()));
    +                } elseif ($parm['ofm'] == 'tofiles') {
    +                    $fname = 'topics_' . $lng . '.xml';
    +
    +                    @rename($registry->get('GV_RootPath') . 'config/topics/' . $fname, $registry->get('GV_RootPath') . 'config/topics/topics_' . $lng . '_BKP_' . $now . '.xml');
    +
    +                    if ($dom->save($registry->get('GV_RootPath') . 'config/topics/' . $fname))
    +                        echo p4string::MakeString(sprintf(_('thesaurus:: fichier genere : %s'), $fname));
    +                    else
    +                        echo p4string::MakeString(_('thesaurus:: erreur lors de l\'enregsitrement du fichier'));
    +                    print("

    \n"); + } + } + if ($parm['ofm'] == 'toscreen') + print("
    \n"); } - } - if ($parm['ofm'] == 'toscreen') - print("
    \n"); - } - } - catch (Exception $e) - { + } catch (Exception $e) { - } + } } -if ($parm['ofm'] == 'tofiles') -{ -?> -
    -
    -
    -
    - -
    - -
    - +if ($parm['ofm'] == 'tofiles') { + ?> +
    +
    +
    +
    + +
    + +
    + -appendChild($dom->createElement('topics')); - export($znode, $dom, $topics, '', $lng, 0); - } - - function export($node, &$dom, &$topics, $prevQuery, $lng, $depth=0) - { - global $parm; - global $tnodes; - global $obr; - global $opened_display; - $ntopics = 0; - if ($node->nodeType == XML_ELEMENT_NODE) - { - $t_node = array(); - $t_sort = array(); - $i = 0; - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "te") - { - $ntopics++; - $label0 = $label = ""; - $query0 = $query = ""; - for ($n2 = $n->firstChild; $n2; $n2 = $n2->nextSibling) + function export0($znode, &$dom, &$root, $lng) { - if ($n2->nodeName == "sy") - { - if (!$query0) - { - $query0 = $n2->getAttribute("w"); - if ($n2->getAttribute("k")) - $query0 .= ( ' (' . $n2->getAttribute("k") . ')'); - $label0 = $n2->getAttribute("v"); - } - if ($n2->getAttribute("lng") == $lng) - { - $query = $n2->getAttribute("w"); - if ($n2->getAttribute("k")) - $query .= ( ' (' . $n2->getAttribute("k") . ')'); - $label = $n2->getAttribute("v"); - break; - } - } + $topics = $root->appendChild($dom->createElement('topics')); + export($znode, $dom, $topics, '', $lng, 0); } - if (!$query) - $query = $query0; - if (!$label) - $label = $label0; - $t_sort[$i] = $query; // tri sur w - $t_node[$i] = array('label' => $label, 'node' => $n); + function export($node, &$dom, &$topics, $prevQuery, $lng, $depth = 0) + { + global $parm; + global $tnodes; + global $obr; + global $opened_display; + $ntopics = 0; + if ($node->nodeType == XML_ELEMENT_NODE) { + $t_node = array(); + $t_sort = array(); + $i = 0; + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "te") { + $ntopics ++; + $label0 = $label = ""; + $query0 = $query = ""; + for ($n2 = $n->firstChild; $n2; $n2 = $n2->nextSibling) { + if ($n2->nodeName == "sy") { + if ( ! $query0) { + $query0 = $n2->getAttribute("w"); + if ($n2->getAttribute("k")) + $query0 .= ( ' (' . $n2->getAttribute("k") . ')'); + $label0 = $n2->getAttribute("v"); + } + if ($n2->getAttribute("lng") == $lng) { + $query = $n2->getAttribute("w"); + if ($n2->getAttribute("k")) + $query .= ( ' (' . $n2->getAttribute("k") . ')'); + $label = $n2->getAttribute("v"); + break; + } + } + } + if ( ! $query) + $query = $query0; + if ( ! $label) + $label = $label0; - $i++; - } - } + $t_sort[$i] = $query; // tri sur w + $t_node[$i] = array('label' => $label, 'node' => $n); - if ($parm['srt']) - natcasesort($t_sort); + $i ++; + } + } - foreach ($t_sort as $i => $query) - { - $topic = $topics->appendChild($dom->createElement('topic')); - // $topic->setAttribute('id', $n->getAttribute('id')); - if ($opened_display != '' && in_array($t_node[$i]['node']->getAttribute('id'), $obr)) - $topic->setAttribute('view', $opened_display); - $topic->appendChild($dom->createElement('label'))->appendChild($dom->createTextNode($t_node[$i]['label'])); + if ($parm['srt']) + natcasesort($t_sort); - $query = '"' . $query . '"'; - if ($parm['sth']) - { - $query = '*:' . $query; - if ($parm['sand']) - $query = '(' . $query . ')'; - } + foreach ($t_sort as $i => $query) { + $topic = $topics->appendChild($dom->createElement('topic')); + // $topic->setAttribute('id', $n->getAttribute('id')); + if ($opened_display != '' && in_array($t_node[$i]['node']->getAttribute('id'), $obr)) + $topic->setAttribute('view', $opened_display); + $topic->appendChild($dom->createElement('label'))->appendChild($dom->createTextNode($t_node[$i]['label'])); - if ($parm['sand'] && $prevQuery != '') - $query = $prevQuery . ' ' . _('phraseanet::technique:: et') . ' ' . $query . ''; + $query = '"' . $query . '"'; + if ($parm['sth']) { + $query = '*:' . $query; + if ($parm['sand']) + $query = '(' . $query . ')'; + } - $topic->appendChild($dom->createElement('query'))->appendChild($dom->createTextNode('' . $query . '')); + if ($parm['sand'] && $prevQuery != '') + $query = $prevQuery . ' ' . _('phraseanet::technique:: et') . ' ' . $query . ''; - $topics2 = $dom->createElement('topics'); + $topic->appendChild($dom->createElement('query'))->appendChild($dom->createTextNode('' . $query . '')); - if (export($t_node[$i]['node'], $dom, $topics2, $query, $lng, $depth + 1) > 0) - $topic->appendChild($topics2); - } - } + $topics2 = $dom->createElement('topics'); - return($ntopics); - } + if (export($t_node[$i]['node'], $dom, $topics2, $query, $lng, $depth + 1) > 0) + $topic->appendChild($topics2); + } + } + return($ntopics); + } diff --git a/www/thesaurus2/export_topics_dlg.php b/www/thesaurus2/export_topics_dlg.php index 4ce1da19ec..a73f1f7d25 100644 --- a/www/thesaurus2/export_topics_dlg.php +++ b/www/thesaurus2/export_topics_dlg.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,172 +22,169 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "typ" - , "dlg" - , 'obr' // liste des branches ouvertes + "bid" + , "piv" + , "id" + , "typ" + , "dlg" + , 'obr' // liste des branches ouvertes ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - <?php echo p4string::MakeString(_('thesaurus:: export en topics')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: export en topics')) ?> - - - - + + + +
    -
    - " > - " > - " > - " > - " > - " > + + " > + " > + " > + " > + " > + " > -
    -
    - -
    - +
    +
    + +
    + -
    - -
    - +
    + +
    + -
    -
    +
    +
    -
    +
    -
    - -
    - +
    + +
    + -
    -
    +
    +
    -
    +
    -
    - -
    - +
    + +
    + -
    -
    - - -
    -
    - - -
    -
    +
    +
    + + +
    +
    + + +
    +
    -
    +
    -
    - -
    - +
    + +
    + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    -
    - -     - - + +     + +
    - + diff --git a/www/thesaurus2/import.php b/www/thesaurus2/import.php index 1e8610d330..d2ce74db34 100644 --- a/www/thesaurus2/import.php +++ b/www/thesaurus2/import.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,11 +22,11 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , 'piv' - , "id" - , 't' - , 'dlg' + "bid" + , 'piv' + , "id" + , 't' + , 'dlg' ); set_time_limit(300); @@ -35,392 +34,340 @@ set_time_limit(300); $imported = false; $err = ''; -if ($parm["bid"] !== null) -{ - $loaded = false; - try - { - $databox = databox::get_instance((int) $parm['bid']); - $connbas = connection::getPDOConnection($parm['bid']); +if ($parm["bid"] !== null) { + $loaded = false; + try { + $databox = databox::get_instance((int) $parm['bid']); + $connbas = connection::getPDOConnection($parm['bid']); - $dom = $databox->get_dom_thesaurus(); + $dom = $databox->get_dom_thesaurus(); - if ($dom) - { - $err = ''; - if ($parm['id'] == '') - { - // on importe un theaurus entier - $node = $dom->documentElement; - while ($node->firstChild) - $node->removeChild($node->firstChild); + if ($dom) { + $err = ''; + if ($parm['id'] == '') { + // on importe un theaurus entier + $node = $dom->documentElement; + while ($node->firstChild) + $node->removeChild($node->firstChild); - $err = importFile($dom, $node); - } - else - { - // on importe dans une branche - $err = 'not implemented'; - } + $err = importFile($dom, $node); + } else { + // on importe dans une branche + $err = 'not implemented'; + } + + if ( ! $err) { + $imported = true; + $databox->saveThesaurus($dom); + } + } + + if ( ! $err) { + $meta_struct = $databox->get_meta_structure(); + + foreach ($meta_struct->get_elements() as $meta_field) { + $meta_field->set_tbranch('')->save(); + } + + $dom = $databox->get_dom_cterms(); + if ($dom) { + $node = $dom->documentElement; + while ($node->firstChild) + $node->removeChild($node->firstChild); + + $databox->saveCterms($dom); + } + + $sql = 'UPDATE RECORD SET status=status & ~3'; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } + } catch (Exception $e) { - if (!$err) - { - $imported = true; - $databox->saveThesaurus($dom); - } } - - if (!$err) - { - $meta_struct = $databox->get_meta_structure(); - - foreach ($meta_struct->get_elements() as $meta_field) - { - $meta_field->set_tbranch('')->save(); - } - - $dom = $databox->get_dom_cterms(); - if ($dom) - { - $node = $dom->documentElement; - while ($node->firstChild) - $node->removeChild($node->firstChild); - - $databox->saveCterms($dom); - } - - $sql = 'UPDATE RECORD SET status=status & ~3'; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - } - catch (Exception $e) - { - - } } -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - ");'> - + ");'> + -1, 0 => -1); - while (!$err && !feof($fp) && ($line = fgets($fp)) !== FALSE) - { - $iline++; - if (trim($line) == '') - continue; - for ($depth = 0; $line != '' && $line[0] == "\t"; $depth++) - $line = substr($line, 1); - if ($depth > $curdepth + 1) - { - $err = sprintf(_("over-indent at line %s"), $iline); - continue; - } - - $line = trim($line); - - if (!checkEncoding($line, 'UTF-8')) - { - $err = sprintf(_("bad encoding at line %s"), $iline); - continue; - } - - $line = str_replace($cbad, $cok, ($oldline = $line)); - if ($line != $oldline) - { - $err = sprintf(_("bad character at line %s"), $iline); - continue; - } - - while ($curdepth >= $depth) - { - $curdepth--; - $node = $node->parentNode; - } - $curdepth = $depth; - - $nid = (int) ($node->getAttribute('nextid')); - $id = $node->getAttribute('id') . '.' . $nid; - $pid = $node->getAttribute('id'); - - $te_id = ($pid ? ($pid . '.') : 'T') . $nid; - - $node->setAttribute('nextid', (string) ($nid + 1)); - - $te = $node->appendChild($dom->createElement('te')); - $te->setAttribute('id', $te_id); - - $node = $te; - - $tsy = explode(';', $line); - $nsy = 0; - foreach ($tsy as $syn) - { - $lng = $parm['piv']; - $hit = ''; - $kon = ''; - - if (($ob = strpos($syn, '[')) !== false) - { - if (($cb = strpos($syn, ']', $ob)) !== false) - { - $lng = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $lng = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } - - if (($ob = strpos($syn, '[')) !== false) - { - if (($cb = strpos($syn, ']', $ob)) !== false) - { - $hit = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $hit = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } - } - } - if (($ob = strpos($syn, '(')) !== false) - { - if (($cb = strpos($syn, ')', $ob)) !== false) - { - $kon = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $kon = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } - } - - $syn = trim($syn); - - $sy = $node->appendChild($dom->createElement('sy')); - $sy->setAttribute('id', $te_id . '.' . $nsy); - $v = $syn; - if ($kon) - $v .= ' (' . $kon . ')'; - $sy->setAttribute('v', $v); - $sy->setAttribute('w', $unicode->remove_indexer_chars($syn)); - if ($kon) - $sy->setAttribute('k', $unicode->remove_indexer_chars($kon)); - - $sy->setAttribute('lng', $lng); - - $nsy++; - } - - $te->setAttribute('nextid', (string) $nsy); + $cbad = array(); + $cok = array(); + for ($i = 0; $i < 32; $i ++ ) { + $cbad[] = chr($i); + $cok[] = '_'; } - fclose($fp); - } + if (($fp = fopen($_FILES['fil']['tmp_name'], 'rb'))) { + $iline = 0; + $curdepth = -1; + $tid = array(-1 => -1, 0 => -1); + while ( ! $err && ! feof($fp) && ($line = fgets($fp)) !== FALSE) { + $iline ++; + if (trim($line) == '') + continue; + for ($depth = 0; $line != '' && $line[0] == "\t"; $depth ++ ) + $line = substr($line, 1); + if ($depth > $curdepth + 1) { + $err = sprintf(_("over-indent at line %s"), $iline); + continue; + } - return($err); + $line = trim($line); + + if ( ! checkEncoding($line, 'UTF-8')) { + $err = sprintf(_("bad encoding at line %s"), $iline); + continue; + } + + $line = str_replace($cbad, $cok, ($oldline = $line)); + if ($line != $oldline) { + $err = sprintf(_("bad character at line %s"), $iline); + continue; + } + + while ($curdepth >= $depth) { + $curdepth --; + $node = $node->parentNode; + } + $curdepth = $depth; + + $nid = (int) ($node->getAttribute('nextid')); + $id = $node->getAttribute('id') . '.' . $nid; + $pid = $node->getAttribute('id'); + + $te_id = ($pid ? ($pid . '.') : 'T') . $nid; + + $node->setAttribute('nextid', (string) ($nid + 1)); + + $te = $node->appendChild($dom->createElement('te')); + $te->setAttribute('id', $te_id); + + $node = $te; + + $tsy = explode(';', $line); + $nsy = 0; + foreach ($tsy as $syn) { + $lng = $parm['piv']; + $hit = ''; + $kon = ''; + + if (($ob = strpos($syn, '[')) !== false) { + if (($cb = strpos($syn, ']', $ob)) !== false) { + $lng = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $lng = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } + + if (($ob = strpos($syn, '[')) !== false) { + if (($cb = strpos($syn, ']', $ob)) !== false) { + $hit = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $hit = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } + } + } + if (($ob = strpos($syn, '(')) !== false) { + if (($cb = strpos($syn, ')', $ob)) !== false) { + $kon = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $kon = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } + } + + $syn = trim($syn); + + $sy = $node->appendChild($dom->createElement('sy')); + $sy->setAttribute('id', $te_id . '.' . $nsy); + $v = $syn; + if ($kon) + $v .= ' (' . $kon . ')'; + $sy->setAttribute('v', $v); + $sy->setAttribute('w', $unicode->remove_indexer_chars($syn)); + if ($kon) + $sy->setAttribute('k', $unicode->remove_indexer_chars($kon)); + + $sy->setAttribute('lng', $lng); + + $nsy ++; + } + + $te->setAttribute('nextid', (string) $nsy); + } + + fclose($fp); + } + + return($err); } function no_dof($dom, $node) { - global $parm; - $unicode = new unicode(); + global $parm; + $unicode = new unicode(); - $t = $parm['t']; + $t = $parm['t']; - $t = preg_replace('/\\r|\\n/', '£', $t); - $t = preg_replace('/££*/', '£', $t); - $t = preg_replace('/£\\s*;/', ' ;', $t); - $tlig = explode('£', $t); + $t = preg_replace('/\\r|\\n/', '£', $t); + $t = preg_replace('/££*/', '£', $t); + $t = preg_replace('/£\\s*;/', ' ;', $t); + $tlig = explode('£', $t); - $mindepth = 999999; - foreach ($tlig as $lig) - { + $mindepth = 999999; + foreach ($tlig as $lig) { // echo('.'); // flush(); - if (trim($lig) == '') - continue; - for ($depth = 0; $lig != '' && $lig[$depth] == "\t"; $depth++) - ; - if ($depth < $mindepth) - $mindepth = $depth; - } + if (trim($lig) == '') + continue; + for ($depth = 0; $lig != '' && $lig[$depth] == "\t"; $depth ++ ) + ; + if ($depth < $mindepth) + $mindepth = $depth; + } - $curdepth = -1; - $tid = array(-1 => -1, 0 => -1); - foreach ($tlig as $lig) - { + $curdepth = -1; + $tid = array(-1 => -1, 0 => -1); + foreach ($tlig as $lig) { // echo('-'); // flush(); - $lig = substr($lig, $mindepth); - if (trim($lig) == '') - continue; - for ($depth = 0; $lig != '' && $lig[0] == "\t"; $depth++) - $lig = substr($lig, 1); + $lig = substr($lig, $mindepth); + if (trim($lig) == '') + continue; + for ($depth = 0; $lig != '' && $lig[0] == "\t"; $depth ++ ) + $lig = substr($lig, 1); // printf("curdepth=%s, depth=%s : %s\n", $curdepth, $depth, $lig); - if ($depth > $curdepth + 1) - { - // error + if ($depth > $curdepth + 1) { + // error // print('error over-indent at \'' . $lig . "'\n"); - continue; - } + continue; + } - while ($curdepth >= $depth) - { - $curdepth--; - $node = $node->parentNode; - } - $curdepth = $depth; + while ($curdepth >= $depth) { + $curdepth --; + $node = $node->parentNode; + } + $curdepth = $depth; - $nid = (int) ($node->getAttribute('nextid')); - $id = $node->getAttribute('id') . '.' . $nid; - $pid = $node->getAttribute('id'); + $nid = (int) ($node->getAttribute('nextid')); + $id = $node->getAttribute('id') . '.' . $nid; + $pid = $node->getAttribute('id'); // print("pid=".$pid); - $te_id = ($pid ? ($pid . '.') : 'T') . $nid; + $te_id = ($pid ? ($pid . '.') : 'T') . $nid; - $node->setAttribute('nextid', (string) ($nid + 1)); + $node->setAttribute('nextid', (string) ($nid + 1)); - $te = $node->appendChild($dom->createElement('te')); - $te->setAttribute('id', $te_id); + $te = $node->appendChild($dom->createElement('te')); + $te->setAttribute('id', $te_id); - $node = $te; + $node = $te; - $tsy = explode(';', $lig); - $nsy = 0; - foreach ($tsy as $syn) - { - $lng = $parm['piv']; - $hit = ''; - $kon = ''; + $tsy = explode(';', $lig); + $nsy = 0; + foreach ($tsy as $syn) { + $lng = $parm['piv']; + $hit = ''; + $kon = ''; - if (($ob = strpos($syn, '[')) !== false) - { - if (($cb = strpos($syn, ']', $ob)) !== false) - { - $lng = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $lng = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } + if (($ob = strpos($syn, '[')) !== false) { + if (($cb = strpos($syn, ']', $ob)) !== false) { + $lng = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $lng = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } - if (($ob = strpos($syn, '[')) !== false) - { - if (($cb = strpos($syn, ']', $ob)) !== false) - { - $hit = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $hit = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } - } - } - if (($ob = strpos($syn, '(')) !== false) - { - if (($cb = strpos($syn, ')', $ob)) !== false) - { - $kon = trim(substr($syn, $ob + 1, $cb - $ob - 1)); - $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); - } - else - { - $kon = trim(substr($syn, $ob + 1)); - $syn = substr($syn, 0, $ob); - } - } - /* - */ - $syn = trim($syn); + if (($ob = strpos($syn, '[')) !== false) { + if (($cb = strpos($syn, ']', $ob)) !== false) { + $hit = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $hit = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } + } + } + if (($ob = strpos($syn, '(')) !== false) { + if (($cb = strpos($syn, ')', $ob)) !== false) { + $kon = trim(substr($syn, $ob + 1, $cb - $ob - 1)); + $syn = substr($syn, 0, $ob) . substr($syn, $cb + 1); + } else { + $kon = trim(substr($syn, $ob + 1)); + $syn = substr($syn, 0, $ob); + } + } + /* + */ + $syn = trim($syn); - // for($id='T',$i=0; $i<=$curdepth; $i++) - // $id .= '.' . $tid[$i]; + // for($id='T',$i=0; $i<=$curdepth; $i++) + // $id .= '.' . $tid[$i]; // $id = '?'; // printf("depth=%s (%s) ; sy='%s', kon='%s', lng='%s', hit='%s' \n", $depth, $id, $syn, $kon, $lng, $hit); - /* - $nid = (int)($node->getAttribute('nextid')); - $pid = $node->getAttribute('id'); + /* + $nid = (int)($node->getAttribute('nextid')); + $pid = $node->getAttribute('id'); - $id = ($pid ? ($pid.'.'):'T') . $nid ; - $node->setAttribute('nextid', (string)($nid+1)); + $id = ($pid ? ($pid.'.'):'T') . $nid ; + $node->setAttribute('nextid', (string)($nid+1)); - */ - $sy = $node->appendChild($dom->createElement('sy')); - $sy->setAttribute('id', $te_id . '.' . $nsy); - $v = $syn; - if ($kon) - $v .= ' (' . $kon . ')'; - $sy->setAttribute('v', $v); - $sy->setAttribute('w', $unicode->remove_indexer_chars($syn)); - if ($kon) - $sy->setAttribute('k', $unicode->remove_indexer_chars($kon)); + */ + $sy = $node->appendChild($dom->createElement('sy')); + $sy->setAttribute('id', $te_id . '.' . $nsy); + $v = $syn; + if ($kon) + $v .= ' (' . $kon . ')'; + $sy->setAttribute('v', $v); + $sy->setAttribute('w', $unicode->remove_indexer_chars($syn)); + if ($kon) + $sy->setAttribute('k', $unicode->remove_indexer_chars($kon)); - $sy->setAttribute('lng', $lng); + $sy->setAttribute('lng', $lng); - $nsy++; + $nsy ++; + } + + $te->setAttribute('nextid', (string) $nsy); } - - $te->setAttribute('nextid', (string) $nsy); - } } diff --git a/www/thesaurus2/import_dlg.php b/www/thesaurus2/import_dlg.php index 042e54fb71..f255e8f448 100644 --- a/www/thesaurus2/import_dlg.php +++ b/www/thesaurus2/import_dlg.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -23,104 +22,101 @@ phrasea::headers(200, true); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "dlg" + "bid" + , "piv" + , "id" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - - <?php echo p4string::MakeString(_('thesaurus:: Importer')) ?> + + + <?php echo p4string::MakeString(_('thesaurus:: Importer')) ?> - - - - -
    -
    - " > - " > - " > - " > -
    - -
    " . ' ' . $parm['piv']; ?>
    -
    -
    - - - - -  (max 16Mo) -
    - -
    - - - - - - - - -
    + else + { + alert(err); + } + } + + +
    - -     - -
    -
    - - +
    + " > + " > + " > + " > +
    + +
    " . ' ' . $parm['piv']; ?>
    +
    +
    + + + + +  (max 16Mo) +
    + +
    + + + + + + + + +
    +
    + +     + +
    +
    + + diff --git a/www/thesaurus2/index.php b/www/thesaurus2/index.php index bb3a03d624..3826f9fcee 100644 --- a/www/thesaurus2/index.php +++ b/www/thesaurus2/index.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; $appbox = appbox::get_instance($Core); @@ -23,8 +22,7 @@ $registry = $appbox->get_registry(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bas", - "res" + "bas", "res" ); $conn = $appbox->get_connection(); @@ -46,20 +44,20 @@ HAVING bas_edit_thesaurus>0 ORDER BY sbas.ord"; ?> - - -<?php echo $appbox->get_registry()->get('GV_homeTitle'); ?> - <?php echo p4string::MakeString(_('phraseanet:: thesaurus')) ?> + + + <?php echo $appbox->get_registry()->get('GV_homeTitle'); ?> - <?php echo p4string::MakeString(_('phraseanet:: thesaurus')) ?> - - + + - + - -
    -
    -
    + +
    +
    +
    execute(array(':usr_id' => $session->get_usr_id())); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); -foreach ($rs as $row) -{ - try - { - $connbas = connection::getPDOConnection($row['sbas_id']); - } - catch (Exception $e) - { - continue; - } - $name = phrasea::sbas_names($row['sbas_id']); - $select_bases .= "\n"; - $last_base = array("sbid" => $row["sbas_id"], "name" => $name); - $nbases++; +foreach ($rs as $row) { + try { + $connbas = connection::getPDOConnection($row['sbas_id']); + } catch (Exception $e) { + continue; + } + $name = phrasea::sbas_names($row['sbas_id']); + $select_bases .= "\n"; + $last_base = array("sbid" => $row["sbas_id"], "name" => $name); + $nbases ++; } -if ($nbases > 0) -{ -?> +if ($nbases > 0) { + ?> -
    - " /> - - + + " /> + + + %s
    \n", $last_base["sbid"], $last_base["name"]); + ?> + %s
    \n", $last_base["sbid"], $last_base["name"]); + } else { ?> - - - - -
    - + + +
    + -
    - - +
    + $lng) - { - printf("", $nf == 0 ? p4string::MakeString(_('thesaurus:: langue pivot')) /* Langue pivot : */ : ""); - print("\n"); - $nf++; - } -?> -
    %s (" . $lng_code . ")
    -
    -
    - - -
    -
    - - - - $lng) { + printf("%s", $nf == 0 ? p4string::MakeString(_('thesaurus:: langue pivot')) /* Langue pivot : */ : ""); + print(" (" . $lng_code . ")\n"); + $nf ++; + } + ?> + +
    +
    + + +
    + + + + +
    - + diff --git a/www/thesaurus2/linkfield.php b/www/thesaurus2/linkfield.php index 75b4259c78..bf22341f56 100644 --- a/www/thesaurus2/linkfield.php +++ b/www/thesaurus2/linkfield.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; @@ -24,134 +23,123 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "tid" + "bid" + , "piv" + , "tid" ); ?> - - <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus au champ')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus au champ')) ?> - + - - - -get_dom_structure(); - $domth = $databox->get_dom_thesaurus(); - - if ($domstruct && $domth) - { - $xpathth = new DOMXPath($domth); - $xpathstruct = new DOMXPath($domstruct); - - if ($parm["tid"] !== "") - $q = "//te[@id='" . $parm["tid"] . "']"; - else - $q = "//te[not(@id)]"; - $nodes = $xpathth->query($q); - $fullBranch = ""; - if ($nodes->length == 1) - { - for ($n = $nodes->item(0); $n && $n->nodeType == XML_ELEMENT_NODE && $n->getAttribute("id") !== ""; $n = $n->parentNode) - { - $sy = $xpathth->query("sy", $n)->item(0); - $sy = $sy ? $sy->getAttribute("v") : ""; - if (!$sy) - $sy = $sy = "..."; - $fullBranch = " / " . $sy . $fullBranch; - } - } -?> -
    -
    - "> - "> - "> -" . $fullBranch . "
    "; - printf(_('thesaurus:: Lier la branche de thesaurus au champ %s'), $fbhtml); -?> -
    -query("/record/description/*"); - for ($i = 0; $i < $nodes->length; $i++) - { - $fieldname = $nodes->item($i)->nodeName; - $tbranch = $nodes->item($i)->getAttribute("tbranch"); - $ck = ""; - if ($tbranch) - { - // ce champ a deje un tbranch, est-ce qu'il pointe sur la branche selectionnee ? - $thnodes = $xpathth->query($tbranch); - for ($j = 0; $j < $thnodes->length; $j++) - { - if ($thnodes->item($j)->getAttribute("id") == $parm["tid"]) + + + + get_dom_structure(); + $domth = $databox->get_dom_thesaurus(); + + if ($domstruct && $domth) { + $xpathth = new DOMXPath($domth); + $xpathstruct = new DOMXPath($domstruct); + + if ($parm["tid"] !== "") + $q = "//te[@id='" . $parm["tid"] . "']"; + else + $q = "//te[not(@id)]"; + $nodes = $xpathth->query($q); + $fullBranch = ""; + if ($nodes->length == 1) { + for ($n = $nodes->item(0); $n && $n->nodeType == XML_ELEMENT_NODE && $n->getAttribute("id") !== ""; $n = $n->parentNode) { + $sy = $xpathth->query("sy", $n)->item(0); + $sy = $sy ? $sy->getAttribute("v") : ""; + if ( ! $sy) + $sy = $sy = "..."; + $fullBranch = " / " . $sy . $fullBranch; + } + } + ?> +
    + + "> + "> + "> + " . $fullBranch . "
    "; + printf(_('thesaurus:: Lier la branche de thesaurus au champ %s'), $fbhtml); + ?> +
    + query("/record/description/*"); + for ($i = 0; $i < $nodes->length; $i ++ ) { + $fieldname = $nodes->item($i)->nodeName; + $tbranch = $nodes->item($i)->getAttribute("tbranch"); + $ck = ""; + if ($tbranch) { + // ce champ a deje un tbranch, est-ce qu'il pointe sur la branche selectionnee ? + $thnodes = $xpathth->query($tbranch); + for ($j = 0; $j < $thnodes->length; $j ++ ) { + if ($thnodes->item($j)->getAttribute("id") == $parm["tid"]) { + $ck = "checked"; + } + } + } + printf("\t\t%s
    \n" + , $fieldname, $ck, $ck ? "1" : "0", $fieldname); + } + ?> +
    +
    + +     + + +
    + + diff --git a/www/thesaurus2/linkfield2.php b/www/thesaurus2/linkfield2.php index b2ebd1a83e..61c37e1a84 100644 --- a/www/thesaurus2/linkfield2.php +++ b/www/thesaurus2/linkfield2.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,180 +22,154 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "tid" - , "field" + "bid" + , "piv" + , "tid" + , "field" ); ?> - - <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus')) ?> - + - - - + + +
    -get_dom_structure(); - $domth = $databox->get_dom_thesaurus(); + if ($parm["bid"] !== null) { + $loaded = false; + try { + $databox = databox::get_instance((int) $parm['bid']); + $domstruct = $databox->get_dom_structure(); + $domth = $databox->get_dom_thesaurus(); - if ($domstruct && $domth) - { - $xpathth = new DOMXPath($domth); - $xpathstruct = new DOMXPath($domstruct); -?> -
    - "> - "> - "> -
    -
    -
    -
    -query("/record/description/*"); - for ($i = 0; $i < $nodes->length; $i++) - { - $fieldname = $nodes->item($i)->nodeName; - $tbranch = $nodes->item($i)->getAttribute("tbranch"); - $ck = false; - $tids = array(); // les ids de branches liees e ce champ - if ($tbranch) - { - // ce champ a deje un tbranch, on balaye les branches auxquelles il est lie - $thnodes = $xpathth->query($tbranch); - for ($j = 0; $j < $thnodes->length; $j++) - { - if ($thnodes->item($j)->getAttribute("id") == $parm["tid"]) - { - // il etait deje lie e la branche selectionnee - $tids[$thnodes->item($j)->getAttribute("id")] = $thnodes->item($j); - $ck = true; - } - else - { - // il etait lie e une autre branche - $tids[$thnodes->item($j)->getAttribute("id")] = $thnodes->item($j); - } - } - } - // printf("'%s' avant:%s apres:%s
    \n", $fieldname, $ck, array_key_exists($fieldname, $parm["field"])); - if (array_key_exists($fieldname, $parm["field"]) != $ck) - { - print("\t\t
    "); - echo "" . $fieldname . "" . p4string::MakeString(sprintf(_('thesaurus:: Ce champ a ete modifie ; ancienne branche : %s '), $tbranch)); - print("
    \n"); - if ($ck) - { - // print("il etait lie a la branche, il ne l'est plus
    \n"); - unset($tids[$parm["tid"]]); - } - else - { - // print("il n'etait pas lie a la branche, il l'est maintenant
    \n"); - $tids[$parm["tid"]] = $xpathth->query("/thesaurus//te[@id='" . thesaurus::xquery_escape($parm["tid"]) . "']")->item(0); - } - $newtbranch = ""; - foreach ($tids as $kitd => $node) - { - if ($kitd === "") - $newtbranch .= ( $newtbranch ? " | " : "") . "/thesaurus"; - else - { - // $newtbranch .= ($newtbranch?" | ":"") . "/thesaurus//te[@id='" . $kitd . "']"; - $neb = ""; - while ($node && $node->nodeName == "te") - { - $neb = "/te[@id='" . $node->getAttribute("id") . "']" . $neb; - $node = $node->parentNode; - } - $newtbranch .= ( $newtbranch ? " | " : "") . "/thesaurus" . $neb; - } - } - echo p4string::MakeString(_('thesaurus:: nouvelle branche')) . $newtbranch; - print("
    \n"); + if ($domstruct && $domth) { + $xpathth = new DOMXPath($domth); + $xpathstruct = new DOMXPath($domstruct); + ?> + + "> + "> + "> +
    +
    +
    +
    + query("/record/description/*"); + for ($i = 0; $i < $nodes->length; $i ++ ) { + $fieldname = $nodes->item($i)->nodeName; + $tbranch = $nodes->item($i)->getAttribute("tbranch"); + $ck = false; + $tids = array(); // les ids de branches liees e ce champ + if ($tbranch) { + // ce champ a deje un tbranch, on balaye les branches auxquelles il est lie + $thnodes = $xpathth->query($tbranch); + for ($j = 0; $j < $thnodes->length; $j ++ ) { + if ($thnodes->item($j)->getAttribute("id") == $parm["tid"]) { + // il etait deje lie e la branche selectionnee + $tids[$thnodes->item($j)->getAttribute("id")] = $thnodes->item($j); + $ck = true; + } else { + // il etait lie e une autre branche + $tids[$thnodes->item($j)->getAttribute("id")] = $thnodes->item($j); + } + } + } + // printf("'%s' avant:%s apres:%s
    \n", $fieldname, $ck, array_key_exists($fieldname, $parm["field"])); + if (array_key_exists($fieldname, $parm["field"]) != $ck) { + print("\t\t
    "); + echo "" . $fieldname . "" . p4string::MakeString(sprintf(_('thesaurus:: Ce champ a ete modifie ; ancienne branche : %s '), $tbranch)); + print("
    \n"); + if ($ck) { + // print("il etait lie a la branche, il ne l'est plus
    \n"); + unset($tids[$parm["tid"]]); + } else { + // print("il n'etait pas lie a la branche, il l'est maintenant
    \n"); + $tids[$parm["tid"]] = $xpathth->query("/thesaurus//te[@id='" . thesaurus::xquery_escape($parm["tid"]) . "']")->item(0); + } + $newtbranch = ""; + foreach ($tids as $kitd => $node) { + if ($kitd === "") + $newtbranch .= ( $newtbranch ? " | " : "") . "/thesaurus"; + else { + // $newtbranch .= ($newtbranch?" | ":"") . "/thesaurus//te[@id='" . $kitd . "']"; + $neb = ""; + while ($node && $node->nodeName == "te") { + $neb = "/te[@id='" . $node->getAttribute("id") . "']" . $neb; + $node = $node->parentNode; + } + $newtbranch .= ( $newtbranch ? " | " : "") . "/thesaurus" . $neb; + } + } + echo p4string::MakeString(_('thesaurus:: nouvelle branche')) . $newtbranch; + print("
    \n"); - if ($tbranch != "" && $newtbranch == "") - { - echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: ce champ n\'est plus lie au thesaurus, les termes indexes et candidats seront supprimes')); - print("
    \n"); - printf("\t\t\n", $fieldname); - } - if ($newtbranch != "") - { - if ($tbranch == "") - { - echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: ce champ doit etre lie au thesaurus. La reindexation de la base est necessaire')); - } - else - { - echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: le lien au thesaurus doit etre modifie, la reindexation de la base est necessaire')); - } - print("
    \n"); + if ($tbranch != "" && $newtbranch == "") { + echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: ce champ n\'est plus lie au thesaurus, les termes indexes et candidats seront supprimes')); + print("
    \n"); + printf("\t\t\n", $fieldname); + } + if ($newtbranch != "") { + if ($tbranch == "") { + echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: ce champ doit etre lie au thesaurus. La reindexation de la base est necessaire')); + } else { + echo "" . $fieldname . "" . p4string::MakeString(_('thesaurus:: le lien au thesaurus doit etre modifie, la reindexation de la base est necessaire')); + } + print("
    \n"); - $needreindex = true; - printf("\t\t\n", $fieldname . "<" . $newtbranch); - } - } - } -?> -
    -\n"); - print("
    " . p4string::MakeString(_('thesaurus:: reindexation necessaire')) /* Reindexation necessaire ! */ . "
    "); - } - else - { - print("
    " . p4string::MakeString(_('thesaurus:: pas de reindexation')) /* Pas de reindexation necessaire ! */ . "
    "); - } -?> -
    - -     - - -\n", $fieldname . "<" . $newtbranch); + } + } + } + ?> +
    + \n"); + print("
    " . p4string::MakeString(_('thesaurus:: reindexation necessaire')) /* Reindexation necessaire ! */ . "
    "); + } else { + print("
    " . p4string::MakeString(_('thesaurus:: pas de reindexation')) /* Pas de reindexation necessaire ! */ . "
    "); + } + ?> +
    + +     + + + + } + } + ?>
    - + diff --git a/www/thesaurus2/linkfield3.php b/www/thesaurus2/linkfield3.php index 943713017c..c136066b44 100644 --- a/www/thesaurus2/linkfield3.php +++ b/www/thesaurus2/linkfield3.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,131 +22,117 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "f2unlk" - , "fbranch" - , "reindex" + "bid" + , "piv" + , "f2unlk" + , "fbranch" + , "reindex" ); ?> - - <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: Lier la branche de thesaurus')) ?> - + - - -
    -
    -
    -
    -
    -
    - + +
    +
    +
    +
    + +
    + get_meta_structure(); - $domct = $databox->get_dom_cterms(); - $domst = $databox->get_dom_structure(); + if ($parm["bid"] !== null) { + $loaded = false; + try { + $databox = databox::get_instance((int) $parm['bid']); + $connbas = connection::getPDOConnection($parm['bid']); + $meta_struct = $databox->get_meta_structure(); + $domct = $databox->get_dom_cterms(); + $domst = $databox->get_dom_structure(); - if ($domct && $domst) - { - $xpathct = new DOMXPath($domct); - $xpathst = new DOMXPath($domst); - $ctchanged = false; + if ($domct && $domst) { + $xpathct = new DOMXPath($domct); + $xpathst = new DOMXPath($domst); + $ctchanged = false; - $candidates2del = array(); - foreach ($parm["f2unlk"] as $f2unlk) - { - $q = "/cterms/te[@field='" . thesaurus::xquery_escape($f2unlk) . "']"; - $nodes = $xpathct->query($q); - for ($i = 0; $i < $nodes->length; $i++) - { - $candidates2del[] = array("field" => $f2unlk, "node" => $nodes->item($i)); + $candidates2del = array(); + foreach ($parm["f2unlk"] as $f2unlk) { + $q = "/cterms/te[@field='" . thesaurus::xquery_escape($f2unlk) . "']"; + $nodes = $xpathct->query($q); + for ($i = 0; $i < $nodes->length; $i ++ ) { + $candidates2del[] = array("field" => $f2unlk, "node" => $nodes->item($i)); + } + + echo p4string::MakeString(sprintf(_('thesaurus:: suppression du lien du champ %s'), $f2unlk)); + print("
    \n"); + $field = $meta_struct->get_element_by_name($f2unlk); + if ($field) + $field->set_tbranch('')->save(); + } + foreach ($candidates2del as $candidate2del) { + echo p4string::MakeString(sprintf(_('thesaurus:: suppression de la branche de mot candidats pour le champ %s'), $candidate2del["field"])); + print("
    \n"); + $candidate2del["node"]->parentNode->removeChild($candidate2del["node"]); + $ctchanged = true; + } + + foreach ($parm["fbranch"] as $fbranch) { + $p = strpos($fbranch, "<"); + if ($p > 1) { + $fieldname = substr($fbranch, 0, $p); + $tbranch = substr($fbranch, $p + 1); + $field = $meta_struct->get_element_by_name($fieldname); + if ($field) + $field->set_tbranch($tbranch)->save(); + echo p4string::MakeString(sprintf(_('thesaurus:: suppression de la branche de mot candidats pour le champ %s'), $fieldname)); + print("
    \n"); + } + } + + if ($ctchanged) { + if ($ctchanged) { + $databox->saveCterms($domct); + print(p4string::MakeString(_('thesaurus:: enregistrement de la liste modifiee des mots candidats.'))); + print("
    \n"); + } + } + } + + + $sql = "DELETE FROM thit WHERE name = :name"; + $stmt = $connbas->prepare($sql); + foreach ($parm["f2unlk"] as $f2unlk) { + $stmt->execute(array(':name' => $f2unlk)); + echo p4string::MakeString(_('thesaurus:: suppression des indexes vers le thesaurus pour le champ') . " " . $f2unlk . ""); + print("
    \n"); + } + $stmt->closeCursor(); + + if ($parm["reindex"]) { + $sql = "UPDATE record SET status=status & ~2"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + echo p4string::MakeString(_('thesaurus:: reindexer tous les enregistrements')); + print("
    \n"); + } + } catch (Exception $e) { + + } } - - echo p4string::MakeString(sprintf(_('thesaurus:: suppression du lien du champ %s'), $f2unlk)); - print("
    \n"); - $field = $meta_struct->get_element_by_name($f2unlk); - if($field) - $field->set_tbranch('')->save(); - } - foreach ($candidates2del as $candidate2del) - { - echo p4string::MakeString(sprintf(_('thesaurus:: suppression de la branche de mot candidats pour le champ %s'), $candidate2del["field"])); - print("
    \n"); - $candidate2del["node"]->parentNode->removeChild($candidate2del["node"]); - $ctchanged = true; - } - - foreach ($parm["fbranch"] as $fbranch) - { - $p = strpos($fbranch, "<"); - if ($p > 1) - { - $fieldname = substr($fbranch, 0, $p); - $tbranch = substr($fbranch, $p + 1); - $field = $meta_struct->get_element_by_name($fieldname); - if($field) - $field->set_tbranch($tbranch)->save(); - echo p4string::MakeString(sprintf(_('thesaurus:: suppression de la branche de mot candidats pour le champ %s'), $fieldname)); - print("
    \n"); - } - } - - if ($ctchanged) - { - if ($ctchanged) - { - $databox->saveCterms($domct); - print(p4string::MakeString(_('thesaurus:: enregistrement de la liste modifiee des mots candidats.'))); - print("
    \n"); - } - } - } - - - $sql = "DELETE FROM thit WHERE name = :name"; - $stmt = $connbas->prepare($sql); - foreach ($parm["f2unlk"] as $f2unlk) - { - $stmt->execute(array(':name' => $f2unlk)); - echo p4string::MakeString(_('thesaurus:: suppression des indexes vers le thesaurus pour le champ') . " " . $f2unlk . ""); - print("
    \n"); - } - $stmt->closeCursor(); - - if ($parm["reindex"]) - { - $sql = "UPDATE record SET status=status & ~2"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - echo p4string::MakeString(_('thesaurus:: reindexer tous les enregistrements')); - print("
    \n"); - } - } - catch (Exception $e) - { - - } - } - ?> -
    -
    - - -
    + ?> +
    +
    + + +
    diff --git a/www/thesaurus2/loadth.php b/www/thesaurus2/loadth.php index 3ce20dedbb..099cf421b3 100644 --- a/www/thesaurus2/loadth.php +++ b/www/thesaurus2/loadth.php @@ -21,208 +21,184 @@ $debug = false; $request = http_request::getInstance(); $parm = $request->get_parms( - "bid", - "piv", - "repair" + "bid", "piv", "repair" ); -function fixW(&$node, $depth=0) +function fixW(&$node, $depth = 0) { - if ($node && $node->nodeType == XML_ELEMENT_NODE) - { - if (($v = $node->getAttribute("v")) != "") - { - $unicode = new unicode(); - $node->setAttribute("w", $unicode->remove_indexer_chars($v)); + if ($node && $node->nodeType == XML_ELEMENT_NODE) { + if (($v = $node->getAttribute("v")) != "") { + $unicode = new unicode(); + $node->setAttribute("w", $unicode->remove_indexer_chars($v)); + } + for ($c = $node->firstChild; $c; $c = $c->nextSibling) + fixW($c, $depth + 1); } - for ($c = $node->firstChild; $c; $c = $c->nextSibling) - fixW($c, $depth + 1); - } } - -if ($hdir = opendir($registry->get('GV_RootPath') . "www/thesaurus2/patch")) -{ - while (false !== ($file = readdir($hdir))) - { - if (substr($file, 0, 1) == ".") - continue; - if (is_file($f = $registry->get('GV_RootPath') . "www/thesaurus2/patch/" . $file)) - { - require_once($f); - print("\n"); +if ($hdir = opendir($registry->get('GV_RootPath') . "www/thesaurus2/patch")) { + while (false !== ($file = readdir($hdir))) { + if (substr($file, 0, 1) == ".") + continue; + if (is_file($f = $registry->get('GV_RootPath') . "www/thesaurus2/patch/" . $file)) { + require_once($f); + print("\n"); + } } - } - closedir($hdir); + closedir($hdir); } function fixThesaurus(&$domct, &$domth, &$connbas) { - $oldversion = $version = $domth->documentElement->getAttribute("version"); + $oldversion = $version = $domth->documentElement->getAttribute("version"); // $cls = "patch_th_".str_replace(".","_",$version); //printf("---- %s %s %s \n", $version, $cls, class_exists($cls) ); //printf("---- %s %s \n", $version, $cls ); - while (class_exists($cls = "patch_th_" . str_replace(".", "_", $version), false)) - { - print("// ============== patching from version='$version'\n"); + while (class_exists($cls = "patch_th_" . str_replace(".", "_", $version), false)) { + print("// ============== patching from version='$version'\n"); - $last_version = $version; - $zcls = new $cls; - print("// ----------- calling class '$cls'\n"); - $version = $zcls->patch($version, $domct, $domth, $connbas); - print("// ----------- method 'patch' -> returned '$version'\n"); + $last_version = $version; + $zcls = new $cls; + print("// ----------- calling class '$cls'\n"); + $version = $zcls->patch($version, $domct, $domth, $connbas); + print("// ----------- method 'patch' -> returned '$version'\n"); - if ($version == $last_version) - break; - } + if ($version == $last_version) + break; + } - return($version); + return($version); } ?> diff --git a/www/thesaurus2/newsy_dlg.php b/www/thesaurus2/newsy_dlg.php index b2e50dc9b1..1ca29036c5 100644 --- a/www/thesaurus2/newsy_dlg.php +++ b/www/thesaurus2/newsy_dlg.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,106 +22,104 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "piv" - , "typ" // type de dlg : "TS"=nouvo terme specifique ; "SY"=nouvo synonyme + "piv" + , "typ" // type de dlg : "TS"=nouvo terme specifique ; "SY"=nouvo synonyme ); $lng = Session_Handler::get_locale(); -switch ($parm["typ"]) -{ - case "TS": - $tstr = array(p4string::MakeString(_('thesaurus:: Nouveau terme')), p4string::MakeString(_('thesaurus:: terme'))); - break; - case "SY": - $tstr = array(p4string::MakeString(_('thesaurus:: Nouveau synonyme')), p4string::MakeString(_('thesaurus:: synonyme'))); - break; - default: - $tstr = array("", ""); - break; +switch ($parm["typ"]) { + case "TS": + $tstr = array(p4string::MakeString(_('thesaurus:: Nouveau terme')), p4string::MakeString(_('thesaurus:: terme'))); + break; + case "SY": + $tstr = array(p4string::MakeString(_('thesaurus:: Nouveau synonyme')), p4string::MakeString(_('thesaurus:: synonyme'))); + break; + default: + $tstr = array("", ""); + break; } ?> - - <?php echo $tstr[0] ?> + + <?php echo $tstr[0] ?> - + - - + switch(button) + { + case "submit": + t = document.forms[0].term.value; + k = document.forms[0].context.value; + if(k != "") + t += " ("+k+")"; + self.returnValue = {"t":t, "lng":null }; + for(i=0; i<(n=document.getElementsByName("lng")).length; i++) + { + if(n[i].checked) + { + self.returnValue.lng = n[i].value; + break; + } + } + // self.setTimeout('self.close();', 3000); + self.close(); + break; + case "cancel": + self.close(); + break; + } + } + + - -
    -
    - - - - - - - - - - - - - - - + +
    (  )
    + +
    + + + + + + + + + + + + + + + + - -
    (  )
    $lng) -{ - $ck = $lng_code == $parm["piv"] ? " checked" : ""; +foreach ($tlng as $lng_code => $lng) { + $ck = $lng_code == $parm["piv"] ? " checked" : ""; + ?> + + name="lng" value="" id="lng_"> + + +    + - - name="lng" value="" id="lng_"> - - -    - -
    -
    -
    - -    - -
    -
    -
    - - +
    +
    +
    + +    + +
    +
    +
    + + diff --git a/www/thesaurus2/newterm.php b/www/thesaurus2/newterm.php index d88f571fc6..a823720b7b 100644 --- a/www/thesaurus2/newterm.php +++ b/www/thesaurus2/newterm.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -26,324 +25,304 @@ require($registry->get('GV_RootPath') . "www/thesaurus2/xmlhttp.php"); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" // pivot - , "pid" - , "t" - , "sylng" // lng nouvo sy - , "typ" // "TS" ou "SY" - , "dlg" + "bid" + , "piv" // pivot + , "pid" + , "t" + , "sylng" // lng nouvo sy + , "typ" // "TS" ou "SY" + , "dlg" ); ?> - - <?php echo $parm["typ"] == "TS" ? p4string::MakeString(_('thesaurus:: Nouveau terme specifique')) : p4string::MakeString(_('thesaurus:: Nouveau synonyme')) ?> + + <?php echo $parm["typ"] == "TS" ? p4string::MakeString(_('thesaurus:: Nouveau terme specifique')) : p4string::MakeString(_('thesaurus:: Nouveau synonyme')) ?> - + - - - - - + + + + " . $term . " ")); -if ($context != "") - $zterm .= p4string::MakeString(sprintf(_('thesaurus:: avec contexte %s'), "" . $context . "")); -else - $zterm .= p4string::MakeString(_('thesaurus:: sans contexte')); + $zterm = p4string::MakeString(sprintf(_('thesaurus:: le terme %s'), "" . $term . " ")); + if ($context != "") + $zterm .= p4string::MakeString(sprintf(_('thesaurus:: avec contexte %s'), "" . $context . "")); + else + $zterm .= p4string::MakeString(_('thesaurus:: sans contexte')); // print($dom->saveXML()); -$xpath = new DOMXPath($dom); + $xpath = new DOMXPath($dom); -$candidates = $xpath->query("/result/candidates_list/ct"); + $candidates = $xpath->query("/result/candidates_list/ct"); // on verifie si au moins un champ candidat est acceptable -$nb_candidates_ok = $nb_candidates_bad = 0; -$flist_ok = $flist_bad = ""; -for ($i = 0; $i < $candidates->length; $i++) -{ - if ($candidates->item($i)->getAttribute("sourceok") == "1") // && $candidates->item($i)->getAttribute("cid")) - { - $flist_ok .= ( $flist_ok ? ", " : "") . $candidates->item($i)->getAttribute("field"); - $nb_candidates_ok++; - } - else - { - $flist_bad .= ( $flist_bad ? ", " : "") . $candidates->item($i)->getAttribute("field"); - $nb_candidates_bad++; - } -} -if ($nb_candidates_ok > 0) -{ - // au moins un champ est acceptable : on presente des radio - if ($nb_candidates_ok == 1) - $t = p4string::MakeString(_('thesaurus:: est deja candidat en provenance du champ acceptable : ')); - else - $t = p4string::MakeString(_('thesaurus:: est deja candidat en provenance des champs acceptables : ')); -?> -
    -
    - -
    -
    - -
    -
    -
    - "> - "> -\n"); + $nb_candidates_ok = $nb_candidates_bad = 0; + $flist_ok = $flist_bad = ""; + for ($i = 0; $i < $candidates->length; $i ++ ) { + if ($candidates->item($i)->getAttribute("sourceok") == "1") { // && $candidates->item($i)->getAttribute("cid")) + $flist_ok .= ( $flist_ok ? ", " : "") . $candidates->item($i)->getAttribute("field"); + $nb_candidates_ok ++; + } else { + $flist_bad .= ( $flist_bad ? ", " : "") . $candidates->item($i)->getAttribute("field"); + $nb_candidates_bad ++; + } + } + if ($nb_candidates_ok > 0) { + // au moins un champ est acceptable : on presente des radio + if ($nb_candidates_ok == 1) + $t = p4string::MakeString(_('thesaurus:: est deja candidat en provenance du champ acceptable : ')); + else + $t = p4string::MakeString(_('thesaurus:: est deja candidat en provenance des champs acceptables : ')); + ?> +
    +
    + +
    +
    + +
    +
    + + "> + "> + \n"); // if($nb_candidates_bad) // printf("\t\t\t\t%s
    \n", $flist_bad); // if($nb_candidates_ok) // printf("\t\t\t\t%s
    \n", $flist_ok); - // $ck = "checked"; - for ($i = 0; $i < $candidates->length; $i++) - { - if ($candidates->item($i)->getAttribute("sourceok") == "1") - { + // $ck = "checked"; + for ($i = 0; $i < $candidates->length; $i ++ ) { + if ($candidates->item($i)->getAttribute("sourceok") == "1") { // printf("\t\t\t\n", $candidates->item($i)->getAttribute("id") ); - printf("\t\t%s
    \n" - , $candidates->item($i)->getAttribute("id") - , $candidates->item($i)->getAttribute("field")); - // $ck = ""; - } - else - { + printf("\t\t%s
    \n" + , $candidates->item($i)->getAttribute("id") + , $candidates->item($i)->getAttribute("field")); + // $ck = ""; + } else { // printf("\t\t%s
    \n" // , $candidates->item($i)->getAttribute("id") // , $candidates->item($i)->getAttribute("field") ); - } - } - print("\t\t\t
    \n"); + } + } + print("\t\t\t
    \n"); - if ($nb_candidates_ok > 1) - print(p4string::MakeString(_('thesaurus:: selectionner la provenance a accepter')) . "
    \n"); -?> -
    - -     - - - - 0) - { - // present dans les candidats, mais aucun champ acceptable : on informe - if ($nb_candidates_bad == 1) - $t = p4string::MakeString(_('thesaurus:: est candidat en provenance des champs mais ne peut etre accepte a cet emplacement du thesaurus')); - else - $t = p4string::MakeString(_('thesaurus:: est candidat en provenance des champs mais ne peut etre accepte a cet emplacement du thesaurus')); - } - else - { - // pas present dans les candidats - $t = p4string::MakeString(_('thesaurus:: n\'est pas present dans les candidats')) . "\n"; - } -?> + if ($nb_candidates_ok > 1) + print(p4string::MakeString(_('thesaurus:: selectionner la provenance a accepter')) . "
    \n"); + ?> +
    + +     + + + + 0) { + // present dans les candidats, mais aucun champ acceptable : on informe + if ($nb_candidates_bad == 1) + $t = p4string::MakeString(_('thesaurus:: est candidat en provenance des champs mais ne peut etre accepte a cet emplacement du thesaurus')); + else + $t = p4string::MakeString(_('thesaurus:: est candidat en provenance des champs mais ne peut etre accepte a cet emplacement du thesaurus')); + } + else { + // pas present dans les candidats + $t = p4string::MakeString(_('thesaurus:: n\'est pas present dans les candidats')) . "\n"; + } + ?>



    - +

    - +
    -
    -
    -
    -
    -
    -
    -
    - -     - +
    +
    +
    +
    +
    +
    +
    + +     +
    - - + - - + function loaded() + { + clkCid(); + self.focus(); + } + + diff --git a/www/thesaurus2/patch/th_.php b/www/thesaurus2/patch/th_.php index 937c37080b..ff7d050181 100644 --- a/www/thesaurus2/patch/th_.php +++ b/www/thesaurus2/patch/th_.php @@ -18,75 +18,68 @@ class patch_th_ { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - if ($version == "") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $th = $domth->documentElement; - $ct = $domct->documentElement; + if ($version == "") { + $th = $domth->documentElement; + $ct = $domct->documentElement; - $th->setAttribute("id", "0"); + $th->setAttribute("id", "0"); - $xp = new DOMXPath($domth); - $te = $xp->query("/thesaurus/te"); - if ($te->length > 0) - { - $te0 = $te->item(0); - $th->setAttribute("nextid", $te0->getAttribute("nextid")); - $te = $xp->query("te", $te0); - $te1 = array(); - for ($i = 0; $i < $te->length; $i++) - { - $te1[] = $te->item($i); + $xp = new DOMXPath($domth); + $te = $xp->query("/thesaurus/te"); + if ($te->length > 0) { + $te0 = $te->item(0); + $th->setAttribute("nextid", $te0->getAttribute("nextid")); + $te = $xp->query("te", $te0); + $te1 = array(); + for ($i = 0; $i < $te->length; $i ++ ) { + $te1[] = $te->item($i); + } + foreach ($te1 as $tei) { + $th->appendChild($tei); + $this->fixThesaurus2($domth, $tei); + // $tei->parentNode->removeChild($tei); + } + $te0->parentNode->removeChild($te0); + } + $ct->setAttribute("version", $version = "2.0.0"); + $th->setAttribute("version", "2.0.0"); + $th->setAttribute("creation_date", $now = date("YmdHis")); + $th->setAttribute("modification_date", $now); + $version = "2.0.0"; } - foreach ($te1 as $tei) - { - $th->appendChild($tei); - $this->fixThesaurus2($domth, $tei); - // $tei->parentNode->removeChild($tei); + + return($version); + } + + function fixThesaurus2(&$domth, &$tenode, $depth = 0) + { + $unicode = new unicode(); + $sy = $tenode->appendChild($domth->createElement("sy")); + $sy->setAttribute("lng", $v = $tenode->getAttribute("lng")); + $sy->setAttribute("v", $v = $tenode->getAttribute("v")); + $sy->setAttribute("w", $unicode->remove_indexer_chars($v)); + if (($k = $tenode->getAttribute("k")) != "") + $sy->setAttribute("k", $k); + $tenode->removeAttribute("lng"); + $tenode->removeAttribute("v"); + $tenode->removeAttribute("w"); + $tenode->removeAttribute("k"); + if ($tenode->getAttribute("nextid") == "") + $tenode->setAttribute("nextid", "0"); + // $tenode->setAttribute("id", "0.".$tenode->getAttribute("id")); + $todel = array(); + for ($n = $tenode->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "ta") + $todel[] = $n; + if ($n->nodeName == "te") + $this->fixThesaurus2($domth, $n, $depth + 1); + } + foreach ($todel as $n) { + $n->parentNode->removeChild($n); } - $te0->parentNode->removeChild($te0); - } - $ct->setAttribute("version", $version = "2.0.0"); - $th->setAttribute("version", "2.0.0"); - $th->setAttribute("creation_date", $now = date("YmdHis")); - $th->setAttribute("modification_date", $now); - $version = "2.0.0"; } - - return($version); - } - - function fixThesaurus2(&$domth, &$tenode, $depth=0) - { - $unicode = new unicode(); - $sy = $tenode->appendChild($domth->createElement("sy")); - $sy->setAttribute("lng", $v = $tenode->getAttribute("lng")); - $sy->setAttribute("v", $v = $tenode->getAttribute("v")); - $sy->setAttribute("w", $unicode->remove_indexer_chars($v)); - if (($k = $tenode->getAttribute("k")) != "") - $sy->setAttribute("k", $k); - $tenode->removeAttribute("lng"); - $tenode->removeAttribute("v"); - $tenode->removeAttribute("w"); - $tenode->removeAttribute("k"); - if ($tenode->getAttribute("nextid") == "") - $tenode->setAttribute("nextid", "0"); - // $tenode->setAttribute("id", "0.".$tenode->getAttribute("id")); - $todel = array(); - for ($n = $tenode->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "ta") - $todel[] = $n; - if ($n->nodeName == "te") - $this->fixThesaurus2($domth, $n, $depth + 1); - } - foreach ($todel as $n) - { - $n->parentNode->removeChild($n); - } - } - } ?> diff --git a/www/thesaurus2/patch/th_2.0.0.php b/www/thesaurus2/patch/th_2.0.0.php index 2b0c8419e1..14f3fc26f2 100644 --- a/www/thesaurus2/patch/th_2.0.0.php +++ b/www/thesaurus2/patch/th_2.0.0.php @@ -18,33 +18,30 @@ class patch_th_2_0_0 { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - if ($version == "2.0.0") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $th = $domth->documentElement; - $ct = $domct->documentElement; + if ($version == "2.0.0") { + $th = $domth->documentElement; + $ct = $domct->documentElement; - $xp = new DOMXPath($domth); + $xp = new DOMXPath($domth); - $te = $xp->query("/thesaurus//te"); - for ($i = 0; $i < $te->length; $i++) - { - $id = $te->item($i)->getAttribute("id"); - if ($id[0] >= "0" && $id[0] <= "9") - $te->item($i)->setAttribute("id", "T" . $id); - } - $ct->setAttribute("version", $version = "2.0.1"); - $th->setAttribute("version", $version = "2.0.1"); - $th->setAttribute("modification_date", date("YmdHis")); - $sql = "UPDATE thit SET value=CONCAT('T',value) WHERE LEFT(value,1)>='0' AND LEFT(value,1)<='9'"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - $version = "2.0.1"; + $te = $xp->query("/thesaurus//te"); + for ($i = 0; $i < $te->length; $i ++ ) { + $id = $te->item($i)->getAttribute("id"); + if ($id[0] >= "0" && $id[0] <= "9") + $te->item($i)->setAttribute("id", "T" . $id); + } + $ct->setAttribute("version", $version = "2.0.1"); + $th->setAttribute("version", $version = "2.0.1"); + $th->setAttribute("modification_date", date("YmdHis")); + $sql = "UPDATE thit SET value=CONCAT('T',value) WHERE LEFT(value,1)>='0' AND LEFT(value,1)<='9'"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + $version = "2.0.1"; + } + + return($version); } - - return($version); - } - } diff --git a/www/thesaurus2/patch/th_2.0.1.php b/www/thesaurus2/patch/th_2.0.1.php index 9240fd6187..9374c47666 100644 --- a/www/thesaurus2/patch/th_2.0.1.php +++ b/www/thesaurus2/patch/th_2.0.1.php @@ -18,52 +18,47 @@ class patch_th_2_0_1 { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - if ($version == "2.0.1") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $th = $domth->documentElement; - $ct = $domct->documentElement; + if ($version == "2.0.1") { + $th = $domth->documentElement; + $ct = $domct->documentElement; - $xp = new DOMXPath($domth); - $te = $xp->query("/thesaurus//te"); - for ($i = 0; $i < $te->length; $i++) - { - // $id = "S" . substr($te->item($i)->getAttribute("id"), 1); - $id = $te->item($i)->getAttribute("id"); - $nid = (int) ($te->item($i)->getAttribute("nextid")); - for ($n = $te->item($i)->firstChild; $n; $n = $n->nextSibling) - { - if ($n->nodeName == "sy") - { - $n->setAttribute("id", $id . "." . $nid); - $te->item($i)->setAttribute("nextid", ++$nid); - } + $xp = new DOMXPath($domth); + $te = $xp->query("/thesaurus//te"); + for ($i = 0; $i < $te->length; $i ++ ) { + // $id = "S" . substr($te->item($i)->getAttribute("id"), 1); + $id = $te->item($i)->getAttribute("id"); + $nid = (int) ($te->item($i)->getAttribute("nextid")); + for ($n = $te->item($i)->firstChild; $n; $n = $n->nextSibling) { + if ($n->nodeName == "sy") { + $n->setAttribute("id", $id . "." . $nid); + $te->item($i)->setAttribute("nextid", ++ $nid); + } + } + } + + $sql = "UPDATE record SET status=status & ~2"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + $sql = "DELETE FROM thit"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + $domct = @DOMDocument::load("../thesaurus2/blank_cterms.xml"); + $ct = $domct->documentElement; + $ct->setAttribute("creation_date", $now = date("YmdHis")); + $ct->setAttribute("modification_date", $now); + + $ct->setAttribute("version", $version = "2.0.2"); + $th->setAttribute("version", $version = "2.0.2"); + $th->setAttribute("modification_date", date("YmdHis")); + $version = "2.0.2"; } - } - $sql = "UPDATE record SET status=status & ~2"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $sql = "DELETE FROM thit"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $domct = @DOMDocument::load("../thesaurus2/blank_cterms.xml"); - $ct = $domct->documentElement; - $ct->setAttribute("creation_date", $now = date("YmdHis")); - $ct->setAttribute("modification_date", $now); - - $ct->setAttribute("version", $version = "2.0.2"); - $th->setAttribute("version", $version = "2.0.2"); - $th->setAttribute("modification_date", date("YmdHis")); - $version = "2.0.2"; + return($version); } - - return($version); - } - } diff --git a/www/thesaurus2/patch/th_2.0.2.php b/www/thesaurus2/patch/th_2.0.2.php index c2e913a2b1..c21457db1a 100644 --- a/www/thesaurus2/patch/th_2.0.2.php +++ b/www/thesaurus2/patch/th_2.0.2.php @@ -18,36 +18,34 @@ class patch_th_2_0_2 { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - if ($version == "2.0.2") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $th = $domth->documentElement; - $ct = $domct->documentElement; + if ($version == "2.0.2") { + $th = $domth->documentElement; + $ct = $domct->documentElement; - $sql = "ALTER TABLE `pref` ADD `cterms_moddate` DATETIME"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); + $sql = "ALTER TABLE `pref` ADD `cterms_moddate` DATETIME"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); - $sql = "ALTER TABLE `pref` ADD `thesaurus_moddate` DATETIME"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); + $sql = "ALTER TABLE `pref` ADD `thesaurus_moddate` DATETIME"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); - $sql = "UPDATE pref SET thesaurus_moddate = :date1, cterms_moddate = :date2"; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':date1' => $th->getAttribute("modification_date"), ':date2' => $ct->getAttribute("modification_date"))); - $stmt->closeCursor(); + $sql = "UPDATE pref SET thesaurus_moddate = :date1, cterms_moddate = :date2"; + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':date1' => $th->getAttribute("modification_date"), ':date2' => $ct->getAttribute("modification_date"))); + $stmt->closeCursor(); - $ct->setAttribute("version", $version = "2.0.3"); - $th->setAttribute("version", $version = "2.0.3"); - $th->setAttribute("modification_date", date("YmdHis")); + $ct->setAttribute("version", $version = "2.0.3"); + $th->setAttribute("version", $version = "2.0.3"); + $th->setAttribute("modification_date", date("YmdHis")); - $version = "2.0.3"; + $version = "2.0.3"; + } + + return($version); } - - return($version); - } - } diff --git a/www/thesaurus2/patch/th_2.0.3.php b/www/thesaurus2/patch/th_2.0.3.php index 1176c7e567..4ed8d0db8d 100644 --- a/www/thesaurus2/patch/th_2.0.3.php +++ b/www/thesaurus2/patch/th_2.0.3.php @@ -18,164 +18,145 @@ class patch_th_2_0_3 { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - global $debug; - global $ctchanged, $thchanged, $needreindex; - $unicode = new unicode(); - - if ($version == "2.0.3") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $xp = new DOMXPath($domth); - $sy = $xp->query("//sy"); - for ($i = 0; $i < $sy->length; $i++) - { - if (($k = $sy->item($i)->getAttribute("k"))) - { - $v = $sy->item($i)->getAttribute("v"); - if (strpos($v, "(") === false) - { - $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); - printf("// context '($k)' pasted to value '$v'\n"); - $needreindex = true; - } - else - { - printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); - } + global $debug; + global $ctchanged, $thchanged, $needreindex; + $unicode = new unicode(); - $newk = trim($unicode->remove_indexer_chars($k)); - if ($newk != $k) - { - $sy->item($i)->setAttribute("k", $newk); - $needreindex = true; - } + if ($version == "2.0.3") { + $xp = new DOMXPath($domth); + $sy = $xp->query("//sy"); + for ($i = 0; $i < $sy->length; $i ++ ) { + if (($k = $sy->item($i)->getAttribute("k"))) { + $v = $sy->item($i)->getAttribute("v"); + if (strpos($v, "(") === false) { + $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); + printf("// context '($k)' pasted to value '$v'\n"); + $needreindex = true; + } else { + printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); + } + + $newk = trim($unicode->remove_indexer_chars($k)); + if ($newk != $k) { + $sy->item($i)->setAttribute("k", $newk); + $needreindex = true; + } + } + } + $domth->documentElement->setAttribute("version", "2.0.4"); + $domth->documentElement->setAttribute("modification_date", date("YmdHis")); + + $thchanged = true; + + if ($needreindex) { + print("// need to reindex, deleting cterms (keeping rejected)\n"); + + $xp = new DOMXPath($domct); + + $nodes = $xp->query("//te[not(starts-with(@id, 'R')) and count(te[starts-with(@id, 'R')])=0]"); + $nodestodel = array(); + for ($i = 0; $i < $nodes->length; $i ++ ) + $nodestodel[] = $nodes->item($i); + $ctdel = 0; + foreach ($nodestodel as $node) { + $sql2 = "DELETE FROM thit WHERE value LIKE :like"; + + $stmt = $connbas->prepare($sql2); + $stmt->execute(array(':like' => str_replace(".", "d", $node->getAttribute("id")) . "d%")); + $stmt->closeCursor(); + + $node->parentNode->removeChild($node); + $ctdel ++; + } + print("// $ctdel nodes removed\n"); + + $sql2 = "UPDATE record SET status=((status | 15) & ~2)"; + $stmt = $connbas->prepare($sql2); + $stmt->execute(); + $stmt->closeCursor(); + } + + $sy = $xp->query("//sy"); + for ($i = 0; $i < $sy->length; $i ++ ) { + if (($k = $sy->item($i)->getAttribute("k"))) { + if (strpos($v = $sy->item($i)->getAttribute("v"), "(") === false) + $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); + else + printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); + $sy->item($i)->setAttribute("k", $unicode->remove_indexer_chars($k)); + } + } + + $domct->documentElement->removeAttribute("id"); + + $this->fixRejected($connbas, $domct->documentElement, false); + + $this->fixIds($connbas, $domct->documentElement); + + $domct->documentElement->setAttribute("version", "2.0.4"); + $domct->documentElement->setAttribute("modification_date", date("YmdHis")); + $ctchanged = true; + + $version = "2.0.4"; } - } - $domth->documentElement->setAttribute("version", "2.0.4"); - $domth->documentElement->setAttribute("modification_date", date("YmdHis")); - $thchanged = true; - - if ($needreindex) - { - print("// need to reindex, deleting cterms (keeping rejected)\n"); - - $xp = new DOMXPath($domct); - - $nodes = $xp->query("//te[not(starts-with(@id, 'R')) and count(te[starts-with(@id, 'R')])=0]"); - $nodestodel = array(); - for ($i = 0; $i < $nodes->length; $i++) - $nodestodel[] = $nodes->item($i); - $ctdel = 0; - foreach ($nodestodel as $node) - { - $sql2 = "DELETE FROM thit WHERE value LIKE :like"; - - $stmt = $connbas->prepare($sql2); - $stmt->execute(array(':like' => str_replace(".", "d", $node->getAttribute("id")) . "d%")); - $stmt->closeCursor(); - - $node->parentNode->removeChild($node); - $ctdel++; - } - print("// $ctdel nodes removed\n"); - - $sql2 = "UPDATE record SET status=((status | 15) & ~2)"; - $stmt = $connbas->prepare($sql2); - $stmt->execute(); - $stmt->closeCursor(); - } - - $sy = $xp->query("//sy"); - for ($i = 0; $i < $sy->length; $i++) - { - if (($k = $sy->item($i)->getAttribute("k"))) - { - if (strpos($v = $sy->item($i)->getAttribute("v"), "(") === false) - $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); - else - printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); - $sy->item($i)->setAttribute("k", $unicode->remove_indexer_chars($k)); - } - } - - $domct->documentElement->removeAttribute("id"); - - $this->fixRejected($connbas, $domct->documentElement, false); - - $this->fixIds($connbas, $domct->documentElement); - - $domct->documentElement->setAttribute("version", "2.0.4"); - $domct->documentElement->setAttribute("modification_date", date("YmdHis")); - $ctchanged = true; - - $version = "2.0.4"; + return($version); } - return($version); - } - - function fixRejected(connection_pdo &$connbas, &$node, $rejected) - { - global $debug; - if ($node->nodeType != XML_ELEMENT_NODE) - - return; - $id = $node->getAttribute("id"); - if (substr($id, 0, 1) == "R") - $rejected = true; - if ($rejected) + function fixRejected(connection_pdo &$connbas, &$node, $rejected) { - $newid = "R" . substr($id, 1); - if ($newid != $id) - { - print("// \tid '$id' (child of '" . $node->parentNode->getAttribute("id") . "') fixed to '$newid'\n"); - $node->setAttribute("id", $newid); - $id = str_replace(".", "d", $id) . "d"; - $newid = str_replace(".", "d", $newid) . "d"; - $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; - - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); - $stmt->closeCursor(); - } - } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - $this->fixRejected($connbas, $n, $rejected); - } - - function fixIds(connection_pdo &$connbas, &$node) - { - global $debug; - if ($node->nodeType != XML_ELEMENT_NODE) - - return; - if ($node->parentNode && $node->parentNode->nodeType == XML_ELEMENT_NODE) - { - $pid = $node->parentNode->getAttribute("id"); - if ($pid != "") - { + global $debug; + if ($node->nodeType != XML_ELEMENT_NODE) + return; $id = $node->getAttribute("id"); - if (substr($id, 1, strlen($pid)) != substr($pid, "1") . ".") - { - //printf("pid='%s', id='%s'\n", $pid, $id); - $nid = $node->parentNode->getAttribute("nextid"); - $node->parentNode->setAttribute("nextid", $nid + 1); - $node->setAttribute("id", $newid = ($pid . "." . $nid)); - printf("// \tid '%s' (child of '%s') fixed to '%s'\n", $id, $pid, $newid); - $id = str_replace(".", "d", $id) . "d"; - $newid = str_replace(".", "d", $newid) . "d"; - $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; + if (substr($id, 0, 1) == "R") + $rejected = true; + if ($rejected) { + $newid = "R" . substr($id, 1); + if ($newid != $id) { + print("// \tid '$id' (child of '" . $node->parentNode->getAttribute("id") . "') fixed to '$newid'\n"); + $node->setAttribute("id", $newid); + $id = str_replace(".", "d", $id) . "d"; + $newid = str_replace(".", "d", $newid) . "d"; + $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); + $stmt->closeCursor(); + } } - } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) + $this->fixRejected($connbas, $n, $rejected); } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - $this->fixIds($connbas, $n); - } + function fixIds(connection_pdo &$connbas, &$node) + { + global $debug; + if ($node->nodeType != XML_ELEMENT_NODE) + return; + if ($node->parentNode && $node->parentNode->nodeType == XML_ELEMENT_NODE) { + $pid = $node->parentNode->getAttribute("id"); + if ($pid != "") { + $id = $node->getAttribute("id"); + if (substr($id, 1, strlen($pid)) != substr($pid, "1") . ".") { + //printf("pid='%s', id='%s'\n", $pid, $id); + $nid = $node->parentNode->getAttribute("nextid"); + $node->parentNode->setAttribute("nextid", $nid + 1); + $node->setAttribute("id", $newid = ($pid . "." . $nid)); + printf("// \tid '%s' (child of '%s') fixed to '%s'\n", $id, $pid, $newid); + $id = str_replace(".", "d", $id) . "d"; + $newid = str_replace(".", "d", $newid) . "d"; + $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; + + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); + $stmt->closeCursor(); + } + } + } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) + $this->fixIds($connbas, $n); + } } diff --git a/www/thesaurus2/patch/th_2.0.4.php b/www/thesaurus2/patch/th_2.0.4.php index 89246b550e..b02abdae20 100644 --- a/www/thesaurus2/patch/th_2.0.4.php +++ b/www/thesaurus2/patch/th_2.0.4.php @@ -18,170 +18,148 @@ class patch_th_2_0_4 { - function patch($version, &$domct, &$domth, connection_pdo &$connbas) - { - global $debug; - global $ctchanged, $thchanged, $needreindex; - - $unicode = new unicode(); - // $debug = true; - if ($version == "2.0.4") + function patch($version, &$domct, &$domth, connection_pdo &$connbas) { - $xp = new DOMXPath($domth); - $sy = $xp->query("//sy"); - for ($i = 0; $i < $sy->length; $i++) - { - if (($k = $sy->item($i)->getAttribute("k"))) - { - $v = $sy->item($i)->getAttribute("v"); - if (strpos($v, "(") === false) - { - $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); - printf("// context '($k)' pasted to value '$v'\n"); - $needreindex = true; - } - else - { - printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); - } + global $debug; + global $ctchanged, $thchanged, $needreindex; - $newk = trim($unicode->remove_indexer_chars($k)); - if ($newk != $k) - { - $sy->item($i)->setAttribute("k", $newk); - $needreindex = true; - } + $unicode = new unicode(); + // $debug = true; + if ($version == "2.0.4") { + $xp = new DOMXPath($domth); + $sy = $xp->query("//sy"); + for ($i = 0; $i < $sy->length; $i ++ ) { + if (($k = $sy->item($i)->getAttribute("k"))) { + $v = $sy->item($i)->getAttribute("v"); + if (strpos($v, "(") === false) { + $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); + printf("// context '($k)' pasted to value '$v'\n"); + $needreindex = true; + } else { + printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); + } + + $newk = trim($unicode->remove_indexer_chars($k)); + if ($newk != $k) { + $sy->item($i)->setAttribute("k", $newk); + $needreindex = true; + } + } + } + $domth->documentElement->setAttribute("version", "2.0.5"); + $domth->documentElement->setAttribute("modification_date", date("YmdHis")); + + $thchanged = true; + + if ($needreindex) { + print("// need to reindex, deleting cterms (keeping rejected)\n"); + + $xp = new DOMXPath($domct); + + $nodes = $xp->query("//te[not(starts-with(@id, 'R')) and count(te[starts-with(@id, 'R')])=0]"); + $nodestodel = array(); + for ($i = 0; $i < $nodes->length; $i ++ ) + $nodestodel[] = $nodes->item($i); + $ctdel = 0; + foreach ($nodestodel as $node) { + $sql2 = "DELETE FROM thit WHERE value LIKE :like"; + + $stmt = $connbas->prepare($sql2); + $stmt->execute(array(':like' => str_replace(".", "d", $node->getAttribute("id")) . "d%")); + $stmt->closeCursor(); + + $node->parentNode->removeChild($node); + $ctdel ++; + } + print("// $ctdel nodes removed\n"); + + $sql2 = "UPDATE record SET status=((status | 15) & ~2)"; + + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } + + $sy = $xp->query("//sy"); + for ($i = 0; $i < $sy->length; $i ++ ) { + if (($k = $sy->item($i)->getAttribute("k"))) { + if (strpos($v = $sy->item($i)->getAttribute("v"), "(") === false) { + $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); + } else { + printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); + } + $sy->item($i)->setAttribute("k", $unicode->remove_indexer_chars($k)); + } + } + + $domct->documentElement->removeAttribute("id"); + + $this->fixRejected($connbas, $domct->documentElement, false); + + $this->fixIds($connbas, $domct->documentElement); + + $domct->documentElement->setAttribute("version", "2.0.5"); + $domct->documentElement->setAttribute("modification_date", date("YmdHis")); + $ctchanged = true; + + $version = "2.0.5"; } - } - $domth->documentElement->setAttribute("version", "2.0.5"); - $domth->documentElement->setAttribute("modification_date", date("YmdHis")); - $thchanged = true; - - if ($needreindex) - { - print("// need to reindex, deleting cterms (keeping rejected)\n"); - - $xp = new DOMXPath($domct); - - $nodes = $xp->query("//te[not(starts-with(@id, 'R')) and count(te[starts-with(@id, 'R')])=0]"); - $nodestodel = array(); - for ($i = 0; $i < $nodes->length; $i++) - $nodestodel[] = $nodes->item($i); - $ctdel = 0; - foreach ($nodestodel as $node) - { - $sql2 = "DELETE FROM thit WHERE value LIKE :like"; - - $stmt = $connbas->prepare($sql2); - $stmt->execute(array(':like' => str_replace(".", "d", $node->getAttribute("id")) . "d%")); - $stmt->closeCursor(); - - $node->parentNode->removeChild($node); - $ctdel++; - } - print("// $ctdel nodes removed\n"); - - $sql2 = "UPDATE record SET status=((status | 15) & ~2)"; - - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - - $sy = $xp->query("//sy"); - for ($i = 0; $i < $sy->length; $i++) - { - if (($k = $sy->item($i)->getAttribute("k"))) - { - if (strpos($v = $sy->item($i)->getAttribute("v"), "(") === false) - { - $sy->item($i)->setAttribute("v", $v . " (" . $k . ")"); - } - else - { - printf("// warning : <sy id='%s' v='%s' ...> already had context (left unchanged)\n", $sy->item($i)->getAttribute("id"), htmlentities($v)); - } - $sy->item($i)->setAttribute("k", $unicode->remove_indexer_chars($k)); - } - } - - $domct->documentElement->removeAttribute("id"); - - $this->fixRejected($connbas, $domct->documentElement, false); - - $this->fixIds($connbas, $domct->documentElement); - - $domct->documentElement->setAttribute("version", "2.0.5"); - $domct->documentElement->setAttribute("modification_date", date("YmdHis")); - $ctchanged = true; - - $version = "2.0.5"; + return($version); } - return($version); - } - - function fixRejected(connection_pdo &$connbas, &$node, $rejected) - { - global $debug; - if ($node->nodeType != XML_ELEMENT_NODE) - - return; - $id = $node->getAttribute("id"); - if (substr($id, 0, 1) == "R") - $rejected = true; - if ($rejected) + function fixRejected(connection_pdo &$connbas, &$node, $rejected) { - $newid = "R" . substr($id, 1); - if ($newid != $id) - { - print("// \tid '$id' (child of '" . $node->parentNode->getAttribute("id") . "') fixed to '$newid'\n"); - $node->setAttribute("id", $newid); - $id = str_replace(".", "d", $id) . "d"; - $newid = str_replace(".", "d", $newid) . "d"; - $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; - - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); - $stmt->closeCursor(); - } - } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - $this->fixRejected($connbas, $n, $rejected); - } - - function fixIds(connection_pdo &$connbas, &$node) - { - global $debug; - if ($node->nodeType != XML_ELEMENT_NODE) - - return; - if ($node->parentNode && $node->parentNode->nodeType == XML_ELEMENT_NODE) - { - $pid = $node->parentNode->getAttribute("id"); - if ($pid != "") - { + global $debug; + if ($node->nodeType != XML_ELEMENT_NODE) + return; $id = $node->getAttribute("id"); - if (substr($id, 1, strlen($pid)) != substr($pid, "1") . ".") - { - //printf("pid='%s', id='%s'\n", $pid, $id); - $nid = $node->parentNode->getAttribute("nextid"); - $node->parentNode->setAttribute("nextid", $nid + 1); - $node->setAttribute("id", $newid = ($pid . "." . $nid)); - printf("// \tid '%s' (child of '%s') fixed to '%s'\n", $id, $pid, $newid); - $id = str_replace(".", "d", $id) . "d"; - $newid = str_replace(".", "d", $newid) . "d"; - $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; + if (substr($id, 0, 1) == "R") + $rejected = true; + if ($rejected) { + $newid = "R" . substr($id, 1); + if ($newid != $id) { + print("// \tid '$id' (child of '" . $node->parentNode->getAttribute("id") . "') fixed to '$newid'\n"); + $node->setAttribute("id", $newid); + $id = str_replace(".", "d", $id) . "d"; + $newid = str_replace(".", "d", $newid) . "d"; + $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; - $stmt = $connbas->prepare($sql); - $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); - $stmt->closeCursor(); + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); + $stmt->closeCursor(); + } } - } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) + $this->fixRejected($connbas, $n, $rejected); } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - $this->fixIds($connbas, $n); - } + function fixIds(connection_pdo &$connbas, &$node) + { + global $debug; + if ($node->nodeType != XML_ELEMENT_NODE) + return; + if ($node->parentNode && $node->parentNode->nodeType == XML_ELEMENT_NODE) { + $pid = $node->parentNode->getAttribute("id"); + if ($pid != "") { + $id = $node->getAttribute("id"); + if (substr($id, 1, strlen($pid)) != substr($pid, "1") . ".") { + //printf("pid='%s', id='%s'\n", $pid, $id); + $nid = $node->parentNode->getAttribute("nextid"); + $node->parentNode->setAttribute("nextid", $nid + 1); + $node->setAttribute("id", $newid = ($pid . "." . $nid)); + printf("// \tid '%s' (child of '%s') fixed to '%s'\n", $id, $pid, $newid); + $id = str_replace(".", "d", $id) . "d"; + $newid = str_replace(".", "d", $newid) . "d"; + $sql = "UPDATE thit SET value = :newid WHERE value = :oldid"; + + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':newid' => $newid, ':oldid' => $id)); + $stmt->closeCursor(); + } + } + } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) + $this->fixIds($connbas, $n); + } } diff --git a/www/thesaurus2/properties.php b/www/thesaurus2/properties.php index 30a9650c26..6adf92173e 100644 --- a/www/thesaurus2/properties.php +++ b/www/thesaurus2/properties.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -25,513 +24,504 @@ require($registry->get('GV_RootPath') . "www/thesaurus2/xmlhttp.php"); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "typ" - , "dlg" + "bid" + , "piv" + , "id" + , "typ" + , "dlg" ); $lng = Session_Handler::get_locale(); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - <?php echo p4string::MakeString(_('thesaurus:: Proprietes')) ?> + + <?php echo p4string::MakeString(_('thesaurus:: Proprietes')) ?> - - + + - - - - + + + + - - - - + \n"); - $dom = xmlhttp($url); - printf("
    id: %s
    \n", $parm["id"]); - $fullpath = $dom->getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; - print("

    " . $fullpath . "


    \n"); - if ($parm["typ"] == "CT") - { + // print($url. "
    \n"); + $dom = xmlhttp($url); + printf("
    id: %s
    \n", $parm["id"]); + $fullpath = $dom->getElementsByTagName("fullpath_html")->item(0)->firstChild->nodeValue; + print("

    " . $fullpath . "


    \n"); + if ($parm["typ"] == "CT") { // printf("present dans %s fiche(s).
    \n", $dom->getElementsByTagName("hits")->item(0)->firstChild->nodeValue ); - print("
    \n"); - } - elseif ($parm["typ"] == "TH") - { - echo p4string::MakeString(sprintf(_('thesaurus:: %s reponses retournees'), $dom->getElementsByTagName("allhits")->item(0)->firstChild->nodeValue)); - print("
    \n"); - print("
    \n"); - } -?> -
    -
    - - - - - - - - - - - - - - - - - - - - - - -
       
    -
    -
    -
    - - - - - - - - - getElementsByTagName("sy_list")->item(0); - $nsy = 0; - for ($n = $sy_list->firstChild; $n; $n = $n->nextSibling) - { - printf("\t\t\t\t\t\t\n", $id = $n->getAttribute("id"), $n->getAttribute("hits")); - printf("\t\t\t\t\t\t\t\n"); - printf("\t\t\t\t\t\t\t\n"); - if (($lng = $n->getAttribute("lng"))) - printf("\t\t\t\t\t\t\t\n", $n->getAttribute("id"), $lng); - else - printf("\t\t\t\t\t\t\t\n", $n->getAttribute("id")); - printf("\t\t\t\t\t\t\t\n", $n->getAttribute("t")); - printf("\t\t\t\t\t\t\t\n", $n->getAttribute("hits")); - printf("\t\t\t\t\t\t\t\n", $id); + print("
    \n"); + } elseif ($parm["typ"] == "TH") { + echo p4string::MakeString(sprintf(_('thesaurus:: %s reponses retournees'), $dom->getElementsByTagName("allhits")->item(0)->firstChild->nodeValue)); + print("
    \n"); + print("
    \n"); + } + ?> +
    +
    +
    \n"); - if ($nsy > 0) - printf("\t\t\t\t\t\t\t\t\n"); - if ($nsy > 0 && $n->nextSibling) - print(" "); - if ($n->nextSibling) - printf("\t\t\t\t\t\t\t\t%s%s%s
    + + + + + + + + + + + + + + + + + + + + + +
       
    +
    +
    +
    + + + + + + + + + getElementsByTagName("sy_list")->item(0); + $nsy = 0; + for ($n = $sy_list->firstChild; $n; $n = $n->nextSibling) { + printf("\t\t\t\t\t\t\n", $id = $n->getAttribute("id"), $n->getAttribute("hits")); + printf("\t\t\t\t\t\t\t\n"); + printf("\t\t\t\t\t\t\t\n"); + if (($lng = $n->getAttribute("lng"))) + printf("\t\t\t\t\t\t\t\n", $n->getAttribute("id"), $lng); + else + printf("\t\t\t\t\t\t\t\n", $n->getAttribute("id")); + printf("\t\t\t\t\t\t\t\n", $n->getAttribute("t")); + printf("\t\t\t\t\t\t\t\n", $n->getAttribute("hits")); + printf("\t\t\t\t\t\t\t\n", $id); // printf("\n"); - print("\t\t\t\t\t\t\n"); - $nsy++; - } + print("\t\t\t\t\t\t\n"); + $nsy ++; + } // if($parm["typ"]=="TH") // { // print("\n"); // } - ?> - -
    \n"); + if ($nsy > 0) + printf("\t\t\t\t\t\t\t\t\n"); + if ($nsy > 0 && $n->nextSibling) + print(" "); + if ($n->nextSibling) + printf("\t\t\t\t\t\t\t\t%s%s%s
    nouveau synonyme...
    -
    -
    -
    -
    -
    - -
    -
    - %s\n", htmlentities($dom->saveXML())); - } ?> - - + diff --git a/www/thesaurus2/replace.php b/www/thesaurus2/replace.php index 2a684196c8..0f68e7a1b3 100644 --- a/www/thesaurus2/replace.php +++ b/www/thesaurus2/replace.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -25,21 +24,18 @@ require($registry->get('GV_RootPath') . "www/thesaurus2/xmlhttp.php"); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "pid" // id du pere (te) - , "id" // id du synonyme (sy) - , "typ" - , "dlg" + "bid" + , "piv" + , "pid" // id du pere (te) + , "id" // id du synonyme (sy) + , "typ" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } $url = "thesaurus2/xmlhttp/getsy.x.php"; @@ -56,163 +52,151 @@ $hits = $dom->getElementsByTagName("hits")->item(0)->firstChild->nodeValue; ?> - - Corriger... + + Corriger... - - + + - - + - - -
    id: 
    -



    + return(true); + } + function clkBut(button) + { + switch(button) + { + case "submit": + // document.forms[0].target="LINKFIELD"; + document.forms[0].submit(); + break; + case "cancel": + self.close(); + break; + } + } + function clkRepl() + { + var o; + if(!(o=document.getElementById("rplrec")).checked) + { + fields = document.getElementsByName("field[]"); + for(i=0; i + + +
    id: 
    +



    \n", $dom->getElementsByTagName("hits")->item(0)->firstChild->nodeValue ); -if ($parm["typ"] == "TH") -{ - $loaded = false; - try - { - $databox = databox::get_instance((int) $parm['bid']); - $domstruct = $databox->get_dom_structure(); - $domth = $databox->get_dom_thesaurus(); +if ($parm["typ"] == "TH") { + $loaded = false; + try { + $databox = databox::get_instance((int) $parm['bid']); + $domstruct = $databox->get_dom_structure(); + $domth = $databox->get_dom_thesaurus(); - if ($domstruct && $domth) - { - $xpathth = new DOMXPath($domth); - $xpathstruct = new DOMXPath($domstruct); -?> -
    -
    - "> - "> - "> - "> - "> - - "> -"> -
    -
    - - -
    -
    -
    -query("/record/description/*"); - for ($i = 0; $i < $fields->length; $i++) - { - $fieldname = $fields->item($i)->nodeName; - $tbranch = $fields->item($i)->getAttribute("tbranch"); - $ck = ""; - if ($tbranch) - { - // ce champ a un tbranch, est-ce qu'il permet d'atteindre le terme selectionne ? - $branches = $xpathth->query($tbranch); - for ($j = 0; $j < $branches->length; $j++) - { - $q = ".//sy[@id='" . $parm["id"] . "']"; - // printf("searching %s against id=%s
    \n", $q, $branches->item($j)->getAttribute("id")); - if ($xpathth->query($q, $branches->item($j))->length > 0) - { - // oui - $ck = true; - } + if ($domstruct && $domth) { + $xpathth = new DOMXPath($domth); + $xpathstruct = new DOMXPath($domstruct); + ?> +
    + + "> + "> + "> + "> + "> + + "> + "> +
    +
    + + +
    +
    +
    + query("/record/description/*"); + for ($i = 0; $i < $fields->length; $i ++ ) { + $fieldname = $fields->item($i)->nodeName; + $tbranch = $fields->item($i)->getAttribute("tbranch"); + $ck = ""; + if ($tbranch) { + // ce champ a un tbranch, est-ce qu'il permet d'atteindre le terme selectionne ? + $branches = $xpathth->query($tbranch); + for ($j = 0; $j < $branches->length; $j ++ ) { + $q = ".//sy[@id='" . $parm["id"] . "']"; + // printf("searching %s against id=%s
    \n", $q, $branches->item($j)->getAttribute("id")); + if ($xpathth->query($q, $branches->item($j))->length > 0) { + // oui + $ck = true; + } + } + } + if ($ck) { + printf("\t\t%s
    \n" + , $fieldname, $fieldname); + } else { + printf("\t\t%s
    \n" + , $fieldname, $fieldname); + } } - } - if ($ck) - { - printf("\t\t%s
    \n" - , $fieldname, $fieldname); - } - else - { - printf("\t\t%s
    \n" - , $fieldname, $fieldname); - } - } -?> -
    -
    - -     - - -
    - +
    +
    + +     + + +
    + - + } + } + ?> + diff --git a/www/thesaurus2/replace2.php b/www/thesaurus2/replace2.php index 08a090764e..21962c3f29 100644 --- a/www/thesaurus2/replace2.php +++ b/www/thesaurus2/replace2.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -25,24 +24,21 @@ require($registry->get('GV_RootPath') . "www/thesaurus2/xmlhttp.php"); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "pid" // id du pere (te) - , "id" // id du synonyme (sy) - , "src" - , "rpl" - , "rplrec" - , "field" - , "dlg" + "bid" + , "piv" + , "pid" // id du pere (te) + , "id" // id du synonyme (sy) + , "src" + , "rpl" + , "rplrec" + , "field" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } $url3 = "./replace3.php"; @@ -53,248 +49,228 @@ $url3 .= "&src=" . urlencode($parm["src"]); $url3 .= "&rplrec=" . urlencode($parm["rplrec"]); $url3 .= "&rpl=" . urlencode($parm["rpl"]); $lstfld = ""; -if ($parm["rplrec"] && is_array($parm["field"])) -{ - foreach ($parm["field"] as $f) - { - $url3 .= "&field[]=" . urlencode($f); - $lstfld .= ( $lstfld ? ", " : "") . "" . $f . ""; - } +if ($parm["rplrec"] && is_array($parm["field"])) { + foreach ($parm["field"] as $f) { + $url3 .= "&field[]=" . urlencode($f); + $lstfld .= ( $lstfld ? ", " : "") . "" . $f . ""; + } } $url3 .= "&dlg=" . urlencode($parm["dlg"] ? 1 : 0); ?> - - Corriger... + + Corriger... - - + } + #barBg + { + BACKGROUND-COLOR:#ffffff; + COLOR:#0000FF; + } + #barMv + { + CLIP:rect(0px 0px auto 0px); + BACKGROUND-POSITION: left top; + BACKGROUND-IMAGE: url(./images/pbar.gif); + COLOR:#FFFFFF; + } + - - + - + document.getElementById("barMv").style.clip="rect(0px "+(clipright+1)+"px auto 0px)"; + document.getElementById("barMv").innerHTML = document.getElementById("barBg").innerHTML = percent + "%"; + document.getElementById("barCptr").innerHTML = "( " + newtraite + " / " + newnbtotal + ")"; + } + function pdone(nrecdone, nrectot, nrecchanged, nspot) + { + msg.innerText = nspot + "" + nrecchanged + " documents."; + } + + \n"); - // print($dom->saveXML()); + print("\n"); + // print($dom->saveXML()); - $xpath = new DOMXPath($dom); + $xpath = new DOMXPath($dom); - $candidates = $xpath->query("/result/candidates_list/ct"); - if ($candidates->length > 0) - { - // le terme saisi existait dans les candidats, on peut choisir qui accepter -?> -
    - "> - "> -
    -le terme " . $term . ""; - if ($context != "") - $t .= " (avec contexte " . $context . ")"; - $t .= utf8_encode(" est deje candidat en provenance"); - $t .= ( $candidates->length == 1) ? " du champ :" : " des champs suivants :"; - $t .= "

    \n"; + $candidates = $xpath->query("/result/candidates_list/ct"); + if ($candidates->length > 0) { + // le terme saisi existait dans les candidats, on peut choisir qui accepter + ?> + + "> + "> +
    + le terme " . $term . ""; + if ($context != "") + $t .= " (avec contexte " . $context . ")"; + $t .= utf8_encode(" est deje candidat en provenance"); + $t .= ( $candidates->length == 1) ? " du champ :" : " des champs suivants :"; + $t .= "

    \n"; - print($t); + print($t); - $candidates_ok = 0; - for ($i = 0; $i < $candidates->length; $i++) - { - if ($candidates->item($i)->getAttribute("sourceok") == "1") - $candidates_ok++; - } + $candidates_ok = 0; + for ($i = 0; $i < $candidates->length; $i ++ ) { + if ($candidates->item($i)->getAttribute("sourceok") == "1") + $candidates_ok ++; + } - print("
    \n"); - for ($i = 0; $i < $candidates->length; $i++) - { - if ($candidates->item($i)->getAttribute("sourceok") == "1") - { - printf("\t\t%s
    \n" - , $candidates->item($i)->getAttribute("id") - , $candidates->item($i)->getAttribute("field")); - } - else - { - printf("\t\t%s
    \n" - , $candidates->item($i)->getAttribute("id") - , $candidates->item($i)->getAttribute("field")); - } - } - print("

    \n"); - if ($candidates_ok > 1) - print(utf8_encode("selectionnez la provenance e accepter.
    \n")); - } - - $nrec = 0; - if ($parm["rplrec"]) // remplacer egalement dans les record - { - // table temporaire - $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS `tmprecord` (`xml` TEXT COLLATE utf8_general_ci) SELECT record_id, xml FROM record"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $unicode = new unicode(); - $src_noacc = $unicode->remove_indexer_chars($parm["src"]); - $src_noacc_len = mb_strlen($src_noacc, "UTF-8"); - $src_noacc_tchar = array(); - for ($i = 0; $i < $src_noacc_len; $i++) - $src_noacc_tchar[$i] = mb_substr($src_noacc, $i, 1, "UTF-8"); - - $sql = ""; - $params = array(); - $n = 0; - foreach ($parm["field"] as $field) - { - $params[':like' . $n] = "%<$field>%" . $src_noacc . "%%"; - $sql .= ( $sql == "" ? "" : " OR ") . "(xml LIKE :like" . $n . ")"; - $n++; - } - - $sql = "SELECT record_id, BINARY xml AS xml FROM tmprecord WHERE $sql"; - $stmt = $connbas->prepare($sql); - $stmt->execute($params); - $nrec = $stmt->rowCount(); - $stmt->closeCursor(); - - $out .= "remplacement de " . $parm["src"] . " par " . $parm["rpl"] . " dans le champ " . $lstfld . "
    \n"; - $out .= "
    \n"; - - $out .= "
    \n"; - $out .= "
    0%
    \n"; - $out .= "
    0%
    \n"; - $out .= "
    \n"; - $out .= "
     
    \n"; - $out .= "
    \n"; - - if ($nrec >= 0) - { - $out .= "
    " . utf8_encode(" $nrec documents concernes !") . "
    \n"; - $out .= "
    \n
    \n"; - $out .= " \n"; - $out .= "    \n"; - $out .= " \n"; - $onload = "loaded();"; - } - else - { - $out .= "
    " . utf8_encode(" $nrec records concernes !") . "
    \n"; - $out .= "
    \n
    \n"; - $out .= " \n"; - $onload = "loaded();doContinue();"; - } - } - else - { - $onload = "loaded();"; - } -?> - -
    -
    - - - -
    - -
    - -\n"); + for ($i = 0; $i < $candidates->length; $i ++ ) { + if ($candidates->item($i)->getAttribute("sourceok") == "1") { + printf("\t\t%s
    \n" + , $candidates->item($i)->getAttribute("id") + , $candidates->item($i)->getAttribute("field")); + } else { + printf("\t\t%s
    \n" + , $candidates->item($i)->getAttribute("id") + , $candidates->item($i)->getAttribute("field")); + } + } + print("

    \n"); + if ($candidates_ok > 1) + print(utf8_encode("selectionnez la provenance e accepter.
    \n")); } - } - return(array($term, $context)); - } -?> - + $nrec = 0; + if ($parm["rplrec"]) { // remplacer egalement dans les record + // table temporaire + $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS `tmprecord` (`xml` TEXT COLLATE utf8_general_ci) SELECT record_id, xml FROM record"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + $unicode = new unicode(); + $src_noacc = $unicode->remove_indexer_chars($parm["src"]); + $src_noacc_len = mb_strlen($src_noacc, "UTF-8"); + $src_noacc_tchar = array(); + for ($i = 0; $i < $src_noacc_len; $i ++ ) + $src_noacc_tchar[$i] = mb_substr($src_noacc, $i, 1, "UTF-8"); + + $sql = ""; + $params = array(); + $n = 0; + foreach ($parm["field"] as $field) { + $params[':like' . $n] = "%<$field>%" . $src_noacc . "%%"; + $sql .= ( $sql == "" ? "" : " OR ") . "(xml LIKE :like" . $n . ")"; + $n ++; + } + + $sql = "SELECT record_id, BINARY xml AS xml FROM tmprecord WHERE $sql"; + $stmt = $connbas->prepare($sql); + $stmt->execute($params); + $nrec = $stmt->rowCount(); + $stmt->closeCursor(); + + $out .= "remplacement de " . $parm["src"] . " par " . $parm["rpl"] . " dans le champ " . $lstfld . "
    \n"; + $out .= "
    \n"; + + $out .= "
    \n"; + $out .= "
    0%
    \n"; + $out .= "
    0%
    \n"; + $out .= "
    \n"; + $out .= "
     
    \n"; + $out .= "
    \n"; + + if ($nrec >= 0) { + $out .= "
    " . utf8_encode(" $nrec documents concernes !") . "
    \n"; + $out .= "
    \n
    \n"; + $out .= " \n"; + $out .= "    \n"; + $out .= " \n"; + $onload = "loaded();"; + } else { + $out .= "
    " . utf8_encode(" $nrec records concernes !") . "
    \n"; + $out .= "
    \n
    \n"; + $out .= " \n"; + $onload = "loaded();doContinue();"; + } + } else { + $onload = "loaded();"; + } + ?> + +
    +
    +
    + +
    +
    + +
    + + + diff --git a/www/thesaurus2/replace3.php b/www/thesaurus2/replace3.php index 7bc399ec81..97eb24dbac 100644 --- a/www/thesaurus2/replace3.php +++ b/www/thesaurus2/replace3.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,169 +22,150 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "id" - , "src" - , "rpl" - , "field" - , "dlg" + "bid" + , "piv" + , "id" + , "src" + , "rpl" + , "field" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - + prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $unicode = new unicode(); - $src_noacc = $unicode->remove_indexer_chars($parm["src"]); - $src_noacc_len = mb_strlen($src_noacc, "UTF-8"); - $src_noacc_tchar = array(); - for ($i = 0; $i < $src_noacc_len; $i++) - $src_noacc_tchar[$i] = mb_substr($src_noacc, $i, 1, "UTF-8"); - - $sql = ""; - $params = array(); - $n = 0; - foreach ($parm["field"] as $field) - { - $params[':like' . $n] = "%<$field>%" . $src_noacc . "%%"; - $sql .= ( $sql == "" ? "" : " OR ") . "(xml LIKE :like" . $n . ")"; - } - $sql = "SELECT record_id, BINARY xml AS xml FROM tmprecord WHERE $sql"; - $stmt = $connbas->prepare($sql); - $stmt->execute($params); - $rsbas2 = $stmt->fetchAll(PDO::FETCH_ASSOC); - $nrectot = $stmt->rowCount(); - $stmt->closeCursor(); - - $nrecdone = $nrecchanged = $nspot = 0; - foreach ($rsbas2 as $rowbas2) - { - $nrecdone++; - printf("\n"); - flush(); - - set_time_limit(30); - - $xml = $rowbas2["xml"]; - $spots = array(); - foreach ($parm["field"] as $field) - { - $ibyte_min = $ichar_min = 0; - while (true) - { - if (($ibyte_min = strpos($xml, "<$field>", $ibyte_min)) === false) - break; - $ibyte_min += strlen("<$field>"); - if (($ibyte_max = strpos($xml, "", $ibyte_min)) === false) - break; - - $ichar_min = mb_strpos($xml, "<$field>", $ichar_min, "UTF-8") + mb_strlen("<$field>"); - $ichar_max = mb_strpos($xml, "", $ichar_min, "UTF-8"); // + mb_strlen(""); - - $txml = substr($xml, $ibyte_min, $ibyte_max - $ibyte_min); - - $xml_noacc_tchar = array(); // buffer circulaire taille+2 (car prec. et car suiv. pour trouver uniquement les mots entiers) - $xml_noacc_tchar[0] = array(">", ">", 1); // car precedent - for ($i = 0; $i < $src_noacc_len + 1; $i++) - { - $c = mb_substr($txml, 0, 1, "UTF-8"); - $xml_noacc_tchar[$i + 1] = array($c, $unicode->remove_indexer_chars($c), $l = strlen($c)); - $txml = substr($txml, $l); - } - - for ($ib = $ibyte_min, $ic = $ichar_min; $ic <= $ichar_max - $src_noacc_len; $ic++) - { - - if (isdelim($xml_noacc_tchar[0][0]) && isdelim($xml_noacc_tchar[$src_noacc_len + 1][0])) - { - for ($i = 0; $i < $src_noacc_len; $i++) - { - if ($xml_noacc_tchar[$i + 1][1] !== $src_noacc_tchar[$i]) - break; - } - - if ($i == $src_noacc_len) - { - for ($l = 0, $i = 1; $i < $src_noacc_len + 1; $i++) - $l += $xml_noacc_tchar[$i][2]; - - if (count($spots) == 0) - { - $nrecchanged++; - } - $nspot++; - - $spots[$ib] = array("p" => $ib, "l" => $l); - } - } - $lost = array_shift($xml_noacc_tchar); - $c = mb_substr($txml, 0, 1, "UTF-8"); - $xml_noacc_tchar[] = array($c, $unicode->remove_indexer_chars($c), $l = strlen($c)); - // $txml = mb_substr($txml, 1, 9999, "UTF-8"); - $txml = substr($txml, $l); - $ib += $lost[2]; - - $ibyte_min = $ibyte_max + strlen(""); - $ichar_min = $ichar_max + mb_strlen(""); - } - } - } - if (count($spots) > 0) - { - ksort($spots); - $dp = 0; - $ddp = (strlen($parm["rpl"]) - strlen($parm["src"])); - - foreach ($spots as $spot) - { - $xml = substr($xml, 0, $dp + $spot["p"]) . $parm["rpl"] . substr($xml, $dp + $spot["p"] + $spot["l"]); - $dp += $ddp; // strlen(""); - } - print($xml); - print("
    \n"); - - $sql = "UPDATE tmprecord SET xml = :xml"; $stmt = $connbas->prepare($sql); - $stmt->execute(array(':xml' => $xml)); + $stmt->execute(); $stmt->closeCursor(); - } - } - printf("found %d times in %d records
    \n", $nspot, $nrecdone); - printf("\n"); - } - catch (Exception $e) - { - } + $unicode = new unicode(); + $src_noacc = $unicode->remove_indexer_chars($parm["src"]); + $src_noacc_len = mb_strlen($src_noacc, "UTF-8"); + $src_noacc_tchar = array(); + for ($i = 0; $i < $src_noacc_len; $i ++ ) + $src_noacc_tchar[$i] = mb_substr($src_noacc, $i, 1, "UTF-8"); + + $sql = ""; + $params = array(); + $n = 0; + foreach ($parm["field"] as $field) { + $params[':like' . $n] = "%<$field>%" . $src_noacc . "%%"; + $sql .= ( $sql == "" ? "" : " OR ") . "(xml LIKE :like" . $n . ")"; + } + $sql = "SELECT record_id, BINARY xml AS xml FROM tmprecord WHERE $sql"; + $stmt = $connbas->prepare($sql); + $stmt->execute($params); + $rsbas2 = $stmt->fetchAll(PDO::FETCH_ASSOC); + $nrectot = $stmt->rowCount(); + $stmt->closeCursor(); + + $nrecdone = $nrecchanged = $nspot = 0; + foreach ($rsbas2 as $rowbas2) { + $nrecdone ++; + printf("\n"); + flush(); + + set_time_limit(30); + + $xml = $rowbas2["xml"]; + $spots = array(); + foreach ($parm["field"] as $field) { + $ibyte_min = $ichar_min = 0; + while (true) { + if (($ibyte_min = strpos($xml, "<$field>", $ibyte_min)) === false) + break; + $ibyte_min += strlen("<$field>"); + if (($ibyte_max = strpos($xml, "", $ibyte_min)) === false) + break; + + $ichar_min = mb_strpos($xml, "<$field>", $ichar_min, "UTF-8") + mb_strlen("<$field>"); + $ichar_max = mb_strpos($xml, "", $ichar_min, "UTF-8"); // + mb_strlen(""); + + $txml = substr($xml, $ibyte_min, $ibyte_max - $ibyte_min); + + $xml_noacc_tchar = array(); // buffer circulaire taille+2 (car prec. et car suiv. pour trouver uniquement les mots entiers) + $xml_noacc_tchar[0] = array(">", ">", 1); // car precedent + for ($i = 0; $i < $src_noacc_len + 1; $i ++ ) { + $c = mb_substr($txml, 0, 1, "UTF-8"); + $xml_noacc_tchar[$i + 1] = array($c, $unicode->remove_indexer_chars($c), $l = strlen($c)); + $txml = substr($txml, $l); + } + + for ($ib = $ibyte_min, $ic = $ichar_min; $ic <= $ichar_max - $src_noacc_len; $ic ++ ) { + + if (isdelim($xml_noacc_tchar[0][0]) && isdelim($xml_noacc_tchar[$src_noacc_len + 1][0])) { + for ($i = 0; $i < $src_noacc_len; $i ++ ) { + if ($xml_noacc_tchar[$i + 1][1] !== $src_noacc_tchar[$i]) + break; + } + + if ($i == $src_noacc_len) { + for ($l = 0, $i = 1; $i < $src_noacc_len + 1; $i ++ ) + $l += $xml_noacc_tchar[$i][2]; + + if (count($spots) == 0) { + $nrecchanged ++; + } + $nspot ++; + + $spots[$ib] = array("p" => $ib, "l" => $l); + } + } + $lost = array_shift($xml_noacc_tchar); + $c = mb_substr($txml, 0, 1, "UTF-8"); + $xml_noacc_tchar[] = array($c, $unicode->remove_indexer_chars($c), $l = strlen($c)); + // $txml = mb_substr($txml, 1, 9999, "UTF-8"); + $txml = substr($txml, $l); + $ib += $lost[2]; + + $ibyte_min = $ibyte_max + strlen(""); + $ichar_min = $ichar_max + mb_strlen(""); + } + } + } + if (count($spots) > 0) { + ksort($spots); + $dp = 0; + $ddp = (strlen($parm["rpl"]) - strlen($parm["src"])); + + foreach ($spots as $spot) { + $xml = substr($xml, 0, $dp + $spot["p"]) . $parm["rpl"] . substr($xml, $dp + $spot["p"] + $spot["l"]); + $dp += $ddp; // strlen(""); + } + print($xml); + print("
    \n"); + + $sql = "UPDATE tmprecord SET xml = :xml"; + $stmt = $connbas->prepare($sql); + $stmt->execute(array(':xml' => $xml)); + $stmt->closeCursor(); + } + } + printf("found %d times in %d records
    \n", $nspot, $nrecdone); + printf("\n"); + } catch (Exception $e) { + + } } function isdelim($utf8char) { - $unicode = new unicode(); + $unicode = new unicode(); - return in_array($utf8char, $unicode->get_indexer_bad_chars()); + return in_array($utf8char, $unicode->get_indexer_bad_chars()); } ?> - + diff --git a/www/thesaurus2/rescan.php b/www/thesaurus2/rescan.php index 3557c96ebf..5825d21d6f 100644 --- a/www/thesaurus2/rescan.php +++ b/www/thesaurus2/rescan.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,114 +22,101 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "dlg" - , "dct" // delete candidates terms - , "drt" // delete rejected terms + "bid" + , "piv" + , "dlg" + , "dct" // delete candidates terms + , "drt" // delete rejected terms ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - Relire les candidats + + Relire les candidats - - + + - + get_dom_cterms(); + $domct = $databox->get_dom_cterms(); - if ($domct) - { - $nodestodel = array(); - removeCandidates($domct->documentElement, $nodestodel); + if ($domct) { + $nodestodel = array(); + removeCandidates($domct->documentElement, $nodestodel); - foreach ($nodestodel as $nodetodel) - { - $nodetodel->parentNode->removeChild($nodetodel); - } - if ($parm["dct"]) - { - $sql = "DELETE FROM thit WHERE value LIKE 'C%'"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } - if ($parm["drt"]) - { - $sql = "DELETE FROM thit WHERE value LIKE 'R%'"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - } + foreach ($nodestodel as $nodetodel) { + $nodetodel->parentNode->removeChild($nodetodel); + } + if ($parm["dct"]) { + $sql = "DELETE FROM thit WHERE value LIKE 'C%'"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } + if ($parm["drt"]) { + $sql = "DELETE FROM thit WHERE value LIKE 'R%'"; + $stmt = $connbas->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + } - $databox->saveCterms($domct); + $databox->saveCterms($domct); - $sql = "UPDATE record SET status=status & ~2"; - $stmt = $connbas->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); -?> -
    -
    - -
    -
    - " onclick="refreshCterms();self.close();"> -
    -
    -prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + ?> +
    +
    + +
    +
    + " onclick="refreshCterms();self.close();"> +
    +
    + nodeType == XML_ELEMENT_NODE && $node->nodeName == "te" && $node->getAttribute("field") == "") - { - $id0 = substr($node->getAttribute("id"), 0, 1); - if (($parm["dct"] && $id0 == "C") || ($parm["drt"] && $id0 == "R")) - $nodestodel[] = $node; - } - else - { - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - removeCandidates($n, $nodestodel); - } -} -?> - - + diff --git a/www/thesaurus2/rescan_dlg.php b/www/thesaurus2/rescan_dlg.php index 4c9d39b914..a690ab842d 100644 --- a/www/thesaurus2/rescan_dlg.php +++ b/www/thesaurus2/rescan_dlg.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,134 +22,124 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "bid" - , "piv" - , "dlg" + "bid" + , "piv" + , "dlg" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - Relire les candidats + + Relire les candidats - + - - - -
    -
    - - prepare($sql); - $stmt->execute(); - $rowbas = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if ($rowbas) - $nrec = $rowbas["nrec"]; - - $domct = $databox->get_dom_cterms(); - - if ($domct) + + + + +
    + +prepare($sql); + $stmt->execute(); + $rowbas = $stmt->fetch(PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + if ($rowbas) + $nrec = $rowbas["nrec"]; + + $domct = $databox->get_dom_cterms(); + + if ($domct) { + $r = countCandidates($domct->documentElement); + + printf(utf8_encode("%s termes candidats, %s termes refuses

    \n"), $r["nc"], $r["nr"]); + ?> + "> + "> + "> +
    +
    +
    + \n"); ?> +
    +
    +
    + +    + +
    +
    +
    + + 0, "nr" => 0); - if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName == "sy" && strlen($id = $node->getAttribute("id")) > 1) - { - if (substr($id, 0, 1) == "C") - $ret["nc"]++; - elseif (substr($id, 0, 1) == "R") - $ret["nr"]++; - } - for ($n = $node->firstChild; $n; $n = $n->nextSibling) - { - $r = countCandidates($n); - $ret["nc"] += $r["nc"]; - $ret["nr"] += $r["nr"]; - } + } +} - return($ret); - } - ?> - - +function countCandidates(&$node) +{ + global $parm; + $ret = array("nc" => 0, "nr" => 0); + if ($node->nodeType == XML_ELEMENT_NODE && $node->nodeName == "sy" && strlen($id = $node->getAttribute("id")) > 1) { + if (substr($id, 0, 1) == "C") + $ret["nc"] ++; + elseif (substr($id, 0, 1) == "R") + $ret["nr"] ++; + } + for ($n = $node->firstChild; $n; $n = $n->nextSibling) { + $r = countCandidates($n); + $ret["nc"] += $r["nc"]; + $ret["nr"] += $r["nr"]; + } + + return($ret); +} +?> + + diff --git a/www/thesaurus2/search.php b/www/thesaurus2/search.php index bafab72fe9..667f64ad19 100644 --- a/www/thesaurus2/search.php +++ b/www/thesaurus2/search.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(200, true); @@ -23,86 +22,83 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "dlg" - , "piv" + "dlg" + , "piv" ); -if ($parm["dlg"]) -{ - $opener = "window.dialogArguments.win"; -} -else -{ - $opener = "opener"; +if ($parm["dlg"]) { + $opener = "window.dialogArguments.win"; +} else { + $opener = "opener"; } ?> - - Chercher + + Chercher - - - - + + + +
    -
    -
    -
    - - - - - - - - - - - - -
    -
    -
    -
    -

    -
    - -     - -
    +
    + + + + + + + + + + + + +
    +
    +
    +
    + +
    +
    +
    + +     + +
    - + diff --git a/www/thesaurus2/thesaurus.php b/www/thesaurus2/thesaurus.php index 013afddee2..08f974d4bd 100644 --- a/www/thesaurus2/thesaurus.php +++ b/www/thesaurus2/thesaurus.php @@ -14,7 +14,6 @@ * @license http://opensource.org/licenses/gpl-3.0 GPLv3 * @link www.phraseanet.com */ - /* @var $Core \Alchemy\Phrasea\Core */ $Core = require_once __DIR__ . "/../../lib/bootstrap.php"; phrasea::headers(); @@ -23,10 +22,7 @@ $session = $appbox->get_session(); $request = http_request::getInstance(); $parm = $request->get_parms( - "piv", - "res", - "dbg", - "bid" + "piv", "res", "dbg", "bid" ); $dispdbg = $parm["dbg"] ? "" : " visibility:hidden; "; @@ -37,1489 +33,1487 @@ $lng = Session_Handler::get_locale(); User_Adapter::updateClientInfos(5); ?> - - <?php echo $appbox->get_registry()->get('GV_homeTitle'); ?> - <?php echo p4string::MakeString(_('phraseanet:: thesaurus')) ?> + + <?php echo $appbox->get_registry()->get('GV_homeTitle'); ?> - <?php echo p4string::MakeString(_('phraseanet:: thesaurus')) ?> - + - - + + - - - - - + + + + }; - + sessionactive(); + - + -