diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Users.php b/lib/Alchemy/Phrasea/Controller/Admin/Users.php index 51f6359efa..934794b6aa 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Users.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Users.php @@ -354,40 +354,35 @@ class Users implements ControllerProviderInterface })->bind('admin_users_export_csv'); $controllers->get('/demands/', function (Application $app) { - $lastMonth = time() - (3 * 4 * 7 * 24 * 60 * 60); - $sql = "DELETE FROM demand WHERE date_modif < :date"; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':date' => date('Y-m-d', $lastMonth)]); - $stmt->closeCursor(); + $app['registration-manager']->deleteOldDemand(); - $basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])); $models = $app['manipulator.user']->getRepository()->findModelOf($app['authentication']->getUser()); - $currentUsr = null; - $table = ['users' => [], 'coll' => []]; + $demands = $app['registration-manager']->getRepository()->getDemandsForUser( + $app['authentication']->getUser(), + array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])) + ); - foreach ($app['EM.native-query']->getUsersRegistrationDemand($basList) as $row) { - $user = $row[0]; + $currentUsr = null; + $table = ['user' => [], 'demand' => []]; + + foreach ($demands as $demand) { + $user = $demand->getUser(); if ($user->getId() !== $currentUsr) { $currentUsr = $user->getId(); - $table['users'][$currentUsr] = [ - 'user' => $user, - 'date_demand' => $row['date_demand'], - ]; + $table['user'][$user->getId()] = $user; } - if (!isset($table['coll'][$user->getId()])) { - $table['coll'][$user->getId()] = []; + if (!isset($table['demand'][$user->getId()])) { + $table['demand'][$user->getId()] = []; } - if (!in_array($row['base_demand'], $table['coll'][$user->getId()])) { - $table['coll'][$user->getId()][] = $row['base_demand']; + if (!array_key_exists($demand->getBaseId(), $table['demand'][$user->getId()][$demand->getBaseId()])) { + $table['demand'][$user->getId()][$demand->getBaseId()] = $demand; } } - $stmt->closeCursor(); - return $app['twig']->render('admin/user/demand.html.twig', [ 'table' => $table, 'models' => $models, @@ -395,7 +390,6 @@ class Users implements ControllerProviderInterface })->bind('users_display_demands'); $controllers->post('/demands/', function (Application $app, Request $request) { - $templates = $deny = $accept = $options = []; foreach ($request->request->get('template', []) as $tmp) { @@ -458,27 +452,13 @@ class Users implements ControllerProviderInterface $done[$usr][$base_id] = true; } - $sql = " - DELETE FROM demand - WHERE usr_id = :usr_id - AND (base_id = " . implode(' OR base_id = ', $base_ids) . ")"; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $usr]); - $stmt->closeCursor(); + $app['registration-manager']->getRepository()->deleteUserDemands($user, $base_ids); } - $sql = " - UPDATE demand SET en_cours=0, refuser=1, date_modif=now() - WHERE usr_id = :usr_id - AND base_id = :base_id"; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - foreach ($deny as $usr => $bases) { $cache_to_update[$usr] = true; foreach ($bases as $bas) { - $stmt->execute([':usr_id' => $usr, ':base_id' => $bas]); + $app['registration-manager']->rejectDemand($usr, $bas); if (!isset($done[$usr])) { $done[$usr] = []; @@ -488,36 +468,18 @@ class Users implements ControllerProviderInterface } } - $stmt->closeCursor(); - foreach ($accept as $usr => $bases) { $user = $app['manipulator.user']->getRepository()->find($usr); $cache_to_update[$usr] = true; foreach ($bases as $bas) { - $app['acl']->get($user)->give_access_to_sbas([\phrasea::sbasFromBas($app, $bas)]); - - $rights = [ - 'canputinalbum' => '1', - 'candwnldhd' => ($options[$usr][$bas]['HD'] ? '1' : '0'), - 'nowatermark' => ($options[$usr][$bas]['WM'] ? '0' : '1'), - 'candwnldpreview' => '1', - 'actif' => '1', - ]; - - $app['acl']->get($user)->give_access_to_base([$bas]); - $app['acl']->get($user)->update_rights_to_base($bas, $rights); - + $collection = \collection::get_from_base_id($app, $bas); if (!isset($done[$usr])) { $done[$usr] = []; } - $done[$usr][$bas] = true; - $sql = "DELETE FROM demand WHERE usr_id = :usr_id AND base_id = :base_id"; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $usr, ':base_id' => $bas]); - $stmt->closeCursor(); + $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 6be7b357c8..cf831f73e8 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Account.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Account.php @@ -231,10 +231,8 @@ class Account implements ControllerProviderInterface */ public function accountAccess(Application $app, Request $request) { - require_once $app['root.path'] . '/lib/classes/deprecated/inscript.api.php'; - return $app['twig']->render('account/access.html.twig', [ - 'inscriptions' => giveMeBases($app, $app['authentication']->getUser()->getId()) + 'inscriptions' => $app['registration-manager']->getRegistrationInformations($app['authentication']->getUser()->getId()) ]); } @@ -328,17 +326,11 @@ class Account implements ControllerProviderInterface */ public function updateAccount(PhraseaApplication $app, Request $request) { - $demands = (array) $request->request->get('demand', []); - - if (0 !== count($demands)) { + if (0 !== count($demands = (array) $request->request->get('demand', []))) { foreach ($demands as $baseId) { - try { - $app['phraseanet.appbox-register']->add_request($app['authentication']->getUser(), \collection::get_from_base_id($app, $baseId)); - $app->addFlash('success', $app->trans('login::notification: Vos demandes ont ete prises en compte')); - } catch (\Exception $e) { - - } + $app['registration-manager']->newDemand($app['authentication']->getUser()->getId(), $baseId); } + $app->addFlash('success', $app->trans('login::notification: Vos demandes ont ete prises en compte')); } $accountFields = [ diff --git a/lib/Alchemy/Phrasea/Controller/Root/Login.php b/lib/Alchemy/Phrasea/Controller/Root/Login.php index d5c3feb814..cbf8af0df9 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Login.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Login.php @@ -38,6 +38,7 @@ use Alchemy\Phrasea\Form\Login\PhraseaForgotPasswordForm; use Alchemy\Phrasea\Form\Login\PhraseaRecoverPasswordForm; use Alchemy\Phrasea\Form\Login\PhraseaRegisterForm; use Doctrine\ORM\EntityManager; +use igorw; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Cookie; @@ -329,14 +330,12 @@ class Login implements ControllerProviderInterface throw new FormProcessingException($app->trans('Invalid captcha answer.')); } - require_once $app['root.path'] . '/lib/classes/deprecated/inscript.api.php'; - if ($app['conf']->get(['registry', 'registration', 'auto-select-collections'])) { $selected = null; } else { $selected = isset($data['collections']) ? $data['collections'] : null; } - $inscriptions = giveMeBases($app); + $inscriptions = $app['registration-manager']->getRegistrationInformations(); $inscOK = []; foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { @@ -345,15 +344,8 @@ class Login implements ControllerProviderInterface 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; - } else { - $inscOK[$collection->get_base_id()] = false; + if ($canRegister = igorw\get_in($inscriptions, [$databox->get_sbas_id(), 'config', 'collections', $collection->get_base_id(), 'can-register'])) { + $inscOK[$collection->get_base_id()] = $canRegister; } } } @@ -414,8 +406,7 @@ class Login implements ControllerProviderInterface continue; } - $collection = \collection::get_from_base_id($app, $base_id); - $app['phraseanet.appbox-register']->add_request($user, $collection); + $app['registration-manager']->newDemand($user->getId(), $base_id); $demandOK[$base_id] = true; } @@ -750,8 +741,6 @@ class Login implements ControllerProviderInterface */ public function login(PhraseaApplication $app, Request $request) { - require_once $app['root.path'] . '/lib/classes/deprecated/inscript.api.php'; - try { $app['phraseanet.appbox']->get_connection(); } catch (\Exception $e) { diff --git a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php index 62c1cf2fa2..8f1110c82c 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Core\Provider; use Alchemy\Phrasea\Form\Constraint\NewLogin; +use Alchemy\Phrasea\Registration\RegistrationManager; use Alchemy\Phrasea\Model\Entities\User; use Silex\Application; use Silex\ServiceProviderInterface; @@ -26,19 +27,7 @@ class RegistrationServiceProvider implements ServiceProviderInterface }); $app['registration.enabled'] = $app->share(function (Application $app) { - require_once __DIR__ . '/../../../../classes/deprecated/inscript.api.php'; - - $bases = giveMeBases($app); - - if ($bases) { - foreach ($bases as $base) { - if ($base['inscript']) { - return true; - } - } - } - - return false; + return $app['registration-manager']->isRegistrationEnabled(); }); $app['registration.optional-fields'] = $app->share(function (Application $app) { @@ -134,6 +123,10 @@ class RegistrationServiceProvider implements ServiceProviderInterface ], ]; }); + + $app['registration-manager'] = $app->share(function (Application $app) { + return new RegistrationManager($app['EM'], $app['phraseanet.appbox'], $app['acl']); + }); } public function boot(Application $app) diff --git a/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php b/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php index 0792dce296..0654856c3b 100644 --- a/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php +++ b/lib/Alchemy/Phrasea/Form/Login/PhraseaRegisterForm.php @@ -72,39 +72,22 @@ class PhraseaRegisterForm extends AbstractType $builder->add('provider-id', 'hidden'); - require_once $this->app['root.path'] . '/lib/classes/deprecated/inscript.api.php'; $choices = []; $baseIds = []; - foreach (\giveMeBases($this->app) as $sbas_id => $baseInsc) { - if (($baseInsc['CollsCGU'] || $baseInsc['Colls']) && $baseInsc['inscript']) { - if ($baseInsc['Colls']) { - foreach ($baseInsc['Colls'] as $collId => $collName) { - $baseId = \phrasea::baseFromColl($sbas_id, $collId, $this->app); - $sbasName= \phrasea::sbas_names($sbas_id, $this->app); - - if (!isset($choices[$sbasName])) { - $choices[$sbasName] = []; - } - - $choices[$sbasName][$baseId] = \phrasea::bas_labels($baseId, $this->app); - $baseIds[] = $baseId; - } + foreach ($this->app['registration-manager']->getRegistrationInformations() as $baseInfo) { + $dbName = $baseInfo['config']['db-name']; + foreach ($baseInfo['config']['collections'] as $baseId => $collInfo) { + if (false === $collInfo['can-register']) { + continue; } - if ($baseInsc['CollsCGU']) { - foreach ($baseInsc['CollsCGU'] as $collId => $collName) { - $baseId = \phrasea::baseFromColl($sbas_id, $collId, $this->app); - $sbasName= \phrasea::sbas_names($sbas_id, $this->app); - - if (!isset($choices[$sbasName])) { - $choices[$sbasName] = []; - } - - $choices[$sbasName][$baseId] = \phrasea::bas_labels($baseId, $this->app); - $baseIds[] = $baseId; - } + if (!isset($choices[$dbName])) { + $choices[$dbName] = []; } + + $choices[$dbName][$baseId] = \phrasea::bas_labels($baseId, $this->app); + $baseIds[] = $baseId; } } diff --git a/lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php b/lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php new file mode 100644 index 0000000000..f4a45a9e4a --- /dev/null +++ b/lib/Alchemy/Phrasea/Model/Entities/RegistrationDemand.php @@ -0,0 +1,183 @@ +id; + } + + /** + * @param mixed $pending + * + * @return RegistrationDemand + */ + public function setPending($pending) + { + $this->pending = (Boolean) $pending; + + return $this; + } + + /** + * @return mixed + */ + public function isPending() + { + return $this->pending; + } + + /** + * @param mixed $rejected + * + * @return RegistrationDemand + */ + public function setRejected($rejected) + { + $this->rejected = (Boolean) $rejected; + + return $this; + } + + /** + * @return mixed + */ + public function isRejected() + { + return $this->rejected; + } + + /** + * @param mixed $user + * + * @return RegistrationDemand + */ + public function setUser($user) + { + $this->user = $user; + + return $this; + } + + /** + * @return mixed + */ + public function getUser() + { + return $this->user; + } + + /** + * @param mixed $baseId + * + * @return RegistrationDemand + */ + public function setBaseId($baseId) + { + $this->baseId = $baseId; + + return $this; + } + + /** + * @return mixed + */ + public function getBaseId() + { + return $this->baseId; + } + + /** + * @return \DateTime + */ + public function getCreated() + { + return $this->created; + } + + /** + * @return \DateTime + */ + public function getUpdated() + { + return $this->updated; + } + + /** + * @param \Datetime $created + */ + public function setCreated(\Datetime $created) + { + $this->created = $created; + } + + /** + * @param \Datetime $updated + */ + public function setUpdated(\Datetime $updated) + { + $this->updated = $updated; + } +} diff --git a/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.php new file mode 100644 index 0000000000..84a9ae9774 --- /dev/null +++ b/lib/Alchemy/Phrasea/Model/Repositories/RegistrationDemandRepository.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(); + } + + /** + * 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/Registration/RegistrationManager.php b/lib/Alchemy/Phrasea/Registration/RegistrationManager.php new file mode 100644 index 0000000000..542ba32d23 --- /dev/null +++ b/lib/Alchemy/Phrasea/Registration/RegistrationManager.php @@ -0,0 +1,454 @@ +em = $em; + $this->appbox = $appbox; + $this->repository = $this->em->getRepository('Alchemy\Phrasea\Model\Entities\RegistrationDemand'); + $this->aclProvider = $aclProvider; + } + + /** + * Creates a new demand. + * + * @param $userId + * @param $baseId + * + * @return RegistrationDemand + */ + public function newDemand($userId, $baseId) + { + $demand = new RegistrationDemand(); + $demand->setUser($userId); + $demand->setBaseId($baseId); + $this->em->persist($demand); + $this->em->flush(); + + return $demand; + } + + /** + * Rejects a demand. + * + * @param $usrId + * @param $baseId + */ + public function rejectDemand($usrId, $baseId) + { + if ($demand = $this->getRepository()->findOneBy([ + 'user' => $usrId, + 'baseId' => $baseId + ])) { + $demand->setPending(false); + $demand->setRejected(true); + $this->em->persist($demand); + } + $this->em->flush(); + } + + /** + * Accepts a demand. + * + * @param $userId + * @param $basId + */ + public function acceptDemand(\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(); + } + } + + /** + * 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. + * + * @param null|integer $userId + * + * @return array + */ + public function getRegistrationInformations($userId = null) + { + $data = $userData = []; + + if (null !== $userId) { + $userData = $this->getRegistrationDemandsForUser($userId); + } + + foreach ($this->appbox->get_databoxes() as $databox) { + $ddata = [ + 'demands' => [ + 'by-type' => [ + 'inactive' => [], + 'accepted' => [], + 'in-time' => [], + 'out-dated' => [], + 'pending' => [], + 'rejected' => [], + ], + 'by-collection' => [] + ], + 'config' => [ + 'db-name' => $databox->get_dbname(), + 'cgu' => $this->getCguPreferencesForDatabox($databox), + 'cgu-release' => $this->getCguReleasedPreferencesForDatabox($databox), + 'can-register' => $this->isRegistrationEnabledForDatabox($databox), + 'collections' => [], + ] + ]; + + foreach ($databox->get_collections() as $collection) { + // sets collection info + $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 + ]; + + if (null === $userDemand = 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']; + + $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']; + $isNotTimeLimited = !$isTimeLimited; + $isOnTime = (Boolean) $userDemand['in-time']; + $isOutDated = !$isOnTime; + + if ($noDemandMade) { + continue; + } + // sets demands + $ddata['config']['collections'][$collection->get_base_id()]['demand'] = $userDemand; + $ddata['demands']['by-collection'][$collection->get_base_id()] = $userDemand; + + if (!$isActive) { + $ddata['demands']['by-type']['inactive'][] = $userDemand; + continue; + } + + if ($isDone) { + $ddata['demands']['by-type']['accepted'][] = $userDemand; + continue; + } + + if ($isRejected) { + $ddata['demands']['by-type']['rejected'][] = $userDemand; + continue; + } + + if ($isTimeLimited && $isOnTime && $isPending) { + $ddata['demands']['by-type']['in-time'][] = $userDemand; + continue; + } + + if ($isTimeLimited && $isOutDated && $isPending) { + $ddata['demands']['by-type']['out-time'][] = $userDemand; + continue; + } + + if ($isNotTimeLimited && $isPending) { + $ddata['demands']['by-type']['pending'][] = $userDemand; + } + } + } + + $data[$databox->get_sbas_id()] = $ddata; + + return $data; + } + + /** + * Gets registration demands for a user. + * + * @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 + */ + public function getRepository() + { + return $this->repository; + } + + /** + * Deletes old demands. + */ + public function deleteOldDemand() + { + $this->repository->deleteDemandsOldestThan('-1 month'); + } + + /** + * Tells whether the registration is enable for provided databox or not. + * + * @param \databox $databox + * + * @return boolean + */ + public function isRegistrationEnabledForDatabox(\databox $databox) + { + $enabled = false; + + if ($xml = $databox->get_sxml_structure()) { + foreach ($xml->xpath('/record/caninscript') as $caninscript) { + $enabled = (Boolean) (string) $caninscript; + break; + } + } + + return $enabled; + } + + /** + * Gets CGU released preference for provided databox. + * + * @param \databox $databox + * + * @return null|string + */ + public function getCguReleasedPreferencesForDatabox(\databox $databox) + { + $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; + } +} diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php new file mode 100644 index 0000000000..1da763cc79 --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/RegistrationDemandMigration.php @@ -0,0 +1,28 @@ +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"); + } + + public function doDownSql(Schema $schema) + { + $this->addSql("DROP TABLE RegistrationDemand"); + } +} diff --git a/lib/classes/appbox/register.php b/lib/classes/appbox/register.php deleted file mode 100644 index 89442dc565..0000000000 --- a/lib/classes/appbox/register.php +++ /dev/null @@ -1,95 +0,0 @@ -appbox = $appbox; - - return $this; - } - - /** - * Add a registration request for a user on a collection - * - * @param User $user - * @param collection $collection - * @return appbox_register - */ - public function add_request(User $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([':usr_id' => $user->getId(), ':base_id' => $collection->get_base_id()]); - $stmt->closeCursor(); - - return $this; - } - - /** - * Return an array of collection objects where provided - * user is waiting for approbation - * - * @param Application $app - * @param User $user - * - * @return array - */ - public function get_collection_awaiting_for_user(Application $app, User $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([':usr_id' => $user->getId()]); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $ret = []; - foreach ($rs as $row) { - $ret[] = collection::get_from_base_id($app, $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([':lastMonth' => $lastMonth->format(DATE_ISO8601)]); - $stmt->closeCursor(); - - return; - } -} diff --git a/lib/classes/collection.php b/lib/classes/collection.php index 2e39306bb4..70056d1db7 100644 --- a/lib/classes/collection.php +++ b/lib/classes/collection.php @@ -406,10 +406,7 @@ class collection implements cache_cacheableInterface $stmt->execute([':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([':base_id' => $this->get_base_id()]); - $stmt->closeCursor(); + $this->app['registration-manager']->getRepository()->deleteDemandsOnCollection($this->get_base_id()); $this->get_databox()->delete_data_from_cache(databox::CACHE_COLLECTIONS); @@ -537,10 +534,7 @@ class collection implements cache_cacheableInterface $stmt->execute($params); $stmt->closeCursor(); - $sql = "DELETE FROM demand WHERE base_id = :base_id"; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); + $this->app['registration-manager']->getRepository()->deleteDemandsOnCollection($this->get_base_id()); phrasea::reset_baseDatas($app['phraseanet.appbox']); diff --git a/lib/classes/deprecated/inscript.api.php b/lib/classes/deprecated/inscript.api.php deleted file mode 100644 index f0c266dcc1..0000000000 --- a/lib/classes/deprecated/inscript.api.php +++ /dev/null @@ -1,294 +0,0 @@ -get_connection(); - - $inscriptions = null; - - $usrerRegis = null; - - if ($usr != null) { - - $sqlU = ' - SELECT sbas.dbname, time_limited, UNIX_TIMESTAMP( limited_from ) AS limited_from, - UNIX_TIMESTAMP( limited_to ) AS limited_to, bas.server_coll_id, - u.id, basusr.actif, demand.en_cours, demand.refuser - FROM (Users u, bas, sbas) - LEFT JOIN basusr ON ( u.id = basusr.usr_id - AND bas.base_id = basusr.base_id ) - LEFT JOIN demand ON ( demand.usr_id = u.id - AND bas.base_id = demand.base_id ) - WHERE bas.active > 0 - AND bas.sbas_id = sbas.sbas_id - AND u.id = :usr_id - AND u.model_of IS NULL - '; - - $stmt = $conn->prepare($sqlU); - $stmt->execute([':usr_id' => $usr]); - $rsU = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if (count($rsU) == 0) { - return null; - } - - foreach ($rsU as $rowU) { - if ( ! isset($usrerRegis[$rowU['dbname']])) - $usrerRegis[$rowU['dbname']] = null; - - if ( ! is_null($rowU['actif']) || ! is_null($rowU['en_cours'])) { - - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = true; - if ($rowU['actif'] == '0') - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'NONACTIF'; - elseif ($rowU['time_limited'] == '1' && ! ($rowU['limited_from'] >= time() && $rowU['limited_to'] <= time())) - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'OUTTIME'; - elseif ($rowU['time_limited'] == '1' && ($rowU['limited_from'] > time() && $rowU['limited_to'] < time())) - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'INTIME'; - elseif ($rowU['en_cours'] == '1') - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'WAIT'; - elseif ($rowU['refuser'] == '1') - $usrerRegis[$rowU['dbname']][$rowU['server_coll_id']] = 'REFUSE'; - } - } - } - - foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { - $collname = $basname = null; - $sbas_id = $databox->get_sbas_id(); - $inscriptions[$sbas_id] = []; - $inscriptions[$sbas_id]['CGU'] = false; - $inscriptions[$sbas_id]['CGUrelease'] = false; - $inscriptions[$sbas_id]['inscript'] = false; - $inscriptions[$sbas_id]['CollsCGU'] = null; - $inscriptions[$sbas_id]['Colls'] = null; - $inscriptions[$sbas_id]['CollsRegistered'] = null; - $inscriptions[$sbas_id]['CollsWait'] = null; - $inscriptions[$sbas_id]['CollsRefuse'] = null; - $inscriptions[$sbas_id]['CollsIntime'] = null; - $inscriptions[$sbas_id]['CollsOuttime'] = null; - $inscriptions[$sbas_id]['CollsNonactif'] = null; - - foreach ($databox->get_collections() as $key => $coll) { - $collname[$key] = $coll->get_label($app['locale']); - $basname[$key] = $coll->get_coll_id(); - } - $sbpcgu = ''; - - $xml = $databox->get_sxml_structure(); - if ($xml) { - foreach ($xml->xpath('/record/caninscript') as $caninscript) { - if ($inscriptions[$sbas_id]['inscript'] === false) - $inscriptions[$sbas_id]['inscript'] = ((string) $caninscript == "1"); - } - foreach ($xml->xpath('/record/cgu') as $sbpcgu) { - foreach ($sbpcgu->attributes() as $a => $b) { - if ($a == "release") - $inscriptions[$sbas_id]['CGUrelease'] = (string) $b; - } - $inscriptions[$sbas_id]['CGU'] = (string) $sbpcgu->saveXML(); - } - } - $baseInscript = $inscriptions[$sbas_id]['inscript']; - foreach ($databox->get_collections() as $collection) { - $cguColl = false; - - $collInscript = $baseInscript; - $cguSpec = false; - if (false !== $xml = simplexml_load_string($collection->get_prefs())) { - foreach ($xml->xpath('/baseprefs/caninscript') as $caninscript) { - $tmp = (string) $caninscript; - if ($tmp === "1") - $collInscript = true; - elseif ($tmp === "0") - $collInscript = false; - } - if ($collInscript) { - $cguCollRelease = false; - - if ($inscriptions[$sbas_id]['inscript'] === false) - $inscriptions[$sbas_id]['inscript'] = ! ! $collInscript; - - foreach ($xml->xpath('/baseprefs/cgu') as $bpcgu) { - foreach ($bpcgu->attributes() as $a => $b) { - if ($a == "release") - $cguCollRelease = (string) $b; - } - $cguColl = (string) $bpcgu->saveXML(); - } - if ($cguColl) { - $cguSpec = true; - } else { - if ( ! isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()])) - $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_label($app['locale']); - } - } - } - $lacgu = $cguColl ? $cguColl : (string) $sbpcgu; - - if (isset($usrerRegis[$databox->get_dbname()]) && isset($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()])) { - if ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "WAIT") - $inscriptions[$sbas_id]['CollsWait'][$collection->get_coll_id()] = $lacgu; - elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "REFUSE") - $inscriptions[$sbas_id]['CollsRefuse'][$collection->get_coll_id()] = $lacgu; - elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "INTIME") - $inscriptions[$sbas_id]['CollsIntime'][$collection->get_coll_id()] = $lacgu; - elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "OUTTIME") - $inscriptions[$sbas_id]['CollsOuttime'][$collection->get_coll_id()] = $lacgu; - elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === "NONACTIF") - $inscriptions[$sbas_id]['CollsNonactif'][$collection->get_coll_id()] = $lacgu; - elseif ($usrerRegis[$databox->get_dbname()][$collection->get_coll_id()] === true) - $inscriptions[$sbas_id]['CollsRegistered'][$collection->get_coll_id()] = $lacgu; - } elseif (! $cguSpec && $collInscript) {//ne va pas.. si l'inscriptio na la coll est explicitement non autorise, je refuse' - $inscriptions[$sbas_id]['Colls'][$collection->get_coll_id()] = $collection->get_label($app['locale']); - } elseif ($cguSpec) { - $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['name'] = $collection->get_label($app['locale']); - $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGU'] = $cguColl; - $inscriptions[$sbas_id]['CollsCGU'][$collection->get_coll_id()]['CGUrelease'] = $cguCollRelease; - } - } - } - - return $inscriptions; -} - -function giveMeBaseUsr(Application $app, $usr) -{ - $noDemand = true; - - $out = '
' . - ' | ' . - ' | ' . - ' |
' . phrasea::sbas_labels($sbasId, $app) . ' | ||
' . $app->trans('login::register: acces authorise sur la collection') . phrasea::bas_labels($base_id, $app); - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: acces refuse sur la collection') . phrasea::bas_labels($base_id, $app) . ''; - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: en attente d\'acces sur') . ' ' . phrasea::bas_labels($base_id, $app) . ''; - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: acces temporaire sur') . phrasea::bas_labels($base_id, $app) . ''; - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: acces temporaire termine sur') . phrasea::bas_labels($base_id, $app) . ''; - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: acces supendu sur') . phrasea::bas_labels($base_id, $app) . ''; - if (trim($isTrue) != '') - $out .= ' ' . $app->trans('login::register::CGU: lire les CGU') . ''; - $out .= ' | ||
' . $app->trans('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' | ||
' . $baseInsc['CGU'] . ' | ||
' . $collName . ' | ' . - '' . - ' | ' . - '' . - '' . $app->trans('login::register: Faire une demande d\'acces') . '' . - ' | ' . - '
' . $app->trans('login::register: L\'acces aux bases ci-dessous implique l\'acceptation des Conditions Generales d\'Utilisation (CGU) suivantes') . ' | ||
' .
- ' ' . $collDesc['CGU'] . ' ' .
- ' | ' .
- '||
' . $collDesc['name'] . ' | ' . - '' . - ' | ' . - '' . - '' . $app->trans('login::register: Faire une demande d\'acces') . '' . - ' | ' . - '
- {% set colls = tableColls[user.getId()] %}
|
- {% for basId in colls %}
+ {% for baseId, demand in userDemands %}
+
+ {{ app['date-formatter'].getPrettyString(demand.getUpdated()) }}
+
{{ basId| bas_labels(app) }}
diff --git a/tests/Alchemy/Tests/Phrasea/Controller/Admin/UsersTest.php b/tests/Alchemy/Tests/Phrasea/Controller/Admin/UsersTest.php
index 4062970a50..90198bb359 100644
--- a/tests/Alchemy/Tests/Phrasea/Controller/Admin/UsersTest.php
+++ b/tests/Alchemy/Tests/Phrasea/Controller/Admin/UsersTest.php
@@ -428,7 +428,6 @@ class UsersTest extends \PhraseanetAuthenticatedWebTestCase
]);
self::$DI['app']['phraseanet.appbox'] = $appbox;
-
$this->assertTrue(self::$DI['client']->getResponse()->isRedirect());
}
diff --git a/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php b/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php
index 05292a5d54..dfb43e2737 100644
--- a/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php
+++ b/tests/Alchemy/Tests/Phrasea/Controller/Root/AccountTest.php
@@ -47,10 +47,44 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
*/
public function testGetAccountAccess()
{
+ $data = [
+ [
+ '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
+ ]
+ ],
+ ]
+ ]
+ ];
+
+ $service = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager')
+ ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']])
+ ->setMethods(['getRegistrationDemandsForUser'])
+ ->getMock();
+
+ $service->expects($this->once())->method('getRegistrationDemandsForUser')->will($this->returnValue($data));
+
+ self::$DI['app']['registration-manager'] = $service;
self::$DI['client']->request('GET', '/account/access/');
$response = self::$DI['client']->getResponse();
-
$this->assertTrue($response->isOk());
}
@@ -303,11 +337,10 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
$this->assertTrue($response->isRedirect());
$this->assertEquals('minet', self::$DI['app']['authentication']->getUser()->getLastName());
- $sql = 'SELECT base_id FROM demand WHERE usr_id = :usr_id AND en_cours="1" ';
- $stmt = self::$DI['app']['phraseanet.appbox']->get_connection()->prepare($sql);
- $stmt->execute([':usr_id' => self::$DI['app']['authentication']->getUser()->getId()]);
- $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
- $stmt->closeCursor();
+ $rs = self::$DI['app']['EM']->getRepository('Alchemy\Phrasea\Model\Entities\RegistrationDemand')->findBy([
+ 'user' => self::$DI['app']['authentication']->getUser(),
+ 'pending' => true
+ ]);
$this->assertCount(count($bases), $rs);
}
diff --git a/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php b/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php
index aa9dcda634..a0f2adbcca 100644
--- a/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php
+++ b/tests/Alchemy/Tests/Phrasea/Controller/Root/LoginTest.php
@@ -9,6 +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\User;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
@@ -36,7 +37,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$sxml->caninscript = 1;
$dom = new \DOMDocument();
$dom->loadXML($sxml->asXML());
-
self::$DI['collection']->set_prefs($dom);
}
if (null === self::$login) {
@@ -45,6 +45,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
if (null === self::$email) {
self::$email = self::$DI['user']->getEmail();
}
+ self::$DI['app']['registration.enabled'] = true;
}
public function tearDown()
@@ -208,7 +209,13 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
self::$DI['user']->setMailLocked(true);
$this->deleteRequest();
- self::$DI['app']['phraseanet.appbox-register']->add_request(self::$DI['user'], self::$DI['collection']);
+ $demand = new RegistrationDemand();
+ $demand->setUser(self::$DI['user']);
+ $demand->setBaseId(self::$DI['collection']->get_base_id());
+
+ self::$DI['app']['EM']->persist($demand);
+ self::$DI['app']['EM']->flush();
+
self::$DI['client']->request('GET', '/login/register-confirm/', ['code' => $token]);
$response = self::$DI['client']->getResponse();
@@ -470,7 +477,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
*/
public function testGetRegister($type, $message)
{
- self::$DI['app']['registration.enabled'] = true;
$this->logout(self::$DI['app']);
self::$DI['app']->addFlash($type, $message);
$crawler = self::$DI['client']->request('GET', '/login/register-classic/');
@@ -483,7 +489,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
public function testGetRegisterWithRegisterIdBindDataToForm()
{
- self::$DI['app']['registration.enabled'] = true;
$this->logout(self::$DI['app']);
$provider = $this->getMock('Alchemy\Phrasea\Authentication\Provider\ProviderInterface');
@@ -540,6 +545,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
*/
public function testPostRegisterbadArguments($parameters, $extraParameters, $errors)
{
+ $this->enableTOU();
self::$DI['app']['registration.enabled'] = true;
self::$DI['app']['registration.fields'] = $extraParameters;
@@ -572,6 +578,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
{
$this->logout(self::$DI['app']);
$crawler = self::$DI['client']->request('POST', '/login/register-classic/');
+
$this->assertFalse(self::$DI['client']->getResponse()->isRedirect());
$this->assertFormOrFlashError($crawler, self::$DI['app']['conf']->get(['registry', 'registration', 'auto-select-collections']) ? 6 : 7);
}
@@ -815,6 +822,13 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
self::$DI['app']['registration.fields'] = [];
$this->logout(self::$DI['app']);
+ $managerMock = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager')
+ ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']])
+ ->setMethods(['getRepository'])
+ ->getMock();
+ $managerMock->expects($this->any())->method('getRepository')->will($this->returnValue(self::$DI['app']['registration-manager']->getRepository()));
+ self::$DI['app']['registration-manager'] = $managerMock;
+
$provider = $this->getMock('Alchemy\Phrasea\Authentication\Provider\ProviderInterface');
$this->addProvider('provider-test', $provider);
@@ -1454,6 +1468,13 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
public function testAuthenticateProviderCallbackAlreadyBound()
{
+ $managerMock = $this->getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager')
+ ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']])
+ ->setMethods(['getRepository'])
+ ->getMock();
+ $managerMock->expects($this->any())->method('getRepository')->will($this->returnValue(self::$DI['app']['registration-manager']->getRepository()));
+ self::$DI['app']['registration-manager'] = $managerMock;
+
$provider = $this->getMock('Alchemy\Phrasea\Authentication\Provider\ProviderInterface');
$this->addProvider('provider-test', $provider);
@@ -1626,8 +1647,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
->method('isEnabled')
->will($this->returnValue(false));
- self::$DI['app']['registration.enabled'] = true;
-
$this->logout(self::$DI['app']);
self::$DI['client']->request('GET', '/login/provider/provider-test/callback/');
@@ -1778,10 +1797,9 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
*/
private function deleteRequest()
{
- $sql = "DELETE FROM demand WHERE usr_id = :usr_id";
- $stmt = self::$DI['app']['phraseanet.appbox']->get_connection()->prepare($sql);
- $stmt->execute([':usr_id' => self::$DI['user']->getId()]);
- $stmt->closeCursor();
+ $query = self::$DI['app']['EM']->createQuery('DELETE FROM Alchemy\Phrasea\Model\Entities\RegistrationDemand 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
new file mode 100644
index 0000000000..c88241ea67
--- /dev/null
+++ b/tests/Alchemy/Tests/Phrasea/Registration/RegistrationManagerTest.php
@@ -0,0 +1,349 @@
+getMockBuilder('Alchemy\Phrasea\Registration\RegistrationManager')
+ ->setConstructorArgs([self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']])
+ ->setMethods(['getRegistrationInformations'])
+ ->getMock();
+
+ $service->expects($this->once())->method('getRegistrationInformations')->will($this->returnValue($data));
+ $this->assertEquals($value, $service->isRegistrationEnabled());
+ }
+
+ /**
+ * @dataProvider databoxXmlConfiguration
+ */
+ public function testIsRegistrationEnabledForDatabox($data, $value)
+ {
+ $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']);
+
+ $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, $service->isRegistrationEnabledForDatabox($mock));
+ }
+
+ /**
+ * @dataProvider collectionXmlConfiguration
+ */
+ public function testIsRegistrationEnabledForCollection($data, $value)
+ {
+ $service = new RegistrationManager(self::$DI['app']['EM'], self::$DI['app']['phraseanet.appbox'], self::$DI['app']['acl']);
+
+ $mock = $this->getMockBuilder('\collection')
+ ->disableOriginalConstructor()
+ ->setMethods(['get_prefs'])
+ ->getMock();
+
+ $mock->expects($this->once())->method('get_prefs')->will($this->returnValue($data));
+ $this->assertEquals($value, $service->isRegistrationEnabledForCollection($mock));
+ }
+
+ /**
+ * @dataProvider userDataProvider
+ */
+ public function testGetRegistrationInformationsWithUserData($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'])
+ ->getMock();
+
+ $service->expects($this->once())->method('getRegistrationDemandsForUser')->will($this->returnValue($data));
+
+ $rs = $service->getRegistrationInformations(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 =
+<< |