From 52f3baac056fd03661657f45b357bda1f754a4bb Mon Sep 17 00:00:00 2001 From: Nicolas Le Goff Date: Mon, 3 Feb 2014 18:10:49 +0100 Subject: [PATCH] Fix neutron's comment --- .../Command/Developer/RegenerateSqliteDb.php | 19 + .../Phrasea/Controller/Admin/Users.php | 60 ++- .../Phrasea/Controller/Root/Account.php | 12 +- lib/Alchemy/Phrasea/Controller/Root/Login.php | 4 +- .../Provider/RegistrationServiceProvider.php | 9 +- .../Form/Login/PhraseaRegisterForm.php | 2 +- ...egistrationDemand.php => Registration.php} | 14 +- .../RegistrationDemandRepository.php | 98 ----- .../Repositories/RegistrationRepository.php | 98 +++++ .../Registration/RegistrationManager.php | 388 +++++------------- .../RegistrationDemandMigration.php | 6 +- lib/classes/collection.php | 46 ++- lib/classes/databox.php | 18 + lib/conf.d/migrations.yml | 4 +- templates/web/account/access.html.twig | 26 +- templates/web/admin/user/demand.html.twig | 7 +- .../Phrasea/Controller/Root/AccountTest.php | 28 +- .../Phrasea/Controller/Root/LoginTest.php | 6 +- .../Registration/RegistrationManagerTest.php | 345 ++++++---------- tests/classes/collectionTest.php | 39 ++ tests/classes/databoxTest.php | 39 ++ 21 files changed, 571 insertions(+), 697 deletions(-) rename lib/Alchemy/Phrasea/Model/Entities/{RegistrationDemand.php => Registration.php} (92%) delete mode 100644 lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php create mode 100644 lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php diff --git a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php index fe39bd6a51..3e53c2aa7a 100644 --- a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php +++ b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php @@ -23,6 +23,7 @@ use Alchemy\Phrasea\Model\Entities\FeedItem; use Alchemy\Phrasea\Model\Entities\FeedPublisher; use Alchemy\Phrasea\Model\Entities\FeedToken; use Alchemy\Phrasea\Model\Entities\LazaretSession; +use Alchemy\Phrasea\Model\Entities\Registration; use Alchemy\Phrasea\Model\Entities\Session; use Alchemy\Phrasea\Model\Entities\Task; use Alchemy\Phrasea\Model\Entities\User; @@ -36,6 +37,7 @@ use Alchemy\Phrasea\Model\Entities\StoryWZ; use Alchemy\Phrasea\Core\Provider\ORMServiceProvider; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; +use Gedmo\Timestampable\TimestampableListener; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; @@ -94,6 +96,10 @@ class RegenerateSqliteDb extends Command $this->insertOneAggregateToken($this->container['EM'], $DI); $this->insertLazaretFiles($this->container['EM'], $DI); $this->insertAuthFailures($this->container['EM'], $DI); + $this->insertOneRegistration($this->container['EM'],$DI['user_alt1'], $DI['coll']); + $this->insertOneRegistration($this->container['EM'],$DI['user_alt2'], $DI['coll'], '-3 months'); + $this->insertOneRegistration($this->container['EM'],$DI['user_alt2'], $DI['coll']); + $fixtures['user']['test_phpunit'] = $DI['user']->getId(); $fixtures['user']['test_phpunit_not_admin'] = $DI['user_notAdmin']->getId(); @@ -637,4 +643,17 @@ class RegenerateSqliteDb extends Command $em->persist($entry); } + + private function insertOneRegistration(EntityManager $em, \User_Adapter $user, \collection $collection, $when = 'now') + { + $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); + $registration = new Registration(); + $registration->setBaseId($collection->get_base_id()); + $registration->setUser($user->get_id()); + $registration->setUpdated(new \DateTime($when)); + $registration->setCreated(new \DateTime($when)); + $em->persist($registration); + $em->flush(); + $em->getEventManager()->addEventSubscriber(new TimestampableListener()); + } } diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Users.php b/lib/Alchemy/Phrasea/Controller/Admin/Users.php index 934794b6aa..b0b1a3a900 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Users.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Users.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Admin; use Alchemy\Phrasea\Helper\User as UserHelper; use Alchemy\Phrasea\Model\Entities\FtpCredential; use Alchemy\Phrasea\Model\Entities\User; +use igorw; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; @@ -354,37 +355,27 @@ class Users implements ControllerProviderInterface })->bind('admin_users_export_csv'); $controllers->get('/demands/', function (Application $app) { - $app['registration-manager']->deleteOldDemand(); + $app['registration-manager']->deleteOldRegistrations(); $models = $app['manipulator.user']->getRepository()->findModelOf($app['authentication']->getUser()); - $demands = $app['registration-manager']->getRepository()->getDemandsForUser( + $users = $registrations = []; + foreach ($app['registration-manager']->getRepository()->getDemandsForUser( $app['authentication']->getUser(), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])) - ); + ) as $registration) { + $user = $registration->getUser(); + $users[$user->getId()] = $user; - $currentUsr = null; - $table = ['user' => [], 'demand' => []]; - foreach ($demands as $demand) { - $user = $demand->getUser(); - - if ($user->getId() !== $currentUsr) { - $currentUsr = $user->getId(); - $table['user'][$user->getId()] = $user; - } - - if (!isset($table['demand'][$user->getId()])) { - $table['demand'][$user->getId()] = []; - } - - if (!array_key_exists($demand->getBaseId(), $table['demand'][$user->getId()][$demand->getBaseId()])) { - $table['demand'][$user->getId()][$demand->getBaseId()] = $demand; + if (null !== igorw::get_in($registrations, [$user->getId(), $registration->getBaseId()])) { + $registrations[$user->getId()][$registration->getBaseId()] = $registration; } } return $app['twig']->render('admin/user/demand.html.twig', [ - 'table' => $table, + 'users' => $users, + 'registrations' => $registrations, 'models' => $models, ]); })->bind('users_display_demands'); @@ -444,27 +435,23 @@ class Users implements ControllerProviderInterface $app['acl']->get($user)->apply_model($user_template, $base_ids); - if (!isset($done[$usr])) { - $done[$usr] = []; - } - foreach ($base_ids as $base_id) { $done[$usr][$base_id] = true; } - $app['registration-manager']->getRepository()->deleteUserDemands($user, $base_ids); + $app['registration-manager']->deleteRegistrationsForUser($user->get_id(), $base_ids); } foreach ($deny as $usr => $bases) { $cache_to_update[$usr] = true; foreach ($bases as $bas) { - $app['registration-manager']->rejectDemand($usr, $bas); - - if (!isset($done[$usr])) { - $done[$usr] = []; + if (null !== $registration = $this->getRepository()->findOneBy([ + 'user' => $usr, + 'baseId' => $bas + ])) { + $app['registration-manager']->rejectDemand($registration); + $done[$usr][$bas] = false; } - - $done[$usr][$bas] = false; } } @@ -474,12 +461,13 @@ class Users implements ControllerProviderInterface foreach ($bases as $bas) { $collection = \collection::get_from_base_id($app, $bas); - if (!isset($done[$usr])) { - $done[$usr] = []; + if (null !== $registration = $this->getRepository()->findOneBy([ + 'user' => $user->get_id(), + 'baseId' => $collection->get_base_id() + ])) { + $done[$usr][$bas] = true; + $app['registration-manager']->acceptDemand($registration, $user, $collection, $options[$usr][$bas]['HD'], $options[$usr][$bas]['WM']); } - $done[$usr][$bas] = true; - - $app['registration-manager']->acceptDemand($user, $collection, $options[$usr][$bas]['HD'], $options[$usr][$bas]['WM']); } } diff --git a/lib/Alchemy/Phrasea/Controller/Root/Account.php b/lib/Alchemy/Phrasea/Controller/Root/Account.php index cf831f73e8..5b6fd60f35 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Account.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Account.php @@ -232,7 +232,7 @@ class Account implements ControllerProviderInterface public function accountAccess(Application $app, Request $request) { return $app['twig']->render('account/access.html.twig', [ - 'inscriptions' => $app['registration-manager']->getRegistrationInformations($app['authentication']->getUser()->getId()) + 'inscriptions' => $app['registration-manager']->getRegistrationSummary($app['authentication']->getUser()->getId()) ]); } @@ -326,11 +326,15 @@ class Account implements ControllerProviderInterface */ public function updateAccount(PhraseaApplication $app, Request $request) { - if (0 !== count($demands = (array) $request->request->get('demand', []))) { + $demands = $request->request->get('demand'); + if (false === is_array($demands)) { + $app->abort(400, '"demand" parameter must be an array of base id '); + } + if (0 !== count($demands)) { foreach ($demands as $baseId) { - $app['registration-manager']->newDemand($app['authentication']->getUser()->getId(), $baseId); + $app['registration-manager']->createRegistration($app['authentication']->getUser()->getId(), $baseId); } - $app->addFlash('success', $app->trans('login::notification: Vos demandes ont ete prises en compte')); + $app->addFlash('success', $app->trans('Your registration requests have been taken into account.')); } $accountFields = [ diff --git a/lib/Alchemy/Phrasea/Controller/Root/Login.php b/lib/Alchemy/Phrasea/Controller/Root/Login.php index cbf8af0df9..103a260725 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Login.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Login.php @@ -335,7 +335,7 @@ class Login implements ControllerProviderInterface } else { $selected = isset($data['collections']) ? $data['collections'] : null; } - $inscriptions = $app['registration-manager']->getRegistrationInformations(); + $inscriptions = $app['registration-manager']->getRegistrationSummary(); $inscOK = []; foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { @@ -406,7 +406,7 @@ class Login implements ControllerProviderInterface continue; } - $app['registration-manager']->newDemand($user->getId(), $base_id); + $app['registration-manager']->createRegistration($user->getId(), $base_id); $demandOK[$base_id] = true; } diff --git a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php index 8f1110c82c..9c36512c7a 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php @@ -27,7 +27,14 @@ class RegistrationServiceProvider implements ServiceProviderInterface }); $app['registration.enabled'] = $app->share(function (Application $app) { - return $app['registration-manager']->isRegistrationEnabled(); + foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { + foreach($databox->get_collections() as $collection) { + if ($collection->isRegistrationEnabled()) { + return true; + } + } + } + return false; }); $app['registration.optional-fields'] = $app->share(function (Application $app) { diff --git a/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php b/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php index 0654856c3b..2389dea842 100644 --- a/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php +++ b/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php @@ -75,7 +75,7 @@ class PhraseaRegisterForm extends AbstractType $choices = []; $baseIds = []; - foreach ($this->app['registration-manager']->getRegistrationInformations() as $baseInfo) { + foreach ($this->app['registration-manager']->getRegistrationSummary() as $baseInfo) { $dbName = $baseInfo['config']['db-name']; foreach ($baseInfo['config']['collections'] as $baseId => $collInfo) { if (false === $collInfo['can-register']) { diff --git a/lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php b/lib/Alchemy/Phrasea/Model/Entities/Registration.php similarity index 92% rename from lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php rename to lib/Alchemy/Phrasea/Model/Entities/Registration.php index f4a45a9e4a..c6b6e26d10 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php +++ b/lib/Alchemy/Phrasea/Model/Entities/Registration.php @@ -15,10 +15,10 @@ use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** - * @ORM\Table(name="RegistrationDemand") - * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\RegistrationDemandRepository") + * @ORM\Table(name="Registration") + * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\RegistrationRepository") */ -class RegistrationDemand +class Registration { /** * @ORM\Column(type="integer") @@ -72,7 +72,7 @@ class RegistrationDemand /** * @param mixed $pending * - * @return RegistrationDemand + * @return Registration */ public function setPending($pending) { @@ -92,7 +92,7 @@ class RegistrationDemand /** * @param mixed $rejected * - * @return RegistrationDemand + * @return Registration */ public function setRejected($rejected) { @@ -112,7 +112,7 @@ class RegistrationDemand /** * @param mixed $user * - * @return RegistrationDemand + * @return Registration */ public function setUser($user) { @@ -132,7 +132,7 @@ class RegistrationDemand /** * @param mixed $baseId * - * @return RegistrationDemand + * @return Registration */ public function setBaseId($baseId) { diff --git a/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php deleted file mode 100644 index 84a9ae9774..0000000000 --- a/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php +++ /dev/null @@ -1,98 +0,0 @@ -createQueryBuilder('d'); - $qb->where($qb->expr()->eq('d.user', ':user')); - $qb->setParameter(':user', $user->get_id()); - - if (count($baseList) > 0) { - $qb->andWhere('d.baseId IN (:bases)'); - $qb->setParameter(':bases', $baseList); - } - - $qb->orderBy('d.created', 'DESC'); - - return $qb->getQuery()->getResult(); - } - - /** - * Deletes demands for user on collection. - * - * @param \User_Adapter $user - * @param array $baseList - * - * @return mixed - */ - public function deleteUserDemands(\User_Adapter $user, $baseList = []) - { - $qb = $this->createQueryBuilder('d'); - $qb->delete('Alchemy\Phrasea\Model\Entities\RegistrationDemand', 'd'); - $qb->where($qb->expr()->eq('d.user', ':user')); - $qb->setParameter(':user', $user->get_id()); - - if (count($baseList) > 0) { - $qb->andWhere('d.baseId IN (:bases)'); - $qb->setParameter(':bases', $baseList); - } - - return $qb->getQuery()->execute(); - } - - /** - * Deletes outdated demands. - * - * @param string $limit - */ - public function deleteDemandsOldestThan($limit = '-1 month') - { - $qb = $this->createQueryBuilder('d'); - $qb->delete('Alchemy\Phrasea\Model\Entities\RegistrationDemand', 'd'); - $qb->where($qb->expr()->lt('d.created', ':date')); - $qb->setParameter(':date', new \DateTime($limit)); - $qb->getQuery()->execute(); - } - - /** - * Deletes demands on collection. - * - * @param $baseId - */ - public function deleteDemandsOnCollection($baseId) - { - $qb = $this->createQueryBuilder('d'); - $qb->delete('Alchemy\Phrasea\Model\Entities\RegistrationDemand', 'd'); - $qb->where($qb->expr()->eq('d.baseId', ':base')); - $qb->setParameter(':base', $baseId); - $qb->getQuery()->execute(); - } -} diff --git a/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php new file mode 100644 index 0000000000..a75aeee1c4 --- /dev/null +++ b/lib/Alchemy/Phrasea/Model/Repositories/RegistrationRepository.php @@ -0,0 +1,98 @@ +createQueryBuilder('d'); + $qb->where($qb->expr()->eq('d.user', ':user')); + $qb->setParameter(':user', $user->get_id()); + + if (count($baseList) > 0) { + $qb->andWhere('d.baseId IN (:bases)'); + $qb->setParameter(':bases', $baseList); + } + + $qb->orderBy('d.created', 'DESC'); + + return $qb->getQuery()->getResult(); + } + + /** + * Gets registration registrations for a user. + * + * @param $usrId + * + * @return array + */ + public function getRegistrationsSummaryForUser($usrId) + { + $data = []; + $rsm = $this->createResultSetMappingBuilder('d'); + $rsm->addScalarResult('sbas_id','sbas_id'); + $rsm->addScalarResult('bas_id','bas_id'); + $rsm->addScalarResult('dbname','dbname'); + $rsm->addScalarResult('time_limited', 'time_limited'); + $rsm->addScalarResult('limited_from', 'limited_from'); + $rsm->addScalarResult('limited_to', 'limited_to'); + $rsm->addScalarResult('actif', 'actif'); + + $sql = " + SELECT dbname, sbas.sbas_id, time_limited, + UNIX_TIMESTAMP( limited_from ) AS limited_from, + UNIX_TIMESTAMP( limited_to ) AS limited_to, + bas.server_coll_id, usr.usr_id, basusr.actif, + bas.base_id AS bas_id , " . $rsm->generateSelectClause(['d' => 'd',]) . " + FROM (usr, bas, sbas) + LEFT JOIN basusr ON ( usr.usr_id = basusr.usr_id AND bas.base_id = basusr.base_id ) + LEFT JOIN Registration d ON ( d.user_id = usr.usr_id AND bas.base_id = d.base_id ) + WHERE bas.active = 1 AND bas.sbas_id = sbas.sbas_id + AND usr.usr_id = ? + AND model_of = 0"; + + $query = $this->_em->createNativeQuery($sql, $rsm); + $query->setParameter(1, $usrId); + + foreach ($query->getResult() as $row) { + $registrationEntity = $row[0]; + + $data[$row['sbas_id']][$row['bas_id']] = [ + 'base-id' => $row['bas_id'], + 'db-name' => $row['dbname'], + 'active' => (Boolean) $row['actif'], + 'time-limited' => (Boolean) $row['time_limited'], + 'in-time' => $row['time_limited'] && ! ($row['limited_from'] >= time() && $row['limited_to'] <= time()), + 'registration' => $registrationEntity + ]; + } + + return $data; + } +} diff --git a/lib/Alchemy/Phrasea/Registration/RegistrationManager.php b/lib/Alchemy/Phrasea/Registration/RegistrationManager.php index 542ba32d23..9aac344646 100644 --- a/lib/Alchemy/Phrasea/Registration/RegistrationManager.php +++ b/lib/Alchemy/Phrasea/Registration/RegistrationManager.php @@ -12,9 +12,9 @@ namespace Alchemy\Phrasea\Registration; use Alchemy\Phrasea\Authentication\ACLProvider; -use Alchemy\Phrasea\Model\Entities\RegistrationDemand; +use Alchemy\Phrasea\Model\Entities\Registration; +use Alchemy\Phrasea\Model\Repositories\RegistrationRepository; use Doctrine\ORM\EntityManager; -use Doctrine\ORM\Query\ResultSetMappingBuilder; use igorw; class RegistrationManager @@ -28,112 +28,82 @@ class RegistrationManager { $this->em = $em; $this->appbox = $appbox; - $this->repository = $this->em->getRepository('Alchemy\Phrasea\Model\Entities\RegistrationDemand'); + $this->repository = $this->em->getRepository('Alchemy\Phrasea\Model\Entities\Registration'); $this->aclProvider = $aclProvider; } /** - * Creates a new demand. + * Creates a new registration. * * @param $userId * @param $baseId * - * @return RegistrationDemand + * @return Registration */ - public function newDemand($userId, $baseId) + public function createRegistration($userId, $baseId) { - $demand = new RegistrationDemand(); - $demand->setUser($userId); - $demand->setBaseId($baseId); - $this->em->persist($demand); + $registration = new Registration(); + $registration->setUser($userId); + $registration->setBaseId($baseId); + $this->em->persist($registration); $this->em->flush(); - return $demand; + return $registration; } /** - * Rejects a demand. + * Rejects a registration. * * @param $usrId * @param $baseId */ - public function rejectDemand($usrId, $baseId) + public function rejectRegistration(Registration $registration) { - if ($demand = $this->getRepository()->findOneBy([ - 'user' => $usrId, - 'baseId' => $baseId - ])) { - $demand->setPending(false); - $demand->setRejected(true); - $this->em->persist($demand); - } + $registration->setPending(false); + $registration->setRejected(true); + $this->em->persist($registration); $this->em->flush(); } /** - * Accepts a demand. + * Accepts a registration. * * @param $userId * @param $basId */ - public function acceptDemand(\User_Adapter $user, \Collection $collection, $grantHd = false, $grantWatermark = false) + public function acceptRegistration(Registration $registration, \User_Adapter $user, \Collection $collection, $grantHd = false, $grantWatermark = false) { - if ($demand = $this->getRepository()->findOneBy([ - 'user' => $user->get_id(), - 'baseId' => $collection->get_base_id() - ])) { - $this->aclProvider->get($user)->give_access_to_sbas([$collection->get_sbas_id()]); - $this->aclProvider->get($user)->give_access_to_base([$collection->get_base_id()]); - $this->aclProvider->get($user)->update_rights_to_base($collection->get_base_id(), [ - 'canputinalbum' => '1', - 'candwnldhd' => (string) (int) $grantHd, - 'nowatermark' => (string) (int) $grantWatermark, - 'candwnldpreview' => '1', - 'actif' => '1', - ]); - $this->em->remove($demand); - $this->em->flush(); - } + $this->aclProvider->get($user)->give_access_to_sbas([$collection->get_sbas_id()]); + $this->aclProvider->get($user)->give_access_to_base([$collection->get_base_id()]); + $this->aclProvider->get($user)->update_rights_to_base($collection->get_base_id(), [ + 'canputinalbum' => '1', + 'candwnldhd' => (string) (int) $grantHd, + 'nowatermark' => (string) (int) $grantWatermark, + 'candwnldpreview' => '1', + 'actif' => '1', + ]); + $this->em->remove($registration); + $this->em->flush(); } /** - * Tells whether registration is enabled or not. - * - * @return boolean - */ - public function isRegistrationEnabled() - { - $enabled = false; - foreach ($this->getRegistrationInformations() as $baseInfo) { - foreach ($baseInfo['config']['collections'] as $collInfo) { - if ($collInfo['can-register']) { - $enabled = true; - break 2; - } - } - } - - return $enabled; - } - - /** - * Gets information about registration configuration and demand status if a user id is provided. + * Gets information about registration configuration and registration status if a user id is provided. * * @param null|integer $userId * * @return array */ - public function getRegistrationInformations($userId = null) + public function getRegistrationSummary($userId = null) { $data = $userData = []; if (null !== $userId) { - $userData = $this->getRegistrationDemandsForUser($userId); + $userData = $this->getRepository()->getRegistrationsSummaryForUser($userId); } foreach ($this->appbox->get_databoxes() as $databox) { $ddata = [ - 'demands' => [ + 'registrations' => [ 'by-type' => [ 'inactive' => [], 'accepted' => [], @@ -146,9 +116,8 @@ class RegistrationManager ], 'config' => [ 'db-name' => $databox->get_dbname(), - 'cgu' => $this->getCguPreferencesForDatabox($databox), - 'cgu-release' => $this->getCguReleasedPreferencesForDatabox($databox), - 'can-register' => $this->isRegistrationEnabledForDatabox($databox), + 'cgu' => $databox->get_cgus(), + 'can-register' => $databox->isRegistrationEnabled(), 'collections' => [], ] ]; @@ -158,69 +127,67 @@ class RegistrationManager $ddata['config']['collections'][$collection->get_base_id()] = [ 'coll-name' => $collection->get_name(), // gets collection registration or fallback to databox configuration - 'can-register' => $this->isRegistrationDefinedForCollection($collection) ? - $this->isRegistrationEnabledForCollection($collection) : $ddata['config']['can-register'], - 'cgu' => $this->getCguPreferencesForCollection($collection), - 'cgu-release' => $this->getCguReleasedPreferencesForCollection($collection), - 'demand' => null + 'can-register' => $collection->isRegistrationEnabled(), + 'cgu' => $collection->getTermsOfUse(), + 'registration' => null ]; - if (null === $userDemand = igorw\get_in($userData, [$databox->get_sbas_id(), $collection->get_base_id()])) { + if (null === $userRegistration = igorw\get_in($userData, [$databox->get_sbas_id(), $collection->get_base_id()])) { continue; } // sets collection name - $userDemand['coll-name'] = $collection->get_name(); - // gets demand entity - $demand = $userDemand['demand']; + $userRegistration['coll-name'] = $collection->get_name(); + // gets registration entity + $registration = $userRegistration['registration']; - $noDemandMade = is_null($userDemand['active']); - $demandMade = !$noDemandMade; - $demandStillExists = !is_null($demand); - $demandNoMoreExists = !$demandStillExists; - $isPending = $demandStillExists && $demand->isPending() && !$demand->isRejected(); - $isRejected = $demandStillExists && $demand->isRejected(); - $isDone = ($demandNoMoreExists && $demandMade) || (!$isPending && !$isRejected); - $isActive = (Boolean) $userDemand['active']; - $isTimeLimited = (Boolean) $userDemand['time-limited']; + $noRegistrationMade = is_null($userRegistration['active']); + $registrationMade = !$noRegistrationMade; + $registrationStillExists = !is_null($registration); + $registrationNoMoreExists = !$registrationStillExists; + $isPending = $registrationStillExists && $registration->isPending() && !$registration->isRejected(); + $isRejected = $registrationStillExists && $registration->isRejected(); + $isDone = ($registrationNoMoreExists && $registrationMade) || (!$isPending && !$isRejected); + $isActive = (Boolean) $userRegistration['active']; + $isTimeLimited = (Boolean) $userRegistration['time-limited']; $isNotTimeLimited = !$isTimeLimited; - $isOnTime = (Boolean) $userDemand['in-time']; + $isOnTime = (Boolean) $userRegistration['in-time']; $isOutDated = !$isOnTime; - if ($noDemandMade) { + if ($noRegistrationMade) { continue; } - // sets demands - $ddata['config']['collections'][$collection->get_base_id()]['demand'] = $userDemand; - $ddata['demands']['by-collection'][$collection->get_base_id()] = $userDemand; + // sets registrations + $ddata['config']['collections'][$collection->get_base_id()]['registration'] = $userRegistration; + $ddata['registrations']['by-collection'][$collection->get_base_id()] = $userRegistration; if (!$isActive) { - $ddata['demands']['by-type']['inactive'][] = $userDemand; + $ddata['registrations']['by-type']['inactive'][] = $userRegistration; continue; } if ($isDone) { - $ddata['demands']['by-type']['accepted'][] = $userDemand; + $ddata['registrations']['by-type']['accepted'][] = $userRegistration; continue; } if ($isRejected) { - $ddata['demands']['by-type']['rejected'][] = $userDemand; + $ddata['registrations']['by-type']['rejected'][] = $userRegistration; continue; } if ($isTimeLimited && $isOnTime && $isPending) { - $ddata['demands']['by-type']['in-time'][] = $userDemand; + $ddata['registrations']['by-type']['in-time'][] = $userRegistration; continue; } if ($isTimeLimited && $isOutDated && $isPending) { - $ddata['demands']['by-type']['out-time'][] = $userDemand; + $ddata['registrations']['by-type']['out-time'][] = $userRegistration; continue; } if ($isNotTimeLimited && $isPending) { - $ddata['demands']['by-type']['pending'][] = $userDemand; + $ddata['registrations']['by-type']['pending'][] = $userRegistration; } } } @@ -231,61 +198,9 @@ class RegistrationManager } /** - * Gets registration demands for a user. + * Gets Registration Repository. * - * @param $usrId - * - * @return array - */ - public function getRegistrationDemandsForUser($usrId) - { - $data = []; - $rsm = new ResultSetMappingBuilder($this->em); - $rsm->addRootEntityFromClassMetadata('Alchemy\Phrasea\Model\Entities\RegistrationDemand', 'd'); - $rsm->addScalarResult('sbas_id','sbas_id'); - $rsm->addScalarResult('bas_id','bas_id'); - $rsm->addScalarResult('dbname','dbname'); - $rsm->addScalarResult('time_limited', 'time_limited'); - $rsm->addScalarResult('limited_from', 'limited_from'); - $rsm->addScalarResult('limited_to', 'limited_to'); - $rsm->addScalarResult('actif', 'actif'); - - $sql = " - SELECT dbname, sbas.sbas_id, time_limited, - UNIX_TIMESTAMP( limited_from ) AS limited_from, - UNIX_TIMESTAMP( limited_to ) AS limited_to, - bas.server_coll_id, usr.usr_id, basusr.actif, - bas.base_id AS bas_id , " . $rsm->generateSelectClause(['d' => 'd',]) . " - FROM (usr, bas, sbas) - LEFT JOIN basusr ON ( usr.usr_id = basusr.usr_id AND bas.base_id = basusr.base_id ) - LEFT JOIN RegistrationDemand d ON ( d.user_id = usr.usr_id AND bas.base_id = d.base_id ) - WHERE bas.active = 1 AND bas.sbas_id = sbas.sbas_id - AND usr.usr_id = ? - AND model_of = 0"; - - $query = $this->em->createNativeQuery($sql, $rsm); - $query->setParameter(1, $usrId); - - foreach ($query->getResult() as $row) { - $demandEntity = $row[0]; - - $data[$row['sbas_id']][$row['bas_id']] = [ - 'base-id' => $row['bas_id'], - 'db-name' => $row['dbname'], - 'active' => (Boolean) $row['actif'], - 'time-limited' => (Boolean) $row['time_limited'], - 'in-time' => $row['time_limited'] && ! ($row['limited_from'] >= time() && $row['limited_to'] <= time()), - 'demand' => $demandEntity - ]; - } - - return $data; - } - - /** - * Gets RegistrationDemands Repository. - * - * @return \Doctrine\ORM\EntityRepository + * @return RegistrationRepository */ public function getRepository() { @@ -293,162 +208,49 @@ class RegistrationManager } /** - * Deletes old demands. + * @param $userId + * @param array $baseList + * + * @return mixed */ - public function deleteOldDemand() + public function deleteRegistrationsForUser($userId, array $baseList) { - $this->repository->deleteDemandsOldestThan('-1 month'); + $qb = $this->getRepository()->createQueryBuilder('d'); + $qb->delete('Alchemy\Phrasea\Model\Entities\Registration', 'd'); + $qb->where($qb->expr()->eq('d.user', ':user')); + $qb->setParameter(':user', $userId); + + if (count($baseList) > 0) { + $qb->andWhere('d.baseId IN (:bases)'); + $qb->setParameter(':bases', $baseList); + } + + return $qb->getQuery()->execute(); } /** - * Tells whether the registration is enable for provided databox or not. - * - * @param \databox $databox - * - * @return boolean + * Deletes old registrations. */ - public function isRegistrationEnabledForDatabox(\databox $databox) + public function deleteOldRegistrations() { - $enabled = false; - - if ($xml = $databox->get_sxml_structure()) { - foreach ($xml->xpath('/record/caninscript') as $caninscript) { - $enabled = (Boolean) (string) $caninscript; - break; - } - } - - return $enabled; + $qb = $this->getRepository()->createQueryBuilder('d'); + $qb->delete('Alchemy\Phrasea\Model\Entities\Registration', 'd'); + $qb->where($qb->expr()->lt('d.created', ':date')); + $qb->setParameter(':date', new \DateTime('-1 month')); + $qb->getQuery()->execute(); } /** - * Gets CGU released preference for provided databox. + * Deletes registrations on given collection. * - * @param \databox $databox - * - * @return null|string + * @param $baseId */ - public function getCguReleasedPreferencesForDatabox(\databox $databox) + public function deleteRegistrationsOnCollection($baseId) { - $cguRelease = null; - - if ($xml = $databox->get_sxml_structure()) { - foreach ($xml->xpath('/record/cgu') as $sbpcgu) { - foreach ($sbpcgu->attributes() as $a => $b) { - if ($a == "release") { - $cguRelease = (string) $b; - break 2; - } - } - } - } - - return $cguRelease; - } - - /** - * Gets Cgu preference for provided databox. - * - * @param \databox $databox - * - * @return null|string - */ - public function getCguPreferencesForDatabox(\databox $databox) - { - $cgu = null; - - if ($xml = $databox->get_sxml_structure()) { - foreach ($xml->xpath('/record/cgu') as $sbpcgu) { - $cgu = (string) $sbpcgu->saveXML(); - break; - } - } - - return $cgu; - } - - /** - * Tells whether registration is activated for provided collection or not. - * - * @param \collection $collection - * - * @return boolean - */ - public function isRegistrationEnabledForCollection(\collection $collection) - { - $enabled = false; - if ($xml = simplexml_load_string($collection->get_prefs())) { - foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript) { - $enabled = (Boolean) (string) $caninscript; - break; - } - } - - return $enabled; - } - - /** - * Gets CGU released preferences for provided collection. - * - * @param \collection $collection - * - * @return null|string - */ - public function getCguReleasedPreferencesForCollection(\collection $collection) - { - $cguRelease = null; - - if ($xml = simplexml_load_string($collection->get_prefs())) { - foreach ($xml->xpath('/baseprefs/cgu') as $sbpcgu) { - foreach ($sbpcgu->attributes() as $a => $b) { - if ($a == "release") { - $cguRelease = (string) $b; - break 2; - } - } - } - } - - return $cguRelease; - } - - /** - * Gets CGU preferences for provided collection. - * - * @param \collection $collection - * - * @return null|string - */ - public function getCguPreferencesForCollection(\collection $collection) - { - $cgu = null; - - if ($xml = simplexml_load_string($collection->get_prefs())) { - foreach ($xml->xpath('/baseprefs/cgu') as $sbpcgu) { - $cgu = (string) $sbpcgu->saveXML(); - break; - } - } - - return $cgu; - } - - /** - * Tells whether registration preference is defined for provided collection. - * - * @param \collection $collection - * - * @return bool - */ - private function isRegistrationDefinedForCollection(\collection $collection) - { - $defined = false; - if ($xml = simplexml_load_string($collection->get_prefs())) { - if (count($xml->xpath('/baseprefs/caninscript')) > 0) { - $defined = true; - } - } - - return $defined; + $qb = $this->getRepository()->createQueryBuilder('d'); + $qb->delete('Alchemy\Phrasea\Model\Entities\Registration', 'd'); + $qb->where($qb->expr()->eq('d.baseId', ':base')); + $qb->setParameter(':base', $baseId); + $qb->getQuery()->execute(); } } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php index 1da763cc79..ef06201fdb 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php @@ -14,15 +14,15 @@ namespace Alchemy\Phrasea\Setup\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\ORM\Query\ResultSetMapping; -class RegistrationDemandMigration extends AbstractMigration +class RegistrationMigration extends AbstractMigration { public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE RegistrationDemand (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, base_id INT NOT NULL, pending TINYINT(1) NOT NULL, rejected TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Registration (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, base_id INT NOT NULL, pending TINYINT(1) NOT NULL, rejected TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); } public function doDownSql(Schema $schema) { - $this->addSql("DROP TABLE RegistrationDemand"); + $this->addSql("DROP TABLE Registration"); } } diff --git a/lib/classes/collection.php b/lib/classes/collection.php index 70056d1db7..fa51210cfc 100644 --- a/lib/classes/collection.php +++ b/lib/classes/collection.php @@ -406,7 +406,7 @@ class collection implements cache_cacheableInterface $stmt->execute([':base_id' => $this->get_base_id()]); $stmt->closeCursor(); - $this->app['registration-manager']->getRepository()->deleteDemandsOnCollection($this->get_base_id()); + $this->app['registration-manager']->deleteRegistrationsOnCollection($this->get_base_id()); $this->get_databox()->delete_data_from_cache(databox::CACHE_COLLECTIONS); @@ -534,7 +534,7 @@ class collection implements cache_cacheableInterface $stmt->execute($params); $stmt->closeCursor(); - $this->app['registration-manager']->getRepository()->deleteDemandsOnCollection($this->get_base_id()); + $this->app['registration-manager']->deleteRegistrationsOnCollection($this->get_base_id()); phrasea::reset_baseDatas($app['phraseanet.appbox']); @@ -740,4 +740,46 @@ class collection implements cache_cacheableInterface { self::$_collections = []; } + + /** + * Tells whether registration is activated for provided collection or not. + * + * @return boolean + */ + public function isRegistrationEnabled() + { + if ($xml = simplexml_load_string($this->get_prefs())) { + $element = $xml->xpath('/baseprefs/caninscript'); + + if (count($element) === 0) { + return $this->databox->isRegistrationEnabled(); + } + + foreach ($element as $caninscript) { + if (false !== (Boolean) (string) $caninscript) { + return true; + } + } + } + + return false; + } + + /** + * Gets terms of use. + * + * @param \collection $collection + * + * @return null|string + */ + public function getTermsOfUse() + { + if ($xml = simplexml_load_string($this->get_prefs())) { + foreach ($xml->xpath('/baseprefs/cgu') as $sbpcgu) { + return $sbpcgu->saveXML(); + } + } + + return null; + } } diff --git a/lib/classes/databox.php b/lib/classes/databox.php index 0ac8b268d9..d9d689f436 100644 --- a/lib/classes/databox.php +++ b/lib/classes/databox.php @@ -1482,4 +1482,22 @@ class databox extends base { self::$_xpath_thesaurus = self::$_dom_thesaurus = self::$_thesaurus = self::$_sxml_thesaurus = []; } + + /** + * Tells whether the registration is enable for provided databox or not. + * + * @return boolean + */ + public function isRegistrationEnabled() + { + if (false !== $xml = $this->get_sxml_structure()) { + foreach ($xml->xpath('/record/caninscript') as $canRegister) { + if (false !== (Boolean) (string) $canRegister) { + return true; + } + } + } + + return false; + } } diff --git a/lib/conf.d/migrations.yml b/lib/conf.d/migrations.yml index 8dd2b848fa..904f62ace8 100644 --- a/lib/conf.d/migrations.yml +++ b/lib/conf.d/migrations.yml @@ -55,5 +55,5 @@ migrations: version: user-auth-provider class: Alchemy\Phrasea\Setup\DoctrineMigrations\UserAuthProviderMigration migration18: - version: registration-demand - class: Alchemy\Phrasea\Setup\DoctrineMigrations\RegistrationDemandMigration + version: registration-request + class: Alchemy\Phrasea\Setup\DoctrineMigrations\RegistrationMigration \ No newline at end of file diff --git a/templates/web/account/access.html.twig b/templates/web/account/access.html.twig index 1732decbef..6f632fbeac 100644 --- a/templates/web/account/access.html.twig +++ b/templates/web/account/access.html.twig @@ -19,8 +19,8 @@

{{ sbasName }}

- {% if baseInfo["demands"]["by-type"]["accepted"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["accepted"] %} + {% if baseInfo["registrations"]["by-type"]["accepted"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["accepted"] %} {{ "login::register: acces authorise sur la collection" | trans }}{{ sbasName }} @@ -35,8 +35,8 @@ {% endif %} - {% if baseInfo["demands"]["by-type"]["rejected"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["rejected"] %} + {% if baseInfo["registrations"]["by-type"]["rejected"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["rejected"] %} {{ "login::register: acces refuse sur la collection" | trans }}{{ sbasName }} @@ -51,8 +51,8 @@ {% endif %} - {% if baseInfo["demands"]["by-type"]["pending"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["pending"] %} + {% if baseInfo["registrations"]["by-type"]["pending"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["pending"] %} {{ "login::register: en attente d\'acces sur" | trans }} {{ sbasId |sbas_labels(app) }} @@ -67,8 +67,8 @@ {% endif %} - {% if baseInfo["demands"]["by-type"]["in-time"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["in-time"] %} + {% if baseInfo["registrations"]["by-type"]["in-time"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["in-time"] %} {{ "login::register: acces temporaire sur" | trans }} {{ sbasId |sbas_labels(app) }} @@ -83,8 +83,8 @@ {% endif %} - {% if baseInfo["demands"]["by-type"]["out-dated"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["out-dated"] %} + {% if baseInfo["registrations"]["by-type"]["out-dated"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["out-dated"] %} {{ "login::register: acces temporaire termine sur" | trans }}{{ sbasId |sbas_labels(app) }} @@ -99,8 +99,8 @@ {% endif %} - {% if baseInfo["demands"]["by-type"]["inactive"]|length > 0 %} - {% for baseId in baseInfo["demands"]["by-type"]["inactive"] %} + {% if baseInfo["registrations"]["by-type"]["inactive"]|length > 0 %} + {% for baseId in baseInfo["registrations"]["by-type"]["inactive"] %} {{ "login::register: acces supendu sur" | trans }} {{ sbasId |sbas_labels(app) }} @@ -127,7 +127,7 @@
{{ baseInfo["config"]["cgu"] }}
{% endif %} - {% for baseId, collInfo in baseInfo["config"]["collections"] if (collInfo['demand'] is none and collInfo['can-register']) %} + {% for baseId, collInfo in baseInfo["config"]["collections"] if (collInfo['registration'] is none and collInfo['can-register']) %} {% if collInfo["cgu"] is not none %} {{ "login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes" | trans }} diff --git a/templates/web/admin/user/demand.html.twig b/templates/web/admin/user/demand.html.twig index b72b6c6e15..e0bb3735f0 100644 --- a/templates/web/admin/user/demand.html.twig +++ b/templates/web/admin/user/demand.html.twig @@ -201,9 +201,8 @@
- {% set demands = table['demand'] %} - {% for user in table['user'] %} - {% set userDemands = demands[user.getId()] %} + {% for user in users %} + {% set userRegistrations = registrations[user.getId()] %}
@@ -231,7 +230,7 @@
- {% for baseId, demand in userDemands %} + {% for baseId, demand in userRegistrations %}
{{ app['date-formatter'].getPrettyString(demand.getUpdated()) }}
diff --git a/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php b/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php index dfb43e2737..fc9d0012ea 100644 --- a/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php +++ b/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php @@ -3,6 +3,7 @@ namespace Alchemy\Tests\Phrasea\Controller\Root; use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\Registration; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Alchemy\Phrasea\Model\Entities\User; @@ -49,6 +50,17 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase { $data = [ [ + 'registrations' => [ + 'by-type' => [ + 'inactive' => [new Registration()], + 'accepted' => [new Registration()], + 'in-time' => [new Registration()], + 'out-dated' => [new Registration()], + 'pending' => [new Registration()], + 'rejected' => [new Registration()], + ], + 'by-collection' => [] + ], 'config' => [ 'db-name' => 'a_db_name', 'cgu' => null, @@ -58,16 +70,14 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase [ 'coll-name' => 'a_coll_name', 'can-register' => false, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null + 'cgu' => 'Some terms of use.', + 'registration' => null ], [ 'coll-name' => 'an_other_coll_name', 'can-register' => false, 'cgu' => null, - 'cgu-release' => null, - 'demand' => null + 'registration' => null ] ], ] @@ -76,10 +86,10 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase $service = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager') ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']]) - ->setMethods(['getRegistrationDemandsForUser']) + ->setMethods(['getRegistrationSummary']) ->getMock(); - $service->expects($this->once())->method('getRegistrationDemandsForUser')->will($this->returnValue($data)); + $service->expects($this->once())->method('getRegistrationSummary')->will($this->returnValue($data)); self::$DI['app']['registration-manager'] = $service; self::$DI['client']->request('GET', '/account/access/'); @@ -337,8 +347,8 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase $this->assertTrue($response->isRedirect()); $this->assertEquals('minet', self::$DI['app']['authentication']->getUser()->getLastName()); - $rs = self::$DI['app']['EM']->getRepository('Alchemy\Phrasea\Model\Entities\RegistrationDemand')->findBy([ - 'user' => self::$DI['app']['authentication']->getUser(), + $rs = self::$DI['app']['EM']->getRepository('Alchemy\Phrasea\Model\Entities\Registration')->findBy([ + 'user' => self::$DI['app']['authentication']->getUser()->getId(), 'pending' => true ]); diff --git a/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php b/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php index a0f2adbcca..1b73487e55 100644 --- a/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php +++ b/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php @@ -9,7 +9,7 @@ use Alchemy\Phrasea\Authentication\Provider\Token\Identity; use Alchemy\Phrasea\Authentication\Exception\NotAuthenticatedException; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Authentication\ProvidersCollection; -use Alchemy\Phrasea\Model\Entities\RegistrationDemand; +use Alchemy\Phrasea\Model\Entities\Registration; use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpKernel\Client; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -209,7 +209,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase self::$DI['user']->setMailLocked(true); $this->deleteRequest(); - $demand = new RegistrationDemand(); + $demand = new Registration(); $demand->setUser(self::$DI['user']); $demand->setBaseId(self::$DI['collection']->get_base_id()); @@ -1797,7 +1797,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase */ private function deleteRequest() { - $query = self::$DI['app']['EM']->createQuery('DELETE FROM Alchemy\Phrasea\Model\Entities\RegistrationDemand d WHERE d.user=?1'); + $query = self::$DI['app']['EM']->createQuery('DELETE FROM Alchemy\Phrasea\Model\Entities\Registration d WHERE d.user=?1'); $query->setParameter(1, self::$DI['user']->getId()); $query->execute(); } diff --git a/tests/Alchemy/Tests/Phrasea/Registration/RegistrationManagerTest.php b/tests/Alchemy/Tests/Phrasea/Registration/RegistrationManagerTest.php index c88241ea67..8350dcbf43 100644 --- a/tests/Alchemy/Tests/Phrasea/Registration/RegistrationManagerTest.php +++ b/tests/Alchemy/Tests/Phrasea/Registration/RegistrationManagerTest.php @@ -3,256 +3,163 @@ namespace Alchemy\Tests\Phrasea\Registration; use Alchemy\Phrasea\Application; -use Alchemy\Phrasea\Authentication\ProvidersCollection; -use Alchemy\Phrasea\Exception\InvalidArgumentException; -use Alchemy\Phrasea\Model\Entities\RegistrationDemand; +use Alchemy\Phrasea\Model\Entities\Registration; use Alchemy\Phrasea\Registration\RegistrationManager; class RegistrationManagerTest extends \PhraseanetTestCase { - /** - * @dataProvider registrationConfigProvider - */ - public function testRegistrationIsEnable($data, $value) + public function testCreateRegistration() { - $service = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager') - ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']]) - ->setMethods(['getRegistrationInformations']) + $em = $this->getMockBuilder('Doctrine\ORM\EntityManager') + ->disableOriginalConstructor() ->getMock(); + $em->expects($this->once())->method('persist')->with($this->isInstanceOf('Alchemy\Phrasea\Model\Entities\Registration')); + $em->expects($this->once())->method('flush'); - $service->expects($this->once())->method('getRegistrationInformations')->will($this->returnValue($data)); - $this->assertEquals($value, $service->isRegistrationEnabled()); + $service = new RegistrationManager($em, self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); + + $registration = $service->createRegistration(self::$DI['user']->get_id(), self::$DI['collection']->get_base_id()); + + $this->assertInstanceOf('Alchemy\Phrasea\Model\Entities\Registration', $registration); + $this->assertEquals(self::$DI['collection']->get_base_id(), $registration->getBaseId()); + $this->assertEquals(self::$DI['user']->get_id(), $registration->getUser()); + + return $registration; } /** - * @dataProvider databoxXmlConfiguration + * @depends testCreateRegistration */ - public function testIsRegistrationEnabledForDatabox($data, $value) + public function testRejectRegistration($registration) { - $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); - - $mock = $this->getMockBuilder('\databox') + $em = $this->getMockBuilder('Doctrine\ORM\EntityManager') ->disableOriginalConstructor() - ->setMethods(['get_sxml_structure']) ->getMock(); + $em->expects($this->once())->method('persist')->with($this->isInstanceOf('Alchemy\Phrasea\Model\Entities\Registration')); + $em->expects($this->once())->method('flush'); - $mock->expects($this->once())->method('get_sxml_structure')->will($this->returnValue($data)); - $this->assertEquals($value, $service->isRegistrationEnabledForDatabox($mock)); + $service = new RegistrationManager($em, self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); + + $service->rejectRegistration($registration); + $this->assertFalse($registration->isPending()); + $this->assertTrue($registration->isRejected()); + + return $registration; } /** - * @dataProvider collectionXmlConfiguration + * @depends testCreateRegistration */ - public function testIsRegistrationEnabledForCollection($data, $value) + public function testAcceptRegistration($registration) + { + $aclMock = $this->getMockBuilder('ACL') + ->disableOriginalConstructor() + ->getMock(); + $aclMock->expects($this->once())->method('give_access_to_sbas')->with($this->equalTo([self::$DI['collection']->get_sbas_id()])); + $aclMock->expects($this->once())->method('give_access_to_base')->with($this->equalTo([self::$DI['collection']->get_base_id()])); + $aclMock->expects($this->once())->method('update_rights_to_base')->with($this->equalTo(self::$DI['collection']->get_base_id()), $this->equalTo([ + 'canputinalbum' => '1', + 'candwnldhd' => '1', + 'nowatermark' => '0', + 'candwnldpreview' => '1', + 'actif' => '1', + ])); + $aclProviderMock = $this->getMockBuilder('Alchemy\Phrasea\Authentication\ACLProvider') + ->disableOriginalConstructor() + ->getMock(); + $aclProviderMock->expects($this->any())->method('get')->with($this->equalTo(self::$DI['user']))->will($this->returnvalue($aclMock)); + $em = $this->getMockBuilder('Doctrine\ORM\EntityManager') + ->disableOriginalConstructor() + ->getMock(); + $em->expects($this->once())->method('remove')->with($this->isInstanceOf('Alchemy\Phrasea\Model\Entities\Registration')); + $em->expects($this->once())->method('flush'); + + $service = new RegistrationManager($em, self::$DI['app']['phraseanet.appbox'], $aclProviderMock); + $service->acceptRegistration($registration, self::$DI['user'], self::$DI['collection'], true, false); + } + + public function testDeleteRegistrationForUser() { $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); + $qb = $service->getRepository()->createQueryBuilder('r'); + $nbRegistrationBefore = $qb->select('COUNT(r)') + ->where($qb->expr()->eq('r.user', ':user')) + ->setParameter(':user', self::$DI['user_alt1']->get_id()) + ->getQuery() + ->getSingleScalarResult(); + $service->deleteRegistrationsForUser(self::$DI['user_alt1']->get_id(), [self::$DI['collection']->get_base_id()]); + $nbRegistrationAfter = $qb->getQuery()->getSingleScalarResult(); + $this->assertGreaterThan($nbRegistrationAfter, $nbRegistrationBefore); + } - $mock = $this->getMockBuilder('\collection') - ->disableOriginalConstructor() - ->setMethods(['get_prefs']) - ->getMock(); + public function testDeleteOldRegistrations() + { + $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); + $qb = $service->getRepository()->createQueryBuilder('r'); + $nbRegistrationBefore = $qb->select('COUNT(r)') + ->getQuery() + ->getSingleScalarResult(); + $service->deleteOldRegistrations(); + $nbRegistrationAfter = $qb->getQuery()->getSingleScalarResult(); + $this->assertGreaterThan($nbRegistrationAfter, $nbRegistrationBefore); + } - $mock->expects($this->once())->method('get_prefs')->will($this->returnValue($data)); - $this->assertEquals($value, $service->isRegistrationEnabledForCollection($mock)); + public function testDeleteRegistrationOnCollection() + { + $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); + $qb = $service->getRepository()->createQueryBuilder('r'); + $nbRegistrationBefore = $qb->select('COUNT(r)') + ->getQuery() + ->getSingleScalarResult(); + $service->deleteRegistrationsOnCollection(self::$DI['collection']->get_base_id()); + $nbRegistrationAfter = $qb->getQuery()->getSingleScalarResult(); + $this->assertGreaterThan($nbRegistrationAfter, $nbRegistrationBefore); } /** * @dataProvider userDataProvider */ - public function testGetRegistrationInformationsWithUserData($data, $type, $value) + public function testGetRegistrationSummaryWithUserData($data, $type, $value) { - $service = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager') - ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']]) - ->setMethods(['getRegistrationDemandsForUser']) + $repoMock = $this->getMockBuilder('Alchemy\Phrasea\Model\Repositories\RegistrationRepository') + ->disableOriginalConstructor() + ->setMethods(['getRegistrationsSummaryForUser']) ->getMock(); + $repoMock->expects($this->once())->method('getRegistrationsSummaryForUser')->will($this->returnValue($data)); + $em = $this->getMockBuilder('Doctrine\ORM\EntityManager') + ->disableOriginalConstructor() + ->getMock(); + $em->expects($this->once())->method('getRepository')->will($this->returnValue($repoMock)); - $service->expects($this->once())->method('getRegistrationDemandsForUser')->will($this->returnValue($data)); + $service = new RegistrationManager($em, self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']); - $rs = $service->getRegistrationInformations(4); + $rs = $service->getRegistrationSummary(4); $databox = current(self::$DI['app']['phraseanet.appbox']->get_databoxes()); $collection = current($databox->get_collections()); - $this->assertEquals($value, count($rs[$databox->get_sbas_id()]['demands']['by-type'][$type])); - $this->assertNotNull($rs[$databox->get_sbas_id()]['demands']['by-collection'][$collection->get_base_id()]); - } - - public function databoxXmlConfiguration() - { - $xmlInscript = -<< -11 -XML; - $xmlNoInscript = - << -01 -XML; - $xmlNoInscriptEmpty = - << - -XML; - - return [ - [simplexml_load_string($xmlInscript), true], - [simplexml_load_string($xmlNoInscript), false], - [simplexml_load_string($xmlNoInscriptEmpty), false], - ]; - } - - public function collectionXmlConfiguration() - { - $xmlInscript = -<< -11 -XML; - $xmlNoInscript = -<< -01 -XML; - $xmlNoInscriptEmpty = -<< - -XML; - - return [ - [$xmlInscript, true], - [$xmlNoInscript, false], - [$xmlNoInscriptEmpty, false], - ]; - } - - public function registrationConfigProvider() - { - $enableDataboxConfig = [ - [ - [ - 'config' => [ - 'db-name' => 'a_db_name', - 'cgu' => null, - 'cgu-release' => null, - 'can-register' => true, - 'collections' => [], - ] - ] - ], - false - ]; - - $enableCollectionConfig = [ - [ - [ - 'config' => [ - 'db-name' => 'a_db_name', - 'cgu' => null, - 'cgu-release' => null, - 'can-register' => false, - 'collections' => [ - [ - 'coll-name' => 'a_coll_name', - 'can-register' => true, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null - ] - ], - ] - ] - ], - true - ]; - - $nothingEnabledConfig = [ - [ - [ - 'config' => [ - 'db-name' => 'a_db_name', - 'cgu' => null, - 'cgu-release' => null, - 'can-register' => false, - 'collections' => [ - [ - 'coll-name' => 'a_coll_name', - 'can-register' => false, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null - ], - [ - 'coll-name' => 'an_other_coll_name', - 'can-register' => false, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null - ] - ], - ] - ] - ], - false - ]; - - $noCollectionEnabledButBaseEnabledConfig = [ - [ - [ - 'config' => [ - 'db-name' => 'a_db_name', - 'cgu' => null, - 'cgu-release' => null, - 'can-register' => true, - 'collections' => [ - [ - 'coll-name' => 'a_coll_name', - 'can-register' => false, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null - ], - [ - 'coll-name' => 'an_other_coll_name', - 'can-register' => false, - 'cgu' => null, - 'cgu-release' => null, - 'demand' => null - ] - ], - ] - ] - ], - false - ]; - - return [ - $enableDataboxConfig, - $enableCollectionConfig, - $nothingEnabledConfig, - $noCollectionEnabledButBaseEnabledConfig - ]; + $this->assertEquals($value, count($rs[$databox->get_sbas_id()]['registrations']['by-type'][$type])); + $this->assertNotNull($rs[$databox->get_sbas_id()]['registrations']['by-collection'][$collection->get_base_id()]); } public function userDataProvider() { - $pendingDemand = new RegistrationDemand(); - $pendingDemand->setBaseId(1); - $pendingDemand->setUser(3); - $pendingDemand->setPending(true); - $pendingDemand->setRejected(false); + $pendingRegistration = new Registration(); + $pendingRegistration->setBaseId(1); + $pendingRegistration->setUser(3); + $pendingRegistration->setPending(true); + $pendingRegistration->setRejected(false); - $rejectedDemand = new RegistrationDemand(); - $rejectedDemand->setBaseId(1); - $rejectedDemand->setUser(3); - $rejectedDemand->setPending(true); - $rejectedDemand->setRejected(true); + $rejectedRegistration = new Registration(); + $rejectedRegistration->setBaseId(1); + $rejectedRegistration->setUser(3); + $rejectedRegistration->setPending(true); + $rejectedRegistration->setRejected(true); $databox = current((new \appbox(new Application()))->get_databoxes()); $collection = current($databox->get_collections()); - $noLimitedPendingDemand = [ + $noLimitedPendingRegistration = [ [ $databox->get_sbas_id() => [ $collection->get_base_id() => [ @@ -261,7 +168,7 @@ XML; 'active' => true, 'time-limited' => false, 'in-time' => null, - 'demand' => $pendingDemand + 'registration' => $pendingRegistration ] ] ], @@ -270,7 +177,7 @@ XML; ]; - $rejectedDemand = [ + $rejectedRegistration = [ [ $databox->get_sbas_id() => [ $collection->get_base_id() => [ @@ -279,7 +186,7 @@ XML; 'active' => true, 'time-limited' => false, 'in-time' => null, - 'demand' => $rejectedDemand + 'registration' => $rejectedRegistration ] ] ], @@ -287,7 +194,7 @@ XML; 1 ]; - $noActiveDemand = [ + $noActiveRegistration = [ [ $databox->get_sbas_id() => [ $collection->get_base_id() => [ @@ -296,7 +203,7 @@ XML; 'active' => false, 'time-limited' => false, 'in-time' => null, - 'demand' => $pendingDemand + 'registration' => $pendingRegistration ] ] ], @@ -304,7 +211,7 @@ XML; 1 ]; - $limitedActiveIntimePendingDemand = [ + $limitedActiveIntimePendingRegistration = [ [ $databox->get_sbas_id() => [ $collection->get_base_id() => [ @@ -313,7 +220,7 @@ XML; 'active' => true, 'time-limited' => true, 'in-time' => true, - 'demand' => $pendingDemand + 'registration' => $pendingRegistration ] ] ], @@ -321,7 +228,7 @@ XML; 1 ]; - $limitedActiveOutdatedPendingDemand = [ + $limitedActiveOutdatedPendingRegistration = [ [ $databox->get_sbas_id() => [ $collection->get_base_id() => [ @@ -330,7 +237,7 @@ XML; 'active' => true, 'time-limited' => true, 'in-time' => false, - 'demand' => $pendingDemand + 'registration' => $pendingRegistration ] ] ], @@ -339,11 +246,11 @@ XML; ]; return [ - $noLimitedPendingDemand, - $noActiveDemand, - $limitedActiveIntimePendingDemand, - $limitedActiveOutdatedPendingDemand, - $rejectedDemand + $noLimitedPendingRegistration, + $noActiveRegistration, + $limitedActiveIntimePendingRegistration, + $limitedActiveOutdatedPendingRegistration, + $rejectedRegistration ]; } } diff --git a/tests/classes/collectionTest.php b/tests/classes/collectionTest.php index 0949bbd416..6f7c084618 100644 --- a/tests/classes/collectionTest.php +++ b/tests/classes/collectionTest.php @@ -363,4 +363,43 @@ class collectionTest extends \PhraseanetAuthenticatedTestCase 'This test has not been implemented yet.' ); } + + /** + * @dataProvider collectionXmlConfiguration + */ + public function testIsRegistrationEnabled($data, $value) + { + $mock = $this->getMockBuilder('\collection') + ->disableOriginalConstructor() + ->setMethods(['get_prefs']) + ->getMock(); + + $mock->expects($this->once())->method('get_prefs')->will($this->returnValue($data)); + $this->assertEquals($value, $mock->isRegistrationEnabled()); + } + + public function collectionXmlConfiguration() + { + $xmlInscript = +<< +11 +XML; + $xmlNoInscript = +<< +01 +XML; + $xmlNoInscriptEmpty = +<< + +XML; + + return [ + [$xmlInscript, true], + [$xmlNoInscript, false], + [$xmlNoInscriptEmpty, false], + ]; + } } diff --git a/tests/classes/databoxTest.php b/tests/classes/databoxTest.php index c53911ead7..8da601ee8b 100644 --- a/tests/classes/databoxTest.php +++ b/tests/classes/databoxTest.php @@ -112,4 +112,43 @@ class databoxTest extends \PhraseanetAuthenticatedWebTestCase $this->assertNull($databox->get_label('fr', false)); $this->assertNull($databox->get_label('en', false)); } + + /** + * @dataProvider databoxXmlConfiguration + */ + public function testIsRegistrationEnabled($data, $value) + { + $mock = $this->getMockBuilder('\databox') + ->disableOriginalConstructor() + ->setMethods(['get_sxml_structure']) + ->getMock(); + + $mock->expects($this->once())->method('get_sxml_structure')->will($this->returnValue($data)); + $this->assertEquals($value, $mock->isRegistrationEnabled()); + } + + public function databoxXmlConfiguration() + { + $xmlInscript = +<< +11 +XML; + $xmlNoInscript = +<< +01 +XML; + $xmlNoInscriptEmpty = +<< + +XML; + + return [ + [simplexml_load_string($xmlInscript), true], + [simplexml_load_string($xmlNoInscript), false], + [simplexml_load_string($xmlNoInscriptEmpty), false], + ]; + } }