diff --git a/.travis.yml b/.travis.yml index 1c18b515ad..b4cd208cfa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,10 +32,11 @@ before_script: - sh -c "cd sphinx-2.0.6-release && wget http://snowball.tartarus.org/dist/libstemmer_c.tgz && tar xzf libstemmer_c.tgz && ./configure --with-libstemmer --with-iconv --with-mysql --enable-id64 --quiet && make -j --quiet && sudo make install" - sudo mkdir -p /var/sphinx/datas - sudo chmod -R 0777 /var/sphinx - - mysql -e 'create database ab_test;create database db_test; create database ab_unitTests; create database db_unitTests;' + - mysql -e 'create database update39_test;create database ab_test;create database db_test; create database ab_unitTests; create database db_unitTests;' - sudo mysql -e "GRANT ALL PRIVILEGES ON ab_unitTests.* TO 'phraseaUnitTests'@'localhost' IDENTIFIED BY 'iWvGxPE8' WITH GRANT OPTION" - sudo mysql -e "GRANT ALL PRIVILEGES ON db_unitTests.* TO 'phraseaUnitTests'@'localhost' IDENTIFIED BY 'iWvGxPE8' WITH GRANT OPTION" - mysql -e 'SET @@global.sql_mode= "";' + - mysql -e 'SET @@global.max_allowed_packet= 33554432;' - mysql -e 'SET @@global.wait_timeout= 999999;' - git clone git://github.com/alchemy-fr/Phraseanet-Extension.git - sh -c "cd Phraseanet-Extension && phpize && ./configure --quiet && make -j --quiet && sudo make install" diff --git a/build-env.sh b/build-env.sh index 6bf532465d..d2ec94ffa6 100755 --- a/build-env.sh +++ b/build-env.sh @@ -10,8 +10,8 @@ then else echo "Dependencies retrieval discarded" fi -sudo mysql -e 'drop database ab_test;drop database db_test; drop database ab_unitTests; drop database db_unitTests;' || exit 1 -sudo mysql -e 'create database ab_test;create database db_test; create database ab_unitTests; create database db_unitTests;' || exit 1 +sudo mysql -e 'drop database update39_test;drop database ab_test;drop database db_test; drop database ab_unitTests; drop database db_unitTests;' || exit 1 +sudo mysql -e 'create database update39_test;create database ab_test;create database db_test; create database ab_unitTests; create database db_unitTests;' || exit 1 sudo mysql -e "GRANT ALL PRIVILEGES ON ab_unitTests.* TO 'phraseaUnitTests'@'localhost' IDENTIFIED BY 'iWvGxPE8' WITH GRANT OPTION" || exit 1 sudo mysql -e "GRANT ALL PRIVILEGES ON db_unitTests.* TO 'phraseaUnitTests'@'localhost' IDENTIFIED BY 'iWvGxPE8' WITH GRANT OPTION" || exit 1 sudo mysql -e "source `pwd`/hudson/fixtures.sql" || exit 1 diff --git a/features/bootstrap/GuiContext.php b/features/bootstrap/GuiContext.php index eb6d748ff1..b97da5e5de 100644 --- a/features/bootstrap/GuiContext.php +++ b/features/bootstrap/GuiContext.php @@ -14,6 +14,7 @@ require_once __DIR__ . '/../../vendor/autoload.php'; use Alchemy\Phrasea\Application; use Behat\Behat\Exception\PendingException; use Behat\MinkExtension\Context\MinkContext; +use Alchemy\Phrasea\Model\Entities\User; class GuiContext extends MinkContext { @@ -65,14 +66,12 @@ class GuiContext extends MinkContext */ public function aUserDoesNotExist($login) { - if (false !== $userId = \User_Adapter::get_usr_id_from_login($this->app, $login)) { - $user = \User_Adapter::getInstance($userId, $this->app); - - $user->ACL()->revoke_access_from_bases(array_keys( - $this->app['authentication']->getUser()->ACL()->get_granted_base(array('canadmin')) + if (null !== $user = $this->app['manipulator.user']->getRepository()->findByLogin($login)) { + $this->app['acl']->get($user)->revoke_access_from_bases(array_keys( + $this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(array('canadmin')) )); - $user->delete(); + $this->app['manipulator.user']->delete($user); } } @@ -81,14 +80,8 @@ class GuiContext extends MinkContext */ public function aUserExistsWithAsPassword($login, $password) { - if (false === \User_Adapter::get_usr_id_from_login($this->app, $login)) { - \User_Adapter::create( - $this->app, - $login, - $password, - $login, - false - ); + if (null === $user = $this->app['manipulator.user']->getRepository()->findByLogin($login)) { + $this->app['manipulator.user']->create($login, $password, null, false); } } @@ -168,24 +161,15 @@ class GuiContext extends MinkContext */ public function userGuestAccessIsEnable() { - if (false === $usrId = \User_Adapter::get_usr_id_from_login($this->app, 'invite')) { - $user = \User_Adapter::create( - $this->app, - 'invite', - '', - null, - false, - true - ); - } else { - $user = \User_Adapter::getInstance($usrId, $this->app); + if (null === $user = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) { + $user = $this->app['manipulator.user']->create(User::USER_GUEST, ''); } - $user->ACL()->give_access_to_sbas(array_keys($this->app['phraseanet.appbox']->get_databoxes())); + $this->app['acl']->get($user)->give_access_to_sbas(array_keys($this->app['phraseanet.appbox']->get_databoxes())); foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($databox->get_collections() as $collection) { - $user->ACL()->give_access_to_base(array($collection->get_base_id())); + $this->app['acl']->get($user)->give_access_to_base(array($collection->get_base_id())); } } } @@ -195,12 +179,10 @@ class GuiContext extends MinkContext */ public function userGuestAccessIsDisable() { - if (false !== $usrId = \User_Adapter::get_usr_id_from_login($this->app, 'invite')) { - $user = \User_Adapter::getInstance($usrId, $this->app); - + if (null !== $user = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) { foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($databox->get_collections() as $collection) { - $user->ACL()->revoke_access_from_bases(array($collection->get_base_id())); + $this->app['acl']->get($user)->revoke_access_from_bases(array($collection->get_base_id())); } } } @@ -227,12 +209,10 @@ class GuiContext extends MinkContext */ public function isAuthenticated($login) { - if (false == $usrId = \User_Adapter::get_usr_id_from_login($this->app, $login)) { + if (null === $user = $this->app['manipulator.user']->getRepository()->findByLogin($login)) { throw new \Exception(sprintf('User %s does not exists, use the following definition to create it : a user "%s" exists', $login, $login)); } - $user = \User_Adapter::getInstance($usrId, $this->app); - $this->app['authentication']->openAccount($user); throw new PendingException(); diff --git a/lib/Alchemy/Phrasea/ACL/BasketACL.php b/lib/Alchemy/Phrasea/ACL/BasketACL.php index 75d17296c4..cba34291b0 100644 --- a/lib/Alchemy/Phrasea/ACL/BasketACL.php +++ b/lib/Alchemy/Phrasea/ACL/BasketACL.php @@ -12,11 +12,11 @@ namespace Alchemy\Phrasea\ACL; use Alchemy\Phrasea\Model\Entities\Basket; -use User_Adapter; +use Alchemy\Phrasea\Model\Entities\User; class BasketACL { - public function hasAccess(Basket $basket, User_Adapter $user) + public function hasAccess(Basket $basket, User $user) { if ($this->isOwner($basket, $user)) { return true; @@ -24,7 +24,7 @@ class BasketACL if ($basket->getValidation()) { foreach ($basket->getValidation()->getParticipants() as $participant) { - if ($participant->getUsrId() === $user->get_id()) { + if ($participant->getUser()->getId() === $user->getId()) { return true; } } @@ -33,8 +33,8 @@ class BasketACL return false; } - public function isOwner(Basket $basket, User_Adapter $user) + public function isOwner(Basket $basket, User $user) { - return $basket->getUsrId() === $user->get_id(); + return $basket->getUser()->getId() === $user->getId(); } } diff --git a/lib/Alchemy/Phrasea/Application.php b/lib/Alchemy/Phrasea/Application.php index def0cf4bfc..3f22de834d 100644 --- a/lib/Alchemy/Phrasea/Application.php +++ b/lib/Alchemy/Phrasea/Application.php @@ -111,6 +111,7 @@ use Alchemy\Phrasea\Core\Provider\TokensServiceProvider; use Alchemy\Phrasea\Core\Provider\TranslationServiceProvider; use Alchemy\Phrasea\Core\Provider\UnicodeServiceProvider; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Form\Extension\HelpTypeExtension; use Alchemy\Phrasea\Twig\JSUniqueID; use Alchemy\Phrasea\Twig\Camelize; @@ -773,13 +774,11 @@ class Application extends SilexApplication */ public function isGuestAllowed() { - $usrId = \User_Adapter::get_usr_id_from_login($this, 'invite'); - - if (!$usrId) { + if (null === $user = $this['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) { return false; } - return count($this['acl']->get(\User_Adapter::getInstance($usrId, $this))->get_granted_base()) > 0; + return count($this['acl']->get($user)->get_granted_base()) > 0; } /** diff --git a/lib/Alchemy/Phrasea/Authentication/ACLProvider.php b/lib/Alchemy/Phrasea/Authentication/ACLProvider.php index 88484a05b3..b5b65ee610 100644 --- a/lib/Alchemy/Phrasea/Authentication/ACLProvider.php +++ b/lib/Alchemy/Phrasea/Authentication/ACLProvider.php @@ -37,7 +37,7 @@ class ACLProvider * * @return \ACL */ - public function get(\User_Adapter $user) + public function get(User $user) { if (null !== $acl = $this->fetchFromCache($user)) { return $acl; @@ -61,9 +61,9 @@ class ACLProvider * * @return null || \ACL */ - private function fetchFromCache(\User_Adapter $user) + private function fetchFromCache(User $user) { - return $this->hasCache($user) ? self::$cache[$user->get_id()] : null; + return $this->hasCache($user) ? self::$cache[$user->getId()] : null; } /** @@ -73,9 +73,9 @@ class ACLProvider * * @return boolean */ - private function hasCache(\User_Adapter $user) + private function hasCache(User $user) { - return isset(self::$cache[$user->get_id()]); + return isset(self::$cache[$user->getId()]); } /** @@ -85,8 +85,8 @@ class ACLProvider * * @return \ACL */ - private function fetch(\User_Adapter $user) + private function fetch(User $user) { - return self::$cache[$user->get_id()] = new \ACL($user, $this->app); + return self::$cache[$user->getId()] = new \ACL($user, $this->app); } } diff --git a/lib/Alchemy/Phrasea/Authentication/AccountCreator.php b/lib/Alchemy/Phrasea/Authentication/AccountCreator.php index 6abd30e64b..baa59a1a23 100644 --- a/lib/Alchemy/Phrasea/Authentication/AccountCreator.php +++ b/lib/Alchemy/Phrasea/Authentication/AccountCreator.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Authentication; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\RuntimeException; +use Alchemy\Phrasea\Model\Entities\User; class AccountCreator { @@ -56,7 +57,7 @@ class AccountCreator * @param string $email The email * @param array $templates Some extra templates to apply with the ones of this creator * - * @return \User_Adapter + * @return User * * @throws RuntimeException In case the AccountCreator is disabled * @throws InvalidArgumentException In case a user with the same email already exists @@ -70,16 +71,16 @@ class AccountCreator $login = $id; $n = 1; - if (null !== $email && false !== \User_Adapter::get_usr_id_from_email($app, $email)) { + if (null !== $email && null !== $app['manipulator.user']->getRepository()->findByEmail($email)) { throw new InvalidArgumentException('Provided email already exist in account base.'); } - while (false !== \User_Adapter::get_usr_id_from_login($app, $login)) { + while (null !== $app['manipulator.user']->getRepository()->findByLogin($login)) { $login = $id . '#' . $n; $n++; } - $user = \User_Adapter::create($app, $login, $this->random->generatePassword(), $email, false, false); + $user = $app['manipulator.user']->createUser($login, $this->random->generatePassword(), $email); $base_ids = []; foreach ($this->appbox->get_databoxes() as $databox) { diff --git a/lib/Alchemy/Phrasea/Authentication/Authenticator.php b/lib/Alchemy/Phrasea/Authentication/Authenticator.php index 4a60e7e872..d3d15e8ff9 100644 --- a/lib/Alchemy/Phrasea/Authentication/Authenticator.php +++ b/lib/Alchemy/Phrasea/Authentication/Authenticator.php @@ -13,11 +13,11 @@ namespace Alchemy\Phrasea\Authentication; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Exception\RuntimeException; +use Alchemy\Phrasea\Model\Entities\User; use Browser; use Doctrine\ORM\EntityManager; use Alchemy\Phrasea\Model\Entities\Session; use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class Authenticator { @@ -43,7 +43,7 @@ class Authenticator return $this->user; } - public function setUser(\User_Adapter $user = null) + public function setUser(User $user = null) { $this->user = $user; @@ -53,13 +53,13 @@ class Authenticator /** * Open user session * - * @param \User_Adapter $user + * @param User $user * * @return Session * * @throws \Exception_InternalServerError */ - public function openAccount(\User_Adapter $user) + public function openAccount(User $user) { $this->session->remove('usr_id'); $this->session->remove('session_id'); @@ -69,7 +69,7 @@ class Authenticator ->setBrowserVersion($this->browser->getVersion()) ->setPlatform($this->browser->getPlatform()) ->setUserAgent($this->browser->getUserAgent()) - ->setUsrId($user->get_id()); + ->setUser($user); $this->em->persist($session); $this->em->flush(); @@ -93,7 +93,7 @@ class Authenticator $rights[] = 'task-manager'; } - $this->session->set('usr_id', $user->get_id()); + $this->session->set('usr_id', $user->getId()); $this->session->set('websockets_rights', $rights); $this->session->set('session_id', $session->getId()); } @@ -104,10 +104,8 @@ class Authenticator throw new RuntimeException('Unable to refresh the session, it does not exist anymore'); } - try { - $user = \User_Adapter::getInstance($session->getUsrId(), $this->app); - } catch (NotFoundHttpException $e) { - throw new RuntimeException('Unable to refresh the session', $e->getCode(), $e); + if (null === $user = $session->getUser()) { + throw new RuntimeException('Unable to refresh the session'); } $this->session->clear(); @@ -145,7 +143,7 @@ class Authenticator public function reinitUser() { if ($this->isAuthenticated()) { - $this->user = \User_Adapter::getInstance($this->session->get('usr_id'), $this->app); + $this->user = $this->app['manipulator.user']->getRepository()->find($this->session->get('usr_id')); } else { $this->user = null; } diff --git a/lib/Alchemy/Phrasea/Authentication/Manager.php b/lib/Alchemy/Phrasea/Authentication/Manager.php index bc3779b80e..707fab805a 100644 --- a/lib/Alchemy/Phrasea/Authentication/Manager.php +++ b/lib/Alchemy/Phrasea/Authentication/Manager.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Authentication; use Alchemy\Phrasea\Model\Entities\Session; +use Alchemy\Phrasea\Model\Entities\User; class Manager { @@ -26,11 +27,11 @@ class Manager /** * - * @param \User_Adapter $user + * @param User $user * * @return Session */ - public function openAccount(\User_Adapter $user) + public function openAccount(User $user) { return $this->authenticator->openAccount($user); } diff --git a/lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php b/lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php index ee9e069b89..3b4c082aba 100644 --- a/lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php +++ b/lib/Alchemy/Phrasea/Authentication/Phrasea/NativeAuthentication.php @@ -13,20 +13,22 @@ namespace Alchemy\Phrasea\Authentication\Phrasea; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Authentication\Exception\AccountLockedException; +use Alchemy\Phrasea\Model\Manipulator\UserManipulator; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Request; class NativeAuthentication implements PasswordAuthenticationInterface { - /** @var \connection_interface */ - private $conn; + /** @var UserManipulator */ + private $userManipulator; /** @var PasswordEncoder */ private $encoder; /** @var OldPasswordEncoder */ private $oldEncoder; - public function __construct(PasswordEncoder $encoder, OldPasswordEncoder $oldEncoder, \connection_interface $conn) + public function __construct(PasswordEncoder $encoder, OldPasswordEncoder $oldEncoder, UserManipulator $userManipulator) { - $this->conn = $conn; + $this->userManipulator = $userManipulator; $this->encoder = $encoder; $this->oldEncoder = $oldEncoder; } @@ -36,55 +38,31 @@ class NativeAuthentication implements PasswordAuthenticationInterface */ public function getUsrId($username, $password, Request $request) { - if (in_array($username, ['invite', 'autoregister'])) { + if (null === $user = $this->userManipulator->getRepository()->findRealUserByLogin($username)) { return null; } - $sql = 'SELECT nonce, salted_password, mail_locked, usr_id, usr_login, usr_password - FROM usr - WHERE usr_login = :login - AND usr_login NOT LIKE "(#deleted_%" - AND model_of="0" AND invite="0" - LIMIT 0, 1'; - - $stmt = $this->conn->prepare($sql); - $stmt->execute([':login' => $username]); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if (!$row) { + if ($user->isSpecial()) { return null; } // check locked account - if ('1' == $row['mail_locked']) { - throw new AccountLockedException('The account is locked', $row['usr_id']); + if ($user->isMailLocked()) { + throw new AccountLockedException('The account is locked', $user->getId()); } - if ('0' == $row['salted_password']) { + if (false === $user->isSaltedPassword()) { // we need a quick update and continue - if ($this->oldEncoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) { - - $row['nonce'] = \random::generatePassword(8, \random::LETTERS_AND_NUMBERS); - $row['usr_password'] = $this->encoder->encodePassword($password, $row['nonce']); - - $sql = 'UPDATE usr SET usr_password = :password, nonce = :nonce - WHERE usr_id = :usr_id'; - $stmt = $this->conn->prepare($sql); - $stmt->execute([ - ':password' => $row['usr_password'], - ':nonce' => $row['nonce'], - ':usr_id' => $row['usr_id'], - ]); - $stmt->closeCursor(); + if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { + $this->userManipulator->setPassword($user, $password); } } - if (!$this->encoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) { + if (false === $this->encoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { return null; } - return $row['usr_id']; + return $user->getId(); } /** diff --git a/lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php b/lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php index 92620e2da1..28b6b62ff2 100644 --- a/lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php +++ b/lib/Alchemy/Phrasea/Authentication/SuggestionFinder.php @@ -15,6 +15,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Authentication\Exception\NotAuthenticatedException; use Alchemy\Phrasea\Authentication\Provider\Token\Token; use Alchemy\Phrasea\Authentication\Provider\Token\Identity; +use Alchemy\Phrasea\Model\Entities\User; class SuggestionFinder { @@ -30,7 +31,7 @@ class SuggestionFinder * * @param Token $token * - * @return null|\User_Adapter + * @return null|User * * @throws NotAuthenticatedException In case the token is not authenticated. */ @@ -39,16 +40,7 @@ class SuggestionFinder $infos = $token->getIdentity(); if ($infos->has(Identity::PROPERTY_EMAIL)) { - - $sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':email' => $infos->get(Identity::PROPERTY_EMAIL)]); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if ($row) { - return \User_Adapter::getInstance($row['usr_id'], $this->app); - } + return $this->app['manipulator.user']->getRepository()->findByEmail($infos->get(Identity::PROPERTY_EMAIL)); } return null; diff --git a/lib/Alchemy/Phrasea/CLI.php b/lib/Alchemy/Phrasea/CLI.php index 317c36b892..9698e890c7 100644 --- a/lib/Alchemy/Phrasea/CLI.php +++ b/lib/Alchemy/Phrasea/CLI.php @@ -18,6 +18,7 @@ use Alchemy\Phrasea\Exception\RuntimeException; use Symfony\Component\Console; use Alchemy\Phrasea\Core\CLIProvider\CLIDriversServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\ComposerSetupServiceProvider; +use Alchemy\Phrasea\Core\CLIProvider\DoctrineMigrationServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\LessBuilderServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\PluginServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\SignalHandlerServiceProvider; @@ -31,7 +32,6 @@ use Alchemy\Phrasea\Core\CLIProvider\TaskManagerServiceProvider; */ class CLI extends Application { - /** * Registers the autoloader and necessary components. * @@ -63,6 +63,7 @@ class CLI extends Application $this->register(new SignalHandlerServiceProvider()); $this->register(new TaskManagerServiceProvider()); $this->register(new TranslationExtractorServiceProvider()); + $this->register(new DoctrineMigrationServiceProvider()); $this->bindRoutes(); } diff --git a/lib/Alchemy/Phrasea/Command/CreateCollection.php b/lib/Alchemy/Phrasea/Command/CreateCollection.php index 2cfa3e35a8..320c98f5cd 100644 --- a/lib/Alchemy/Phrasea/Command/CreateCollection.php +++ b/lib/Alchemy/Phrasea/Command/CreateCollection.php @@ -60,9 +60,7 @@ class CreateCollection extends Command } $app = $this->container; - $this->container['manipulator.acl']->resetAdminRights(array_map(function ($id) use ($app) { - return \User_Adapter::getInstance($id, $app); - }, array_keys(\User_Adapter::get_sys_admins($this->container)))); + $this->container['manipulator.acl']->resetAdminRights($this->container['manipulator.user']->getRepository()->findAdmins()); $this->container['dispatcher']->dispatch(PhraseaEvents::COLLECTION_CREATE, new CollectionCreateEvent($new_collection)); } diff --git a/lib/Alchemy/Phrasea/Command/Developer/JsFixtures.php b/lib/Alchemy/Phrasea/Command/Developer/JsFixtures.php index cc0f796689..ade173d278 100644 --- a/lib/Alchemy/Phrasea/Command/Developer/JsFixtures.php +++ b/lib/Alchemy/Phrasea/Command/Developer/JsFixtures.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Command\Developer; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Command\Command; use Alchemy\Phrasea\Exception\RuntimeException; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\HttpKernel\Client; @@ -36,17 +37,10 @@ class JsFixtures extends Command copy($dbRefPath, '/tmp/db.sqlite'); - $user = $this->createUser($this->container); $sbasId = current($this->container['phraseanet.appbox']->get_databoxes())->get_sbas_id(); - - try { - $this->writeResponse($output, 'GET', '/login/', '/home/login/index.html'); - $this->writeResponse($output, 'GET', '/admin/fields/'.$sbasId , '/admin/fields/index.html', $user); - $this->writeResponse($output, 'GET', '/admin/task-manager/tasks', '/admin/task-manager/index.html', $user); - } catch (RuntimeException $e) { - $user->delete(); - throw $e; - } + $this->writeResponse($output, 'GET', '/login/', '/home/login/index.html'); + $this->writeResponse($output, 'GET', '/admin/fields/'.$sbasId , '/admin/fields/index.html', true); + $this->writeResponse($output, 'GET', '/admin/task-manager/tasks', '/admin/task-manager/index.html', true); $this->copy($output, [ ['source' => 'login/common/templates.html.twig', 'target' => 'home/login/templates.html'], @@ -54,11 +48,14 @@ class JsFixtures extends Command ['source' => 'admin/task-manager/templates.html.twig', 'target' => 'admin/task-manager/templates.html'], ]); - $user->delete(); - return 0; } + private function deleteUser(User $user) + { + $this->container['manipulator.user']->delete($user); + } + private function copy(OutputInterface $output, $data) { foreach ($data as $paths) { @@ -82,7 +79,7 @@ class JsFixtures extends Command private function createUser(Application $app) { - $user = \User_Adapter::create($app, uniqid('fixturejs'), uniqid('fixturejs'), uniqid('fixturejs') . '@js.js', true); + $user = $app['manipulator.user']->createUser(uniqid('fixturejs'), uniqid('fixturejs'), uniqid('fixturejs') . '@js.js', true); $app['acl']->get($user)->set_admin(true); $app['manipulator.acl']->resetAdminRights($user); @@ -90,7 +87,7 @@ class JsFixtures extends Command return $user; } - private function loginUser(Application $app, \User_Adapter $user) + private function loginUser(Application $app, User $user) { $app['authentication']->openAccount($user); } @@ -100,10 +97,13 @@ class JsFixtures extends Command $app['authentication']->closeAccount(); } - private function writeResponse(OutputInterface $output, $method, $path, $to, \User_Adapter $user = null) + private function writeResponse(OutputInterface $output, $method, $path, $to, $authenticateUser = false) { $environment = Application::ENV_TEST; $app = require __DIR__ . '/../../Application/Root.php'; + + $user = $this->createUser($app); + // force load of non cached template $app['twig']->enableAutoReload(); $client = new Client($app); @@ -111,19 +111,21 @@ class JsFixtures extends Command $target = sprintf('%s/%s/%s', $app['root.path'],$fixturePath, $to); $output->writeln(sprintf("Generating %s", $target)); - if (null !== $user) { + if ($authenticateUser) { $this->loginUser($app, $user); } $client->request($method, $path); $response = $client->getResponse(); - if (null !== $user) { + if ($authenticateUser) { $this->logoutUser($app); } if (false === $response->isOk()) { + $this->deleteUser($user); throw new RuntimeException(sprintf('Request %s %s returns %d code error', $method, $path, $response->getStatusCode())); } $this->container['filesystem']->mkdir(str_replace(basename($target), '', $target)); $this->container['filesystem']->dumpFile($target, $this->removeHeadTag($this->removeScriptTags($response->getContent()))); + $this->deleteUser($user); } } diff --git a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php index d8e8ad627e..9b2e74bfcb 100644 --- a/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php +++ b/lib/Alchemy/Phrasea/Command/Developer/RegenerateSqliteDb.php @@ -61,7 +61,7 @@ class RegenerateSqliteDb extends Command if (is_file($source)) { $renamed = true; - $fs->rename($source, $target); + $fs->rename($source, $target, true); } try { @@ -92,10 +92,11 @@ class RegenerateSqliteDb extends Command $this->insertLazaretFiles($this->container['EM'], $DI); $this->insertAuthFailures($this->container['EM'], $DI); - $fixtures['user']['test_phpunit'] = $DI['user']->get_id(); - $fixtures['user']['test_phpunit_not_admin'] = $DI['user_notAdmin']->get_id(); - $fixtures['user']['test_phpunit_alt1'] = $DI['user_alt1']->get_id(); - $fixtures['user']['test_phpunit_alt2'] = $DI['user_alt2']->get_id(); + $fixtures['user']['test_phpunit'] = $DI['user']->getId(); + $fixtures['user']['test_phpunit_not_admin'] = $DI['user_notAdmin']->getId(); + $fixtures['user']['test_phpunit_alt1'] = $DI['user_alt1']->getId(); + $fixtures['user']['test_phpunit_alt2'] = $DI['user_alt2']->getId(); + $fixtures['user']['user_guest'] = $DI['user_guest']->getId(); $fixtures['oauth']['user'] = $DI['app-user']->get_id(); $fixtures['oauth']['user_notAdmin'] = $DI['app-user_notAdmin']->get_id(); @@ -134,9 +135,7 @@ class RegenerateSqliteDb extends Command } catch (\Exception $e) { $output->writeln("".$e->getMessage().""); if ($renamed) { - if (is_file($source)) { - unlink($source); - } + $fs->remove($source); $fs->rename($target, $source); } throw $e; @@ -187,6 +186,7 @@ class RegenerateSqliteDb extends Command private function insertLazaretFiles(EntityManager $em, \Pimple $DI) { $session = new LazaretSession(); + $session->setUser($DI['user']); $em->persist($session); $em->flush(); @@ -205,6 +205,7 @@ class RegenerateSqliteDb extends Command $DI['user_alt1'] = $this->getUserAlt1(); $DI['user_alt2'] = $this->getUserAlt2(); $DI['user_notAdmin'] = $this->getUserNotAdmin(); + $DI['user_guest'] = $this->getUserGuest(); $user1 = $this->insertOneUser('user1'); $user2 = $this->insertOneUser('user2', 'user2@phraseanet.com'); @@ -322,44 +323,53 @@ class RegenerateSqliteDb extends Command private function getUser() { - if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit')) { - return \User_Adapter::create($this->container, 'test_phpunit', \random::generatePassword(), 'noone@example.com', false); + if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit')) { + $user = $this->container['manipulator.user']->createUser('test_phpunit', \random::generatePassword(), 'noone@example.com', true); } - return \User_Adapter::getInstance($usr_id, $this->container); + return $user; } private function getUserAlt1() { - if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_alt1')) { - return \User_Adapter::create($this->container, 'test_phpunit_alt1', \random::generatePassword(), 'noonealt1@example.com', false); + if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_alt1')) { + $user = $this->container['manipulator.user']->createUser('test_phpunit_alt1', \random::generatePassword(), 'noonealt1@example.com', false); } - return \User_Adapter::getInstance($usr_id, $this->container); + return $user; } private function getUserAlt2() { - if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_alt2')) { - return \User_Adapter::create($this->container, 'test_phpunit_alt2', \random::generatePassword(), 'noonealt2@example.com', false); + if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_alt2')) { + $user = $this->container['manipulator.user']->createUser('test_phpunit_alt2', \random::generatePassword(), 'noonealt2@example.com', false); } - return \User_Adapter::getInstance($usr_id, $this->container); + return $user; } public function getUserNotAdmin() { - if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_not_admin')) { - return \User_Adapter::create($this->container, 'test_phpunit_not_admin', \random::generatePassword(), 'noone_not_admin@example.com', false); + if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_not_admin')) { + $user = $this->container['manipulator.user']->createUser('test_phpunit_not_admin', \random::generatePassword(), 'noone_not_admin@example.com', false); } - return \User_Adapter::getInstance($usr_id, $this->container); + return $user; + } + + public function getUserGuest() + { + if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) { + $user = $this->container['manipulator.user']->createUser(User::USER_GUEST, User::USER_GUEST); + } + + return $user; } private function insertTwoBasket(EntityManager $em, \Pimple $DI) { $basket1 = new Basket(); - $basket1->setOwner($this->getUser()); + $basket1->setUser($this->getUser()); $basket1->setName('test'); $basket1->setDescription('description test'); @@ -369,12 +379,12 @@ class RegenerateSqliteDb extends Command $element->setBasket($basket1); $basket2 = new Basket(); - $basket2->setOwner($this->getUser()); + $basket2->setUser($this->getUser()); $basket2->setName('test'); $basket2->setDescription('description test'); $basket3 = new Basket(); - $basket3->setOwner($this->getUserAlt1()); + $basket3->setUser($this->getUserAlt1()); $basket3->setName('test'); $basket3->setDescription('description test'); @@ -386,7 +396,7 @@ class RegenerateSqliteDb extends Command $basket4 = new Basket(); $basket4->setName('test'); $basket4->setDescription('description'); - $basket4->setOwner($this->getUser()); + $basket4->setUser($this->getUser()); foreach ([$DI['record_1'], $DI['record_2']] as $record) { $basketElement = new BasketElement(); @@ -490,7 +500,7 @@ class RegenerateSqliteDb extends Command $user = $DI['user']; - $publisher->setUsrId($user->get_id()); + $publisher->setUser($user); $publisher->setIsOwner(true); $publisher->setFeed($feed); @@ -513,7 +523,7 @@ class RegenerateSqliteDb extends Command $user = $DI['user']; - $publisher->setUsrId($user->get_id()); + $publisher->setUser($user); $publisher->setIsOwner(true); $publisher->setFeed($feed); @@ -536,7 +546,7 @@ class RegenerateSqliteDb extends Command $user = $DI['user_alt1']; - $publisher->setUsrId($user->get_id()); + $publisher->setUser($user); $publisher->setIsOwner(true); $publisher->setFeed($feed); @@ -580,7 +590,7 @@ class RegenerateSqliteDb extends Command $token = new FeedToken(); $token->setValue($this->container['tokens']->generatePassword(12)); $token->setFeed($feed); - $token->setUsrId($DI['user']->get_id()); + $token->setUser($DI['user']); $feed->addToken($token); @@ -594,7 +604,7 @@ class RegenerateSqliteDb extends Command $token = new AggregateToken(); $token->setValue($this->container['tokens']->generatePassword(12)); - $token->setUsrId($user->get_id()); + $token->setUser($user); $em->persist($token); } diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Collection.php b/lib/Alchemy/Phrasea/Controller/Admin/Collection.php index 6c1d4392c8..f6a3dc3792 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Collection.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Collection.php @@ -11,6 +11,7 @@ namespace Alchemy\Phrasea\Controller\Admin; +use Alchemy\Phrasea\Exception\RuntimeException; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\JsonResponse; @@ -176,40 +177,45 @@ class Collection implements ControllerProviderInterface public function setOrderAdmins(Application $app, Request $request, $bas_id) { $success = false; + $admins = array_values($request->request->get('admins', [])); - if (count($admins = $request->request->get('admins', [])) > 0) { - $newAdmins = []; + if (count($admins) === 0) { + $app->abort(400, 'No admins provided.'); + } + if (!is_array($admins)) { + $app->abort(400, 'Admins must be an array.'); + } + + $admins = array_map(function ($usrId) use ($app) { + if (null === $user = $app['manipulator.user']->getRepository()->find($usrId)) { + throw new RuntimeException(sprintf('Invalid usrId %s provided.', $usrId)); + } + + return $user; + }, $admins); + + $conn = $app['phraseanet.appbox']->get_connection(); + $conn->beginTransaction(); + + try { + $userQuery = new \User_Query($app); + + $result = $userQuery->on_base_ids([$bas_id]) + ->who_have_right(['order_master']) + ->execute()->get_results(); + + foreach ($result as $user) { + $app['acl']->get($user)->update_rights_to_base($bas_id, ['order_master' => false]); + } foreach ($admins as $admin) { - $newAdmins[] = $admin; - } - - if (count($newAdmins) > 0) { - $conn = $app['phraseanet.appbox']->get_connection(); - $conn->beginTransaction(); - - try { - $userQuery = new \User_Query($app); - - $result = $userQuery->on_base_ids([$bas_id]) - ->who_have_right(['order_master']) - ->execute()->get_results(); - - foreach ($result as $user) { - $app['acl']->get($user)->update_rights_to_base($bas_id, ['order_master' => false]); - } - - foreach (array_filter($newAdmins) as $admin) { - $user = \User_Adapter::getInstance($admin, $app); - $app['acl']->get($user)->update_rights_to_base($bas_id, ['order_master' => true]); - } - $conn->commit(); - - $success = true; - } catch (\Exception $e) { - $conn->rollBack(); - } + $app['acl']->get($admin)->update_rights_to_base($bas_id, ['order_master' => true]); } + $conn->commit(); + $success = true; + } catch (\Exception $e) { + $conn->rollBack(); + throw $e; } return $app->redirectPath('admin_display_collection', [ diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Dashboard.php b/lib/Alchemy/Phrasea/Controller/Admin/Dashboard.php index f53fee9b71..b3d4c5060b 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Dashboard.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Dashboard.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Admin; use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Mail\MailTest; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Exception\RuntimeException; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; @@ -69,7 +70,7 @@ class Dashboard implements ControllerProviderInterface $parameters = [ 'cache_flushed' => $request->query->get('flush_cache') === 'ok', - 'admins' => \User_Adapter::get_sys_admins($app), + 'admins' => $app['manipulator.user']->getRepository()->findAdmins(), 'email_status' => $emailStatus, ]; @@ -132,9 +133,7 @@ class Dashboard implements ControllerProviderInterface */ public function resetAdminRights(Application $app, Request $request) { - $app['manipulator.acl']->resetAdminRights(array_map(function ($id) use ($app) { - return \User_Adapter::getInstance($id, $app); - }, array_keys(\User_Adapter::get_sys_admins($app)))); + $app['manipulator.acl']->resetAdminRights($app['manipulator.user']->getRepository()->findAdmins()); return $app->redirectPath('admin_dashbord'); } @@ -148,19 +147,24 @@ class Dashboard implements ControllerProviderInterface */ public function addAdmins(Application $app, Request $request) { - if (count($admins = $request->request->get('admins', [])) > 0) { - - if (!in_array($app['authentication']->getUser()->get_id(), $admins)) { - $admins[] = $app['authentication']->getUser()->get_id(); - } - - if ($admins > 0) { - \User_Adapter::set_sys_admins($app, array_filter($admins)); - $app['manipulator.acl']->resetAdminRights(array_map(function ($id) use ($app) { - return \User_Adapter::getInstance($id, $app); - }, array_keys(\User_Adapter::get_sys_admins($app)))); - } + $admins = $request->request->get('admins', []); + if (count($admins) === 0 || !is_array($admins)) { + $app->abort(400, '"admins" parameter must contains at least one value.'); } + if (!in_array($app['authentication']->getUser()->getId(), $admins)) { + $admins[] = $app['authentication']->getUser()->getId(); + } + + $admins = array_map(function ($usrId) use ($app) { + if (null === $user = $app['manipulator.user']->getRepository()->find($usrId)) { + throw new RuntimeException(sprintf('Invalid usrId %s provided.', $usrId)); + } + + return $user; + }, $admins); + + $app['manipulator.user']->promote($admins); + $app['manipulator.acl']->resetAdminRights($admins); return $app->redirectPath('admin_dashbord'); } diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Publications.php b/lib/Alchemy/Phrasea/Controller/Admin/Publications.php index f0574df44b..9a20c361a3 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Publications.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Publications.php @@ -52,7 +52,7 @@ class Publications implements ControllerProviderInterface $feed = new Feed(); $publisher->setFeed($feed); - $publisher->setUsrId($app['authentication']->getUser()->get_id()); + $publisher->setUser($app['authentication']->getUser()); $publisher->setIsOwner(true); $feed->addPublisher($publisher); @@ -193,11 +193,11 @@ class Publications implements ControllerProviderInterface $error = ''; try { $request = $app['request']; - $user = \User_Adapter::getInstance($request->request->get('usr_id'), $app); + $user = $app['manipulator.user']->getRepository()->find($request->request->get('usr_id')); $feed = $app["EM"]->find('Phraseanet:Feed', $id); $publisher = new FeedPublisher(); - $publisher->setUsrId($user->get_id()); + $publisher->setUser($user); $publisher->setFeed($feed); $feed->addPublisher($publisher); @@ -226,7 +226,7 @@ class Publications implements ControllerProviderInterface $app->abort(404, "Feed Publisher not found"); } - $user = $publisher->getUser($app); + $user = $publisher->getUser(); if ($feed->isPublisher($user) && !$feed->isOwner($user)) { $feed->removePublisher($publisher); diff --git a/lib/Alchemy/Phrasea/Controller/Admin/Users.php b/lib/Alchemy/Phrasea/Controller/Admin/Users.php index 2f3e47bbec..51f6359efa 100644 --- a/lib/Alchemy/Phrasea/Controller/Admin/Users.php +++ b/lib/Alchemy/Phrasea/Controller/Admin/Users.php @@ -13,6 +13,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 Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\Request; @@ -173,24 +174,23 @@ class Users implements ControllerProviderInterface ]; foreach ($users->export() as $user) { - /* @var $user \User_Adapter */ $userTable[] = [ - $user->get_id(), - $user->get_login(), - $user->get_lastname(), - $user->get_firstname(), - $user->get_email(), - $user->get_creation_date()->format(DATE_ATOM), - $user->get_modification_date()->format(DATE_ATOM), - $user->get_address(), - $user->get_city(), - $user->get_zipcode(), - $user->get_country(), - $user->get_tel(), - $user->get_fax(), - $user->get_job(), - $user->get_company(), - $user->get_position() + $user->getId(), + $user->getLogin(), + $user->getLastName(), + $user->getFirstName(), + $user->getEmail(), + $user->getCreated()->format(DATE_ATOM), + $user->getUpdated()->format(DATE_ATOM), + $user->getAddress(), + $user->getCity(), + $user->getZipCode(), + $user->getCountry(), + $user->getPhone(), + $user->getFax(), + $user->getJob(), + $user->getCompany(), + $user->getActivity() ]; } @@ -241,10 +241,10 @@ class Users implements ControllerProviderInterface foreach ($elligible_users as $user) { $datas[] = [ - 'email' => $user->get_email() ? : '' - , 'login' => $user->get_login() ? : '' - , 'name' => $user->get_display_name() ? : '' - , 'id' => $user->get_id() + 'email' => $user->getEmail() ? : '', + 'login' => $user->getLogin() ? : '', + 'name' => $user->getDisplayName(), + 'id' => $user->getId(), ]; } @@ -252,7 +252,6 @@ class Users implements ControllerProviderInterface }); $controllers->post('/create/', function (Application $app) { - $datas = ['error' => false, 'message' => '', 'data' => null]; try { $request = $app['request']; @@ -262,10 +261,11 @@ class Users implements ControllerProviderInterface } else { $user = $module->create_newuser(); } - if (!($user instanceof \User_Adapter)) + if (!$user instanceof User) { throw new \Exception('Unknown error'); + } - $datas['data'] = $user->get_id(); + $datas['data'] = $user->getId(); } catch (\Exception $e) { $datas['error'] = true; if ($request->request->get('template') == '1') { @@ -296,22 +296,22 @@ class Users implements ControllerProviderInterface $buffer = []; $buffer[] = [ - 'ID' - , 'Login' - , $app->trans('admin::compte-utilisateur nom') - , $app->trans('admin::compte-utilisateur prenom') - , $app->trans('admin::compte-utilisateur email') - , 'CreationDate' - , 'ModificationDate' - , $app->trans('admin::compte-utilisateur adresse') - , $app->trans('admin::compte-utilisateur ville') - , $app->trans('admin::compte-utilisateur code postal') - , $app->trans('admin::compte-utilisateur pays') - , $app->trans('admin::compte-utilisateur telephone') - , $app->trans('admin::compte-utilisateur fax') - , $app->trans('admin::compte-utilisateur poste') - , $app->trans('admin::compte-utilisateur societe') - , $app->trans('admin::compte-utilisateur activite') + 'ID', + 'Login', + $app->trans('admin::compte-utilisateur nom'), + $app->trans('admin::compte-utilisateur prenom'), + $app->trans('admin::compte-utilisateur email'), + 'CreationDate', + 'ModificationDate', + $app->trans('admin::compte-utilisateur adresse'), + $app->trans('admin::compte-utilisateur ville'), + $app->trans('admin::compte-utilisateur code postal'), + $app->trans('admin::compte-utilisateur pays'), + $app->trans('admin::compte-utilisateur telephone'), + $app->trans('admin::compte-utilisateur fax'), + $app->trans('admin::compte-utilisateur poste'), + $app->trans('admin::compte-utilisateur societe'), + $app->trans('admin::compte-utilisateur activite'), ]; do { $elligible_users->limit($offset, 20); @@ -321,22 +321,22 @@ class Users implements ControllerProviderInterface foreach ($results as $user) { $buffer[] = [ - $user->get_id() - , $user->get_login() - , $user->get_lastname() - , $user->get_firstname() - , $user->get_email() - , $app['date-formatter']->format_mysql($user->get_creation_date()) - , $app['date-formatter']->format_mysql($user->get_modification_date()) - , $user->get_address() - , $user->get_city() - , $user->get_zipcode() - , $user->get_country() - , $user->get_tel() - , $user->get_fax() - , $user->get_job() - , $user->get_company() - , $user->get_position() + $user->getId(), + $user->getLogin(), + $user->getLastName(), + $user->getFirstName(), + $user->getEmail(), + $app['date-formatter']->format_mysql($user->getCreated()), + $app['date-formatter']->format_mysql($user->getUpdated()), + $user->getAddress(), + $user->getCity(), + $user->getZipCode(), + $user->getCountry(), + $user->getPhone(), + $user->getFax(), + $user->getJob(), + $user->getCompany(), + $user->getActivity(), ]; } } while (count($results) > 0); @@ -354,51 +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(); - $baslist = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])); - - $sql = 'SELECT usr_id, usr_login FROM usr WHERE model_of = :usr_id'; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $app['authentication']->getUser()->get_id()]); - $models = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $sql = " - SELECT demand.date_modif,demand.base_id, usr.usr_id , usr.usr_login ,usr.usr_nom,usr.usr_prenom, - usr.societe, usr.fonction, usr.usr_mail, usr.tel, usr.activite, - usr.adresse, usr.cpostal, usr.ville, usr.pays, CONCAT(usr.usr_nom,' ',usr.usr_prenom,'\n',fonction,' (',societe,')') AS info - FROM (demand INNER JOIN usr on demand.usr_id=usr.usr_id AND demand.en_cours=1 AND usr.usr_login NOT LIKE '(#deleted%' ) - WHERE (base_id='" . implode("' OR base_id='", $baslist) . "') ORDER BY demand.usr_id DESC,demand.base_id ASC - "; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $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 = ['user' => [], 'coll' => []]; + $table = ['users' => [], 'coll' => []]; - foreach ($rs as $row) { - if ($row['usr_id'] != $currentUsr) { - $currentUsr = $row['usr_id']; - $row['date_modif'] = new \DateTime($row['date_modif']); - $table['user'][$row['usr_id']] = $row; + foreach ($app['EM.native-query']->getUsersRegistrationDemand($basList) as $row) { + $user = $row[0]; + + if ($user->getId() !== $currentUsr) { + $currentUsr = $user->getId(); + $table['users'][$currentUsr] = [ + 'user' => $user, + 'date_demand' => $row['date_demand'], + ]; } - if (!isset($table['coll'][$row['usr_id']])) { - $table['coll'][$row['usr_id']] = []; + if (!isset($table['coll'][$user->getId()])) { + $table['coll'][$user->getId()] = []; } - if (!in_array($row['base_id'], $table['coll'][$row['usr_id']])) { - $table['coll'][$row['usr_id']][] = $row['base_id']; + if (!in_array($row['base_demand'], $table['coll'][$user->getId()])) { + $table['coll'][$user->getId()][] = $row['base_demand']; } } @@ -458,10 +442,10 @@ class Users implements ControllerProviderInterface $cache_to_update = []; foreach ($templates as $usr => $template_id) { - $user = \User_Adapter::getInstance($usr, $app); + $user = $app['manipulator.user']->getRepository()->find($usr); $cache_to_update[$usr] = true; - $user_template = \User_Adapter::getInstance($template_id, $app); + $user_template = $app['manipulator.user']->getRepository()->find($template_id); $base_ids = array_keys($app['acl']->get($user_template)->get_granted_base()); $app['acl']->get($user)->apply_model($user_template, $base_ids); @@ -507,18 +491,18 @@ class Users implements ControllerProviderInterface $stmt->closeCursor(); foreach ($accept as $usr => $bases) { - $user = \User_Adapter::getInstance($usr, $app); + $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' + '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]); @@ -538,23 +522,15 @@ class Users implements ControllerProviderInterface } foreach (array_keys($cache_to_update) as $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $app); + $user = $app['manipulator.user']->getRepository()->find($usr_id); $app['acl']->get($user)->delete_data_from_cache(); unset($user); } foreach ($done as $usr => $bases) { - $sql = 'SELECT usr_mail FROM usr WHERE usr_id = :usr_id'; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $usr]); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - $acceptColl = $denyColl = []; - - if ($row) { - if (\Swift_Validate::email($row['usr_mail'])) { + if (null !== $user = $app['manipulator.user']->getRepository()->find($usr)) { + if (\Swift_Validate::email($user->getEmail())) { foreach ($bases as $bas => $isok) { if ($isok) { $acceptColl[] = \phrasea::bas_labels($bas, $app); @@ -571,7 +547,7 @@ class Users implements ControllerProviderInterface $message .= "\n" . $app->trans('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . implode(', ', $denyColl) . "\n"; } - $receiver = new Receiver(null, $row['usr_mail']); + $receiver = new Receiver(null, $user->getEmail()); $mail = MailSuccessEmailUpdate::create($app, $receiver, null, $message); $app['notification.deliverer']->deliver($mail); @@ -667,7 +643,7 @@ class Users implements ControllerProviderInterface } elseif (in_array($loginToAdd, $loginNew)) { $out['errors'][] = $app->trans("Login %login% is already defined in the file at line %line%", ['%login%' => $loginToAdd, '%line%' => $nbLine]); } else { - if (\User_Adapter::get_usr_id_from_login($app, $loginToAdd)) { + if (null !== $app['manipulator.user']->getRepository()->findByLogin($loginToAdd)) { $out['errors'][] = $app->trans("Login %login% already exists in database", ['%login%' => $loginToAdd]); } else { $loginValid = true; @@ -680,7 +656,7 @@ class Users implements ControllerProviderInterface if ($mailToAdd === "") { $out['errors'][] = $app->trans("Mail line %line% is empty", ['%line%' => $nbLine + 1]); - } elseif (false !== \User_Adapter::get_usr_id_from_email($app, $mailToAdd)) { + } elseif (null !== $app['manipulator.user']->getRepository()->findByEmail($mailToAdd)) { $out['errors'][] = $app->trans("Email '%email%' for login '%login%' already exists in database", ['%email%' => $mailToAdd, '%login%' => $loginToAdd]); } else { $mailValid = true; @@ -716,20 +692,8 @@ class Users implements ControllerProviderInterface ]); } - $sql = " - SELECT usr.usr_id,usr.usr_login - FROM usr - INNER JOIN basusr - ON (basusr.usr_id=usr.usr_id) - WHERE usr.model_of = :usr_id - AND base_id in(" . implode(', ', array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))) . ") - AND usr_login not like '(#deleted_%)' - GROUP BY usr_id"; - - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $app['authentication']->getUser()->get_id()]); - $models = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage'])); + $models = $app['EM.native-query']->getModelForUser($app['authentication']->getUser(), $basList); return $app['twig']->render('/admin/user/import/view.html.twig', [ 'nb_user_to_add' => $nbUsrToAdd, @@ -807,12 +771,13 @@ class Users implements ControllerProviderInterface if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== '' && isset($curUser['usr_password']) && trim($curUser['usr_password']) !== '' && isset($curUser['usr_mail']) && trim($curUser['usr_mail']) !== '') { - if (false === \User_Adapter::get_usr_id_from_login($app, $curUser['usr_login']) - && false === \User_Adapter::get_usr_id_from_email($app, $curUser['usr_mail'])) { - $NewUser = \User_Adapter::create($app, $curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail'], false); + if (null === $app['manipulator.user']->getRepository()->findByLogin($curUser['usr_login']) + && false === $app['manipulator.user']->getRepository()->findByEmail($curUser['usr_mail'])) { + + $newUser = $app['manipulator.user']->createUser($curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail']); $ftpCredential = new FtpCredential(); - $ftpCredential->setUsrId($NewUser->get_id()); + $ftpCredential->setUser($newUser); if (isset($curUser['activeFTP'])) { $ftpCredential->setActive((int) $curUser['activeFTP']); @@ -830,38 +795,38 @@ class Users implements ControllerProviderInterface $ftpCredential->setRepositoryPrefixName($curUser['prefixFTPfolder']); } if (isset($curUser['usr_prenom'])) { - $NewUser->set_firstname($curUser['usr_prenom']); + $newUser->setFirstName($curUser['usr_prenom']); } if (isset($curUser['usr_nom'])) { - $NewUser->set_lastname($curUser['usr_nom']); + $newUser->setLastName($curUser['usr_nom']); } if (isset($curUser['adresse'])) { - $NewUser->set_address($curUser['adresse']); + $newUser->setAdress($curUser['adresse']); } if (isset($curUser['cpostal'])) { - $NewUser->set_zip($curUser['cpostal']); + $newUser->setZipCode($curUser['cpostal']); } if (isset($curUser['usr_sexe'])) { - $NewUser->set_gender((int) ($curUser['usr_sexe'])); + $newUser->setGender((int) ($curUser['usr_sexe'])); } if (isset($curUser['tel'])) { - $NewUser->set_tel($curUser['tel']); + $newUser->setPhone($curUser['tel']); } if (isset($curUser['fax'])) { - $NewUser->set_fax($curUser['fax']); + $newUser->setFax($curUser['fax']); } if (isset($curUser['activite'])) { - $NewUser->set_job($curUser['activite']); + $newUser->setJob($curUser['activite']); } if (isset($curUser['fonction'])) { - $NewUser->set_position($curUser['fonction']); + $newUser->setPosition($curUser['fonction']); } if (isset($curUser['societe'])) { - $NewUser->set_company($curUser['societe']); + $newUser->setCompany($curUser['societe']); } - $app['acl']->get($NewUser)->apply_model( - \User_Adapter::getInstance($model, $app), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage'])) + $app['acl']->get($newUser)->apply_model( + $app['manipulator.user']->getRepository()->find($model), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage'])) ); $nbCreation++; diff --git a/lib/Alchemy/Phrasea/Controller/Api/Oauth2.php b/lib/Alchemy/Phrasea/Controller/Api/Oauth2.php index 87a9d7044f..8471828907 100644 --- a/lib/Alchemy/Phrasea/Controller/Api/Oauth2.php +++ b/lib/Alchemy/Phrasea/Controller/Api/Oauth2.php @@ -91,7 +91,7 @@ class Oauth2 implements ControllerProviderInterface return $app->redirectPath('oauth2_authorize', ['error' => 'account-locked']); } - $app['authentication']->openAccount(\User_Adapter::getInstance($usr_id, $app)); + $app['authentication']->openAccount($app['manipulator.user']->getRepository()->find($usr_id)); } return new Response($app['twig']->render($template, ["auth" => $oauth2_adapter])); @@ -109,7 +109,7 @@ class Oauth2 implements ControllerProviderInterface } } - $account = $oauth2_adapter->updateAccount($app['authentication']->getUser()->get_id()); + $account = $oauth2_adapter->updateAccount($app['authentication']->getUser()->getId()); $params['account_id'] = $account->get_id(); diff --git a/lib/Alchemy/Phrasea/Controller/Api/V1.php b/lib/Alchemy/Phrasea/Controller/Api/V1.php index 9ff9766bc2..c5ff5b05a8 100644 --- a/lib/Alchemy/Phrasea/Controller/Api/V1.php +++ b/lib/Alchemy/Phrasea/Controller/Api/V1.php @@ -82,7 +82,7 @@ class V1 implements ControllerProviderInterface return; } - $user = \User_Adapter::getInstance($oauth2_adapter->get_usr_id(), $app); + $user = $app['manipulator.user']->getRepository()->find($oauth2_adapter->get_usr_id()); $app['authentication']->openAccount($user); $oauth2_adapter->remember_this_ses_id($app['session']->get('session_id')); diff --git a/lib/Alchemy/Phrasea/Controller/Client/Baskets.php b/lib/Alchemy/Phrasea/Controller/Client/Baskets.php index 151c3b8016..9e80571d1d 100644 --- a/lib/Alchemy/Phrasea/Controller/Client/Baskets.php +++ b/lib/Alchemy/Phrasea/Controller/Client/Baskets.php @@ -111,7 +111,7 @@ class Baskets implements ControllerProviderInterface try { $basket = new Basket(); $basket->setName($request->request->get('p0')); - $basket->setOwner($app['authentication']->getUser()); + $basket->setUser($app['authentication']->getUser()); $app['EM']->persist($basket); $app['EM']->flush(); @@ -180,7 +180,7 @@ class Baskets implements ControllerProviderInterface } $basketCollections = $baskets->partition(function ($key, $basket) { - return (Boolean) $basket->getPusherId(); + return null !== $basket->getPusher(); }); return $app['twig']->render('client/baskets.html.twig', [ diff --git a/lib/Alchemy/Phrasea/Controller/Client/Root.php b/lib/Alchemy/Phrasea/Controller/Client/Root.php index b1e135c434..c5bb2cf3ab 100644 --- a/lib/Alchemy/Phrasea/Controller/Client/Root.php +++ b/lib/Alchemy/Phrasea/Controller/Client/Root.php @@ -91,14 +91,14 @@ class Root implements ControllerProviderInterface $result = $app['phraseanet.SE']->query($query, ($currentPage - 1) * $perPage, $perPage, $options); $userQuery = new UserQuery(); - $userQuery->setUsrId($app['authentication']->getUser()->get_id()); + $userQuery->setUser($app['authentication']->getUser()); $userQuery->setQuery($query); $app['EM']->persist($userQuery); $app['EM']->flush(); - if ($app['authentication']->getUser()->getPrefs('start_page') === 'LAST_QUERY') { - $app['authentication']->getUser()->setPrefs('start_page_query', $query); + if ($app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page') === 'LAST_QUERY') { + $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), 'start_page_query', $query); } foreach ($options->getDataboxes() as $databox) { @@ -171,7 +171,7 @@ class Root implements ControllerProviderInterface 'per_page' => $perPage, 'search_engine' => $app['phraseanet.SE'], 'search_engine_option' => $options->serialize(), - 'history' => \queries::history($app, $app['authentication']->getUser()->get_id()), + 'history' => \queries::history($app, $app['authentication']->getUser()->getId()), 'result' => $result, 'proposals' => $currentPage === 1 ? $result->getProposals() : null, 'help' => count($resultData) === 0 ? $this->getHelpStartPage($app) : '', @@ -253,7 +253,7 @@ class Root implements ControllerProviderInterface } return new Response($app['twig']->render('client/index.html.twig', [ - 'last_action' => !$app['authentication']->getUser()->is_guest() && false !== $request->cookies->has('last_act') ? $request->cookies->has('last_act') : null, + 'last_action' => !$app['authentication']->getUser()->isGuest() && false !== $request->cookies->has('last_act') ? $request->cookies->has('last_act') : null, 'phrasea_home' => $this->getDefaultClientStartPage($app), 'render_topics' => $renderTopics, 'grid_properties' => $this->getGridProperty(), @@ -261,12 +261,12 @@ class Root implements ControllerProviderInterface 'storage_access' => $this->getDocumentStorageAccess($app), 'tabs_setup' => $this->getTabSetup($app), 'module' => 'client', - 'menubar' => $app['twig']->render('common/menubar.html.twig', ['module' => 'client']), + 'menubar' => $app['twig']->render('common/menubar.html.twig', ['module' => 'client']), 'css_file' => $this->getCssFile($app), - 'basket_status' => null !== $app['authentication']->getUser()->getPrefs('client_basket_status') ? $app['authentication']->getUser()->getPrefs('client_basket_status') : "1", - 'mod_pres' => null !== $app['authentication']->getUser()->getPrefs('client_view') ? $app['authentication']->getUser()->getPrefs('client_view') : '', - 'start_page' => $app['authentication']->getUser()->getPrefs('start_page'), - 'start_page_query' => null !== $app['authentication']->getUser()->getPrefs('start_page_query') ? $app['authentication']->getUser()->getPrefs('start_page_query') : '' + 'basket_status' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_basket_status', '1'), + 'mod_pres' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_view', '' ), + 'start_page' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page'), + 'start_page_query' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page_query', '') ])); } @@ -350,7 +350,7 @@ class Root implements ControllerProviderInterface $cssPath = __DIR__ . '/../../../../../www/skins/client/'; $css = []; - $cssFile = $app['authentication']->getUser()->getPrefs('client_css'); + $cssFile = $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_css'); $finder = new Finder(); @@ -418,7 +418,7 @@ class Root implements ControllerProviderInterface */ private function getDefaultClientStartPage(Application $app) { - $startPage = strtoupper($app['authentication']->getUser()->getPrefs('start_page')); + $startPage = strtoupper($app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page')); if ($startPage === 'PUBLI') { return $this->getPublicationStartPage($app); @@ -441,7 +441,7 @@ class Root implements ControllerProviderInterface { $collections = $queryParameters = []; - $searchSet = json_decode($app['authentication']->getUser()->getPrefs('search')); + $searchSet = json_decode($app['settings']->getUserSetting($app['authentication']->getUser(), 'search')); if ($searchSet && isset($searchSet->bases)) { foreach ($searchSet->bases as $bases) { @@ -451,9 +451,9 @@ class Root implements ControllerProviderInterface $collections = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base()); } - $queryParameters["mod"] = $app['authentication']->getUser()->getPrefs('client_view') ?: '3X6'; + $queryParameters["mod"] = $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_view', '3X6'); $queryParameters["bas"] = $collections; - $queryParameters["qry"] = $app['authentication']->getUser()->getPrefs('start_page_query') ?: 'all'; + $queryParameters["qry"] = $app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page_query', 'all'); $queryParameters["pag"] = 0; $queryParameters["search_type"] = SearchEngineOptions::RECORD_RECORD; $queryParameters["qryAdv"] = ''; @@ -479,7 +479,7 @@ class Root implements ControllerProviderInterface { return $app['twig']->render('client/home_inter_pub_basket.html.twig', [ 'feeds' => Aggregate::createFromUser($app, $app['authentication']->getUser()), - 'image_size' => (int) $app['authentication']->getUser()->getPrefs('images_size') + 'image_size' => (int) $app['settings']->getUserSetting($app['authentication']->getUser(), 'images_size') ]); } diff --git a/lib/Alchemy/Phrasea/Controller/Lightbox.php b/lib/Alchemy/Phrasea/Controller/Lightbox.php index c1b83b56f8..e198cda1ce 100644 --- a/lib/Alchemy/Phrasea/Controller/Lightbox.php +++ b/lib/Alchemy/Phrasea/Controller/Lightbox.php @@ -44,7 +44,7 @@ class Lightbox implements ControllerProviderInterface return $app->redirectPath('homepage'); } - $app['authentication']->openAccount(\User_Adapter::getInstance($usr_id, $app)); + $app['authentication']->openAccount($app['manipulator.user']->getRepository()->find($usr_id)); try { $datas = $app['tokens']->helloToken($request->query->get('LOG')); @@ -221,9 +221,9 @@ class Lightbox implements ControllerProviderInterface $app['EM']->flush(); } - if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->getIsAware() === false) { + if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) { $basket = $app['EM']->merge($basket); - $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); + $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true); $app['EM']->flush(); } @@ -268,9 +268,9 @@ class Lightbox implements ControllerProviderInterface $app['EM']->flush(); } - if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->getIsAware() === false) { + if ($basket->getValidation() && $basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) { $basket = $app['EM']->merge($basket); - $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); + $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true); $app['EM']->flush(); } @@ -350,7 +350,7 @@ class Lightbox implements ControllerProviderInterface $basket_element = $repository->findUserElement($sselcont_id, $app['authentication']->getUser()); - $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser(), $app); + $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser()); $validationDatas->setNote($note); @@ -400,11 +400,11 @@ class Lightbox implements ControllerProviderInterface , $app['authentication']->getUser() ); /* @var $basket_element BasketElement */ - $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser(), $app); + $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser()); if (!$basket_element->getBasket() ->getValidation() - ->getParticipant($app['authentication']->getUser(), $app)->getCanAgree()) { + ->getParticipant($app['authentication']->getUser())->getCanAgree()) { throw new ControllerException('You can not agree on this'); } @@ -412,7 +412,7 @@ class Lightbox implements ControllerProviderInterface $participant = $basket_element->getBasket() ->getValidation() - ->getParticipant($app['authentication']->getUser(), $app); + ->getParticipant($app['authentication']->getUser()); $app['EM']->merge($basket_element); @@ -446,14 +446,14 @@ class Lightbox implements ControllerProviderInterface throw new ControllerException('There is no validation session attached to this basket'); } - if (!$basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->getCanAgree()) { + if (!$basket->getValidation()->getParticipant($app['authentication']->getUser())->getCanAgree()) { throw new ControllerException('You have not right to agree'); } $agreed = false; /* @var $basket Basket */ foreach ($basket->getElements() as $element) { - if (null !== $element->getUserValidationDatas($app['authentication']->getUser(), $app)->getAgreement()) { + if (null !== $element->getUserValidationDatas($app['authentication']->getUser())->getAgreement()) { $agreed = true; } } @@ -463,20 +463,20 @@ class Lightbox implements ControllerProviderInterface } /* @var $basket Basket */ - $participant = $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app); + $participant = $basket->getValidation()->getParticipant($app['authentication']->getUser()); $expires = new \DateTime('+10 days'); $url = $app->url('lightbox', ['LOG' => $app['tokens']->getUrlToken( \random::TYPE_VALIDATE - , $basket->getValidation()->getInitiator($app)->get_id() + , $basket->getValidation()->getInitiator($app)->getId() , $expires , $basket->getId() )]); - $to = $basket->getValidation()->getInitiator($app)->get_id(); + $to = $basket->getValidation()->getInitiator($app)->getId(); $params = [ 'ssel_id' => $basket->getId(), - 'from' => $app['authentication']->getUser()->get_id(), + 'from' => $app['authentication']->getUser()->getId(), 'url' => $url, 'to' => $to ]; diff --git a/lib/Alchemy/Phrasea/Controller/Permalink.php b/lib/Alchemy/Phrasea/Controller/Permalink.php index 261a3c1d14..d6c438c54c 100644 --- a/lib/Alchemy/Phrasea/Controller/Permalink.php +++ b/lib/Alchemy/Phrasea/Controller/Permalink.php @@ -154,16 +154,14 @@ class Permalink extends AbstractDelivery $watermark = $stamp = false; if ($app['authentication']->isAuthenticated()) { - $user = \User_Adapter::getInstance($app['authentication']->getUser()->get_id(), $app); - - $watermark = !$app['acl']->get($user)->has_right_on_base($record->get_base_id(), 'nowatermark'); + $watermark = !$app['acl']->get($app['authentication']->getUser())->has_right_on_base($record->get_base_id(), 'nowatermark'); if ($watermark) { $repository = $app['EM']->getRepository('Phraseanet:BasketElement'); - if (count($repository->findReceivedValidationElementsByRecord($record, $user)) > 0) { + if (count($repository->findReceivedValidationElementsByRecord($record, $app['authentication']->getUser())) > 0) { $watermark = false; - } elseif (count($repository->findReceivedElementsByRecord($record, $user)) > 0) { + } elseif (count($repository->findReceivedElementsByRecord($record, $app['authentication']->getUser())) > 0) { $watermark = false; } } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/BasketController.php b/lib/Alchemy/Phrasea/Controller/Prod/BasketController.php index 9fd56f5a0e..b85ce05f0a 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/BasketController.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/BasketController.php @@ -99,8 +99,8 @@ class BasketController implements ControllerProviderInterface } if ($basket->getValidation()) { - if ($basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->getIsAware() === false) { - $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); + if ($basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) { + $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true); $app['EM']->flush(); } } @@ -118,7 +118,7 @@ class BasketController implements ControllerProviderInterface $Basket = new BasketEntity(); $Basket->setName($request->request->get('name', '')); - $Basket->setOwner($app['authentication']->getUser()); + $Basket->setUser($app['authentication']->getUser()); $Basket->setDescription($request->request->get('desc')); $app['EM']->persist($Basket); diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php b/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php index 81e82ba00a..26c6566f5d 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Bridge.php @@ -173,7 +173,7 @@ class Bridge implements ControllerProviderInterface try { $account = \Bridge_Account::load_account($app, $account_id); - if ($account->get_user()->get_id() !== $app['authentication']->getUser()->get_id()) { + if ($account->get_user()->getId() !== $app['authentication']->getUser()->getId()) { throw new HttpException(403, 'Access forbiden'); } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Download.php b/lib/Alchemy/Phrasea/Controller/Prod/Download.php index 07f93f6fc1..778491c79d 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Download.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Download.php @@ -66,7 +66,7 @@ class Download implements ControllerProviderInterface $token = $app['tokens']->getUrlToken( \random::TYPE_DOWNLOAD, - $app['authentication']->getUser()->get_id(), + $app['authentication']->getUser()->getId(), new \DateTime('+3 hours'), // Token lifetime serialize($list) ); @@ -77,7 +77,7 @@ class Download implements ControllerProviderInterface $app['events-manager']->trigger('__DOWNLOAD__', [ 'lst' => $lst, - 'downloader' => $app['authentication']->getUser()->get_id(), + 'downloader' => $app['authentication']->getUser()->getId(), 'subdefs' => $subdefs, 'from_basket' => $ssttid, 'export_file' => $download->getExportName() diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Export.php b/lib/Alchemy/Phrasea/Controller/Prod/Export.php index b5b43c8398..51d617b63c 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Export.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Export.php @@ -206,7 +206,7 @@ class Export implements ControllerProviderInterface $destMails[] = $mail; } else { $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ - 'usr_id' => $app['authentication']->getUser()->get_id(), + 'usr_id' => $app['authentication']->getUser()->getId(), 'lst' => $lst, 'ssttid' => $ssttid, 'dest' => $mail, @@ -232,7 +232,7 @@ class Export implements ControllerProviderInterface $url = $app->url('prepare_download', ['token' => $token, 'anonymous']); - $emitter = new Emitter($app['authentication']->getUser()->get_display_name(), $app['authentication']->getUser()->get_email()); + $emitter = new Emitter($app['authentication']->getUser()->getDisplayName(), $app['authentication']->getUser()->getEmail()); foreach ($destMails as $key => $mail) { try { @@ -253,7 +253,7 @@ class Export implements ControllerProviderInterface if (count($remaingEmails) > 0) { foreach ($remaingEmails as $mail) { $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ - 'usr_id' => $app['authentication']->getUser()->get_id(), + 'usr_id' => $app['authentication']->getUser()->getId(), 'lst' => $lst, 'ssttid' => $ssttid, 'dest' => $mail, @@ -264,7 +264,7 @@ class Export implements ControllerProviderInterface } elseif (!$token && count($destMails) > 0) { //couldn't generate token foreach ($destMails as $mail) { $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ - 'usr_id' => $app['authentication']->getUser()->get_id(), + 'usr_id' => $app['authentication']->getUser()->getId(), 'lst' => $lst, 'ssttid' => $ssttid, 'dest' => $mail, diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Feed.php b/lib/Alchemy/Phrasea/Controller/Prod/Feed.php index afe6feac1c..7fca8a6eb6 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Feed.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Feed.php @@ -49,7 +49,7 @@ class Feed implements ControllerProviderInterface $app->abort(404, "Feed not found"); } - $publisher = $app['EM']->getRepository('Phraseanet:FeedPublisher')->findOneBy(['feed' => $feed, 'usrId' => $app['authentication']->getUser()->get_id()]); + $publisher = $app['EM']->getRepository('Phraseanet:FeedPublisher')->findOneBy(['feed' => $feed, 'user' => $app['authentication']->getUser()]); if ('' === $title = trim($request->request->get('title', ''))) { $app->abort(400, "Bad request"); diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Order.php b/lib/Alchemy/Phrasea/Controller/Prod/Order.php index 56e3f38ae8..7c58d9a599 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Order.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Order.php @@ -94,7 +94,7 @@ class Order implements ControllerProviderInterface if (!$records->isEmpty()) { $order = new OrderEntity(); - $order->setUsrId($app['authentication']->getUser()->get_id()); + $order->setUser($app['authentication']->getUser()); $order->setDeadline((null !== $deadLine = $request->request->get('deadline')) ? new \DateTime($deadLine) : $deadLine); $order->setOrderUsage($request->request->get('use', '')); foreach ($records as $key => $record) { @@ -144,7 +144,7 @@ class Order implements ControllerProviderInterface try { $app['events-manager']->trigger('__NEW_ORDER__', [ 'order_id' => $order->getId(), - 'usr_id' => $order->getUsrId() + 'usr_id' => $order->getUser()->getId() ]); $success = true; @@ -237,19 +237,15 @@ class Order implements ControllerProviderInterface public function sendOrder(Application $app, Request $request, $order_id) { $success = false; - $order = $app['EM']->getRepository('Phraseanet:Order')->find($order_id); - if (null === $order) { + if (null === $order = $app['EM']->getRepository('Phraseanet:Order')->find($order_id)) { throw new NotFoundHttpException('Order not found'); } - - $dest_user = \User_Adapter::getInstance($order->getUsrId(), $app); - $basket = $order->getBasket(); if (null === $basket) { $basket = new Basket(); $basket->setName($app->trans('Commande du %date%', ['%date%' => $order->getCreatedOn()->format('Y-m-d')])); - $basket->setOwner($dest_user); + $basket->setUser($order->getUser()); $basket->setPusher($app['authentication']->getUser()); $app['EM']->persist($basket); @@ -267,14 +263,14 @@ class Order implements ControllerProviderInterface $basketElement->setRecord($record); $basketElement->setBasket($basket); - $orderElement->setOrderMasterId($app['authentication']->getUser()->get_id()); + $orderElement->setOrderMaster($app['authentication']->getUser()); $orderElement->setDeny(false); $orderElement->getOrder()->setBasket($basket); $basket->addElement($basketElement); $n++; - $app['acl']->get($dest_user)->grant_hd_on($record, $app['authentication']->getUser(), 'order'); + $app['acl']->get($basket->getUser())->grant_hd_on($record, $app['authentication']->getUser(), 'order'); } } @@ -284,8 +280,8 @@ class Order implements ControllerProviderInterface $app['events-manager']->trigger('__ORDER_DELIVER__', [ 'ssel_id' => $order->getBasket()->getId(), - 'from' => $app['authentication']->getUser()->get_id(), - 'to' => $dest_user->get_id(), + 'from' => $app['authentication']->getUser()->getId(), + 'to' => $order->getUser()->getId(), 'n' => $n ]); } @@ -333,7 +329,7 @@ class Order implements ControllerProviderInterface $elements = $request->request->get('elements', []); foreach ($order->getElements() as $orderElement) { if (in_array($orderElement->getId(),$elements)) { - $orderElement->setOrderMasterId($app['authentication']->getUser()->get_id()); + $orderElement->setOrderMaster($app['authentication']->getUser()); $orderElement->setDeny(true); $app['EM']->persist($orderElement); @@ -346,8 +342,8 @@ class Order implements ControllerProviderInterface $order->setTodo($order->getTodo() - $n); $app['events-manager']->trigger('__ORDER_NOT_DELIVERED__', [ - 'from' => $app['authentication']->getUser()->get_id(), - 'to' => $order->getUsrId(), + 'from' => $app['authentication']->getUser()->getId(), + 'to' => $order->getUser()->getId(), 'n' => $n ]); } diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Push.php b/lib/Alchemy/Phrasea/Controller/Prod/Push.php index 14910240b9..c249d73bef 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Push.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Push.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Controller\Prod; use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Model\Entities\BasketElement; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\UsrList; use Alchemy\Phrasea\Model\Entities\UsrListEntry; use Alchemy\Phrasea\Model\Entities\ValidationSession; @@ -28,26 +29,26 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class Push implements ControllerProviderInterface { - protected function getUserFormatter() + protected function getUserFormatter(Application $app) { - return function (\User_Adapter $user) { - $subtitle = array_filter([$user->get_job(), $user->get_company()]); + return function (User $user) use ($app) { + $subtitle = array_filter([$user->getJob(), $user->getCompany()]); return [ - 'type' => 'USER' - , 'usr_id' => $user->get_id() - , 'firstname' => $user->get_firstname() - , 'lastname' => $user->get_lastname() - , 'email' => $user->get_email() - , 'display_name' => $user->get_display_name() - , 'subtitle' => implode(', ', $subtitle) + 'type' => 'USER', + 'usr_id' => $user->getId(), + 'firstname' => $user->getFirstName(), + 'lastname' => $user->getLastName(), + 'email' => $user->getEmail(), + 'display_name' => $user->getDisplayName(), + 'subtitle' => implode(', ', $subtitle), ]; }; } protected function getListFormatter($app) { - $userFormatter = $this->getUserFormatter(); + $userFormatter = $this->getUserFormatter($app); return function (UsrList $List) use ($userFormatter, $app) { $entries = []; @@ -56,16 +57,16 @@ class Push implements ControllerProviderInterface /* @var $entry UsrListEntry */ $entries[] = [ 'Id' => $entry->getId(), - 'User' => $userFormatter($entry->getUser($app)) + 'User' => $userFormatter($entry->getUser()) ]; } return [ - 'type' => 'LIST' - , 'list_id' => $List->getId() - , 'name' => $List->getName() - , 'length' => count($entries) - , 'entries' => $entries + 'type' => 'LIST', + 'list_id' => $List->getId(), + 'name' => $List->getName(), + 'length' => count($entries), + 'entries' => $entries, ]; }; } @@ -87,7 +88,7 @@ class Push implements ControllerProviderInterface $user = $value->getRessource(); - $Users->set($user->get_id(), $user); + $Users->set($user->getId(), $user); } } } @@ -108,7 +109,7 @@ class Push implements ControllerProviderInterface $app['firewall']->requireRight('push'); }); - $userFormatter = $this->getUserFormatter(); + $userFormatter = $this->getUserFormatter($app); $listFormatter = $this->getListFormatter($app); @@ -161,7 +162,7 @@ class Push implements ControllerProviderInterface try { $pusher = new RecordHelper\Push($app, $app['request']); - $push_name = $request->request->get('name', $app->trans('Push from %user%', ['%user%' => $app['authentication']->getUser()->get_display_name()])); + $push_name = $request->request->get('name', $app->trans('Push from %user%', ['%user%' => $app['authentication']->getUser()->getDisplayName()])); $push_description = $request->request->get('push_description'); $receivers = $request->request->get('participants'); @@ -176,7 +177,7 @@ class Push implements ControllerProviderInterface foreach ($receivers as $receiver) { try { - $user_receiver = \User_Adapter::getInstance($receiver['usr_id'], $app); + $user_receiver = $app['manipulator.user']->getRepository()->find($receiver['usr_id']); } catch (\Exception $e) { throw new ControllerException($app->trans('Unknown user %user_id%', ['%user_id%' => $receiver['usr_id']])); } @@ -184,7 +185,7 @@ class Push implements ControllerProviderInterface $Basket = new Basket(); $Basket->setName($push_name); $Basket->setDescription($push_description); - $Basket->setOwner($user_receiver); + $Basket->setUser($user_receiver); $Basket->setPusher($app['authentication']->getUser()); $Basket->setIsRead(false); @@ -220,31 +221,31 @@ class Push implements ControllerProviderInterface 'basket' => $Basket->getId(), 'LOG' => $app['tokens']->getUrlToken( \random::TYPE_VIEW, - $user_receiver->get_id(), + $user_receiver->getId(), null, $Basket->getId() ) ]); - $receipt = $request->get('recept') ? $app['authentication']->getUser()->get_email() : ''; + $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : ''; $params = [ - 'from' => $app['authentication']->getUser()->get_id() - , 'from_email' => $app['authentication']->getUser()->get_email() - , 'to' => $user_receiver->get_id() - , 'to_email' => $user_receiver->get_email() - , 'to_name' => $user_receiver->get_display_name() - , 'url' => $url - , 'accuse' => $receipt - , 'message' => $request->request->get('message') - , 'ssel_id' => $Basket->getId() + 'from' => $app['authentication']->getUser()->getId(), + 'from_email' => $app['authentication']->getUser()->getEmail(), + 'to' => $user_receiver->getId(), + 'to_email' => $user_receiver->getEmail(), + 'to_name' => $user_receiver->getDisplayName(), + 'url' => $url, + 'accuse' => $receipt, + 'message' => $request->request->get('message'), + 'ssel_id' => $Basket->getId(), ]; $app['events-manager']->trigger('__PUSH_DATAS__', $params); } $app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox()) - ->log($BasketElement->getRecord($app), \Session_Logger::EVENT_VALIDATE, $user_receiver->get_id(), ''); + ->log($BasketElement->getRecord($app), \Session_Logger::EVENT_VALIDATE, $user_receiver->getId(), ''); $app['EM']->flush(); @@ -277,9 +278,7 @@ class Push implements ControllerProviderInterface try { $pusher = new RecordHelper\Push($app, $app['request']); - $repository = $app['EM']->getRepository('Phraseanet:Basket'); - - $validation_name = $request->request->get('name', $app->trans('Validation from %user%', ['%user%' => $app['authentication']->getUser()->get_display_name()])); + $validation_name = $request->request->get('name', $app->trans('Validation from %user%', ['%user%' => $app['authentication']->getUser()->getDisplayName()])); $validation_description = $request->request->get('validation_description'); $participants = $request->request->get('participants'); @@ -298,7 +297,7 @@ class Push implements ControllerProviderInterface $Basket = new Basket(); $Basket->setName($validation_name); $Basket->setDescription($validation_description); - $Basket->setOwner($app['authentication']->getUser()); + $Basket->setUser($app['authentication']->getUser()); $Basket->setIsRead(false); $app['EM']->persist($Basket); @@ -336,17 +335,17 @@ class Push implements ControllerProviderInterface } $found = false; - foreach ($participants as $key => $participant) { - if ($participant['usr_id'] == $app['authentication']->getUser()->get_id()) { + foreach ($participants as $participant) { + if ($participant['usr_id'] === $app['authentication']->getUser()->getId()) { $found = true; break; } } if (!$found) { - $participants[$app['authentication']->getUser()->get_id()] = [ + $participants[] = [ 'see_others' => 1, - 'usr_id' => $app['authentication']->getUser()->get_id(), + 'usr_id' => $app['authentication']->getUser()->getId(), 'agree' => 0, 'HD' => 0 ]; @@ -359,13 +358,13 @@ class Push implements ControllerProviderInterface } try { - $participant_user = \User_Adapter::getInstance($participant['usr_id'], $app); + $participant_user = $app['manipulator.user']->getRepository()->find($participant['usr_id']); } catch (\Exception $e) { throw new ControllerException($app->trans('Unknown user %usr_id%', ['%usr_id%' => $participant['usr_id']])); } try { - $Participant = $Validation->getParticipant($participant_user, $app); + $Participant = $Validation->getParticipant($participant_user); continue; } catch (NotFoundHttpException $e) { @@ -404,7 +403,7 @@ class Push implements ControllerProviderInterface $app['EM']->persist($ValidationData); $app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox()) - ->log($BasketElement->getRecord($app), \Session_Logger::EVENT_PUSH, $participant_user->get_id(), ''); + ->log($BasketElement->getRecord($app), \Session_Logger::EVENT_PUSH, $participant_user->getId(), ''); $Participant->addData($ValidationData); } @@ -417,20 +416,20 @@ class Push implements ControllerProviderInterface 'basket' => $Basket->getId(), 'LOG' => $app['tokens']->getUrlToken( \random::TYPE_VALIDATE, - $participant_user->get_id(), + $participant_user->getId(), null, $Basket->getId() ) ]); - $receipt = $request->get('recept') ? $app['authentication']->getUser()->get_email() : ''; + $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : ''; $params = [ - 'from' => $app['authentication']->getUser()->get_id(), - 'from_email' => $app['authentication']->getUser()->get_email(), - 'to' => $participant_user->get_id(), - 'to_email' => $participant_user->get_email(), - 'to_name' => $participant_user->get_display_name(), + 'from' => $app['authentication']->getUser()->getId(), + 'from_email' => $app['authentication']->getUser()->getEmail(), + 'to' => $participant_user->getId(), + 'to_email' => $participant_user->getEmail(), + 'to_name' => $participant_user->getDisplayName(), 'url' => $url, 'accuse' => $receipt, 'message' => $request->request->get('message'), @@ -494,7 +493,7 @@ class Push implements ControllerProviderInterface $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); if ($list) { $datas = $listFormatter($list); @@ -533,8 +532,7 @@ class Push implements ControllerProviderInterface $email = $request->request->get('email'); try { - $usr_id = \User_Adapter::get_usr_id_from_email($app, $email); - $user = \User_Adapter::getInstance($usr_id, $app); + $user = $app['manipulator.user']->getRepository()->findByEmail($email); $result['message'] = $app->trans('User already exists'); $result['success'] = true; @@ -543,21 +541,24 @@ class Push implements ControllerProviderInterface } - if (!$user instanceof \User_Adapter) { + if (!$user instanceof User) { try { $password = \random::generatePassword(); - $user = \User_Adapter::create($app, $email, $password, $email, false); + $user = $app['manipulator.user']->getRepository()->createUser($email, $password, $email); - $user->set_firstname($request->request->get('firstname')) - ->set_lastname($request->request->get('lastname')); + $user->setFirstName($request->request->get('firstname')) + ->setLastName($request->request->get('lastname')); - if ($request->request->get('company')) - $user->set_company($request->request->get('company')); - if ($request->request->get('job')) - $user->set_company($request->request->get('job')); - if ($request->request->get('form_geonameid')) - $user->set_geonameid($request->request->get('form_geonameid')); + if ($request->request->get('company')) { + $user->setCompany($request->request->get('company')); + } + if ($request->request->get('job')) { + $user->setCompany($request->request->get('job')); + } + if ($request->request->get('form_geonameid')) { + $app['manipulator.user']->setGeonameId($user, $request->request->get('form_geonameid')); + } $result['message'] = $app->trans('User successfully created'); $result['success'] = true; @@ -617,7 +618,7 @@ class Push implements ControllerProviderInterface $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); $query = new \User_Query($app); diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Query.php b/lib/Alchemy/Phrasea/Controller/Prod/Query.php index d926da2426..b973b411db 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Query.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Query.php @@ -12,7 +12,6 @@ namespace Alchemy\Phrasea\Controller\Prod; use Alchemy\Phrasea\SearchEngine\SearchEngineOptions; -use Alchemy\Phrasea\Model\Entities\UserQuery; use Silex\Application; use Silex\ControllerProviderInterface; use Symfony\Component\HttpFoundation\JsonResponse; @@ -52,7 +51,7 @@ class Query implements ControllerProviderInterface { $query = (string) $request->request->get('qry'); - $mod = $app['authentication']->getUser()->getPrefs('view'); + $mod = $app['settings']->getUserSetting($app['authentication']->getUser(), 'view'); $json = []; @@ -60,7 +59,7 @@ class Query implements ControllerProviderInterface $form = $options->serialize(); - $perPage = (int) $app['authentication']->getUser()->getPrefs('images_per_page'); + $perPage = (int) $app['settings']->getUserSetting($app['authentication']->getUser(), 'images_per_page'); $page = (int) $request->request->get('pag'); $firstPage = $page < 1; @@ -72,15 +71,10 @@ class Query implements ControllerProviderInterface $result = $app['phraseanet.SE']->query($query, (($page - 1) * $perPage), $perPage, $options); - $userQuery = new UserQuery(); - $userQuery->setUsrId($app['authentication']->getUser()->get_id()); - $userQuery->setQuery($result->getQuery()); + $app['manipulator.user']->logQuery($app['authentication']->getUser(), $result->getQuery()); - $app['EM']->persist($userQuery); - $app['EM']->flush(); - - if ($app['authentication']->getUser()->getPrefs('start_page') === 'LAST_QUERY') { - $app['authentication']->getUser()->setPrefs('start_page_query', $result->getQuery()); + if ($app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page') === 'LAST_QUERY') { + $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), 'start_page_query', $result->getQuery()); } foreach ($options->getDataboxes() as $databox) { diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Root.php b/lib/Alchemy/Phrasea/Controller/Prod/Root.php index 284938fbb1..3c96a27cb8 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Root.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Root.php @@ -65,7 +65,7 @@ class Root implements ControllerProviderInterface $css[$baseName] = $baseName; } - $cssfile = $app['authentication']->getUser()->getPrefs('css'); + $cssfile = $app['settings']->getUserSetting($app['authentication']->getUser(), 'css'); if (!$cssfile && isset($css['000000'])) { $cssfile = '000000'; @@ -119,7 +119,7 @@ class Root implements ControllerProviderInterface 'GV_google_api' => $app['conf']->get(['registry', 'webservices', 'google-charts-enabled']), 'queries_topics' => $queries_topics, 'search_status' => \databox_status::getSearchStatus($app), - 'queries_history' => \queries::history($app, $app['authentication']->getUser()->get_id()), + 'queries_history' => \queries::history($app, $app['authentication']->getUser()->getId()), 'thesau_js_list' => $thjslist, 'thesau_json_sbas' => json_encode($sbas), 'thesau_json_bas2sbas' => json_encode($bas2sbas), diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php b/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php index 56eb7f4d08..aff22b4728 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Tooltip.php @@ -89,7 +89,7 @@ class Tooltip implements ControllerProviderInterface public function displayUserBadge(Application $app, $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $app); + $user = $app['manipulator.user']->getRepository()->find($usr_id); return $app['twig']->render( 'prod/Tooltip/User.html.twig' diff --git a/lib/Alchemy/Phrasea/Controller/Prod/Upload.php b/lib/Alchemy/Phrasea/Controller/Prod/Upload.php index 1a4919d6d6..5ad126e045 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/Upload.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/Upload.php @@ -158,7 +158,7 @@ class Upload implements ControllerProviderInterface $collection = \collection::get_from_base_id($app, $base_id); $lazaretSession = new LazaretSession(); - $lazaretSession->setUsrId($app['authentication']->getUser()->get_id()); + $lazaretSession->setUser($app['authentication']->getUser()); $app['EM']->persist($lazaretSession); diff --git a/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php b/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php index db89ed8a4c..78e32df93a 100644 --- a/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php +++ b/lib/Alchemy/Phrasea/Controller/Prod/UsrLists.php @@ -91,24 +91,24 @@ class UsrLists implements ControllerProviderInterface foreach ($list->getOwners() as $owner) { $owners[] = [ - 'usr_id' => $owner->getUser($app)->get_id(), - 'display_name' => $owner->getUser($app)->get_display_name(), - 'position' => $owner->getUser($app)->get_position(), - 'job' => $owner->getUser($app)->get_job(), - 'company' => $owner->getUser($app)->get_company(), - 'email' => $owner->getUser($app)->get_email(), + 'usr_id' => $owner->getUser()->getId(), + 'display_name' => $owner->getUser()->getDisplayName(), + 'position' => $owner->getUser()->getActivity(), + 'job' => $owner->getUser()->getJob(), + 'company' => $owner->getUser()->getCompany(), + 'email' => $owner->getUser()->getEmail(), 'role' => $owner->getRole() ]; } foreach ($list->getEntries() as $entry) { $entries[] = [ - 'usr_id' => $owner->getUser($app)->get_id(), - 'display_name' => $owner->getUser($app)->get_display_name(), - 'position' => $owner->getUser($app)->get_position(), - 'job' => $owner->getUser($app)->get_job(), - 'company' => $owner->getUser($app)->get_company(), - 'email' => $owner->getUser($app)->get_email(), + 'usr_id' => $entry->getUser()->getId(), + 'display_name' => $entry->getUser()->getDisplayName(), + 'position' => $entry->getUser()->getActivity(), + 'job' => $entry->getUser()->getJob(), + 'company' => $entry->getUser()->getCompany(), + 'email' => $entry->getUser()->getEmail(), ]; } @@ -195,31 +195,31 @@ class UsrLists implements ControllerProviderInterface { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); $entries = new ArrayCollection(); $owners = new ArrayCollection(); foreach ($list->getOwners() as $owner) { $owners[] = [ - 'usr_id' => $owner->getUser($app)->get_id(), - 'display_name' => $owner->getUser($app)->get_display_name(), - 'position' => $owner->getUser($app)->get_position(), - 'job' => $owner->getUser($app)->get_job(), - 'company' => $owner->getUser($app)->get_company(), - 'email' => $owner->getUser($app)->get_email(), - 'role' => $owner->getRole($app) + 'usr_id' => $owner->getUser()->getId(), + 'display_name' => $owner->getUser()->getDisplayName(), + 'position' => $owner->getUser()->getActivity(), + 'job' => $owner->getUser()->getJob(), + 'company' => $owner->getUser()->getCompany(), + 'email' => $owner->getUser()->getEmail(), + 'role' => $owner->getRole() ]; } foreach ($list->getEntries() as $entry) { $entries[] = [ - 'usr_id' => $entry->getUser($app)->get_id(), - 'display_name' => $entry->getUser($app)->get_display_name(), - 'position' => $entry->getUser($app)->get_position(), - 'job' => $entry->getUser($app)->get_job(), - 'company' => $entry->getUser($app)->get_company(), - 'email' => $entry->getUser($app)->get_email(), + 'usr_id' => $entry->getUser()->getId(), + 'display_name' => $entry->getUser()->getDisplayName(), + 'position' => $entry->getUser()->getActivity(), + 'job' => $entry->getUser()->getJob(), + 'company' => $entry->getUser()->getCompany(), + 'email' => $entry->getUser()->getEmail(), ]; } @@ -253,7 +253,7 @@ class UsrLists implements ControllerProviderInterface $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_EDITOR) { throw new ControllerException($app->trans('You are not authorized to do this')); @@ -284,9 +284,9 @@ class UsrLists implements ControllerProviderInterface try { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_ADMIN) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_ADMIN) { throw new ControllerException($app->trans('You are not authorized to do this')); } @@ -318,10 +318,10 @@ class UsrLists implements ControllerProviderInterface try { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); /* @var $list UsrList */ - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_EDITOR) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_EDITOR) { throw new ControllerException($app->trans('You are not authorized to do this')); } @@ -360,19 +360,19 @@ class UsrLists implements ControllerProviderInterface $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); /* @var $list UsrList */ - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_EDITOR) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_EDITOR) { throw new ControllerException($app->trans('You are not authorized to do this')); } $inserted_usr_ids = []; foreach ($request->request->get('usr_ids') as $usr_id) { - $user_entry = \User_Adapter::getInstance($usr_id, $app); + $user_entry = $app['manipulator.user']->getRepository()->find($usr_id); - if ($list->has($user_entry, $app)) + if ($list->has($user_entry)) continue; $entry = new UsrListEntry(); @@ -383,7 +383,7 @@ class UsrLists implements ControllerProviderInterface $app['EM']->persist($entry); - $inserted_usr_ids[] = $user_entry->get_id(); + $inserted_usr_ids[] = $user_entry->getId(); } $app['EM']->flush(); @@ -424,10 +424,10 @@ class UsrLists implements ControllerProviderInterface try { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); /* @var $list UsrList */ - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_ADMIN) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_ADMIN) { $list = null; throw new \Exception($app->trans('You are not authorized to do this')); } @@ -454,21 +454,21 @@ class UsrLists implements ControllerProviderInterface try { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); /* @var $list UsrList */ - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_EDITOR) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_EDITOR) { throw new ControllerException($app->trans('You are not authorized to do this')); } - $new_owner = \User_Adapter::getInstance($usr_id, $app); + $new_owner = $app['manipulator.user']->getRepository()->find($usr_id); - if ($list->hasAccess($new_owner, $app)) { - if ($new_owner->get_id() == $app['authentication']->getUser()->get_id()) { + if ($list->hasAccess($new_owner)) { + if ($new_owner->getId() == $app['authentication']->getUser()->getId()) { throw new ControllerException('You can not downgrade your Admin right'); } - $owner = $list->getOwner($new_owner, $app); + $owner = $list->getOwner($new_owner); } else { $owner = new UsrListOwner(); $owner->setList($list); @@ -510,10 +510,10 @@ class UsrLists implements ControllerProviderInterface try { $repository = $app['EM']->getRepository('Phraseanet:UsrList'); - $list = $repository->findUserListByUserAndId($app, $app['authentication']->getUser(), $list_id); + $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id); /* @var $list UsrList */ - if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_ADMIN) { + if ($list->getOwner($app['authentication']->getUser())->getRole() < UsrListOwner::ROLE_ADMIN) { throw new \Exception($app->trans('You are not authorized to do this')); } diff --git a/lib/Alchemy/Phrasea/Controller/RecordsRequest.php b/lib/Alchemy/Phrasea/Controller/RecordsRequest.php index 634f05f4d6..e22c4fa2eb 100644 --- a/lib/Alchemy/Phrasea/Controller/RecordsRequest.php +++ b/lib/Alchemy/Phrasea/Controller/RecordsRequest.php @@ -242,7 +242,6 @@ class RecordsRequest extends ArrayCollection $to_remove = []; foreach ($elements as $id => $record) { - if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_record($record)) { $to_remove[] = $id; continue; diff --git a/lib/Alchemy/Phrasea/Controller/Root/Account.php b/lib/Alchemy/Phrasea/Controller/Root/Account.php index 1a956f3c4e..6be7b357c8 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Account.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Account.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Root; use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface; use Alchemy\Phrasea\Application as PhraseaApplication; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\FtpCredential; use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate; use Alchemy\Phrasea\Form\Login\PhraseaRenewPasswordForm; @@ -75,13 +76,6 @@ class Account implements ControllerProviderInterface return $controllers; } - /** - * Reset Password - * - * @param Application $app - * @param Request $request - * @return Response - */ public function resetPassword(Application $app, Request $request) { $form = $app->form(new PhraseaRenewPasswordForm()); @@ -93,8 +87,8 @@ class Account implements ControllerProviderInterface $data = $form->getData(); $user = $app['authentication']->getUser(); - if ($app['auth.password-encoder']->isPasswordValid($user->get_password(), $data['oldPassword'], $user->get_nonce())) { - $user->set_password($data['password']); + if ($app['auth.password-encoder']->isPasswordValid($user->getPassword(), $data['oldPassword'], $user->getNonce())) { + $app['manipulator.user']->setPassword($user, $data['password']); $app->addFlash('success', $app->trans('login::notification: Mise a jour du mot de passe avec succes')); return $app->redirectPath('account'); @@ -126,7 +120,7 @@ class Account implements ControllerProviderInterface $user = $app['authentication']->getUser(); - if (!$app['auth.password-encoder']->isPasswordValid($user->get_password(), $password, $user->get_nonce())) { + if (!$app['auth.password-encoder']->isPasswordValid($user->getPassword(), $password, $user->getNonce())) { $app->addFlash('error', $app->trans('admin::compte-utilisateur:ftp: Le mot de passe est errone')); return $app->redirectPath('account_reset_email'); @@ -145,7 +139,7 @@ class Account implements ControllerProviderInterface } $date = new \DateTime('1 day'); - $token = $app['tokens']->getUrlToken(\random::TYPE_EMAIL, $app['authentication']->getUser()->get_id(), $date, $app['authentication']->getUser()->get_email()); + $token = $app['tokens']->getUrlToken(\random::TYPE_EMAIL, $app['authentication']->getUser()->getId(), $date, $app['authentication']->getUser()->getEmail()); $url = $app->url('account_reset_email', ['token' => $token]); try { @@ -179,8 +173,8 @@ class Account implements ControllerProviderInterface if (null !== $token = $request->query->get('token')) { try { $datas = $app['tokens']->helloToken($token); - $user = \User_Adapter::getInstance((int) $datas['usr_id'], $app); - $user->set_email($datas['datas']); + $user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id']); + $user->setEmail($datas['datas']); $app['tokens']->removeToken($token); $app->addFlash('success', $app->trans('admin::compte-utilisateur: L\'email a correctement ete mis a jour')); @@ -240,7 +234,7 @@ class Account implements ControllerProviderInterface 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()->get_id()) + 'inscriptions' => giveMeBases($app, $app['authentication']->getUser()->getId()) ]); } @@ -268,7 +262,7 @@ class Account implements ControllerProviderInterface public function accountSessionsAccess(Application $app, Request $request) { $dql = 'SELECT s FROM Phraseanet:Session s - WHERE s.usr_id = :usr_id + WHERE s.user = :usr_id ORDER BY s.created DESC'; $query = $app['EM']->createQuery($dql); @@ -321,7 +315,7 @@ class Account implements ControllerProviderInterface return $app['twig']->render('account/account.html.twig', [ 'user' => $app['authentication']->getUser(), 'evt_mngr' => $app['events-manager'], - 'notifications' => $app['events-manager']->list_notifications_available($app['authentication']->getUser()->get_id()), + 'notifications' => $app['events-manager']->list_notifications_available($app['authentication']->getUser()->getId()), ]); } @@ -337,11 +331,9 @@ class Account implements ControllerProviderInterface $demands = (array) $request->request->get('demand', []); if (0 !== count($demands)) { - $register = new \appbox_register($app['phraseanet.appbox']); - foreach ($demands as $baseId) { try { - $register->add_request($app['authentication']->getUser(), \collection::get_from_base_id($app, $baseId)); + $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) { @@ -370,53 +362,48 @@ class Account implements ControllerProviderInterface ]; if (0 === count(array_diff($accountFields, array_keys($request->request->all())))) { + $app['authentication']->getUser() + ->setGender($request->request->get("form_gender")) + ->setFirstName($request->request->get("form_firstname")) + ->setLastName($request->request->get("form_lastname")) + ->setAddress($request->request->get("form_address")) + ->setZipCode($request->request->get("form_zip")) + ->setPhone($request->request->get("form_phone")) + ->setFax($request->request->get("form_fax")) + ->setJob($request->request->get("form_activity")) + ->setCompany($request->request->get("form_company")) + ->setActivity($request->request->get("form_function")) + ->setMailNotificationsActivated((Boolean) $request->request->get("mail_notifications")); - try { - $app['phraseanet.appbox']->get_connection()->beginTransaction(); + $app['manipulator.user']->setGeonameId($app['authentication']->getUser(), $request->request->get("form_geonameid")); - $app['authentication']->getUser() - ->set_gender($request->request->get("form_gender")) - ->set_firstname($request->request->get("form_firstname")) - ->set_lastname($request->request->get("form_lastname")) - ->set_address($request->request->get("form_address")) - ->set_zip($request->request->get("form_zip")) - ->set_tel($request->request->get("form_phone")) - ->set_fax($request->request->get("form_fax")) - ->set_job($request->request->get("form_activity")) - ->set_company($request->request->get("form_company")) - ->set_position($request->request->get("form_function")) - ->set_geonameid($request->request->get("form_geonameid")) - ->set_mail_notifications((bool) $request->request->get("mail_notifications")); + $ftpCredential = $app['authentication']->getUser()->getFtpCredential(); - $ftpCredential = $app['authentication']->getUser()->getFtpCredential(); - - $ftpCredential->setActive($request->request->get("form_activeFTP")); - $ftpCredential->setAddress($request->request->get("form_addressFTP")); - $ftpCredential->setLogin($request->request->get("form_loginFTP")); - $ftpCredential->setPassword($request->request->get("form_pwdFTP")); - $ftpCredential->setPassive($request->request->get("form_passifFTP")); - $ftpCredential->setReceptionFolder($request->request->get("form_destFTP")); - $ftpCredential->setRepositoryPrefixName($request->request->get("form_prefixFTPfolder")); - - $app['phraseanet.appbox']->get_connection()->commit(); - $app['EM']->persist($ftpCredential); - $app['EM']->flush(); - $app->addFlash('success', $app->trans('login::notification: Changements enregistres')); - } catch (\Exception $e) { - $app->addFlash('error', $app->trans('forms::erreurs lors de l\'enregistrement des modifications')); - $app['phraseanet.appbox']->get_connection()->rollBack(); + if (null === $ftpCredential) { + $ftpCredential = new FtpCredential(); + $ftpCredential->setUser($app['authentication']->getUser()); } + + $ftpCredential->setActive($request->request->get("form_activeFTP")); + $ftpCredential->setAddress($request->request->get("form_addressFTP")); + $ftpCredential->setLogin($request->request->get("form_loginFTP")); + $ftpCredential->setPassword($request->request->get("form_pwdFTP")); + $ftpCredential->setPassive($request->request->get("form_passifFTP")); + $ftpCredential->setReceptionFolder($request->request->get("form_destFTP")); + $ftpCredential->setRepositoryPrefixName($request->request->get("form_prefixFTPfolder")); + + $app['EM']->persist($ftpCredential); + $app['EM']->persist($app['authentication']->getUser()); + + $app['EM']->flush(); + $app->addFlash('success', $app->trans('login::notification: Changements enregistres')); } $requestedNotifications = (array) $request->request->get('notifications', []); - foreach ($app['events-manager']->list_notifications_available($app['authentication']->getUser()->get_id()) as $notifications) { + foreach ($app['events-manager']->list_notifications_available($app['authentication']->getUser()->getId()) as $notifications) { foreach ($notifications as $notification) { - if (isset($requestedNotifications[$notification['id']])) { - $app['authentication']->getUser()->set_notification_preference($app, $notification['id'], '1'); - } else { - $app['authentication']->getUser()->set_notification_preference($app, $notification['id'], '0'); - } + $app['manipulator.user']->setNotificationSetting($app['authentication']->getUser(), $notification['id'], isset($requestedNotifications[$notification['id']])); } } diff --git a/lib/Alchemy/Phrasea/Controller/Root/Login.php b/lib/Alchemy/Phrasea/Controller/Root/Login.php index 74b6a12357..5313885f83 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Login.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Login.php @@ -23,6 +23,7 @@ use Alchemy\Phrasea\Core\PhraseaEvents; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\FormProcessingException; use Alchemy\Phrasea\Exception\RuntimeException; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\ValidationParticipant; use Alchemy\Phrasea\Model\Entities\UsrAuthProvider; use Alchemy\Phrasea\Notification\Receiver; @@ -308,7 +309,7 @@ class Login implements ControllerProviderInterface ->findWithProviderAndId($token->getProvider()->getId(), $token->getId()); if (null !== $userAuthProvider) { - $this->postAuthProcess($app, $userAuthProvider->getUser($app)); + $this->postAuthProcess($app, $userAuthProvider->getUser()); if (null !== $redirect = $request->query->get('redirect')) { $redirection = '../' . $redirect; @@ -339,7 +340,6 @@ class Login implements ControllerProviderInterface $inscOK = []; foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { - foreach ($databox->get_collections() as $collection) { if (null !== $selected && !in_array($collection->get_base_id(), $selected)) { continue; @@ -362,26 +362,32 @@ class Login implements ControllerProviderInterface $data['login'] = $data['email']; } - $user = \User_Adapter::create($app, $data['login'], $data['password'], $data['email'], false); + $user = $app['manipulator.user']->createUser($data['login'], $data['password'], $data['email'], false); + + if (isset($data['geonameid'])) { + $app['manipulator.user']->setGeonameId($user, $data['geonameid']); + } foreach ([ - 'gender' => 'set_gender', - 'firstname' => 'set_firstname', - 'lastname' => 'set_lastname', - 'address' => 'set_address', - 'zipcode' => 'set_zip', - 'tel' => 'set_tel', - 'fax' => 'set_fax', - 'job' => 'set_job', - 'company' => 'set_company', - 'position' => 'set_position', - 'geonameid' => 'set_geonameid', + 'gender' => 'setGender', + 'firstname' => 'setFirstName', + 'lastname' => 'setLastName', + 'address' => 'setAddress', + 'zipcode' => 'setZipCode', + 'tel' => 'setPhone', + 'fax' => 'setFax', + 'job' => 'setJob', + 'company' => 'setCompany', + 'position' => 'setActivity', ] as $property => $method) { if (isset($data[$property])) { call_user_func([$user, $method], $data[$property]); } } + $app['EM']->persist($user); + $app['EM']->flush(); + if (null !== $provider) { $this->attachProviderToUser($app['EM'], $provider, $user); $app['EM']->flush(); @@ -390,43 +396,39 @@ class Login implements ControllerProviderInterface $demandOK = []; if ($app['conf']->get(['registry', 'registration', 'auto-register-enabled'])) { - - $template_user_id = \User_Adapter::get_usr_id_from_login($app, 'autoregister'); - - $template_user = \User_Adapter::getInstance($template_user_id, $app); + $template_user = $app['manipulator.user']->getRepository()->findByLogin(User::USER_AUTOREGISTER); $base_ids = []; foreach (array_keys($inscOK) as $base_id) { $base_ids[] = $base_id; } + $app['acl']->get($user)->apply_model($template_user, $base_ids); } $autoReg = $app['acl']->get($user)->get_granted_base(); - $appbox_register = new \appbox_register($app['phraseanet.appbox']); - foreach ($inscOK as $base_id => $autorisation) { if (false === $autorisation || $app['acl']->get($user)->has_access_to_base($base_id)) { continue; } $collection = \collection::get_from_base_id($app, $base_id); - $appbox_register->add_request($user, $collection); + $app['phraseanet.appbox-register']->add_request($user, $collection); $demandOK[$base_id] = true; } $params = [ 'demand' => $demandOK, 'autoregister' => $autoReg, - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; $app['events-manager']->trigger('__REGISTER_AUTOREGISTER__', $params); $app['events-manager']->trigger('__REGISTER_APPROVAL__', $params); - $user->set_mail_locked(true); + $user->setMailLocked(true); try { $this->sendAccountUnlockEmail($app, $user); @@ -462,12 +464,12 @@ class Login implements ControllerProviderInterface ])); } - private function attachProviderToUser(EntityManager $em, ProviderInterface $provider, \User_Adapter $user) + private function attachProviderToUser(EntityManager $em, ProviderInterface $provider, User $user) { $usrAuthProvider = new UsrAuthProvider(); $usrAuthProvider->setDistantId($provider->getToken()->getId()); $usrAuthProvider->setProvider($provider->getId()); - $usrAuthProvider->setUsrId($user->get_id()); + $usrAuthProvider->setUser($user); try { $provider->logout(); @@ -491,9 +493,7 @@ class Login implements ControllerProviderInterface $app->abort(400, 'Missing usr_id parameter.'); } - try { - $user = \User_Adapter::getInstance((int) $usrId, $app); - } catch (\Exception $e) { + if (null === $user = $app['manipulator.user']->getRepository()->find((int) $usrId)) { $app->addFlash('error', $app->trans('Invalid link.')); return $app->redirectPath('homepage'); @@ -514,17 +514,17 @@ class Login implements ControllerProviderInterface * Sends an account unlock email. * * @param PhraseaApplication $app - * @param \User_Adapter $user + * @param User $user * * @throws InvalidArgumentException * @throws RuntimeException */ - private function sendAccountUnlockEmail(PhraseaApplication $app, \User_Adapter $user) + private function sendAccountUnlockEmail(PhraseaApplication $app, User $user) { $receiver = Receiver::fromUser($user); $expire = new \DateTime('+3 days'); - $token = $app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $user->get_id(), $expire, $user->get_email()); + $token = $app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $user->getId(), $expire, $user->getEmail()); $mail = MailRequestEmailConfirmation::create($app, $receiver); $mail->setButtonUrl($app->url('login_register_confirm', ['code' => $token])); @@ -556,22 +556,20 @@ class Login implements ControllerProviderInterface return $app->redirectPath('homepage'); } - try { - $user = \User_Adapter::getInstance((int) $datas['usr_id'], $app); - } catch (\Exception $e) { - $app->addFlash('error', $app->trans('Invalid unlock link.')); + if (null === $user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id'])) { + $app->addFlash('error', _('Invalid unlock link.')); return $app->redirectPath('homepage'); } - if (!$user->get_mail_locked()) { + if (!$user->isMailLocked()) { $app->addFlash('info', $app->trans('Account is already unlocked, you can login.')); return $app->redirectPath('homepage'); } $app['tokens']->removeToken($code); - $user->set_mail_locked(false); + $user->setMailLocked(false); try { $receiver = Receiver::fromUser($user); @@ -621,8 +619,8 @@ class Login implements ControllerProviderInterface $datas = $app['tokens']->helloToken($token); - $user = \User_Adapter::getInstance($datas['usr_id'], $app); - $user->set_password($data['password']); + $user = $app['manipulator.user']->getRepository()->find($datas['usr_id']); + $app['manipulator.user']->setPassword($user, $data['password']); $app['tokens']->removeToken($token); @@ -659,10 +657,8 @@ class Login implements ControllerProviderInterface if ($form->isValid()) { $data = $form->getData(); - try { - $user = \User_Adapter::getInstance(\User_Adapter::get_usr_id_from_email($app, $data['email']), $app); - } catch (\Exception $e) { - throw new FormProcessingException($app->trans('phraseanet::erreur: Le compte n\'a pas ete trouve')); + if (null === $user = $app['manipulator.user']->getRepository()->findByEmail($data['email'])) { + throw new FormProcessingException(_('phraseanet::erreur: Le compte n\'a pas ete trouve')); } try { @@ -671,7 +667,7 @@ class Login implements ControllerProviderInterface throw new FormProcessingException($app->trans('Invalid email address')); } - $token = $app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $user->get_id(), new \DateTime('+1 day')); + $token = $app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $user->getId(), new \DateTime('+1 day')); if (!$token) { return $app->abort(500, 'Unable to generate a token'); @@ -680,7 +676,7 @@ class Login implements ControllerProviderInterface $url = $app->url('login_renew_password', ['token' => $token], true); $mail = MailRequestPasswordUpdate::create($app, $receiver); - $mail->setLogin($user->get_login()); + $mail->setLogin($user->getLogin()); $mail->setButtonUrl($url); $app['notification.deliverer']->deliver($mail); @@ -807,11 +803,8 @@ class Login implements ControllerProviderInterface $context = new Context(Context::CONTEXT_GUEST); $app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context)); - $password = \random::generatePassword(24); - $user = \User_Adapter::create($app, 'invite', $password, null, false, true); - - $inviteUsrid = \User_Adapter::get_usr_id_from_login($app, 'invite'); - $invite_user = \User_Adapter::getInstance($inviteUsrid, $app); + $user = $app['manipulator.user']->createUser(uniqid('guest'), \random::generatePassword(24)); + $invite_user = $app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST); $usr_base_ids = array_keys($app['acl']->get($user)->get_granted_base()); $app['acl']->get($user)->revoke_access_from_bases($usr_base_ids); @@ -822,7 +815,7 @@ class Login implements ControllerProviderInterface $this->postAuthProcess($app, $user); $response = $this->generateAuthResponse($app, $app['browser'], $request->request->get('redirect')); - $response->headers->setCookie(new Cookie('invite-usr-id', $user->get_id())); + $response->headers->setCookie(new Cookie('invite-usr-id', $user->getId())); $event = new PostAuthenticate($request, $response, $user, $context); $app['dispatcher']->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event); @@ -849,7 +842,7 @@ class Login implements ControllerProviderInterface } // move this in an event - public function postAuthProcess(PhraseaApplication $app, \User_Adapter $user) + public function postAuthProcess(PhraseaApplication $app, User $user) { $date = new \DateTime('+' . (int) $app['conf']->get(['registry', 'actions', 'validation-reminder-days']) . ' days'); @@ -860,7 +853,7 @@ class Login implements ControllerProviderInterface /* @var $participant ValidationParticipant */ $validationSession = $participant->getSession(); - $participantId = $participant->getUsrId(); + $participantId = $participant->getUser()->getId(); $basketId = $validationSession->getBasket()->getId(); try { @@ -872,7 +865,7 @@ class Login implements ControllerProviderInterface $app['events-manager']->trigger('__VALIDATION_REMINDER__', [ 'to' => $participantId, 'ssel_id' => $basketId, - 'from' => $validationSession->getInitiatorId(), + 'from' => $validationSession->getInitiator()->getId(), 'validate_id' => $validationSession->getId(), 'url' => $app->url('lightbox_validation', ['basket' => $basketId, 'LOG' => $token]), ]); @@ -885,8 +878,8 @@ class Login implements ControllerProviderInterface $session = $app['authentication']->openAccount($user); - if ($user->get_locale() != $app['locale']) { - $user->set_locale($app['locale']); + if ($user->getLocale() != $app['locale']) { + $user->setLocale($app['locale']); } $width = $height = null; @@ -931,7 +924,7 @@ class Login implements ControllerProviderInterface ->findWithProviderAndId($token->getProvider()->getId(), $token->getId()); if (null !== $userAuthProvider) { - $this->postAuthProcess($app, $userAuthProvider->getUser($app)); + $this->postAuthProcess($app, $userAuthProvider->getUser()); if (null !== $redirect = $request->query->get('redirect')) { $redirection = '../' . $redirect; @@ -1047,7 +1040,7 @@ class Login implements ControllerProviderInterface throw new AuthenticationException(call_user_func($redirector, $params)); } - $user = \User_Adapter::getInstance($usr_id, $app); + $user = $app['manipulator.user']->getRepository()->find($usr_id); $session = $this->postAuthProcess($app, $user); @@ -1055,14 +1048,14 @@ class Login implements ControllerProviderInterface $response->headers->clearCookie('invite-usr-id'); if ($request->cookies->has('postlog') && $request->cookies->get('postlog') == '1') { - if (!$user->is_guest() && $request->cookies->has('invite-usr_id')) { - if ($user->get_id() != $inviteUsrId = $request->cookies->get('invite-usr_id')) { + if (!$user->isGuest() && $request->cookies->has('invite-usr_id')) { + if ($user->getId() != $inviteUsrId = $request->cookies->get('invite-usr_id')) { $repo = $app['EM']->getRepository('Phraseanet:Basket'); $baskets = $repo->findBy(['usr_id' => $inviteUsrId]); foreach ($baskets as $basket) { - $basket->setUsrId($user->get_id()); + $basket->setUser($user); $app['EM']->persist($basket); } } diff --git a/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php b/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php index 7a1a14b03e..2a3e8583b5 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php +++ b/lib/Alchemy/Phrasea/Controller/Root/RSSFeeds.php @@ -55,7 +55,7 @@ class RSSFeeds implements ControllerProviderInterface $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']($format) - ->createResponse($app, $token->getFeed(), $page, \User_Adapter::getInstance($token->getUsrId(), $app)); + ->createResponse($app, $token->getFeed(), $page, $token->getUser()); }) ->bind('feed_user') ->assert('id', '\d+') @@ -63,7 +63,8 @@ class RSSFeeds implements ControllerProviderInterface $controllers->get('/userfeed/aggregated/{token}/{format}/', function (Application $app, $token, $format) { $token = $app['EM']->getRepository('Phraseanet:AggregateToken')->findOneBy(["value" => $token]); - $user = \User_Adapter::getInstance($token->getUsrId(), $app); + + $user = $token->getUser(); $feeds = $app['EM']->getRepository('Phraseanet:Feed')->getAllForUser($app['acl']->get($user)); diff --git a/lib/Alchemy/Phrasea/Controller/Root/Session.php b/lib/Alchemy/Phrasea/Controller/Root/Session.php index 10771d695f..bb697fd398 100644 --- a/lib/Alchemy/Phrasea/Controller/Root/Session.php +++ b/lib/Alchemy/Phrasea/Controller/Root/Session.php @@ -57,7 +57,7 @@ class Session implements ControllerProviderInterface ]; if ($app['authentication']->isAuthenticated()) { - $usr_id = $app['authentication']->getUser()->get_id(); + $usr_id = $app['authentication']->getUser()->getId(); if ($usr_id != $request->request->get('usr')) { // I logged with another user $ret['status'] = 'disconnected'; @@ -138,7 +138,11 @@ class Session implements ControllerProviderInterface $app->abort(404, 'Unknown session'); } - if ($session->getUsrId() !== $app['authentication']->getUser()->get_id()) { + if (null === $session->getUser()) { + $app->abort(403, 'Unauthorized'); + } + + if ($session->getUser()->getId() !== $app['authentication']->getUser()->getId()) { $app->abort(403, 'Unauthorized'); } diff --git a/lib/Alchemy/Phrasea/Controller/Thesaurus/Thesaurus.php b/lib/Alchemy/Phrasea/Controller/Thesaurus/Thesaurus.php index 9b075e005d..981d45d213 100644 --- a/lib/Alchemy/Phrasea/Controller/Thesaurus/Thesaurus.php +++ b/lib/Alchemy/Phrasea/Controller/Thesaurus/Thesaurus.php @@ -765,10 +765,10 @@ class Thesaurus implements ControllerProviderInterface sbasusr.bas_modify_struct AS bas_modify_struct, sbasusr.bas_modif_th AS bas_edit_thesaurus FROM - (usr INNER JOIN sbasusr - ON usr.usr_id = :usr_id - AND usr.usr_id = sbasusr.usr_id - AND model_of = 0) + (Users u INNER JOIN sbasusr + ON u.id = :usr_id + AND u.id = sbasusr.usr_id + AND u.model_of IS NULL) INNER JOIN sbas ON sbas.sbas_id = sbasusr.sbas_id HAVING bas_edit_thesaurus > 0 @@ -777,7 +777,7 @@ class Thesaurus implements ControllerProviderInterface $bases = $languages = []; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $app['authentication']->getUser()->getId()]); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); diff --git a/lib/Alchemy/Phrasea/Controller/Thesaurus/Xmlhttp.php b/lib/Alchemy/Phrasea/Controller/Thesaurus/Xmlhttp.php index 1586ed4169..258c4649f8 100644 --- a/lib/Alchemy/Phrasea/Controller/Thesaurus/Xmlhttp.php +++ b/lib/Alchemy/Phrasea/Controller/Thesaurus/Xmlhttp.php @@ -358,7 +358,7 @@ class Xmlhttp implements ControllerProviderInterface public function EditingPresetsJson(Application $app, Request $request) { - $usr_id = $app['authentication']->getUser()->get_id(); + $usr_id = $app['authentication']->getUser()->getId(); $ret = ['parm' => [ 'act' => $request->get('act'), diff --git a/lib/Alchemy/Phrasea/Controller/User/Notifications.php b/lib/Alchemy/Phrasea/Controller/User/Notifications.php index 9136aa6ce9..88a56334a0 100644 --- a/lib/Alchemy/Phrasea/Controller/User/Notifications.php +++ b/lib/Alchemy/Phrasea/Controller/User/Notifications.php @@ -59,7 +59,7 @@ class Notifications implements ControllerProviderInterface try { $app['events-manager']->read( explode('_', (string) $request->request->get('notifications')), - $app['authentication']->getUser()->get_id() + $app['authentication']->getUser()->getId() ); return $app->json(['success' => true, 'message' => '']); diff --git a/lib/Alchemy/Phrasea/Controller/User/Preferences.php b/lib/Alchemy/Phrasea/Controller/User/Preferences.php index 03311684b5..e0280822f8 100644 --- a/lib/Alchemy/Phrasea/Controller/User/Preferences.php +++ b/lib/Alchemy/Phrasea/Controller/User/Preferences.php @@ -85,7 +85,7 @@ class Preferences implements ControllerProviderInterface $success = false; if (null !== $prop && null !== $value) { - $app['authentication']->getUser()->setPrefs($prop, $value); + $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), $prop, $value); $success = true; $msg = $app->trans('Preference saved !'); } diff --git a/lib/Alchemy/Phrasea/Core/Configuration/DisplaySettingService.php b/lib/Alchemy/Phrasea/Core/Configuration/DisplaySettingService.php index 916f47da0e..751945ffed 100644 --- a/lib/Alchemy/Phrasea/Core/Configuration/DisplaySettingService.php +++ b/lib/Alchemy/Phrasea/Core/Configuration/DisplaySettingService.php @@ -91,6 +91,24 @@ class DisplaySettingService return $user->getSettings()->get($name)->getValue(); } + /** + * Return a user notification setting given a user. + * + * @param User $user + * @param string $name + * @param mixed $default + * + * @return mixed + */ + public function getUserNotificationSetting(User $user, $name, $default = true) + { + if (false === $user->getNotificationSettings()->containsKey($name)) { + return $default; + } + + return $user->getNotificationSettings()->get($name)->getValue(); + } + /** * Returns application setting value. * diff --git a/lib/Alchemy/Phrasea/Core/Event/PostAuthenticate.php b/lib/Alchemy/Phrasea/Core/Event/PostAuthenticate.php index 15f538144d..589cc62025 100644 --- a/lib/Alchemy/Phrasea/Core/Event/PostAuthenticate.php +++ b/lib/Alchemy/Phrasea/Core/Event/PostAuthenticate.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Core\Event; use Alchemy\Phrasea\Authentication\Context; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\EventDispatcher\Event as SfEvent; @@ -23,7 +24,7 @@ class PostAuthenticate extends SfEvent private $request; private $response; - public function __construct(Request $request, Response $response, \User_Adapter $user, Context $context) + public function __construct(Request $request, Response $response, User $user, Context $context) { $this->request = $request; $this->response = $response; diff --git a/lib/Alchemy/Phrasea/Core/Provider/AuthenticationManagerServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/AuthenticationManagerServiceProvider.php index 5b556e03d4..7dee0782ce 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/AuthenticationManagerServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/AuthenticationManagerServiceProvider.php @@ -57,12 +57,11 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface $templates = array_filter(array_map(function ($templateId) use ($app) { try { if (is_int($templateId) || ctype_digit($templateId)) { - return \User_Adapter::getInstance($templateId, $app); - } else { - $template = \User_Adapter::get_usr_id_from_login($app, $templateId); - if (false !== $template) { - return \User_Adapter::getInstance($template, $app); - } + return $app['manipulator.user']->getRepository()->find($templateId); + } + + if (false !== $templateId) { + return $app['manipulator.user']->getRepository()->find($templateId); } } catch (\Exception $e) { @@ -108,7 +107,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface }); $app['auth.password-checker'] = $app->share(function (Application $app) { - return new NativeAuthentication($app['auth.password-encoder'], $app['auth.old-password-encoder'], $app['phraseanet.appbox']->get_connection()); + return new NativeAuthentication($app['auth.password-encoder'], $app['auth.old-password-encoder'], $app['manipulator.user']); }); $app['auth.native'] = $app->share(function (Application $app) { diff --git a/lib/Alchemy/Phrasea/Core/Provider/ConfigurationTesterServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/ConfigurationTesterServiceProvider.php index 73109279fb..7e80258cdb 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/ConfigurationTesterServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/ConfigurationTesterServiceProvider.php @@ -13,6 +13,9 @@ namespace Alchemy\Phrasea\Core\Provider; use Alchemy\Phrasea\Setup\ConfigurationTester; use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Setup\Version\PreSchemaUpgrade\PreSchemaUpgradeCollection; +use Alchemy\Phrasea\Setup\Version\PreSchemaUpgrade\Upgrade39Feeds; +use Alchemy\Phrasea\Setup\Version\PreSchemaUpgrade\Upgrade39Users; use Silex\Application as SilexApplication; use Silex\ServiceProviderInterface; @@ -24,6 +27,14 @@ class ConfigurationTesterServiceProvider implements ServiceProviderInterface $app['phraseanet.configuration-tester'] = $app->share(function (Application $app) { return new ConfigurationTester($app); }); + + $app['phraseanet.pre-schema-upgrader.upgrades'] = $app->share(function () { + return [new Upgrade39Feeds(), new Upgrade39Users()]; + }); + + $app['phraseanet.pre-schema-upgrader'] = $app->share(function (Application $app) { + return new PreSchemaUpgradeCollection($app['phraseanet.pre-schema-upgrader.upgrades']); + }); } public function boot(SilexApplication $app) diff --git a/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php index b0eead5f2c..135c30f81d 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/ORMServiceProvider.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Core\Provider; use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Model\MonologSQLLogger; +use Alchemy\Phrasea\Model\NativeQueryProvider; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\Common\Annotations\FileCacheReader; @@ -155,6 +156,10 @@ class ORMServiceProvider implements ServiceProviderInterface return $em; }); + + $app['EM.native-query'] = $app->share(function ($app) { + return new NativeQueryProvider($app['EM']); + }); } public function boot(Application $app) diff --git a/lib/Alchemy/Phrasea/Core/Provider/PhraseanetServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/PhraseanetServiceProvider.php index 9600537910..0a655cb4c2 100644 --- a/lib/Alchemy/Phrasea/Core/Provider/PhraseanetServiceProvider.php +++ b/lib/Alchemy/Phrasea/Core/Provider/PhraseanetServiceProvider.php @@ -38,6 +38,10 @@ class PhraseanetServiceProvider implements ServiceProviderInterface $app['acl'] = $app->share(function (SilexApplication $app) { return new ACLProvider($app); }); + + $app['phraseanet.appbox-register'] = $app->share(function ($app) { + return new \appbox_register($app['phraseanet.appbox']); + }); } public function boot(SilexApplication $app) diff --git a/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php b/lib/Alchemy/Phrasea/Core/Provider/RegistrationServiceProvider.php index 2f0490c1ae..b6f92189f8 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\Model\Entities\User; use Silex\Application; use Silex\ServiceProviderInterface; use Symfony\Component\Validator\Constraints as Assert; @@ -56,9 +57,9 @@ class RegistrationServiceProvider implements ServiceProviderInterface 'multiple' => false, 'expanded' => false, 'choices' => [ - '0' => 'admin::compte-utilisateur:sexe: mademoiselle', - '1' => 'admin::compte-utilisateur:sexe: madame', - '2' => 'admin::compte-utilisateur:sexe: monsieur', + User::GENDER_MISS => 'admin::compte-utilisateur:sexe: mademoiselle', + User::GENDER_MRS => 'admin::compte-utilisateur:sexe: madame', + User::GENDER_MR => 'admin::compte-utilisateur:sexe: monsieur', ] ], 'firstname' => [ diff --git a/lib/Alchemy/Phrasea/Feed/Aggregate.php b/lib/Alchemy/Phrasea/Feed/Aggregate.php index c14aa18252..dd0b456a07 100644 --- a/lib/Alchemy/Phrasea/Feed/Aggregate.php +++ b/lib/Alchemy/Phrasea/Feed/Aggregate.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\EntityManager; use Alchemy\Phrasea\Model\Entities\AggregateToken; @@ -71,14 +72,14 @@ class Aggregate implements FeedInterface * Creates an aggregate from all the feeds available to a given user. * * @param EntityManager $em - * @param \User_Adapter $user + * @param User $user * * @return Aggregate */ - public static function createFromUser(Application $app, \User_Adapter $user) + public static function createFromUser(Application $app, User $user) { $feeds = $app['EM']->getRepository('Phraseanet:Feed')->getAllForUser($app['acl']->get($user)); - $token = $app['EM']->getRepository('Phraseanet:AggregateToken')->findOneBy(['usrId' => $user->get_id()]); + $token = $app['EM']->getRepository('Phraseanet:AggregateToken')->findOneBy(['user' => $user]); return new static($app['EM'], $feeds, $token); } diff --git a/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php b/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php index 6892cf0166..be7533249d 100644 --- a/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php +++ b/lib/Alchemy/Phrasea/Feed/Formatter/AtomFormatter.php @@ -16,6 +16,7 @@ use Alchemy\Phrasea\Model\Entities\FeedEntry; use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\Link\FeedLink; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Response; class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterface @@ -34,7 +35,7 @@ class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterf /** * {@inheritdoc} */ - public function createResponse(Application $app, FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet') + public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet') { $content = $this->format($feed, $page, $user, $generator, $app); $response = new Response($content, 200, ['Content-Type' => 'application/atom+xml']); @@ -45,7 +46,7 @@ class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterf /** * {@inheritdoc} */ - public function format(FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet', Application $app = null) + public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $updated_on = $feed->getUpdatedOn(); diff --git a/lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php b/lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php index c311e4271f..459aec5f67 100644 --- a/lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php +++ b/lib/Alchemy/Phrasea/Feed/Formatter/CoolirisFormatter.php @@ -17,6 +17,7 @@ use Alchemy\Phrasea\Model\Entities\FeedEntry; use Alchemy\Phrasea\Model\Entities\FeedItem; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; use Alchemy\Phrasea\Feed\RSS\FeedRSSImage; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Response; class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterInterface @@ -36,7 +37,7 @@ class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterIn /** * {@inheritdoc} */ - public function createResponse(Application $app, FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet') + public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet') { $content = $this->format($feed, $page, $user, $generator, $app); $response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']); @@ -47,7 +48,7 @@ class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterIn /** * {@inheritdoc} */ - public function format(FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet', Application $app = null) + public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $updated_on = $feed->getUpdatedOn(); diff --git a/lib/Alchemy/Phrasea/Feed/Formatter/FeedFormatterInterface.php b/lib/Alchemy/Phrasea/Feed/Formatter/FeedFormatterInterface.php index 1dd76396c4..9acbd078cc 100644 --- a/lib/Alchemy/Phrasea/Feed/Formatter/FeedFormatterInterface.php +++ b/lib/Alchemy/Phrasea/Feed/Formatter/FeedFormatterInterface.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Formatter; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Feed\FeedInterface; +use Alchemy\Phrasea\Model\Entities\User; interface FeedFormatterInterface { @@ -21,24 +22,24 @@ interface FeedFormatterInterface * * @param FeedInterface $feed * @param type $page - * @param \User_Adapter $user + * @param User $user * @param type $generator * @param Application $app * * @return string */ - public function format(FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet', Application $app); + public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app); /** * Returns an HTTP Response containing a string representation of the feed. * * @param FeedInterface $feed * @param type $page - * @param \User_Adapter $user + * @param User $user * @param type $generator * @param Application $app * * @return string */ - public function createResponse(Application $app, FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet'); + public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet'); } diff --git a/lib/Alchemy/Phrasea/Feed/Formatter/RssFormatter.php b/lib/Alchemy/Phrasea/Feed/Formatter/RssFormatter.php index 42d5bbad8c..a802118c60 100644 --- a/lib/Alchemy/Phrasea/Feed/Formatter/RssFormatter.php +++ b/lib/Alchemy/Phrasea/Feed/Formatter/RssFormatter.php @@ -16,6 +16,7 @@ use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\Link\FeedLink; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; use Alchemy\Phrasea\Feed\RSS\FeedRSSImage; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Response; use Alchemy\Phrasea\Model\Entities\FeedEntry; use Alchemy\Phrasea\Feed\Link\FeedLinkGenerator; @@ -37,7 +38,7 @@ class RssFormatter extends FeedFormatterAbstract implements FeedFormatterInterfa /** * {@inheritdoc} */ - public function createResponse(Application $app, FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet') + public function createResponse(Application $app, FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet') { $content = $this->format($feed, $page, $user, $generator, $app); $response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']); @@ -48,7 +49,7 @@ class RssFormatter extends FeedFormatterAbstract implements FeedFormatterInterfa /** * {@inheritdoc} */ - public function format(FeedInterface $feed, $page, \User_Adapter $user = null, $generator = 'Phraseanet', Application $app = null) + public function format(FeedInterface $feed, $page, User $user = null, $generator = 'Phraseanet', Application $app = null) { $updated_on = $feed->getUpdatedOn(); diff --git a/lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php b/lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php index f4b9b32690..586f6718c9 100644 --- a/lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php +++ b/lib/Alchemy/Phrasea/Feed/Link/AggregateLinkGenerator.php @@ -15,6 +15,7 @@ use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Feed\Aggregate; use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Model\Entities\AggregateToken; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityManager; use Symfony\Component\Routing\Generator\UrlGenerator; @@ -42,7 +43,7 @@ class AggregateLinkGenerator implements LinkGeneratorInterface /** * {@inheritdoc} */ - public function generate(FeedInterface $aggregate, \User_Adapter $user, $format, $page = null, $renew = false) + public function generate(FeedInterface $aggregate, User $user, $format, $page = null, $renew = false) { if (!$this->supports($aggregate)) { throw new InvalidArgumentException('AggregateLinkGenerator only support aggregate feeds.'); @@ -127,16 +128,16 @@ class AggregateLinkGenerator implements LinkGeneratorInterface } } - private function getAggregateToken(\User_Adapter $user, $renew = false) + private function getAggregateToken(User $user, $renew = false) { $token = $this->em ->getRepository('Phraseanet:AggregateToken') - ->findOneBy(['usrId' => $user->get_id()]); + ->findOneBy(['user' => $user]); if (null === $token || true === $renew) { if (null === $token) { $token = new AggregateToken(); - $token->setUsrId($user->get_id()); + $token->setUser($user); } $token->setValue($this->random->generatePassword(12, \random::LETTERS_AND_NUMBERS)); diff --git a/lib/Alchemy/Phrasea/Feed/Link/FeedLinkGenerator.php b/lib/Alchemy/Phrasea/Feed/Link/FeedLinkGenerator.php index 5e7946e3c9..f23afc918a 100644 --- a/lib/Alchemy/Phrasea/Feed/Link/FeedLinkGenerator.php +++ b/lib/Alchemy/Phrasea/Feed/Link/FeedLinkGenerator.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Link; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Feed\FeedInterface; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityManager; use Alchemy\Phrasea\Model\Entities\Feed; use Alchemy\Phrasea\Model\Entities\FeedToken; @@ -42,7 +43,7 @@ class FeedLinkGenerator implements LinkGeneratorInterface /** * {@inheritdoc} */ - public function generate(FeedInterface $feed, \User_Adapter $user, $format, $page = null, $renew = false) + public function generate(FeedInterface $feed, User $user, $format, $page = null, $renew = false) { if (!$this->supports($feed)) { throw new InvalidArgumentException('FeedLinkGenerator only support aggregate feeds.'); @@ -135,17 +136,17 @@ class FeedLinkGenerator implements LinkGeneratorInterface } } - private function getFeedToken(Feed $feed, \User_Adapter $user, $renew = false) + private function getFeedToken(Feed $feed, User $user, $renew = false) { $token = $this->em ->getRepository('Phraseanet:FeedToken') - ->findOneBy(['usrId' => $user->get_id(), 'feed' => $feed->getId()]); + ->findOneBy(['user' => $user, 'feed' => $feed]); if (null === $token || true === $renew) { if (null === $token) { $token = new FeedToken(); $token->setFeed($feed); - $token->setUsrId($user->get_id()); + $token->setUser($user); $feed->addToken($token); $this->em->persist($feed); diff --git a/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorCollection.php b/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorCollection.php index 44f171fff0..861e52bef1 100644 --- a/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorCollection.php +++ b/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorCollection.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Link; use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; class LinkGeneratorCollection implements LinkGeneratorInterface { @@ -31,7 +32,7 @@ class LinkGeneratorCollection implements LinkGeneratorInterface /** * {@inheritdoc} */ - public function generate(FeedInterface $feed, \User_Adapter $user, $format, $page = null, $renew = false) + public function generate(FeedInterface $feed, User $user, $format, $page = null, $renew = false) { if (null === $generator = $this->findGenerator($feed)) { throw new InvalidArgumentException(sprintf('Unable to find a valid generator for %s', get_class($feed))); diff --git a/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorInterface.php b/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorInterface.php index 4b0b9510e8..f3728d6c23 100644 --- a/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorInterface.php +++ b/lib/Alchemy/Phrasea/Feed/Link/LinkGeneratorInterface.php @@ -12,14 +12,15 @@ namespace Alchemy\Phrasea\Feed\Link; use Alchemy\Phrasea\Feed\FeedInterface; +use Alchemy\Phrasea\Model\Entities\User; interface LinkGeneratorInterface { /** - * Generates a FeedLink based on given FeedInterface and User_Adapter. + * Generates a FeedLink based on given FeedInterface and User. * * @param FeedInterface $feed - * @param \User_Adapter $user + * @param User $user * @param type $format * @param type $page * @param type $renew @@ -28,7 +29,7 @@ interface LinkGeneratorInterface * * @throws InvalidArgumentException */ - public function generate(FeedInterface $feed, \User_Adapter $user, $format, $page = null, $renew = false); + public function generate(FeedInterface $feed, User $user, $format, $page = null, $renew = false); /** * Generates a public FeedLink based on given FeedInterface. diff --git a/lib/Alchemy/Phrasea/Form/Constraint/NewEmail.php b/lib/Alchemy/Phrasea/Form/Constraint/NewEmail.php index 6b93258bfe..910565774b 100644 --- a/lib/Alchemy/Phrasea/Form/Constraint/NewEmail.php +++ b/lib/Alchemy/Phrasea/Form/Constraint/NewEmail.php @@ -27,9 +27,7 @@ class NewEmail extends Constraint public function isAlreadyRegistered($email) { - $ret = (Boolean) \User_Adapter::get_usr_id_from_email($this->app, $email); - - return $ret; + return (Boolean) $this->app['manipulator.user']->getRepository()->findByEmail($email); } public static function create(Application $app) diff --git a/lib/Alchemy/Phrasea/Form/Constraint/NewLogin.php b/lib/Alchemy/Phrasea/Form/Constraint/NewLogin.php index fb85a912fa..86fa67439b 100644 --- a/lib/Alchemy/Phrasea/Form/Constraint/NewLogin.php +++ b/lib/Alchemy/Phrasea/Form/Constraint/NewLogin.php @@ -27,9 +27,7 @@ class NewLogin extends Constraint public function isAlreadyRegistered($login) { - $ret = (Boolean) \User_Adapter::get_usr_id_from_login($this->app, $login); - - return $ret; + return (Boolean) $this->app['manipulator.user']->getRepository()->findByLogin($login); } public static function create(Application $app) diff --git a/lib/Alchemy/Phrasea/Helper/Prod.php b/lib/Alchemy/Phrasea/Helper/Prod.php index ab9bef9094..b81d86b800 100644 --- a/lib/Alchemy/Phrasea/Helper/Prod.php +++ b/lib/Alchemy/Phrasea/Helper/Prod.php @@ -11,6 +11,8 @@ namespace Alchemy\Phrasea\Helper; +use Alchemy\Phrasea\Model\Entities\User; + class Prod extends Helper { @@ -24,12 +26,12 @@ class Prod extends Helper $bases = $fields = $dates = []; - if (! $this->app['authentication']->getUser() instanceof \User_Adapter) { + if (! $this->app['authentication']->getUser() instanceof User) { return $search_datas; } - $searchSet = json_decode($this->app['authentication']->getUser()->getPrefs('search'), true); - $saveSettings = $this->app['authentication']->getUser()->getPrefs('advanced_search_reload'); + $searchSet = json_decode($this->app['settings']->getUserSetting($this->app['authentication']->getUser(), 'search'), true); + $saveSettings = $this->app['settings']->getUserSetting($this->app['authentication']->getUser(), 'advanced_search_reload'); foreach ($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_sbas() as $databox) { $sbas_id = $databox->get_sbas_id(); diff --git a/lib/Alchemy/Phrasea/Helper/User/Edit.php b/lib/Alchemy/Phrasea/Helper/User/Edit.php index 17cfd32cbc..78e25b8753 100644 --- a/lib/Alchemy/Phrasea/Helper/User/Edit.php +++ b/lib/Alchemy/Phrasea/Helper/User/Edit.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Helper\User; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Notification\Mail\MailSuccessEmailUpdate; use Alchemy\Phrasea\Notification\Receiver; use Symfony\Component\HttpFoundation\Request; @@ -60,24 +61,24 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper public function delete_users() { foreach ($this->users as $usr_id) { - if ($this->app['authentication']->getUser()->get_id() === (int) $usr_id) { + if ($this->app['authentication']->getUser()->getId() === (int) $usr_id) { continue; } - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); $this->delete_user($user); } return $this; } - protected function delete_user(\User_Adapter $user) + protected function delete_user(User $user) { $list = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin'])); $this->app['acl']->get($user)->revoke_access_from_bases($list); if ($this->app['acl']->get($user)->is_phantom()) { - $user->delete(); + $this->app['manipulator.user']->delete($user); } return $this; @@ -124,12 +125,12 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper sum(mask_and + mask_xor) as masks - FROM (usr u, bas b, sbas s) + FROM (Users u, bas b, sbas s) LEFT JOIN (basusr bu) - ON (bu.base_id = b.base_id AND u.usr_id = bu.usr_id) + ON (bu.base_id = b.base_id AND u.id = bu.usr_id) LEFT join sbasusr sbu - ON (sbu.sbas_id = b.sbas_id AND u.usr_id = sbu.usr_id) - WHERE ( (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . " ) + ON (sbu.sbas_id = b.sbas_id AND u.id = sbu.usr_id) + WHERE ( (u.id = " . implode(' OR u.id = ', $this->users) . " ) AND b.sbas_id = s.sbas_id AND (b.base_id = '" . implode("' OR b.base_id = '", $list) . "')) GROUP BY b.base_id @@ -180,7 +181,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper if (count($this->users) == 1) { $usr_id = array_pop($this->users); - $out['main_user'] = \User_Adapter::getInstance($usr_id, $this->app); + $out['main_user'] = $this->app['manipulator.user']->getRepository()->find($usr_id); } return $out; @@ -190,9 +191,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper { $this->base_id = (int) $this->request->get('base_id'); - $sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max - FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id) - WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ") + $sql = "SELECT u.id, restrict_dwnld, remain_dwnld, month_dwnld_max + FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id) + WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ") AND bu.base_id = :base_id"; $conn = \connection::getPDOConnection($this->app); @@ -313,9 +314,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper { $this->base_id = (int) $this->request->get('base_id'); - $sql = "SELECT u.usr_id, time_limited, limited_from, limited_to - FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id) - WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ") + $sql = "SELECT u.id, time_limited, limited_from, limited_to + FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id) + WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ") AND bu.base_id = :base_id"; $conn = \connection::getPDOConnection($this->app); @@ -367,11 +368,11 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper { $sbas_id = (int) $this->request->get('sbas_id'); - $sql = "SELECT u.usr_id, time_limited, limited_from, limited_to - FROM (usr u - INNER JOIN basusr bu ON u.usr_id = bu.usr_id + $sql = "SELECT u.id, time_limited, limited_from, limited_to + FROM (Users u + INNER JOIN basusr bu ON u.id = bu.usr_id INNER JOIN bas b ON b.base_id = bu.base_id) - WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ") + WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ") AND b.sbas_id = :sbas_id"; $conn = \connection::getPDOConnection($this->app); @@ -531,7 +532,8 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper try { $this->app['phraseanet.appbox']->get_connection()->beginTransaction(); - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); + $this->app['acl']->get($user)->revoke_access_from_bases($delete) ->give_access_to_base($create) ->give_access_to_sbas($create_sbas); @@ -565,9 +567,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper $users = $this->users; - $user = \User_adapter::getInstance(array_pop($users), $this->app); + $user = $this->app['manipulator.user']->getRepository()->find(array_pop($users)); - if ($user->is_template() || $user->is_special()) { + if ($user->isTemplate() || $user->isSpecial()) { return $this; } @@ -586,28 +588,29 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper , 'fax' ]; - $parm = $this->unserializedRequestData($this->app['request'], $infos, 'user_infos'); + $parm = $this->unserializedRequestData($this->request, $infos, 'user_infos'); if ($parm['email'] && !\Swift_Validate::email($parm['email'])) { throw new \Exception_InvalidArgument('Email addess is not valid'); } - $old_email = $user->get_email(); + $old_email = $user->getEmail(); - $user->set_firstname($parm['first_name']) - ->set_lastname($parm['last_name']) - ->set_gender($parm['gender']) - ->set_email($parm['email']) - ->set_address($parm['address']) - ->set_zip($parm['zip']) - ->set_geonameid($parm['geonameid']) - ->set_position($parm['function']) - ->set_job($parm['activite']) - ->set_company($parm['company']) - ->set_tel($parm['telephone']) - ->set_fax($parm['fax']); + $user->setFirstName($parm['first_name']) + ->setLastName($parm['last_name']) + ->setGender($parm['gender']) + ->setEmail($parm['email']) + ->setAddress($parm['address']) + ->setZipCode($parm['zip']) + ->setActivity($parm['function']) + ->setJob($parm['activite']) + ->setCompany($parm['company']) + ->setPhone($parm['telephone']) + ->setFax($parm['fax']); - $new_email = $user->get_email(); + $this->app['manipulator.user']->setGeonameId($user, $parm['geonameid']); + + $new_email = $user->getEmail(); if ($old_email != $new_email) { $oldReceiver = $newReceiver = null; @@ -639,18 +642,18 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper public function apply_template() { - $template = \User_adapter::getInstance($this->request->get('template'), $this->app); + $template = $this->app['manipulator.user']->getRepository()->find($this->request->get('template')); - if ($template->get_template_owner()->get_id() != $this->app['authentication']->getUser()->get_id()) { + if (null === $template->getModelOf() || $template->getModelOf()->getId() !== $this->app['authentication']->getUser()->getId()) { throw new AccessDeniedHttpException('You are not the owner of the template'); } $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin'])); foreach ($this->users as $usr_id) { - $user = \User_adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); - if ($user->is_template()) { + if ($user->isTemplate()) { continue; } @@ -665,7 +668,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper $this->base_id = (int) $this->request->get('base_id'); foreach ($this->users as $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); if ($this->request->get('quota')) $this->app['acl']->get($user)->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes')); else @@ -686,7 +689,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper if ($vand_and && $vand_or && $vxor_and && $vxor_or) { foreach ($this->users as $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); $this->app['acl']->get($user)->set_masks_on_base($this->base_id, $vand_and, $vand_or, $vxor_and, $vxor_or); } @@ -708,7 +711,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin'])); foreach ($this->users as $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); if ($this->base_id > 0) { $this->app['acl']->get($user)->set_limits($this->base_id, $activate, $dmin, $dmax); @@ -727,13 +730,13 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin'])); foreach ($this->users as $usr_id) { - $user = \User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); $ACL = $this->app['acl']->get($user); - if ($user->is_template()) { + if ($user->isTemplate()) { $template = $user; - if ($template->get_template_owner()->get_id() !== $this->app['authentication']->getUser()->get_id()) { + if ($template->getModelOf()->getId() !== $this->app['authentication']->getUser()->getId()) { continue; } } @@ -755,7 +758,13 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper private function unserializedRequestData(Request $request, array $indexes, $requestIndex) { $parameters = $data = []; - parse_str($request->get($requestIndex), $data); + $requestValue = $request->get($requestIndex); + + if (is_array($requestValue)) { + $data = $requestValue; + } else { + parse_str($requestValue, $data); + } if (count($data) > 0) { foreach ($indexes as $index) { diff --git a/lib/Alchemy/Phrasea/Helper/User/Manage.php b/lib/Alchemy/Phrasea/Helper/User/Manage.php index ec4b5fa08e..6efd77aefb 100644 --- a/lib/Alchemy/Phrasea/Helper/User/Manage.php +++ b/lib/Alchemy/Phrasea/Helper/User/Manage.php @@ -16,6 +16,7 @@ use Alchemy\Phrasea\Helper\Helper; use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Mail\MailRequestPasswordSetup; use Alchemy\Phrasea\Notification\Mail\MailRequestEmailConfirmation; +use Alchemy\Phrasea\Model\Entities\User; class Manage extends Helper { @@ -110,18 +111,12 @@ class Manage extends Helper ->limit($offset_start, $results_quantity) ->execute(); - try { - $invite_id = \User_Adapter::get_usr_id_from_login($this->app, 'invite'); - $invite = \User_Adapter::getInstance($invite_id, $this->app); - } catch (\Exception $e) { - $invite = \User_Adapter::create($this->app, 'invite', 'invite', '', false); + if (null === $invite = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) { + $invite = $this->app['manipulator.user']->createUser(User::USER_GUEST, User::USER_GUEST); } - try { - $autoregister_id = \User_Adapter::get_usr_id_from_login($this->app, 'autoregister'); - $autoregister = \User_Adapter::getInstance($autoregister_id, $this->app); - } catch (\Exception $e) { - $autoregister = \User_Adapter::create($this->app, 'autoregister', 'autoregister', '', false); + if (null == $autoregister = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_AUTOREGISTER)) { + $autoregister = $this->app['manipulator.user']->createUser(User::USER_AUTOREGISTER, User::USER_AUTOREGISTER); } foreach ($this->query_parms as $k => $v) { @@ -151,19 +146,11 @@ class Manage extends Helper throw new \Exception_InvalidArgument('Invalid mail address'); } - $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email'; - $stmt = $conn->prepare($sql); - $stmt->execute([':email' => $email]); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); - $count = count($row); - - if (!is_array($row) || $count == 0) { + if (null === $createdUser = $this->app['manipulator.user']->getRepository()->findByEmail($email)) { $sendCredentials = !!$this->request->get('send_credentials', false); $validateMail = !!$this->request->get('validate_mail', false); - $createdUser = \User_Adapter::create($this->app, $email, \random::generatePassword(16), $email, false, false); - /* @var $createdUser \User_Adapter */ + $createdUser = $this->app['manipulator.user']->createUser($email, \random::generatePassword(16), $email); $receiver = null; try { @@ -173,35 +160,32 @@ class Manage extends Helper } if ($sendCredentials) { - $urlToken = $this->app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $createdUser->get_id()); + $urlToken = $this->app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $createdUser->getId()); if ($receiver && false !== $urlToken) { $url = $this->app->url('login_renew_password', ['token' => $urlToken]); $mail = MailRequestPasswordSetup::create($this->app, $receiver, null, '', $url); - $mail->setLogin($createdUser->get_login()); + $mail->setLogin($createdUser->getLogin()); $this->app['notification.deliverer']->deliver($mail); } } if ($validateMail) { - $createdUser->set_mail_locked(true); + $createdUser->setMailLocked(true); if ($receiver) { $expire = new \DateTime('+3 days'); - $token = $this->app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $createdUser->get_id(), $expire, $createdUser->get_email()); + $token = $this->app['tokens']->getUrlToken(\random::TYPE_PASSWORD, $createdUser->getId(), $expire, $createdUser->getEmail()); $url = $this->app->url('login_register_confirm', ['code' => $token]); $mail = MailRequestEmailConfirmation::create($this->app, $receiver, null, '', $url, $expire); $this->app['notification.deliverer']->deliver($mail); } } - - $this->usr_id = $createdUser->get_id(); - } else { - $this->usr_id = $row['usr_id']; - $createdUser = \User_Adapter::getInstance($this->usr_id, $this->app); } + $this->usr_id = $createdUser->getId(); + return $createdUser; } @@ -213,9 +197,9 @@ class Manage extends Helper throw new \Exception_InvalidArgument('Invalid template name'); } - $created_user = \User_Adapter::create($this->app, $name, \random::generatePassword(16), null, false, false); - $created_user->set_template($this->app['authentication']->getUser()); - $this->usr_id = $this->app['authentication']->getUser()->get_id(); + $created_user = $this->app['manipulator.user']->getRepository()->find($name, \random::generatePassword(16)); + $created_user->setModelOf($this->app['authentication']->getUser()); + $this->usr_id = $this->app['authentication']->getUser()->getId(); return $created_user; } diff --git a/lib/Alchemy/Phrasea/Helper/WorkZone.php b/lib/Alchemy/Phrasea/Helper/WorkZone.php index 1c3717d4dd..03472e84fb 100644 --- a/lib/Alchemy/Phrasea/Helper/WorkZone.php +++ b/lib/Alchemy/Phrasea/Helper/WorkZone.php @@ -46,7 +46,7 @@ class WorkZone extends Helper $basket = new BasketEntity(); $basket->setName($this->app->trans('Default basket')); - $basket->setOwner($this->app['authentication']->getUser()); + $basket->setUser($this->app['authentication']->getUser()); $this->app['EM']->persist($basket); $this->app['EM']->flush(); diff --git a/lib/Alchemy/Phrasea/Model/Entities/AggregateToken.php b/lib/Alchemy/Phrasea/Model/Entities/AggregateToken.php index 29efaf1afa..afb1e361e5 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/AggregateToken.php +++ b/lib/Alchemy/Phrasea/Model/Entities/AggregateToken.php @@ -27,9 +27,12 @@ class AggregateToken private $id; /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string", length=12, nullable=true) @@ -47,26 +50,23 @@ class AggregateToken } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return AggregateToken */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usrId = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usrId; + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/Basket.php b/lib/Alchemy/Phrasea/Model/Entities/Basket.php index 28c0042456..f2dde8f3f1 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/Basket.php +++ b/lib/Alchemy/Phrasea/Model/Entities/Basket.php @@ -43,9 +43,12 @@ class Basket private $description; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="boolean") @@ -53,9 +56,12 @@ class Basket private $is_read = false; /** - * @ORM\Column(type="integer", nullable=true) - */ - private $pusher_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="pusher_id", referencedColumnName="id") + * + * @return User + **/ + private $pusher; /** * @ORM\Column(type="boolean") @@ -155,38 +161,23 @@ class Basket } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return Basket */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - public function setOwner(\User_Adapter $user) - { - $this->setUsrId($user->get_id()); - } - - public function getOwner(Application $app) - { - if ($this->getUsrId()) { - return \User_Adapter::getInstance($this->getUsrId(), $app); - } + return $this->user; } /** @@ -213,38 +204,23 @@ class Basket } /** - * Set pusher_id + * @param User $user * - * @param integer $pusherId - * @return Basket + * @return $this */ - public function setPusherId($pusherId) + public function setPusher(User $user = null) { - $this->pusher_id = $pusherId; + $this->pusher = $user; return $this; } /** - * Get pusher_id - * - * @return integer + * @return mixed */ - public function getPusherId() + public function getPusher() { - return $this->pusher_id; - } - - public function setPusher(\User_Adapter $user) - { - $this->setPusherId($user->get_id()); - } - - public function getPusher(Application $app) - { - if ($this->getPusherId()) { - return \User_Adapter::getInstance($this->getPusherId(), $app); - } + return $this->pusher; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/BasketElement.php b/lib/Alchemy/Phrasea/Model/Entities/BasketElement.php index 6f4ec17499..71e6e3c9b6 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/BasketElement.php +++ b/lib/Alchemy/Phrasea/Model/Entities/BasketElement.php @@ -277,17 +277,16 @@ class BasketElement /** * - * @param \User_Adapter $user * @return ValidationData */ - public function getUserValidationDatas(\User_Adapter $user, Application $app) + public function getUserValidationDatas(User $user) { foreach ($this->validation_datas as $validationData) { - if ($validationData->getParticipant($app)->getUser($app)->get_id() == $user->get_id()) { + if ($validationData->getParticipant()->getUser()->getId() == $user->getId()) { return $validationData; } } - throw new \Exception('There is no such participant ' . $user->get_email()); + throw new \Exception('There is no such participant ' . $user->getEmail()); } } diff --git a/lib/Alchemy/Phrasea/Model/Entities/Feed.php b/lib/Alchemy/Phrasea/Model/Entities/Feed.php index cb78a46981..c9c843dbe3 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/Feed.php +++ b/lib/Alchemy/Phrasea/Model/Entities/Feed.php @@ -278,16 +278,16 @@ class Feed implements FeedInterface } /** - * Returns a boolean indicating whether the given User_Adapter is the owner of the feed. + * Returns a boolean indicating whether the given user is the owner of the feed. * - * @param \User_Adapter $user + * @param User $user * * @return boolean */ - public function isOwner(\User_Adapter $user) + public function isOwner(User $user) { $owner = $this->getOwner(); - if ($owner !== null && $user->get_id() === $owner->getUsrId()) { + if ($owner !== null && $user->getId() === $owner->getUser()->getId()) { return true; } @@ -372,16 +372,16 @@ class Feed implements FeedInterface } /** - * Returns a boolean indicating whether the given User_Adapter is a publisher of the feed. + * Returns a boolean indicating whether the given user is a publisher of the feed. * - * @param \User_Adapter $user + * @param User $user * * @return boolean */ - public function isPublisher(\User_Adapter $user) + public function isPublisher(User $user) { foreach ($this->getPublishers() as $publisher) { - if ($publisher->getUsrId() == $user->get_id()) { + if ($publisher->getUser()->getId() == $user->getId()) { return true; } } @@ -390,16 +390,16 @@ class Feed implements FeedInterface } /** - * Returns an instance of FeedPublisher matching to the given User_Adapter + * Returns an instance of FeedPublisher matching to the given user. * - * @param \User_Adapter $user + * @param User $user * * @return FeedPublisher */ - public function getPublisher(\User_Adapter $user) + public function getPublisher(User $user) { foreach ($this->getPublishers() as $publisher) { - if ($publisher->getUsrId() == $user->get_id()) { + if ($publisher->getUser()->getId() == $user->getId()) { return $publisher; } } @@ -451,14 +451,14 @@ class Feed implements FeedInterface } /** - * Returns a boolean indicating whether the given User_Adapter has access to the feed + * Returns a boolean indicating whether the given user has access to the feed. * - * @param \User_Adapter $user - * @param Application $app + * @param User $user + * @param Application $app * * @return boolean */ - public function hasAccess(\User_Adapter $user, Application $app) + public function hasAccess(User $user, Application $app) { if ($this->getCollection($app) instanceof collection) { return $app['acl']->get($user)->has_access_to_base($this->collection->get_base_id()); @@ -548,12 +548,12 @@ class Feed implements FeedInterface * * Returns a boolean indicating whether a given user has access to the feed * - * @param \User_Adapter $user + * @param User $user * @param \Alchemy\Phrasea\Application $app * * @return boolean */ - public function isAccessible(\User_Adapter $user, Application $app) + public function isAccessible(User $user, Application $app) { $coll = $this->getCollection($app); if ($this->isPublic() diff --git a/lib/Alchemy/Phrasea/Model/Entities/FeedEntry.php b/lib/Alchemy/Phrasea/Model/Entities/FeedEntry.php index e885c0bbce..0ab608482b 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/FeedEntry.php +++ b/lib/Alchemy/Phrasea/Model/Entities/FeedEntry.php @@ -313,16 +313,16 @@ class FeedEntry } /** - * Returns a boolean indicating whether the given User_Adapter is the publisher of the entry. + * Returns a boolean indicating whether the given User is the publisher of the entry. * - * @param \User_Adapter $user + * @param User $user * * @return boolean */ - public function isPublisher(\User_Adapter $user) + public function isPublisher(User $user) { if ($this->publisher) { - if ($this->publisher->getUsrId() === $user->get_id()) { + if ($this->publisher->getUser()->getId() === $user->getId()) { return true; } } diff --git a/lib/Alchemy/Phrasea/Model/Entities/FeedPublisher.php b/lib/Alchemy/Phrasea/Model/Entities/FeedPublisher.php index 540e19ac47..ba7d30b1c4 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/FeedPublisher.php +++ b/lib/Alchemy/Phrasea/Model/Entities/FeedPublisher.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; @@ -29,9 +28,12 @@ class FeedPublisher private $id; /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="boolean") @@ -61,26 +63,23 @@ class FeedPublisher } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return FeedPublisher */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usrId = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usrId; + return $this->user; } /** @@ -129,18 +128,6 @@ class FeedPublisher return $this->feed; } - /** - * Get user - * - * @return \User_Adapter - */ - public function getUser(Application $app) - { - $user = \User_Adapter::getInstance($this->getUsrId(), $app); - - return $user; - } - /** * Set created_on * diff --git a/lib/Alchemy/Phrasea/Model/Entities/FeedToken.php b/lib/Alchemy/Phrasea/Model/Entities/FeedToken.php index f173c9c7db..09e43ebe88 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/FeedToken.php +++ b/lib/Alchemy/Phrasea/Model/Entities/FeedToken.php @@ -27,9 +27,12 @@ class FeedToken private $id; /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string", length=12, nullable=true) @@ -53,26 +56,23 @@ class FeedToken } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return FeedToken */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usrId = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usrId; + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/FtpCredential.php b/lib/Alchemy/Phrasea/Model/Entities/FtpCredential.php index 023fefa03c..536c276af6 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/FtpCredential.php +++ b/lib/Alchemy/Phrasea/Model/Entities/FtpCredential.php @@ -27,14 +27,9 @@ class FtpCredential */ private $id; - /** - * @ORM\Column(type="integer") - */ - private $usrId; - /** * @ORM\OneToOne(targetEntity="User", inversedBy="ftpCredential") - * @ORM\JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) **/ private $user; @@ -97,22 +92,6 @@ class FtpCredential return $this->id; } - /** - * @return integer - */ - public function getUsrId() - { - return $this->usrId; - } - - /** - * @param integer $usrId - */ - public function setUsrId($usrId) - { - $this->usrId = $usrId; - } - /** * @return User */ diff --git a/lib/Alchemy/Phrasea/Model/Entities/FtpExport.php b/lib/Alchemy/Phrasea/Model/Entities/FtpExport.php index 9d20b36669..335dd7a0df 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/FtpExport.php +++ b/lib/Alchemy/Phrasea/Model/Entities/FtpExport.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; @@ -90,9 +89,12 @@ class FtpExport private $textMailReceiver; /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="text", nullable=true) @@ -141,6 +143,26 @@ class FtpExport return $this->id; } + /** + * @param User $user + * + * @return FtpExport + */ + public function setUser(User $user) + { + $this->user = $user; + + return $this; + } + + /** + * @return User + */ + public function getUser() + { + return $this->user; + } + /** * Set crash * @@ -441,54 +463,6 @@ class FtpExport return $this->textMailReceiver; } - /** - * Set usrId - * - * @param integer $usrId - * - * @return FtpExport - */ - public function setUsrId($usrId) - { - $this->usrId = $usrId; - - return $this; - } - - /** - * Get usrId - * - * @return integer - */ - public function getUsrId() - { - return $this->usrId; - } - - /** - * Get user - * - * @return \User_Adapter - */ - public function getUser(Application $app) - { - return \User_Adapter::getInstance($this->getUsr_id(), $app); - } - - /** - * Set user - * - * @param \User_Adapter $user - * - * @return FtpExport - */ - public function setUser(\User_Adapter $user) - { - $this->setUsrId($user->get_id()); - - return $this; - } - /** * Set foldertocreate * diff --git a/lib/Alchemy/Phrasea/Model/Entities/LazaretSession.php b/lib/Alchemy/Phrasea/Model/Entities/LazaretSession.php index 7348129258..f3c83c9ba3 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/LazaretSession.php +++ b/lib/Alchemy/Phrasea/Model/Entities/LazaretSession.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; @@ -28,10 +27,13 @@ class LazaretSession */ private $id; - /** - * @ORM\Column(type="integer", nullable=true) - */ - private $usr_id; + /** + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @Gedmo\Timestampable(on="create") @@ -70,44 +72,23 @@ class LazaretSession } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return LazaretSession */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - /** - * Get user - * - * @return \User_Adapter - */ - public function getUser(Application $app) - { - $user = null; - - try { - $user = \User_Adapter::getInstance($this->usr_id, $app); - } catch (\Exception $e) { - - } - - return $user; + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/Order.php b/lib/Alchemy/Phrasea/Model/Entities/Order.php index 6ea8ee76db..28acc582ff 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/Order.php +++ b/lib/Alchemy/Phrasea/Model/Entities/Order.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; @@ -29,9 +28,12 @@ class Order private $id; /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string", length=2048, name="order_usage") @@ -83,26 +85,23 @@ class Order } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return Order */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usrId = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usrId; + return $this->user; } /** @@ -184,20 +183,6 @@ class Order return $this->elements; } - /** - * Returns the user matching to the usr_id property. - * - * @param Application $app - * - * @return User_Adapter - */ - public function getUser(Application $app) - { - if ($this->getUsrId()) { - return \User_Adapter::getInstance($this->getUsrId(), $app); - } - } - /** * Set todo * diff --git a/lib/Alchemy/Phrasea/Model/Entities/OrderElement.php b/lib/Alchemy/Phrasea/Model/Entities/OrderElement.php index 462d62930a..d5277abf55 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/OrderElement.php +++ b/lib/Alchemy/Phrasea/Model/Entities/OrderElement.php @@ -38,9 +38,12 @@ class OrderElement private $recordId; /** - * @ORM\Column(type="integer", nullable=true, name="order_master_id") - */ - private $orderMasterId; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="order_master", referencedColumnName="id") + * + * @return User + **/ + private $orderMaster; /** * @ORM\Column(type="boolean", nullable=true) @@ -64,44 +67,23 @@ class OrderElement } /** - * Set order_master_id + * @param User $user * - * @param integer $orderMasterId - * @return OrderElement + * @return $this */ - public function setOrderMasterId($orderMasterId) + public function setOrderMaster(User $user = null) { - $this->orderMasterId = $orderMasterId; + $this->orderMaster = $user; return $this; } /** - * Get order_master_id - * - * @return integer + * @return mixed */ - public function getOrderMasterId() + public function getOrderMaster() { - return $this->orderMasterId; - } - - /** - * - * Returns the username matching to the order_master_id - * - * @param Application $app - * @return string - */ - public function getOrderMasterName(Application $app) - { - if (isset($this->orderMasterId) && null !== $this->orderMasterId) { - $user = \User_Adapter::getInstance($this->orderMasterId, $app); - - return $user->get_firstname(); - } - - return null; + return $this->orderMaster; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/Session.php b/lib/Alchemy/Phrasea/Model/Entities/Session.php index bc3928eb72..cf7b58b036 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/Session.php +++ b/lib/Alchemy/Phrasea/Model/Entities/Session.php @@ -11,12 +11,11 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** - * @ORM\Table(name="Sessions", indexes={@ORM\index(name="usr_id", columns={"usr_id"})}) + * @ORM\Table(name="Sessions", indexes={@ORM\index(name="user_id", columns={"user_id"})}) * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\SessionRepository") */ class Session @@ -29,9 +28,12 @@ class Session private $id; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string", length=512) @@ -114,39 +116,24 @@ class Session return $this->id; } - public function setUser(\User_Adapter $user) - { - return $this->setUsrId($user->get_id()); - } - /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return Session */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } - public function getUser(Application $app) - { - if ($this->getUsrId()) { - return \User_Adapter::getInstance($this->getUsrId(), $app); - } - } - /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/StoryWZ.php b/lib/Alchemy/Phrasea/Model/Entities/StoryWZ.php index c484828e6d..c7fdd93a3a 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/StoryWZ.php +++ b/lib/Alchemy/Phrasea/Model/Entities/StoryWZ.php @@ -17,7 +17,7 @@ use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** - * @ORM\Table(name="StoryWZ", uniqueConstraints={@ORM\UniqueConstraint(name="user_story", columns={"usr_id", "sbas_id", "record_id"})}) + * @ORM\Table(name="StoryWZ", uniqueConstraints={@ORM\UniqueConstraint(name="user_story", columns={"user_id", "sbas_id", "record_id"})}) * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\StoryWZRepository") */ class StoryWZ @@ -40,9 +40,12 @@ class StoryWZ private $record_id; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @Gedmo\Timestampable(on="create") @@ -116,40 +119,24 @@ class StoryWZ $this->setRecordId($record->get_record_id()); $this->setSbasId($record->get_sbas_id()); } - /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return StoryWZ */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - public function setUser(\User_Adapter $user) - { - $this->setUsrId($user->get_id()); - } - - public function getUser(Application $app) - { - if ($this->getUsrId()) { - return \User_Adapter::getInstance($this->getUsrId(), $app); - } + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/User.php b/lib/Alchemy/Phrasea/Model/Entities/User.php index 4c860ef3c1..f7fdd96981 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/User.php +++ b/lib/Alchemy/Phrasea/Model/Entities/User.php @@ -16,7 +16,6 @@ use Alchemy\Phrasea\Exception\InvalidArgumentException; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Gedmo\Mapping\Annotation as Gedmo; -use Symfony\Component\Translation\TranslatorInterface; /** * @ORM\Table(name="Users", @@ -37,9 +36,9 @@ use Symfony\Component\Translation\TranslatorInterface; */ class User { - const GENDER_MR = 'mr'; - const GENDER_MRS = 'mrs'; - const GENDER_MISS = 'miss'; + const GENDER_MR = 2; + const GENDER_MRS = 1; + const GENDER_MISS = 0; const USER_GUEST = 'guest'; const USER_AUTOREGISTER = 'autoregister'; @@ -67,14 +66,14 @@ class User private $password; /** - * @ORM\Column(type="string", length=16, nullable=true) + * @ORM\Column(type="string", length=64, nullable=true) */ private $nonce; /** * @ORM\Column(type="boolean", name="salted_password") */ - private $saltedPassword = false; + private $saltedPassword = true; /** * @ORM\Column(type="string", length=64, name="first_name") @@ -87,7 +86,7 @@ class User private $lastName = ''; /** - * @ORM\Column(type="string", length=8, nullable=true) + * @ORM\Column(type="smallint", nullable=true) */ private $gender; @@ -102,7 +101,7 @@ class User private $city = ''; /** - * @ORM\Column(type="string", length=64) + * @ORM\Column(type="string", length=64, nullable=true) */ private $country = ''; @@ -177,8 +176,9 @@ class User private $ldapCreated = false; /** - * @ORM\Column(type="string", length=64, name="last_model", nullable=true) - */ + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="last_model", referencedColumnName="id") + **/ private $lastModel; /** @@ -224,7 +224,7 @@ class User private $updated; /** - * @ORM\OneToOne(targetEntity="User") + * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="model_of", referencedColumnName="id") * * @var User @@ -291,6 +291,8 @@ class User public function setLogin($login) { $this->login = $login; + + return $this; } /** @@ -307,6 +309,8 @@ class User public function setEmail($email) { $this->email = $email; + + return $this; } /** @@ -324,6 +328,8 @@ class User public function setPassword($password) { $this->password = $password; + + return $this; } /** @@ -340,6 +346,8 @@ class User public function setNonce($nonce) { $this->nonce = $nonce; + + return $this; } /** @@ -356,6 +364,8 @@ class User public function setSaltedPassword($saltedPassword) { $this->saltedPassword = (Boolean) $saltedPassword; + + return $this; } /** @@ -372,6 +382,8 @@ class User public function setFirstName($firstName) { $this->firstName = $firstName; + + return $this; } /** @@ -389,6 +401,8 @@ class User public function setLastName($lastName) { $this->lastName = $lastName; + + return $this; } /** @@ -410,11 +424,13 @@ class User self::GENDER_MISS, self::GENDER_MR, self::GENDER_MRS - ])) { + ], true)) { throw new InvalidArgumentException(sprintf("Invalid gender %s.", $gender)); } $this->gender = $gender; + + return $this; } /** @@ -431,6 +447,8 @@ class User public function setAddress($address) { $this->address = $address; + + return $this; } /** @@ -447,6 +465,8 @@ class User public function setCity($city) { $this->city = $city; + + return $this; } /** @@ -463,6 +483,8 @@ class User public function setCountry($country) { $this->country = $country; + + return $this; } /** @@ -479,6 +501,8 @@ class User public function setZipCode($zipCode) { $this->zipCode = $zipCode; + + return $this; } /** @@ -499,6 +523,8 @@ class User } $this->geonameId = $geonameId; + + return $this; } /** @@ -521,6 +547,8 @@ class User } $this->locale = $locale; + + return $this; } /** @@ -537,6 +565,8 @@ class User public function setTimezone($timezone) { $this->timezone = $timezone; + + return $this; } /** @@ -553,6 +583,8 @@ class User public function setJob($job) { $this->job = $job; + + return $this; } /** @@ -569,6 +601,8 @@ class User public function setActivity($activity) { $this->activity = $activity; + + return $this; } /** @@ -585,6 +619,8 @@ class User public function setCompany($company) { $this->company = $company; + + return $this; } /** @@ -601,6 +637,8 @@ class User public function setPhone($phone) { $this->phone = $phone; + + return $this; } /** @@ -617,6 +655,8 @@ class User public function setFax($fax) { $this->fax = $fax; + + return $this; } /** @@ -633,6 +673,8 @@ class User public function setAdmin($admin) { $this->admin = (Boolean) $admin; + + return $this; } /** @@ -649,6 +691,8 @@ class User public function setGuest($guest) { $this->guest = (Boolean) $guest; + + return $this; } /** @@ -665,6 +709,8 @@ class User public function setMailNotificationsActivated($mailNotifications) { $this->mailNotificationsActivated = (Boolean) $mailNotifications; + + return $this; } /** @@ -681,6 +727,8 @@ class User public function setRequestNotificationsActivated($requestNotifications) { $this->requestNotificationsActivated = (Boolean) $requestNotifications; + + return $this; } /** @@ -697,6 +745,8 @@ class User public function setLdapCreated($ldapCreated) { $this->ldapCreated = (Boolean) $ldapCreated; + + return $this; } /** @@ -713,10 +763,12 @@ class User public function setModelOf(User $owner) { $this->modelOf = $owner; + + return $this; } /** - * @return string + * @return User */ public function getLastModel() { @@ -724,11 +776,13 @@ class User } /** - * @param string $lastModel + * @param User $lastModel */ - public function setLastModel($lastModel) + public function setLastModel(User $lastModel) { $this->lastModel = $lastModel; + + return $this; } /** @@ -745,6 +799,8 @@ class User public function setPushList($pushList) { $this->pushList = $pushList; + + return $this; } /** @@ -761,6 +817,8 @@ class User public function setCanChangeProfil($canChangeProfil) { $this->canChangeProfil = (Boolean) $canChangeProfil; + + return $this; } /** @@ -777,6 +835,8 @@ class User public function setCanChangeFtpProfil($canChangeFtpProfil) { $this->canChangeFtpProfil = (Boolean) $canChangeFtpProfil; + + return $this; } /** @@ -793,6 +853,8 @@ class User public function setLastConnection(\DateTime $lastConnection) { $this->lastConnection = $lastConnection; + + return $this; } /** @@ -809,6 +871,8 @@ class User public function setMailLocked($mailLocked) { $this->mailLocked = (Boolean) $mailLocked; + + return $this; } /** @@ -853,6 +917,8 @@ class User public function setCreated(\Datetime $created) { $this->created = $created; + + return $this; } /** @@ -861,6 +927,8 @@ class User public function setUpdated(\Datetime $updated) { $this->updated = $updated; + + return $this; } /** @@ -962,10 +1030,10 @@ class User /** * @return string */ - public function getDisplayName(TranslatorInterface $translator) + public function getDisplayName() { if ($this->isTemplate()) { - return $translator->trans('modele %name%', ['%name%' => $this->getLogin()]); + return $this->getLogin(); } if (trim($this->lastName) !== '' || trim($this->firstName) !== '') { @@ -976,6 +1044,10 @@ class User return $this->email; } - return $translator->trans('Unnamed user'); + if ('' !== trim($this->getLogin())) { + return $this->getLogin(); + } + + return 'Unnamed user'; } } diff --git a/lib/Alchemy/Phrasea/Model/Entities/UserNotificationSetting.php b/lib/Alchemy/Phrasea/Model/Entities/UserNotificationSetting.php index a747270e8c..17c3af0955 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UserNotificationSetting.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UserNotificationSetting.php @@ -31,14 +31,9 @@ class UserNotificationSetting */ private $id; - /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; - /** * @ORM\ManyToOne(targetEntity="User", inversedBy="notificationSettings") - * @ORM\JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) **/ private $user; @@ -85,33 +80,13 @@ class UserNotificationSetting * * @return UserNotificationSetting */ - public function setUser(User $user = null) + public function setUser(User $user) { $this->user = $user; return $this; } - /** - * @return integer - */ - public function getUsrId() - { - return $this->usrId; - } - - /** - * @param integer $usrId - * - * @return UserSetting - */ - public function setUsrId($usrId) - { - $this->usrId = $usrId; - - return $this; - } - /** * @return string */ diff --git a/lib/Alchemy/Phrasea/Model/Entities/UserQuery.php b/lib/Alchemy/Phrasea/Model/Entities/UserQuery.php index fdbfe01ef3..3013271e71 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UserQuery.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UserQuery.php @@ -27,14 +27,9 @@ class UserQuery */ private $id; - /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; - /** * @ORM\ManyToOne(targetEntity="User", inversedBy="queries") - * @ORM\JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) **/ private $user; @@ -57,22 +52,6 @@ class UserQuery return $this->id; } - /** - * @return integer - */ - public function getUsrId() - { - return $this->usrId; - } - - /** - * @param integer $usrId - */ - public function setUsrId($usrId) - { - $this->usrId = $usrId; - } - /** * @return User */ @@ -86,7 +65,7 @@ class UserQuery * * @return UserQuery */ - public function setUser(User $user = null) + public function setUser(User $user) { $this->user = $user; diff --git a/lib/Alchemy/Phrasea/Model/Entities/UserSetting.php b/lib/Alchemy/Phrasea/Model/Entities/UserSetting.php index acfd44ddfc..5d1a9d2534 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UserSetting.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UserSetting.php @@ -31,14 +31,9 @@ class UserSetting */ private $id; - /** - * @ORM\Column(type="integer", name="usr_id") - */ - private $usrId; - /** * @ORM\ManyToOne(targetEntity="User", inversedBy="settings") - * @ORM\JoinColumn(name="user_id", referencedColumnName="id") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) **/ private $user; @@ -85,33 +80,13 @@ class UserSetting * * @return UserSetting */ - public function setUser(User $user = null) + public function setUser(User $user) { $this->user = $user; return $this; } - /** - * @return integer - */ - public function getUsrId() - { - return $this->usrId; - } - - /** - * @param integer $usrId - * - * @return UserSetting - */ - public function setUsrId($usrId) - { - $this->usrId = $usrId; - - return $this; - } - /** * @return string */ diff --git a/lib/Alchemy/Phrasea/Model/Entities/UsrAuthProvider.php b/lib/Alchemy/Phrasea/Model/Entities/UsrAuthProvider.php index aa07140dca..0b46296e27 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UsrAuthProvider.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UsrAuthProvider.php @@ -11,13 +11,12 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * @ORM\Table(name="UsrAuthProviders", uniqueConstraints={ - * @ORM\UniqueConstraint(name="unique_provider_per_user", columns={"usr_id", "provider"}), + * @ORM\UniqueConstraint(name="unique_provider_per_user", columns={"user_id", "provider"}), * @ORM\UniqueConstraint(name="provider_ids", columns={"provider", "distant_id"}) * }) * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrAuthProviderRepository") @@ -32,9 +31,12 @@ class UsrAuthProvider private $id; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string", length=32) @@ -69,31 +71,23 @@ class UsrAuthProvider } /** - * Set usr_id + * @param User $user * - * @param integer $usrId - * @return UsrAuthProvider + * @return usrAuthprovider */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - public function getUser(Application $app) - { - return \User_Adapter::getInstance($this->usr_id, $app); + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/UsrList.php b/lib/Alchemy/Phrasea/Model/Entities/UsrList.php index 44bbeecfed..99d2af8766 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UsrList.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UsrList.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; @@ -209,10 +208,10 @@ class UsrList return $this->entries; } - public function hasAccess(\User_Adapter $user, Application $app) + public function hasAccess(User $user) { foreach ($this->getOwners() as $owner) { - if ($owner->getUser($app)->get_id() == $user->get_id()) { + if ($owner->getUser()->getId() == $user->getId()) { return true; } } @@ -222,13 +221,13 @@ class UsrList /** * - * @param \User_Adapter $user + * @param User $user * @return UsrListOwner */ - public function getOwner(\User_Adapter $user, Application $app) + public function getOwner(User $user) { foreach ($this->getOwners() as $owner) { - if ($owner->getUser($app)->get_id() == $user->get_id()) { + if ($owner->getUser()->getId() == $user->getId()) { return $owner; } } @@ -239,14 +238,14 @@ class UsrList /** * Return true if one of the entry is related to the given user * - * @param \User_Adapter $user + * @param User $user * @return boolean */ - public function has(\User_Adapter $user, Application $app) + public function has(User $user) { return $this->entries->exists( - function ($key, $entry) use ($user, $app) { - return $entry->getUser($app)->get_id() === $user->get_id(); + function ($key, $entry) use ($user) { + return $entry->getUser()->getId() === $user->getId(); } ); } diff --git a/lib/Alchemy/Phrasea/Model/Entities/UsrListEntry.php b/lib/Alchemy/Phrasea/Model/Entities/UsrListEntry.php index 6cdd23d6c2..b3391b1f83 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UsrListEntry.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UsrListEntry.php @@ -11,12 +11,11 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** - * @ORM\Table(name="UsrListsContent", uniqueConstraints={@ORM\UniqueConstraint(name="unique_usr_per_list", columns={"usr_id", "list_id"})}) + * @ORM\Table(name="UsrListsContent", uniqueConstraints={@ORM\UniqueConstraint(name="unique_usr_per_list", columns={"user_id", "list_id"})}) * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrListEntryRepository") */ class UsrListEntry @@ -29,9 +28,12 @@ class UsrListEntry private $id; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @Gedmo\Timestampable(on="create") @@ -62,36 +64,23 @@ class UsrListEntry } /** - * Set usr_id + * @param User $user * - * @param integer $usrId * @return UsrListEntry */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - public function getUser(Application $app) - { - return \User_Adapter::getInstance($this->getUsrId(), $app); - } - - public function setUser(\User_Adapter $user) - { - return $this->setUsrId($user->get_id()); + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php b/lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php index ea69d65834..d607b95535 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php +++ b/lib/Alchemy/Phrasea/Model/Entities/UsrListOwner.php @@ -11,12 +11,11 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** - * @ORM\Table(name="UsrListOwners", uniqueConstraints={@ORM\UniqueConstraint(name="unique_owner", columns={"usr_id", "id"})}) + * @ORM\Table(name="UsrListOwners", uniqueConstraints={@ORM\UniqueConstraint(name="unique_owner", columns={"user_id", "id"})}) * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrListOwnerRepository") */ class UsrListOwner @@ -33,9 +32,12 @@ class UsrListOwner private $id; /** - * @ORM\Column(type="integer") - */ - private $usr_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $user; /** * @ORM\Column(type="string") @@ -71,36 +73,23 @@ class UsrListOwner } /** - * Set usr_id + * @param User $user * - * @param integer $usrId - * @return UsrListOwner + * @return UsrListowner */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - public function setUser(\User_Adapter $user) - { - return $this->setUsrId($user->get_id()); - } - - public function getUser(Application $app) - { - return \User_Adapter::getInstance($this->getUsrId(), $app); + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/ValidationParticipant.php b/lib/Alchemy/Phrasea/Model/Entities/ValidationParticipant.php index 34ae755d07..564c9f6b88 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/ValidationParticipant.php +++ b/lib/Alchemy/Phrasea/Model/Entities/ValidationParticipant.php @@ -11,7 +11,6 @@ namespace Alchemy\Phrasea\Model\Entities; -use Alchemy\Phrasea\Application; use Doctrine\ORM\Mapping as ORM; /** @@ -27,11 +26,6 @@ class ValidationParticipant */ private $id; - /** - * @ORM\Column(type="integer") - */ - private $usr_id; - /** * @ORM\Column(type="boolean") */ @@ -87,43 +81,31 @@ class ValidationParticipant } /** - * Set usr_id + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false) * - * @param integer $usrId - * @return ValidationParticipant + * @return User + **/ + private $user; + + /** + * @param User $user + * + * @return AggregateToken */ - public function setUsrId($usrId) + public function setUser(User $user) { - $this->usr_id = $usrId; + $this->user = $user; return $this; } /** - * Get usr_id - * - * @return integer + * @return User */ - public function getUsrId() + public function getUser() { - return $this->usr_id; - } - - /** - * - * @param \User_Adapter $user - * @return ValidationParticipant - */ - public function setUser(\User_Adapter $user) - { - $this->usr_id = $user->get_id(); - - return $this; - } - - public function getUser(Application $app) - { - return \User_Adapter::getInstance($this->getUsrId(), $app); + return $this->user; } /** diff --git a/lib/Alchemy/Phrasea/Model/Entities/ValidationSession.php b/lib/Alchemy/Phrasea/Model/Entities/ValidationSession.php index fc40c4e460..02a108c625 100644 --- a/lib/Alchemy/Phrasea/Model/Entities/ValidationSession.php +++ b/lib/Alchemy/Phrasea/Model/Entities/ValidationSession.php @@ -30,9 +30,12 @@ class ValidationSession private $id; /** - * @ORM\Column(type="integer") - */ - private $initiator_id; + * @ORM\ManyToOne(targetEntity="User") + * @ORM\JoinColumn(name="initiator_id", referencedColumnName="id", nullable=false) + * + * @return User + **/ + private $initiator; /** * @Gedmo\Timestampable(on="create") @@ -81,45 +84,35 @@ class ValidationSession } /** - * Set initiator_id + * @param User $user * - * @param integer $initiatorId - * @return ValidationSession + * @return $this */ - public function setInitiatorId($initiatorId) + public function setInitiator(User $user) { - $this->initiator_id = $initiatorId; + $this->initiator = $user; return $this; } /** - * Get initiator_id + * Get validation initiator * - * @return integer + * @return User */ - public function getInitiatorId() + public function getInitiator() { - return $this->initiator_id; + return $this->initiator; } - public function isInitiator(\User_Adapter $user) + /** + * @param User $user + * + * @return boolean + */ + public function isInitiator(User $user) { - return $this->getInitiatorId() == $user->get_id(); - } - - public function setInitiator(\User_Adapter $user) - { - $this->initiator_id = $user->get_id(); - - return; - } - - public function getInitiator(Application $app) - { - if ($this->initiator_id) { - return \User_Adapter::getInstance($this->initiator_id, $app); - } + return $this->getInitiator()->getId() == $user->getId(); } /** @@ -258,21 +251,20 @@ class ValidationSession return $date_obj > $this->getExpires(); } - public function getValidationString(Application $app, \User_Adapter $user) + public function getValidationString(Application $app, User $user) { - if ($this->isInitiator($user)) { if ($this->isFinished()) { return $app->trans('Vous aviez envoye cette demande a %n% utilisateurs', ['%n%' => count($this->getParticipants()) - 1]); - } else { - return $app->trans('Vous avez envoye cette demande a %n% utilisateurs', ['%n%' => count($this->getParticipants()) - 1]); } + + return $app->trans('Vous avez envoye cette demande a %n% utilisateurs', ['%n%' => count($this->getParticipants()) - 1]); } else { - if ($this->getParticipant($user, $app)->getCanSeeOthers()) { - return $app->trans('Processus de validation recu de %user% et concernant %n% utilisateurs', ['%user%' => $this->getInitiator($app)->get_display_name(), '%n%' => count($this->getParticipants()) - 1]); - } else { - return $app->trans('Processus de validation recu de %user%', ['%user%' => $this->getInitiator($app)->get_display_name()]); + if ($this->getParticipant($user)->getCanSeeOthers()) { + return $app->trans('Processus de validation recu de %user% et concernant %n% utilisateurs', ['%user%' => $this->getInitiator($app)->getDisplayName(), '%n%' => count($this->getParticipants()) - 1]); } + + return $app->trans('Processus de validation recu de %user%', ['%user%' => $this->getInitiator($app)->getDisplayName()]); } } @@ -281,14 +273,14 @@ class ValidationSession * * @return ValidationParticipant */ - public function getParticipant(\User_Adapter $user, Application $app) + public function getParticipant(User $user) { foreach ($this->getParticipants() as $participant) { - if ($participant->getUser($app)->get_id() == $user->get_id()) { + if ($participant->getUser()->getId() == $user->getId()) { return $participant; } } - throw new NotFoundHttpException('Participant not found ' . $user->get_email()); + throw new NotFoundHttpException('Participant not found' . $user->getEmail()); } } diff --git a/lib/Alchemy/Phrasea/Model/Manager/UserManager.php b/lib/Alchemy/Phrasea/Model/Manager/UserManager.php index ee068193b0..cf5f6aa41d 100644 --- a/lib/Alchemy/Phrasea/Model/Manager/UserManager.php +++ b/lib/Alchemy/Phrasea/Model/Manager/UserManager.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Model\Manager; use Doctrine\Common\Persistence\ObjectManager; use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\UserSetting; +use Doctrine\ORM\UnitOfWork AS UOW; class UserManager { @@ -46,10 +47,6 @@ class UserManager */ public function delete(User $user, $flush = true) { - $user->setDeleted(true); - $user->setEmail(null); - $user->setLogin(sprintf('(#deleted_%s', $user->getLogin())); - $this->cleanProperties($user); $this->cleanRights($user); @@ -137,7 +134,7 @@ class UserManager private function cleanFtpExports(User $user) { $elements = $this->objectManager->getRepository('Phraseanet:FtpExport') - ->findBy(['usrId' => $user->getId()]); + ->findBy(['user' => $user]); foreach ($elements as $element) { $this->objectManager->remove($element); @@ -152,13 +149,43 @@ class UserManager private function cleanOrders(User $user) { $orders = $this->objectManager->getRepository('Phraseanet:Order') - ->findBy(['usrId' => $user->getId()]); + ->findBy(['user' => $user]); foreach ($orders as $order) { $this->objectManager->remove($order); } } + /** + * Removes user orders. + * + * @param User $user + */ + private function cleanUserSessions(User $user) + { + $sessions = $this->objectManager->getRepository('Phraseanet:Session') + ->findByUser(['user' => $user]); + + foreach ($sessions as $session) { + $this->objectManager->remove($session); + } + } + + /** + * Removes user providers. + * + * @param User $user + */ + private function cleanAuthProvider(User $user) + { + $providers = $this->objectManager->getRepository('Phraseanet:UsrAuthProvider') + ->findBy(['user' => $user]); + + foreach ($providers as $provider) { + $this->objectManager->remove($provider); + } + } + /** * Removes all user's properties. * @@ -180,6 +207,8 @@ class UserManager $this->cleanFtpCredentials($user); $this->cleanOrders($user); $this->cleanFtpExports($user); + $this->cleanAuthProvider($user); + $this->cleanUserSessions($user); } /** diff --git a/lib/Alchemy/Phrasea/Model/Manipulator/ACLManipulator.php b/lib/Alchemy/Phrasea/Model/Manipulator/ACLManipulator.php index 70d3c92381..eb78cabc63 100644 --- a/lib/Alchemy/Phrasea/Model/Manipulator/ACLManipulator.php +++ b/lib/Alchemy/Phrasea/Model/Manipulator/ACLManipulator.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Model\Manipulator; use Alchemy\Phrasea\Authentication\ACLProvider; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class ACLManipulator implements ManipulatorInterface { @@ -39,7 +40,7 @@ class ACLManipulator implements ManipulatorInterface /** * Resets rights for users. * - * @param User_Adapter $user + * @param User[] $users * * @throws InvalidArgumentException */ @@ -53,9 +54,9 @@ class ACLManipulator implements ManipulatorInterface /** * Resets rights for a user. * - * @param \User_adapter $user + * @param User $user */ - private function doResetAdminRights(\User_adapter $user) + private function doResetAdminRights(User $user) { $acl = $this->ACLProvider->get($user); $databoxes = $this->appbox->get_databoxes(); diff --git a/lib/Alchemy/Phrasea/Model/Manipulator/UserManipulator.php b/lib/Alchemy/Phrasea/Model/Manipulator/UserManipulator.php index 10c5a3f9b6..a975ecd4b2 100644 --- a/lib/Alchemy/Phrasea/Model/Manipulator/UserManipulator.php +++ b/lib/Alchemy/Phrasea/Model/Manipulator/UserManipulator.php @@ -74,6 +74,21 @@ class UserManipulator implements ManipulatorInterface return $user; } + /** + * Deletes a user. + * + * @param User|User[] $users + */ + public function delete($users) + { + foreach ($this->makeTraversable($users) as $user) { + $user->setDeleted(true); + $user->setEmail(null); + + $this->manager->delete($user); + } + } + /** * Creates a template user and returns it. * @@ -184,13 +199,17 @@ class UserManipulator implements ManipulatorInterface * @param string $name * @param string $value */ - public function addUserSetting(User $user, $name, $value) + public function setUserSetting(User $user, $name, $value) { - $userSetting = new UserSetting(); - $userSetting->setUsrId($user->getId()); - $userSetting->setName($name); - $userSetting->setValue($value); - $user->addSetting($userSetting); + if ($user->getSettings()->containsKey($name)) { + $user->getSettings()->get($name)->setValue($value); + } else { + $userSetting = new UserSetting(); + $userSetting->setUser($user); + $userSetting->setName($name); + $userSetting->setValue($value); + $user->addSetting($userSetting); + } $this->manager->update($user); } @@ -202,13 +221,17 @@ class UserManipulator implements ManipulatorInterface * @param string $name * @param string $value */ - public function addNotificationSetting(User $user, $name, $value) + public function setNotificationSetting(User $user, $name, $value) { - $notifSetting = new UserNotificationSetting(); - $notifSetting->setName($name); - $notifSetting->setValue($value); - $notifSetting->setUsrId($user->getId()); - $user->addNotificationSettings($notifSetting); + if ($user->getNotificationSettings()->containsKey($name)) { + $user->getNotificationSettings()->get($name)->setValue((Boolean) $value); + } else { + $userSetting = new UserNotificationSetting(); + $userSetting->setUser($user); + $userSetting->setName($name); + $userSetting->setValue($value); + $user->addNotificationSettings($userSetting); + } $this->manager->update($user); } @@ -224,7 +247,7 @@ class UserManipulator implements ManipulatorInterface $userQuery = new UserQuery(); $userQuery->setUser($user); $userQuery->setQuery($query); - $userQuery->setUsrId($user->getId()); + $userQuery->setUser($user); $user->addQuery($userQuery); @@ -241,6 +264,7 @@ class UserManipulator implements ManipulatorInterface { $user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36)); $user->setPassword($this->passwordEncoder->encodePassword($password, $user->getNonce())); + $user->setSaltedPassword(true); } /** diff --git a/lib/Alchemy/Phrasea/Model/NativeQueryProvider.php b/lib/Alchemy/Phrasea/Model/NativeQueryProvider.php new file mode 100644 index 0000000000..8ea422c27d --- /dev/null +++ b/lib/Alchemy/Phrasea/Model/NativeQueryProvider.php @@ -0,0 +1,87 @@ +em = $em; + } + + public function getUsersRegistrationDemand(array $basList) + { + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata('Alchemy\Phrasea\Model\Entities\User', 'u'); + $rsm->addScalarResult('date_demand', 'date_demand'); + $rsm->addScalarResult('base_demand', 'base_demand'); + + $selectClause = $rsm->generateSelectClause(); + + return $this->em->createNativeQuery(" + SELECT d.date_modif AS date_demand, d.base_id AS base_demand, " . $selectClause . " + FROM (demand d INNER JOIN Users u ON d.usr_id=u.id + AND d.en_cours=1 + AND u.deleted=0 + ) + WHERE (base_id='" . implode("' OR base_id='", $basList) . "') + ORDER BY d.usr_id DESC, d.base_id ASC + ", $rsm) + ->getResult(); + } + + public function getModelForUser(User $user, array $basList) + { + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata('Alchemy\Phrasea\Model\Entities\User', 'u'); + + $selectClause = $rsm->generateSelectClause(); + + $query = $this->em->createNativeQuery(" + SELECT " . $selectClause . " + FROM Users u + INNER JOIN basusr b ON (b.usr_id=u.id) + WHERE u.model_of = :user_id + AND b.base_id IN (" . implode(', ', $basList) . ") + AND u.deleted='0' + GROUP BY u.id", $rsm); + + $query->setParameter(':user_id', $user->getId()); + + return $query->getResult(); + } + + public function getAdminsOfBases(array $basList) + { + $rsm = new ResultSetMappingBuilder($this->em); + $rsm->addRootEntityFromClassMetadata('Alchemy\Phrasea\Model\Entities\User', 'u'); + $rsm->addScalarResult('base_id', 'base_id'); + $selectClause = $rsm->generateSelectClause(); + + $query = $this->em->createNativeQuery(' + SELECT b.base_id, '.$selectClause.' FROM Users u, basusr b + WHERE u.id = b.usr_id + AND b.base_id IN (' . implode(', ', $basList) . ') + AND u.model_of IS NULL + AND b.actif="1" + AND b.canadmin="1" + AND u.deleted="0"', $rsm + ); + + return $query->getResults(); + } +} diff --git a/lib/Alchemy/Phrasea/Model/Repositories/BasketElementRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/BasketElementRepository.php index 3f6a87ff4d..f2a617af07 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/BasketElementRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/BasketElementRepository.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Model\Repositories; use Alchemy\Phrasea\Model\Entities\BasketElement; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -24,7 +25,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class BasketElementRepository extends EntityRepository { - public function findUserElement($element_id, \User_Adapter $user) + public function findUserElement($element_id, User $user) { $dql = 'SELECT e FROM Phraseanet:BasketElement e @@ -32,12 +33,12 @@ class BasketElementRepository extends EntityRepository LEFT JOIN e.validation_datas vd LEFT JOIN b.validation s LEFT JOIN s.participants p - WHERE (b.usr_id = :usr_id OR p.usr_id = :same_usr_id) + WHERE (b.user = :usr_id OR p.user = :same_usr_id) AND e.id = :element_id'; $params = [ - 'usr_id' => $user->get_id(), - 'same_usr_id' => $user->get_id(), + 'usr_id' => $user->getId(), + 'same_usr_id' => $user->getId(), 'element_id' => $element_id ]; @@ -97,25 +98,25 @@ class BasketElementRepository extends EntityRepository /** * * @param \record_adapter $record - * @param \User_Adapter $user + * @param User $user * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findReceivedElementsByRecord(\record_adapter $record, \User_Adapter $user) + public function findReceivedElementsByRecord(\record_adapter $record, User $user) { $dql = 'SELECT e FROM Phraseanet:BasketElement e JOIN e.basket b LEFT JOIN b.validation s LEFT JOIN s.participants p - WHERE b.usr_id = :usr_id - AND b.pusher_id IS NOT NULL + WHERE b.user = :usr_id + AND b.pusher IS NOT NULL AND e.record_id = :record_id AND e.sbas_id = :sbas_id'; $params = [ 'sbas_id' => $record->get_sbas_id(), 'record_id' => $record->get_record_id(), - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; $query = $this->_em->createQuery($dql); @@ -124,21 +125,21 @@ class BasketElementRepository extends EntityRepository return $query->getResult(); } - public function findReceivedValidationElementsByRecord(\record_adapter $record, \User_Adapter $user) + public function findReceivedValidationElementsByRecord(\record_adapter $record, User $user) { $dql = 'SELECT e FROM Phraseanet:BasketElement e JOIN e.basket b JOIN b.validation v JOIN v.participants p - WHERE p.usr_id = :usr_id + WHERE p.user = :usr_id AND e.record_id = :record_id AND e.sbas_id = :sbas_id'; $params = [ 'sbas_id' => $record->get_sbas_id(), 'record_id' => $record->get_record_id(), - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; $query = $this->_em->createQuery($dql); diff --git a/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php index dd2dec24ca..d2a65b80ed 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/BasketRepository.php @@ -12,7 +12,10 @@ namespace Alchemy\Phrasea\Model\Repositories; use Alchemy\Phrasea\Model\Entities\Basket; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; +use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class BasketRepository extends EntityRepository { @@ -24,15 +27,15 @@ class BasketRepository extends EntityRepository /** * Returns all basket for a given user that are not marked as archived * - * @param \User_Adapter $user + * @param User $user * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findActiveByUser(\User_Adapter $user, $sort = null) + public function findActiveByUser(User $user, $sort = null) { $dql = 'SELECT b FROM Phraseanet:Basket b LEFT JOIN b.elements e - WHERE b.usr_id = :usr_id + WHERE b.user = :usr_id AND b.archived = false'; if ($sort == 'date') { @@ -42,7 +45,7 @@ class BasketRepository extends EntityRepository } $query = $this->_em->createQuery($dql); - $query->setParameters(['usr_id' => $user->get_id()]); + $query->setParameters(['usr_id' => $user->getId()]); return $query->getResult(); } @@ -50,10 +53,10 @@ class BasketRepository extends EntityRepository /** * Returns all unread basket for a given user that are not marked as archived * - * @param \User_Adapter $user + * @param User $user * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findUnreadActiveByUser(\User_Adapter $user) + public function findUnreadActiveByUser(User $user) { $dql = 'SELECT b FROM Phraseanet:Basket b @@ -62,17 +65,17 @@ class BasketRepository extends EntityRepository LEFT JOIN s.participants p WHERE b.archived = false AND ( - (b.usr_id = :usr_id_owner AND b.is_read = false) - OR (b.usr_id != :usr_id_ownertwo - AND p.usr_id = :usr_id_participant + (b.user = :usr_id_owner AND b.is_read = false) + OR (b.user != :usr_id_ownertwo + AND p.user = :usr_id_participant AND p.is_aware = false) ) AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())'; $params = [ - 'usr_id_owner' => $user->get_id(), - 'usr_id_ownertwo' => $user->get_id(), - 'usr_id_participant' => $user->get_id() + 'usr_id_owner' => $user->getId(), + 'usr_id_ownertwo' => $user->getId(), + 'usr_id_participant' => $user->getId() ]; $query = $this->_em->createQuery($dql); @@ -85,10 +88,10 @@ class BasketRepository extends EntityRepository * Returns all baskets that are in validation session not expired and * where a specified user is participant (not owner) * - * @param \User_Adapter $user + * @param User $user * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findActiveValidationByUser(\User_Adapter $user, $sort = null) + public function findActiveValidationByUser(User $user, $sort = null) { $dql = 'SELECT b FROM Phraseanet:Basket b @@ -96,7 +99,7 @@ class BasketRepository extends EntityRepository JOIN e.validation_datas v JOIN b.validation s JOIN s.participants p - WHERE b.usr_id != ?1 AND p.usr_id = ?2 + WHERE b.user != ?1 AND p.user = ?2 AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) '; if ($sort == 'date') { @@ -106,23 +109,68 @@ class BasketRepository extends EntityRepository } $query = $this->_em->createQuery($dql); - $query->setParameters([1 => $user->get_id(), 2 => $user->get_id()]); + $query->setParameters([1 => $user->getId(), 2 => $user->getId()]); return $query->getResult(); } - public function findContainingRecordForUser(\record_adapter $record, \User_Adapter $user) + /** + * Find a basket specified by his basket_id and his owner + * + * @throws NotFoundHttpException + * @throws AccessDeniedHttpException + * @param type $basket_id + * @param User $user + * @return Basket + */ + public function findUserBasket($basket_id, User $user, $requireOwner) + { + $dql = 'SELECT b + FROM Phraseanet:Basket b + LEFT JOIN b.elements e + WHERE b.id = :basket_id'; + + $query = $this->_em->createQuery($dql); + $query->setParameters(['basket_id' => $basket_id]); + + $basket = $query->getOneOrNullResult(); + + /* @var $basket Basket */ + if (null === $basket) { + throw new NotFoundHttpException(_('Basket is not found')); + } + + if ($basket->getUser()->getId() != $user->getId()) { + $participant = false; + + if ($basket->getValidation() && !$requireOwner) { + try { + $basket->getValidation()->getParticipant($user); + $participant = true; + } catch (\Exception $e) { + + } + } + if (!$participant) { + throw new AccessDeniedHttpException(_('You have not access to this basket')); + } + } + + return $basket; + } + + public function findContainingRecordForUser(\record_adapter $record, User $user) { $dql = 'SELECT b FROM Phraseanet:Basket b JOIN b.elements e WHERE e.record_id = :record_id AND e.sbas_id = e.sbas_id - AND b.usr_id = :usr_id'; + AND b.user = :usr_id'; $params = [ 'record_id' => $record->get_record_id(), - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; $query = $this->_em->createQuery($dql); @@ -131,7 +179,7 @@ class BasketRepository extends EntityRepository return $query->getResult(); } - public function findWorkzoneBasket(\User_Adapter $user, $query, $year, $type, $offset, $perPage) + public function findWorkzoneBasket(User $user, $query, $year, $type, $offset, $perPage) { $params = []; @@ -140,9 +188,9 @@ class BasketRepository extends EntityRepository $dql = 'SELECT b FROM Phraseanet:Basket b JOIN b.elements e - WHERE b.usr_id = :usr_id AND b.pusher_id IS NOT NULL'; + WHERE b.user = :usr_id AND b.pusher_id IS NOT NULL'; $params = [ - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; break; case self::VALIDATION_DONE: @@ -151,10 +199,10 @@ class BasketRepository extends EntityRepository JOIN b.elements e JOIN b.validation s JOIN s.participants p - WHERE b.usr_id != ?1 AND p.usr_id = ?2'; + WHERE b.user != ?1 AND p.user = ?2'; $params = [ - 1 => $user->get_id() - , 2 => $user->get_id() + 1 => $user->getId() + , 2 => $user->getId() ]; break; case self::VALIDATION_SENT: @@ -162,9 +210,9 @@ class BasketRepository extends EntityRepository FROM Phraseanet:Basket b JOIN b.elements e JOIN b.validation v - WHERE b.usr_id = :usr_id'; + WHERE b.user = :usr_id'; $params = [ - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; break; default: @@ -173,10 +221,10 @@ class BasketRepository extends EntityRepository LEFT JOIN b.elements e LEFT JOIN b.validation s LEFT JOIN s.participants p - WHERE (b.usr_id = :usr_id OR p.usr_id = :validating_usr_id)'; + WHERE (b.user = :usr_id OR p.user = :validating_usr_id)'; $params = [ - 'usr_id' => $user->get_id(), - 'validating_usr_id' => $user->get_id() + 'usr_id' => $user->getId(), + 'validating_usr_id' => $user->getId() ]; break; case self::MYBASKETS: @@ -185,9 +233,9 @@ class BasketRepository extends EntityRepository LEFT JOIN b.elements e LEFT JOIN b.validation s LEFT JOIN s.participants p - WHERE (b.usr_id = :usr_id)'; + WHERE (b.user = :usr_id)'; $params = [ - 'usr_id' => $user->get_id() + 'usr_id' => $user->getId() ]; break; } @@ -221,19 +269,19 @@ class BasketRepository extends EntityRepository /** * Return all actives validation where current user is involved and user basket * - * @param \User_Adapter $user - * @param type $sort + * @param User $user + * @param type $sort * @return Array */ - public function findActiveValidationAndBasketByUser(\User_Adapter $user, $sort = null) + public function findActiveValidationAndBasketByUser(User $user, $sort = null) { $dql = 'SELECT b FROM Phraseanet:Basket b LEFT JOIN b.elements e LEFT JOIN b.validation s LEFT JOIN s.participants p - WHERE (b.usr_id = :usr_id AND b.archived = false) - OR (b.usr_id != :usr_id AND p.usr_id = :usr_id + WHERE (b.user = :usr_id AND b.archived = false) + OR (b.user != :usr_id AND p.user = :usr_id AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) )'; @@ -244,7 +292,7 @@ class BasketRepository extends EntityRepository } $query = $this->_em->createQuery($dql); - $query->setParameters(['usr_id' => $user->get_id()]); + $query->setParameters(['usr_id' => $user->getId()]); return $query->getResult(); } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/FeedRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/FeedRepository.php index c685785673..ac852df021 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/FeedRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/FeedRepository.php @@ -24,7 +24,6 @@ class FeedRepository extends EntityRepository /** * Returns all the feeds a user can access. * - * @param User_Adapter $user * @return \Doctrine\Common\Collections\Collection */ public function getAllForUser(\ACL $userACL) diff --git a/lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php index 8c3649863d..c5009348ba 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php @@ -11,6 +11,7 @@ namespace Alchemy\Phrasea\Model\Repositories; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; /** @@ -62,12 +63,12 @@ class FtpExportRepository extends EntityRepository /** * Returns the exports initiated by a given user. * - * @param \User_Adapter $user + * @param User $user * * @return array */ - public function findByUser(\User_Adapter $user) + public function findByUser(User $user) { - return $this->findBy(['usrId' => $user->get_id()]); + return $this->findBy(['user' => $user]); } } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php index abf72bd765..4df8e69479 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/OrderRepository.php @@ -11,7 +11,9 @@ namespace Alchemy\Phrasea\Model\Repositories; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\NoResultException; /** * OrderRepository @@ -24,13 +26,13 @@ class OrderRepository extends EntityRepository /** * Returns the orders initiated by a given user. * - * @param \User_Adapter $user + * @param User $user * * @return array */ - public function findByUser(\User_Adapter $user) + public function findByUser(User $user) { - return $this->findBy(['usrId' => $user->get_id()]); + return $this->findBy(['user' => $user->getId()]); } /** @@ -54,7 +56,7 @@ class OrderRepository extends EntityRepository } if ($sort === 'user') { - $qb->orderBy('o.userId', 'ASC'); + $qb->orderBy('o.user', 'ASC'); } elseif ($sort === 'usage') { $qb->orderBy('o.orderUsage', 'ASC'); } else { @@ -88,6 +90,10 @@ class OrderRepository extends EntityRepository $qb->groupBy('o.id'); - return $qb->getQuery()->getSingleScalarResult(); + try { + return $qb->getQuery()->getSingleScalarResult(); + } catch (NoResultException $e) { + return 0; + } } } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/SessionRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/SessionRepository.php index f2f1befa29..fffcb7de41 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/SessionRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/SessionRepository.php @@ -21,15 +21,4 @@ use Doctrine\ORM\EntityRepository; */ class SessionRepository extends EntityRepository { - public function findByUser(\User_Adapter $user) - { - $dql = 'SELECT s - FROM Phraseanet:Session s - WHERE s.usr_id = :usr_id'; - - $query = $this->_em->createQuery($dql); - $query->setParameters(['usr_id' => $user->get_id()]); - - return $query->getResult(); - } } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/StoryWZRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/StoryWZRepository.php index 8e28107e28..c48f3881d2 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/StoryWZRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/StoryWZRepository.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Model\Repositories; use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -25,16 +26,16 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class StoryWZRepository extends EntityRepository { - public function findByUser(Application $app, \User_Adapter $user, $sort) + public function findByUser(Application $app, User $user, $sort) { - $dql = 'SELECT s FROM Phraseanet:StoryWZ s WHERE s.usr_id = :usr_id '; + $dql = 'SELECT s FROM Phraseanet:StoryWZ s WHERE s.user = :user '; if ($sort == 'date') { $dql .= ' ORDER BY s.created DESC'; } $query = $this->_em->createQuery($dql); - $query->setParameters(['usr_id' => $user->get_id()]); + $query->setParameters(['user' => $user]); $stories = $query->getResult(); @@ -71,7 +72,7 @@ class StoryWZRepository extends EntityRepository return $stories; } - public function findByUserAndId(Application $app, \User_Adapter $user, $id) + public function findByUserAndId(Application $app, User $user, $id) { $story = $this->find($id); @@ -83,7 +84,7 @@ class StoryWZRepository extends EntityRepository throw new NotFoundHttpException('Story not found'); } - if ($story->getUser($app)->get_id() !== $user->get_id()) { + if ($story->getUser()->getId() !== $user->getId()) { throw new AccessDeniedHttpException('You have not access to ths story'); } } else { @@ -93,15 +94,13 @@ class StoryWZRepository extends EntityRepository return $story; } - public function findUserStory(Application $app, \User_Adapter $user, \record_adapter $Story) + public function findUserStory(Application $app, User $user, \record_adapter $Story) { - $story = $this->findOneBy( - [ - 'usr_id' => $user->get_id(), - 'sbas_id' => $Story->get_sbas_id(), - 'record_id' => $Story->get_record_id(), - ] - ); + $story = $this->findOneBy([ + 'user' => $user->getId(), + 'sbas_id' => $Story->get_sbas_id(), + 'record_id' => $Story->get_record_id(), + ]); if ($story) { try { @@ -118,7 +117,8 @@ class StoryWZRepository extends EntityRepository public function findByRecord(Application $app, \record_adapter $Story) { - $dql = 'SELECT s FROM Phraseanet:StoryWZ s WHERE s.sbas_id = :sbas_id + $dql = 'SELECT s FROM Phraseanet:StoryWZ s + WHERE s.sbas_id = :sbas_id AND s.record_id = :record_id'; $query = $this->_em->createQuery($dql); @@ -147,9 +147,7 @@ class StoryWZRepository extends EntityRepository $dql = 'SELECT s FROM Phraseanet:StoryWZ s WHERE s.sbas_id = :sbas_id'; $query = $this->_em->createQuery($dql); - $query->setParameters([ - 'sbas_id' => $databox->get_sbas_id(), - ]); + $query->setParameters(['sbas_id' => $databox->get_sbas_id(),]); $stories = $query->getResult(); diff --git a/lib/Alchemy/Phrasea/Model/Repositories/UserRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/UserRepository.php index c2c8f03023..38545cca7e 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/UserRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/UserRepository.php @@ -67,4 +67,35 @@ class UserRepository extends EntityRepository return $qb->getQuery()->getOneOrNullResult(); } + + /** + * Finds a user that is not deleted, not a model and not a guest. + * + * @param $login + * + * @return null|User + */ + public function findRealUserByLogin($login) + { + $qb = $this->createQueryBuilder('u'); + $qb->where($qb->expr()->eq('u.login', $qb->expr()->literal($login))) + ->andWhere($qb->expr()->isNotNull('u.email')) + ->andWhere($qb->expr()->isNull('u.modelOf')) + ->andWhere($qb->expr()->eq('u.guest', $qb->expr()->literal(false))) + ->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false))); + + return $qb->getQuery()->getOneOrNullResult(); + } + + /** + * Finds model of given user. + * + * @param User $user + * + * @return array + */ + public function findModelOf(User $user) + { + return $this->findBy(['modelOf' => $user->getId()]); + } } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/UsrAuthProviderRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/UsrAuthProviderRepository.php index dbee020012..4bf149e366 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/UsrAuthProviderRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/UsrAuthProviderRepository.php @@ -11,6 +11,7 @@ namespace Alchemy\Phrasea\Model\Repositories; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\ORM\EntityRepository; /** @@ -21,13 +22,13 @@ use Doctrine\ORM\EntityRepository; */ class UsrAuthProviderRepository extends EntityRepository { - public function findByUser(\User_Adapter $user) + public function findByUser(User $user) { $dql = 'SELECT u FROM Phraseanet:UsrAuthProvider u - WHERE u.usr_id = :usrId'; + WHERE u.user = :usrId'; - $params = ['usrId' => $user->get_id()]; + $params = ['usrId' => $user->getId()]; $query = $this->_em->createQuery($dql); $query->setParameters($params); diff --git a/lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php index 753caf7ddd..fe78d1a8ac 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/UsrListEntryRepository.php @@ -11,9 +11,11 @@ namespace Alchemy\Phrasea\Model\Repositories; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\UsrList; use Alchemy\Phrasea\Model\Entities\UsrListEntry; use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\NoResultException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -29,16 +31,16 @@ class UsrListEntryRepository extends EntityRepository /** * Get all lists entries matching a given User * - * @param \User_Adapter $user - * @param type $like + * @param User $user + * @param type $like */ - public function findUserList(\User_Adapter $user) + public function findUserList(User $user) { $dql = 'SELECT e FROM Phraseanet:UsrListEntry e - WHERE e.usr_id = :usr_id'; + WHERE e.user = :usr_id'; $params = [ - 'usr_id' => $user->get_id(), + 'usr_id' => $user->getId(), ]; $query = $this->_em->createQuery($dql); @@ -67,7 +69,7 @@ class UsrListEntryRepository extends EntityRepository { $dql = 'SELECT e FROM Phraseanet:UsrListEntry e JOIN e.list l - WHERE e.usr_id = :usr_id AND l.id = :list_id'; + WHERE e.user = :usr_id AND l.id = :list_id'; $params = [ 'usr_id' => $usr_id, @@ -77,12 +79,12 @@ class UsrListEntryRepository extends EntityRepository $query = $this->_em->createQuery($dql); $query->setParameters($params); - $entry = $query->getResult(); - - if (!$entry) { - throw new NotFoundHttpException('Entry not found'); + try { + $entry = $query->getSingleResult(); + } catch (NoResultException $e) { + throw new NotFoundHttpException('Entry not found', null, $e); } - return $query->getSingleResult(); + return $entry; } } diff --git a/lib/Alchemy/Phrasea/Model/Repositories/UsrListOwnerRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/UsrListOwnerRepository.php index fe77e47300..4ece2eb632 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/UsrListOwnerRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/UsrListOwnerRepository.php @@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Model\Repositories; use Alchemy\Phrasea\Model\Entities\UsrListOwner; use Alchemy\Phrasea\Model\Entities\UsrList; use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\NoResultException; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -60,7 +61,7 @@ class UsrListOwnerRepository extends EntityRepository { $dql = 'SELECT o FROM Phraseanet:UsrListOwner o JOIN o.list l - WHERE l.id = :list_id AND o.usr_id = :usr_id'; + WHERE l.id = :list_id AND o.user = :usr_id'; $params = [ 'usr_id' => $usr_id, @@ -70,11 +71,10 @@ class UsrListOwnerRepository extends EntityRepository $query = $this->_em->createQuery($dql); $query->setParameters($params); - $owner = $query->getSingleResult(); - - /* @var $owner UsrListOwner */ - if (null === $owner) { - throw new NotFoundHttpException('Owner is not found'); + try { + $owner = $query->getSingleResult(); + } catch (NoResultException $e) { + throw new NotFoundHttpException('Owner is not found', null, $e); } return $owner; diff --git a/lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php b/lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php index 7cc4ef028a..dc0281191e 100644 --- a/lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php +++ b/lib/Alchemy/Phrasea/Model/Repositories/UsrListRepository.php @@ -11,7 +11,7 @@ namespace Alchemy\Phrasea\Model\Repositories; -use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\UsrList; use Doctrine\ORM\EntityRepository; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; @@ -29,17 +29,17 @@ class UsrListRepository extends EntityRepository /** * Get all lists readable for a given User * - * @param \User_Adapter $user + * @param User $user * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findUserLists(\User_Adapter $user) + public function findUserLists(User $user) { $dql = 'SELECT l FROM Phraseanet:UsrList l JOIN l.owners o - WHERE o.usr_id = :usr_id'; + WHERE o.user = :usr_id'; $params = [ - 'usr_id' => $user->get_id(), + 'usr_id' => $user->getId(), ]; $query = $this->_em->createQuery($dql); @@ -50,11 +50,11 @@ class UsrListRepository extends EntityRepository /** * - * @param \User_Adapter $user - * @param type $list_id + * @param User $user + * @param type $list_id * @return UsrList */ - public function findUserListByUserAndId(Application $app, \User_Adapter $user, $list_id) + public function findUserListByUserAndId(User $user, $list_id) { $list = $this->find($list_id); @@ -63,7 +63,7 @@ class UsrListRepository extends EntityRepository throw new NotFoundHttpException('List is not found.'); } - if ( ! $list->hasAccess($user, $app)) { + if (!$list->hasAccess($user)) { throw new AccessDeniedHttpException('You have not access to this list.'); } @@ -73,18 +73,18 @@ class UsrListRepository extends EntityRepository /** * Search for a UsrList like '' with a given value, for a user * - * @param \User_Adapter $user + * @param User $user * @param type $name * @return \Doctrine\Common\Collections\ArrayCollection */ - public function findUserListLike(\User_Adapter $user, $name) + public function findUserListLike(User $user, $name) { $dql = 'SELECT l FROM Phraseanet:UsrList l JOIN l.owners o - WHERE o.usr_id = :usr_id AND l.name LIKE :name'; + WHERE o.user = :usr_id AND l.name LIKE :name'; $params = [ - 'usr_id' => $user->get_id(), + 'usr_id' => $user->getId(), 'name' => $name . '%' ]; diff --git a/lib/Alchemy/Phrasea/Notification/Emitter.php b/lib/Alchemy/Phrasea/Notification/Emitter.php index 1ca2d9ccd7..868182a734 100644 --- a/lib/Alchemy/Phrasea/Notification/Emitter.php +++ b/lib/Alchemy/Phrasea/Notification/Emitter.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Notification; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; class Emitter implements EmitterInterface { @@ -47,14 +48,14 @@ class Emitter implements EmitterInterface /** * Creates an Emitter given a User * - * @param \User_Adapter $user + * @param User $user * * @return Emitter * * @throws InvalidArgumentException In case no valid email is found for user */ - public static function fromUser(\User_Adapter $user) + public static function fromUser(User $user) { - return new static($user->get_display_name(), $user->get_email()); + return new static($user->getDisplayName(), $user->getEmail()); } } diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoNewOrder.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoNewOrder.php index 256bc741ba..c56b901d14 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoNewOrder.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoNewOrder.php @@ -12,18 +12,19 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoNewOrder extends AbstractMail { - /** @var \User_Adapter */ + /** @var User */ private $user; /** * Set the user that initiates the order * - * @param \User_Adapter $user + * @param User $user */ - public function setUser(\User_Adapter $user) + public function setUser(User $user) { $this->user = $user; } @@ -41,11 +42,11 @@ class MailInfoNewOrder extends AbstractMail */ public function getMessage() { - if (!$this->user instanceof \User_Adapter) { + if (!$this->user instanceof User) { throw new LogicException('You must set a user before calling getMessage()'); } - return $this->app->trans('%user% has ordered documents', ['%user%' => $this->user->get_display_name()]); + return $this->app->trans('%user% has ordered documents', ['%user%' => $this->user->getDisplayName()]); } /** diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderCancelled.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderCancelled.php index 0017f964db..a8da22facb 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderCancelled.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderCancelled.php @@ -12,10 +12,11 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoOrderCancelled extends AbstractMail { - /** @var \User_Adapter */ + /** @var User */ private $deliverer; /** @var integer */ private $quantity; @@ -33,9 +34,9 @@ class MailInfoOrderCancelled extends AbstractMail /** * Sets the user that has denied the some of the order * - * @param \User_Adapter $deliverer + * @param User $deliverer */ - public function setDeliverer(\User_Adapter $deliverer) + public function setDeliverer(User $deliverer) { $this->deliverer = $deliverer; } @@ -53,7 +54,7 @@ class MailInfoOrderCancelled extends AbstractMail */ public function getMessage() { - if (!$this->deliverer instanceof \User_Adapter) { + if (!$this->deliverer instanceof User) { throw new LogicException('You must set a deliverer before calling getMessage()'); } if (null === $this->quantity) { @@ -61,7 +62,7 @@ class MailInfoOrderCancelled extends AbstractMail } return $this->app->trans('%user% a refuse %quantity% elements de votre commande', [ - '%user%' => $this->deliverer->get_display_name(), + '%user%' => $this->deliverer->getDisplayName(), '%quantity%' => $this->quantity, ]); } diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderDelivered.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderDelivered.php index e9444dd9f5..a976be10a2 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderDelivered.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoOrderDelivered.php @@ -13,12 +13,13 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoOrderDelivered extends AbstractMail { /** @var Basket */ private $basket; - /** @var \User_Adapter */ + /** @var User */ private $deliverer; /** @@ -34,9 +35,9 @@ class MailInfoOrderDelivered extends AbstractMail /** * Sets the user that delivers the order * - * @param \User_Adapter $deliverer + * @param User $deliverer */ - public function setDeliverer(\User_Adapter $deliverer) + public function setDeliverer(User $deliverer) { $this->deliverer = $deliverer; } @@ -62,7 +63,7 @@ class MailInfoOrderDelivered extends AbstractMail throw new LogicException('You must set a deliverer before calling getMessage'); } - return $this->app->trans('%user% vous a delivre votre commande, consultez la en ligne a l\'adresse suivante', ['%user%' => $this->deliverer->get_display_name()]); + return $this->app->trans('%user% vous a delivre votre commande, consultez la en ligne a l\'adresse suivante', ['%user%' => $this->deliverer->getDisplayName()]); } /** diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoPushReceived.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoPushReceived.php index 5b4ec30d45..e658c3833d 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoPushReceived.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoPushReceived.php @@ -13,12 +13,13 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoPushReceived extends AbstractMailWithLink { /** @var Basket */ private $basket; - /** @var \User_Adapter */ + /** @var User */ private $pusher; /** @@ -31,7 +32,7 @@ class MailInfoPushReceived extends AbstractMailWithLink $this->basket = $basket; } - public function setPusher(\User_Adapter $pusher) + public function setPusher(User $pusher) { $this->pusher = $pusher; } @@ -61,7 +62,7 @@ class MailInfoPushReceived extends AbstractMailWithLink } return - $this->app->trans('You just received a push containing %quantity% documents from %user%', ['%quantity%' => count($this->basket->getElements()), '%user%' => $this->pusher->get_display_name()]) + $this->app->trans('You just received a push containing %quantity% documents from %user%', ['%quantity%' => count($this->basket->getElements()), '%user%' => $this->pusher->getDisplayName()]) . "\n" . $this->message; } diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoUserRegistered.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoUserRegistered.php index ed436f496c..8e195d2d46 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoUserRegistered.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoUserRegistered.php @@ -12,18 +12,19 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoUserRegistered extends AbstractMail { - /** @var \User_Adapter */ + /** @var User */ private $registeredUser; /** * Sets the user that just registered * - * @param \User_Adapter $registeredUser + * @param User $registeredUser */ - public function setRegisteredUser(\User_Adapter $registeredUser) + public function setRegisteredUser(User $registeredUser) { $this->registeredUser = $registeredUser; } @@ -46,8 +47,8 @@ class MailInfoUserRegistered extends AbstractMail } return $this->app->trans('admin::register: un utilisateur a fait une demande d\'inscription') - . "\n\n" . sprintf('%s %s',$this->registeredUser->get_firstname(), $this->registeredUser->get_lastname()) - . "\n\n" . sprintf('%s %s',$this->registeredUser->get_job(), $this->registeredUser->get_company()); + . "\n\n" . sprintf('%s %s',$this->registeredUser->getFirstName(), $this->registeredUser->getLastName()) + . "\n\n" . sprintf('%s %s',$this->registeredUser->getJob(), $this->registeredUser->getCompany()); } /** diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationDone.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationDone.php index 0490a1f04b..057de54c78 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationDone.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationDone.php @@ -12,12 +12,13 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoValidationDone extends AbstractMailWithLink { /** @var string */ private $title; - /** @var \User_Adapter */ + /** @var User */ private $user; /** @@ -33,9 +34,9 @@ class MailInfoValidationDone extends AbstractMailWithLink /** * Sets the user that finished validation * - * @param \User_Adapter $user + * @param User $user */ - public function setUser(\User_Adapter $user) + public function setUser(User $user) { $this->user = $user; } @@ -53,7 +54,7 @@ class MailInfoValidationDone extends AbstractMailWithLink } return $this->app->trans('push::mail:: Rapport de validation de %user% pour %title%', [ - '%user%' => $this->user->get_display_name(), + '%user%' => $this->user->getDisplayName(), '%title%' => $this->title, ]); } @@ -68,7 +69,7 @@ class MailInfoValidationDone extends AbstractMailWithLink } return $this->app->trans('%user% has just sent its validation report, you can now see it', [ - '%user%' => $this->user->get_display_name(), + '%user%' => $this->user->getDisplayName(), ]); } diff --git a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php index abc36abacd..2aa87739c8 100644 --- a/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php +++ b/lib/Alchemy/Phrasea/Notification/Mail/MailInfoValidationRequest.php @@ -12,12 +12,13 @@ namespace Alchemy\Phrasea\Notification\Mail; use Alchemy\Phrasea\Exception\LogicException; +use Alchemy\Phrasea\Model\Entities\User; class MailInfoValidationRequest extends AbstractMailWithLink { /** @var string */ private $title; - /** @var \User_Adapter */ + /** @var User */ private $user; /** @var integer */ private $duration; @@ -59,7 +60,7 @@ class MailInfoValidationRequest extends AbstractMailWithLink throw new LogicException('You must set a title before calling getSubject'); } - return $this->app->trans("Validation request from %user% for '%title%'", ['%user%' => $this->user->get_display_name(), '%title%' => $this->title]); + return $this->app->trans("Validation request from %user% for '%title%'", ['%user%' => $this->user->getDisplayName(), '%title%' => $this->title]); } /** diff --git a/lib/Alchemy/Phrasea/Notification/Receiver.php b/lib/Alchemy/Phrasea/Notification/Receiver.php index 1707d2d8ee..e3671c882c 100644 --- a/lib/Alchemy/Phrasea/Notification/Receiver.php +++ b/lib/Alchemy/Phrasea/Notification/Receiver.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Notification; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; class Receiver implements ReceiverInterface { @@ -47,14 +48,14 @@ class Receiver implements ReceiverInterface /** * Creates a Receiver given a User * - * @param \User_Adapter $user + * @param User $user * * @return Receiver * * @throws InvalidArgumentException In case no valid email is found for user */ - public static function fromUser(\User_Adapter $user) + public static function fromUser(User $user) { - return new static($user->get_display_name(), $user->get_email()); + return new static($user->getDisplayName(), $user->getEmail()); } } diff --git a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php index e1fc4a44e2..77527adabc 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php +++ b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngine.php @@ -194,8 +194,8 @@ class PhraseaEngine implements SearchEngineInterface throw new \RuntimeException('Phrasea currently support only authenticated queries'); } - if (!phrasea_open_session($this->app['session']->get('phrasea_session_id'), $this->app['authentication']->getUser()->get_id())) { - if (!$ses_id = phrasea_create_session((string) $this->app['authentication']->getUser()->get_id())) { + if (!phrasea_open_session($this->app['session']->get('phrasea_session_id'), $this->app['authentication']->getUser()->getId())) { + if (!$ses_id = phrasea_create_session((string) $this->app['authentication']->getUser()->getId())) { throw new \Exception_InternalServerError('Unable to create phrasea session'); } $this->app['session']->set('phrasea_session_id', $ses_id); diff --git a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngineSubscriber.php b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngineSubscriber.php index 4c5ee6bd00..0f49bb180d 100644 --- a/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngineSubscriber.php +++ b/lib/Alchemy/Phrasea/SearchEngine/Phrasea/PhraseaEngineSubscriber.php @@ -48,7 +48,7 @@ class PhraseaEngineSubscriber implements EventSubscriberInterface $initialized = false; foreach ($rows as $row) { - $user = \User_Adapter::getInstance($row['usr_id'], $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($row['usr_id']); $this->app['acl']->get($user)->inject_rights(); if (null !== $row['session_id']) { if (!$initialized) { diff --git a/lib/Alchemy/Phrasea/Security/Firewall.php b/lib/Alchemy/Phrasea/Security/Firewall.php index d4de18dedc..aee33cbdb0 100644 --- a/lib/Alchemy/Phrasea/Security/Firewall.php +++ b/lib/Alchemy/Phrasea/Security/Firewall.php @@ -104,7 +104,7 @@ class Firewall public function requireNotGuest() { - if ($this->app['authentication']->getUser()->is_guest()) { + if ($this->app['authentication']->getUser()->isGuest()) { $this->app->abort(403, 'Guests do not have admin role'); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php index c530e5cb19..8ce41c2e38 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AbstractMigration.php @@ -84,4 +84,34 @@ abstract class AbstractMigration extends BaseMigration * Execute downgrade SQL. */ abstract public function doDownSql(Schema $schema); + + /** + * Tells whether the patch can be executed or not. + * + * @returns Boolean + */ + public function isAlreadyApplied() + { + return false; + } + + /** + * Tells whether the table exists or not. + * + * @param $tableName + * + * @returns Boolean + */ + protected function tableExists($tableName) + { + $rs = $this->getEntityManager()->getConnection()->fetchAll('SHOW TABLE STATUS'); + + foreach ($rs as $row) { + if ($tableName === $row['Name']) { + return true; + } + } + + return false; + } } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AuthFailureMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AuthFailureMigration.php index 4c145993c7..66bad77a35 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AuthFailureMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/AuthFailureMigration.php @@ -15,9 +15,14 @@ use Doctrine\DBAL\Schema\Schema; class AuthFailureMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('AuthFailures'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS AuthFailures (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(128) NOT NULL, ip VARCHAR(128) DEFAULT NULL, locked TINYINT(1) NOT NULL, created DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE AuthFailures (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(128) NOT NULL, ip VARCHAR(128) DEFAULT NULL, locked TINYINT(1) NOT NULL, created DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); } public function doDownSql(Schema $schema) diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/DeleteUsrIdFieldMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/DeleteUsrIdFieldMigration.php new file mode 100644 index 0000000000..740e5897df --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/DeleteUsrIdFieldMigration.php @@ -0,0 +1,80 @@ +addSql("DROP INDEX unique_owner ON UsrListOwners"); + $this->addSql("ALTER TABLE UsrListOwners DROP usr_id"); + $this->addSql("CREATE UNIQUE INDEX unique_owner ON UsrListOwners (user_id, id)"); + $this->addSql("ALTER TABLE FtpCredential DROP usrId"); + $this->addSql("DROP INDEX usr_id ON Sessions"); + $this->addSql("ALTER TABLE Sessions DROP usr_id"); + $this->addSql("ALTER TABLE Baskets DROP usr_id"); + $this->addSql("DROP INDEX user_story ON StoryWZ"); + $this->addSql("ALTER TABLE StoryWZ DROP usr_id"); + $this->addSql("CREATE UNIQUE INDEX user_story ON StoryWZ (user_id, sbas_id, record_id)"); + $this->addSql("ALTER TABLE UserNotificationSettings DROP usr_id"); + $this->addSql("ALTER TABLE UserSettings DROP usr_id"); + $this->addSql("ALTER TABLE Orders DROP usr_id"); + $this->addSql("ALTER TABLE UserQueries DROP usr_id"); + $this->addSql("ALTER TABLE LazaretSessions DROP usr_id"); + $this->addSql("ALTER TABLE ValidationParticipants DROP usr_id"); + $this->addSql("ALTER TABLE FeedPublishers DROP usr_id"); + $this->addSql("ALTER TABLE AggregateTokens DROP usr_id"); + $this->addSql("ALTER TABLE FtpExports DROP usr_id"); + $this->addSql("DROP INDEX unique_provider_per_user ON UsrAuthProviders"); + $this->addSql("ALTER TABLE UsrAuthProviders DROP usr_id"); + $this->addSql("CREATE UNIQUE INDEX unique_provider_per_user ON UsrAuthProviders (user_id, provider)"); + $this->addSql("ALTER TABLE FeedTokens DROP usr_id"); + $this->addSql("DROP INDEX unique_usr_per_list ON UsrListsContent"); + $this->addSql("ALTER TABLE UsrListsContent DROP usr_id"); + $this->addSql("CREATE UNIQUE INDEX unique_usr_per_list ON UsrListsContent (user_id, list_id)"); + } + + public function doDownSql(Schema $schema) + { + $this->addSql("ALTER TABLE AggregateTokens ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE Baskets ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE FeedPublishers ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE FeedTokens ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE FtpCredential ADD usrId INT NOT NULL"); + $this->addSql("ALTER TABLE FtpExports ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE LazaretSessions ADD usr_id INT DEFAULT NULL"); + $this->addSql("ALTER TABLE Orders ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE Sessions ADD usr_id INT NOT NULL"); + $this->addSql("CREATE INDEX usr_id ON Sessions (usr_id)"); + $this->addSql("DROP INDEX user_story ON StoryWZ"); + $this->addSql("ALTER TABLE StoryWZ ADD usr_id INT NOT NULL"); + $this->addSql("CREATE UNIQUE INDEX user_story ON StoryWZ (usr_id, sbas_id, record_id)"); + $this->addSql("ALTER TABLE UserNotificationSettings ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE UserQueries ADD usr_id INT NOT NULL"); + $this->addSql("ALTER TABLE UserSettings ADD usr_id INT NOT NULL"); + $this->addSql("DROP INDEX unique_provider_per_user ON UsrAuthProviders"); + $this->addSql("ALTER TABLE UsrAuthProviders ADD usr_id INT NOT NULL"); + $this->addSql("CREATE UNIQUE INDEX unique_provider_per_user ON UsrAuthProviders (usr_id, provider)"); + $this->addSql("DROP INDEX unique_owner ON UsrListOwners"); + $this->addSql("ALTER TABLE UsrListOwners ADD usr_id INT NOT NULL"); + $this->addSql("CREATE UNIQUE INDEX unique_owner ON UsrListOwners (usr_id, id)"); + $this->addSql("DROP INDEX unique_usr_per_list ON UsrListsContent"); + $this->addSql("ALTER TABLE UsrListsContent ADD usr_id INT NOT NULL"); + $this->addSql("CREATE UNIQUE INDEX unique_usr_per_list ON UsrListsContent (usr_id, list_id)"); + $this->addSql("ALTER TABLE ValidationParticipants ADD usr_id INT NOT NULL"); + } +} diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FeedMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FeedMigration.php index cce280130f..68bffe345e 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FeedMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FeedMigration.php @@ -12,36 +12,27 @@ namespace Alchemy\Phrasea\Setup\DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; -use Doctrine\ORM\Query\ResultSetMapping; class FeedMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('Feeds'); + } + public function doUpSql(Schema $schema) { - $rsm = (new ResultSetMapping())->addScalarResult('Name', 'Name'); - $backup = false; - - foreach ($this->getEntityManager()->createNativeQuery('SHOW TABLE STATUS', $rsm)->getResult() as $row) { - if ('feeds' === $row['Name']) { - $backup = true; - break; - } - } - - if ($backup) { - $this->getEntityManager()->getConnection()->executeQuery('RENAME TABLE `feeds` TO `feeds_backup`'); - } - - $this->addSql("CREATE TABLE IF NOT EXISTS Feeds (id INT AUTO_INCREMENT NOT NULL, public TINYINT(1) NOT NULL, icon_url TINYINT(1) NOT NULL, base_id INT DEFAULT NULL, title VARCHAR(128) NOT NULL, subtitle VARCHAR(1024) DEFAULT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS FeedPublishers (id INT AUTO_INCREMENT NOT NULL, feed_id INT DEFAULT NULL, usr_id INT NOT NULL, owner TINYINT(1) NOT NULL, created_on DATETIME NOT NULL, INDEX IDX_31AFAB251A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS FeedEntries (id INT AUTO_INCREMENT NOT NULL, publisher_id INT DEFAULT NULL, feed_id INT DEFAULT NULL, title VARCHAR(128) NOT NULL, subtitle VARCHAR(128) NOT NULL, author_name VARCHAR(128) NOT NULL, author_email VARCHAR(128) NOT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, INDEX IDX_5FC892F940C86FCE (publisher_id), INDEX IDX_5FC892F951A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS FeedItems (id INT AUTO_INCREMENT NOT NULL, entry_id INT DEFAULT NULL, record_id INT NOT NULL, sbas_id INT NOT NULL, ord INT NOT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, INDEX IDX_7F9CDFA6BA364942 (entry_id), UNIQUE INDEX lookup_unique_idx (entry_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS FeedTokens (id INT AUTO_INCREMENT NOT NULL, feed_id INT DEFAULT NULL, usr_id INT NOT NULL, value VARCHAR(12) DEFAULT NULL, INDEX IDX_9D1CA84851A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS AggregateTokens (id INT AUTO_INCREMENT NOT NULL, usr_id INT NOT NULL, value VARCHAR(12) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Feeds (id INT AUTO_INCREMENT NOT NULL, public TINYINT(1) NOT NULL, icon_url TINYINT(1) NOT NULL, base_id INT DEFAULT NULL, title VARCHAR(128) NOT NULL, subtitle VARCHAR(1024) DEFAULT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FeedPublishers (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, feed_id INT DEFAULT NULL, owner TINYINT(1) NOT NULL, created_on DATETIME NOT NULL, INDEX IDX_31AFAB2A76ED395 (user_id), INDEX IDX_31AFAB251A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FeedEntries (id INT AUTO_INCREMENT NOT NULL, publisher_id INT DEFAULT NULL, feed_id INT DEFAULT NULL, title VARCHAR(128) NOT NULL, subtitle VARCHAR(128) NOT NULL, author_name VARCHAR(128) NOT NULL, author_email VARCHAR(128) NOT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, INDEX IDX_5FC892F940C86FCE (publisher_id), INDEX IDX_5FC892F951A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FeedItems (id INT AUTO_INCREMENT NOT NULL, entry_id INT DEFAULT NULL, record_id INT NOT NULL, sbas_id INT NOT NULL, ord INT NOT NULL, created_on DATETIME NOT NULL, updated_on DATETIME NOT NULL, INDEX IDX_7F9CDFA6BA364942 (entry_id), UNIQUE INDEX lookup_unique_idx (entry_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FeedTokens (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, feed_id INT DEFAULT NULL, value VARCHAR(12) DEFAULT NULL, INDEX IDX_9D1CA848A76ED395 (user_id), INDEX IDX_9D1CA84851A5BC03 (feed_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE FeedPublishers ADD CONSTRAINT FK_31AFAB2A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); $this->addSql("ALTER TABLE FeedPublishers ADD CONSTRAINT FK_31AFAB251A5BC03 FOREIGN KEY (feed_id) REFERENCES Feeds (id)"); $this->addSql("ALTER TABLE FeedEntries ADD CONSTRAINT FK_5FC892F940C86FCE FOREIGN KEY (publisher_id) REFERENCES FeedPublishers (id)"); $this->addSql("ALTER TABLE FeedEntries ADD CONSTRAINT FK_5FC892F951A5BC03 FOREIGN KEY (feed_id) REFERENCES Feeds (id)"); $this->addSql("ALTER TABLE FeedItems ADD CONSTRAINT FK_7F9CDFA6BA364942 FOREIGN KEY (entry_id) REFERENCES FeedEntries (id)"); + $this->addSql("ALTER TABLE FeedTokens ADD CONSTRAINT FK_9D1CA848A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); $this->addSql("ALTER TABLE FeedTokens ADD CONSTRAINT FK_9D1CA84851A5BC03 FOREIGN KEY (feed_id) REFERENCES Feeds (id)"); } @@ -57,6 +48,5 @@ class FeedMigration extends AbstractMigration $this->addSql("DROP TABLE FeedEntries"); $this->addSql("DROP TABLE FeedItems"); $this->addSql("DROP TABLE FeedTokens"); - $this->addSql("DROP TABLE AggregateTokens"); } } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpCredentialMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpCredentialMigration.php index 7c3b706c16..7180488fd4 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpCredentialMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpCredentialMigration.php @@ -15,9 +15,15 @@ use Doctrine\DBAL\Schema\Schema; class FtpCredentialMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('FtpCredential'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS FtpCredential (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, usrId INT NOT NULL, active TINYINT(1) NOT NULL, address VARCHAR(128) NOT NULL, login VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, reception_folder VARCHAR(128) NOT NULL, repository_prefix_name VARCHAR(128) NOT NULL, passive TINYINT(1) NOT NULL, tls TINYINT(1) NOT NULL, max_retry INT NOT NULL, updated DATETIME NOT NULL, UNIQUE INDEX UNIQ_62DA9661A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FtpCredential (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, active TINYINT(1) NOT NULL, address VARCHAR(128) NOT NULL, login VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, reception_folder VARCHAR(128) NOT NULL, repository_prefix_name VARCHAR(128) NOT NULL, passive TINYINT(1) NOT NULL, tls TINYINT(1) NOT NULL, max_retry INT NOT NULL, updated DATETIME NOT NULL, UNIQUE INDEX UNIQ_62DA9661A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE FtpCredential ADD CONSTRAINT FK_62DA9661A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } public function doDownSql(Schema $schema) diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpExportMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpExportMigration.php index 1ae1c897fa..428505e0af 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpExportMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/FtpExportMigration.php @@ -15,11 +15,17 @@ use Doctrine\DBAL\Schema\Schema; class FtpExportMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('FtpExports'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS FtpExportElements (id INT AUTO_INCREMENT NOT NULL, export_id INT DEFAULT NULL, record_id INT NOT NULL, base_id INT NOT NULL, subdef VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, folder VARCHAR(255) DEFAULT NULL, error TINYINT(1) NOT NULL, done TINYINT(1) NOT NULL, businessfields TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_7BF0AE1264CDAF82 (export_id), INDEX done (done), INDEX error (error), UNIQUE INDEX unique_ftp_export (export_id, base_id, record_id, subdef), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS FtpExports (id INT AUTO_INCREMENT NOT NULL, crash INT NOT NULL, nbretry INT NOT NULL, mail LONGTEXT DEFAULT NULL, addr LONGTEXT NOT NULL, use_ssl TINYINT(1) NOT NULL, login LONGTEXT DEFAULT NULL, pwd LONGTEXT DEFAULT NULL, passif TINYINT(1) NOT NULL, destfolder LONGTEXT NOT NULL, sendermail LONGTEXT DEFAULT NULL, text_mail_sender LONGTEXT DEFAULT NULL, text_mail_receiver LONGTEXT DEFAULT NULL, usr_id INT NOT NULL, foldertocreate LONGTEXT DEFAULT NULL, logfile 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 FtpExportElements (id INT AUTO_INCREMENT NOT NULL, export_id INT DEFAULT NULL, record_id INT NOT NULL, base_id INT NOT NULL, subdef VARCHAR(255) NOT NULL, filename VARCHAR(255) NOT NULL, folder VARCHAR(255) DEFAULT NULL, error TINYINT(1) NOT NULL, done TINYINT(1) NOT NULL, businessfields TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_7BF0AE1264CDAF82 (export_id), INDEX done (done), INDEX error (error), UNIQUE INDEX unique_ftp_export (export_id, base_id, record_id, subdef), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE FtpExports (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, crash INT NOT NULL, nbretry INT NOT NULL, mail LONGTEXT DEFAULT NULL, addr LONGTEXT NOT NULL, use_ssl TINYINT(1) NOT NULL, login LONGTEXT DEFAULT NULL, pwd LONGTEXT DEFAULT NULL, passif TINYINT(1) NOT NULL, destfolder LONGTEXT NOT NULL, sendermail LONGTEXT DEFAULT NULL, text_mail_sender LONGTEXT DEFAULT NULL, text_mail_receiver LONGTEXT DEFAULT NULL, foldertocreate LONGTEXT DEFAULT NULL, logfile TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_CFCEEE7AA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE FtpExportElements ADD CONSTRAINT FK_7BF0AE1264CDAF82 FOREIGN KEY (export_id) REFERENCES FtpExports (id)"); + $this->addSql("ALTER TABLE FtpExports ADD CONSTRAINT FK_CFCEEE7AA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } public function doDownSql(Schema $schema) diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/LazaretMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/LazaretMigration.php index a0f02c2e1d..9778874501 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/LazaretMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/LazaretMigration.php @@ -15,13 +15,19 @@ use Doctrine\DBAL\Schema\Schema; class LazaretMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('LazaretFiles'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS LazaretChecks (id INT AUTO_INCREMENT NOT NULL, lazaret_file_id INT DEFAULT NULL, checkClassname VARCHAR(512) NOT NULL, INDEX IDX_CE873ED44CF84ADD (lazaret_file_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS LazaretSessions (id INT AUTO_INCREMENT NOT NULL, usr_id INT DEFAULT 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 IF NOT EXISTS LazaretAttributes (id INT AUTO_INCREMENT NOT NULL, lazaret_file_id INT DEFAULT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(2048) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_5FF72F9B4CF84ADD (lazaret_file_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS LazaretFiles (id INT AUTO_INCREMENT NOT NULL, lazaret_session_id INT DEFAULT NULL, filename VARCHAR(512) NOT NULL, thumbFilename VARCHAR(512) NOT NULL, originalName VARCHAR(256) NOT NULL, base_id INT NOT NULL, uuid VARCHAR(36) NOT NULL, sha256 VARCHAR(64) NOT NULL, forced TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_D30BD768EE187C01 (lazaret_session_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE LazaretChecks (id INT AUTO_INCREMENT NOT NULL, lazaret_file_id INT DEFAULT NULL, checkClassname VARCHAR(512) NOT NULL, INDEX IDX_CE873ED44CF84ADD (lazaret_file_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE LazaretSessions (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_40A81317A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE LazaretAttributes (id INT AUTO_INCREMENT NOT NULL, lazaret_file_id INT DEFAULT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(2048) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_5FF72F9B4CF84ADD (lazaret_file_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE LazaretFiles (id INT AUTO_INCREMENT NOT NULL, lazaret_session_id INT DEFAULT NULL, filename VARCHAR(512) NOT NULL, thumbFilename VARCHAR(512) NOT NULL, originalName VARCHAR(256) NOT NULL, base_id INT NOT NULL, uuid VARCHAR(36) NOT NULL, sha256 VARCHAR(64) NOT NULL, forced TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_D30BD768EE187C01 (lazaret_session_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE LazaretChecks ADD CONSTRAINT FK_CE873ED44CF84ADD FOREIGN KEY (lazaret_file_id) REFERENCES LazaretFiles (id)"); + $this->addSql("ALTER TABLE LazaretSessions ADD CONSTRAINT FK_40A81317A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); $this->addSql("ALTER TABLE LazaretAttributes ADD CONSTRAINT FK_5FF72F9B4CF84ADD FOREIGN KEY (lazaret_file_id) REFERENCES LazaretFiles (id)"); $this->addSql("ALTER TABLE LazaretFiles ADD CONSTRAINT FK_D30BD768EE187C01 FOREIGN KEY (lazaret_session_id) REFERENCES LazaretSessions (id)"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/OrderMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/OrderMigration.php index 5cab7c4f00..6d4b2e57e8 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/OrderMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/OrderMigration.php @@ -15,11 +15,18 @@ use Doctrine\DBAL\Schema\Schema; class OrderMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('Orders'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS Orders (id INT AUTO_INCREMENT NOT NULL, basket_id INT DEFAULT NULL, usr_id INT NOT NULL, order_usage VARCHAR(2048) NOT NULL, todo INT DEFAULT NULL, deadline DATETIME NOT NULL, created_on DATETIME NOT NULL, UNIQUE INDEX UNIQ_E283F8D81BE1FB52 (basket_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS OrderElements (id INT AUTO_INCREMENT NOT NULL, order_id INT DEFAULT NULL, base_id INT NOT NULL, record_id INT NOT NULL, order_master_id INT DEFAULT NULL, deny TINYINT(1) DEFAULT NULL, INDEX IDX_8C7066C88D9F6D38 (order_id), UNIQUE INDEX unique_ordercle (base_id, record_id, order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Orders (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, basket_id INT DEFAULT NULL, order_usage VARCHAR(2048) NOT NULL, todo INT DEFAULT NULL, deadline DATETIME NOT NULL, created_on DATETIME NOT NULL, INDEX IDX_E283F8D8A76ED395 (user_id), UNIQUE INDEX UNIQ_E283F8D81BE1FB52 (basket_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE OrderElements (id INT AUTO_INCREMENT NOT NULL, order_master INT DEFAULT NULL, order_id INT DEFAULT NULL, base_id INT NOT NULL, record_id INT NOT NULL, deny TINYINT(1) DEFAULT NULL, INDEX IDX_8C7066C8EE86B303 (order_master), INDEX IDX_8C7066C88D9F6D38 (order_id), UNIQUE INDEX unique_ordercle (base_id, record_id, order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE Orders ADD CONSTRAINT FK_E283F8D8A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); $this->addSql("ALTER TABLE Orders ADD CONSTRAINT FK_E283F8D81BE1FB52 FOREIGN KEY (basket_id) REFERENCES Baskets (id)"); + $this->addSql("ALTER TABLE OrderElements ADD CONSTRAINT FK_8C7066C8EE86B303 FOREIGN KEY (order_master) REFERENCES Users (id)"); $this->addSql("ALTER TABLE OrderElements ADD CONSTRAINT FK_8C7066C88D9F6D38 FOREIGN KEY (order_id) REFERENCES Orders (id)"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/SessionMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/SessionMigration.php index 50f8649b06..8993dcb4eb 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/SessionMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/SessionMigration.php @@ -15,11 +15,17 @@ use Doctrine\DBAL\Schema\Schema; class SessionMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('Sessions'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS SessionModules (id INT AUTO_INCREMENT NOT NULL, session_id INT DEFAULT NULL, module_id INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_BA36EF49613FECDF (session_id), UNIQUE INDEX unique_module (session_id, module_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS Sessions (id INT AUTO_INCREMENT NOT NULL, usr_id INT NOT NULL, user_agent VARCHAR(512) NOT NULL, ip_address VARCHAR(40) DEFAULT NULL, platform VARCHAR(128) DEFAULT NULL, browser_name VARCHAR(128) DEFAULT NULL, browser_version VARCHAR(32) DEFAULT NULL, screen_width INT DEFAULT NULL, screen_height INT DEFAULT NULL, token VARCHAR(128) DEFAULT NULL, nonce VARCHAR(16) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, UNIQUE INDEX UNIQ_6316FF455F37A13B (token), INDEX usr_id (usr_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE SessionModules (id INT AUTO_INCREMENT NOT NULL, session_id INT DEFAULT NULL, module_id INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_BA36EF49613FECDF (session_id), UNIQUE INDEX unique_module (session_id, module_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Sessions (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, user_agent VARCHAR(512) NOT NULL, ip_address VARCHAR(40) DEFAULT NULL, platform VARCHAR(128) DEFAULT NULL, browser_name VARCHAR(128) DEFAULT NULL, browser_version VARCHAR(32) DEFAULT NULL, screen_width INT DEFAULT NULL, screen_height INT DEFAULT NULL, token VARCHAR(128) DEFAULT NULL, nonce VARCHAR(16) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, UNIQUE INDEX UNIQ_6316FF455F37A13B (token), INDEX IDX_6316FF45A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE SessionModules ADD CONSTRAINT FK_BA36EF49613FECDF FOREIGN KEY (session_id) REFERENCES Sessions (id)"); + $this->addSql("ALTER TABLE Sessions ADD CONSTRAINT FK_6316FF45A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } public function doDownSql(Schema $schema) diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/TaskMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/TaskMigration.php index 556bd9b6c2..33ee14fd37 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/TaskMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/TaskMigration.php @@ -15,9 +15,14 @@ use Doctrine\DBAL\Schema\Schema; class TaskMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('Tasks'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS Tasks (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, jobId VARCHAR(255) NOT NULL, settings LONGTEXT NOT NULL, completed TINYINT(1) NOT NULL, status VARCHAR(255) NOT NULL, crashed INT NOT NULL, single_run TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, last_execution DATETIME DEFAULT NULL, period INT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Tasks (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, jobId VARCHAR(255) NOT NULL, settings LONGTEXT NOT NULL, completed TINYINT(1) NOT NULL, status VARCHAR(255) NOT NULL, crashed INT NOT NULL, single_run TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, last_execution DATETIME DEFAULT NULL, period INT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); } public function doDownSql(Schema $schema) diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserAuthProviderMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserAuthProviderMigration.php new file mode 100644 index 0000000000..133bac0d25 --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserAuthProviderMigration.php @@ -0,0 +1,36 @@ +tableExists('UsrAuthProviders'); + } + + public function doUpSql(Schema $schema) + { + $this->addSql("CREATE TABLE UsrAuthProviders (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, provider VARCHAR(32) NOT NULL, distant_id VARCHAR(192) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_947F003FA76ED395 (user_id), UNIQUE INDEX unique_provider_per_user (user_id, provider), UNIQUE INDEX provider_ids (provider, distant_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE UsrAuthProviders ADD CONSTRAINT FK_947F003FA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + } + + public function doDownSql(Schema $schema) + { + $this->addSql("DROP TABLE UsrAuthProviders"); + } +} diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserFieldMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserFieldMigration.php new file mode 100644 index 0000000000..9e57e02104 --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserFieldMigration.php @@ -0,0 +1,80 @@ +addSql("ALTER TABLE UsrListOwners ADD CONSTRAINT FK_54E9FE23A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_54E9FE23A76ED395 ON UsrListOwners (user_id)"); + $this->addSql("ALTER TABLE Sessions ADD CONSTRAINT FK_6316FF45A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_6316FF45A76ED395 ON Sessions (user_id)"); + $this->addSql("ALTER TABLE Baskets ADD CONSTRAINT FK_13461873A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_13461873A76ED395 ON Baskets (user_id)"); + $this->addSql("ALTER TABLE StoryWZ ADD CONSTRAINT FK_E0D2CBAEA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_E0D2CBAEA76ED395 ON StoryWZ (user_id)"); + $this->addSql("ALTER TABLE Orders ADD CONSTRAINT FK_E283F8D8A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_E283F8D8A76ED395 ON Orders (user_id)"); + $this->addSql("ALTER TABLE LazaretSessions ADD CONSTRAINT FK_40A81317A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_40A81317A76ED395 ON LazaretSessions (user_id)"); + $this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_17850D7BA76ED395 ON ValidationParticipants (user_id)"); + $this->addSql("ALTER TABLE FeedPublishers ADD CONSTRAINT FK_31AFAB2A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_31AFAB2A76ED395 ON FeedPublishers (user_id)"); + $this->addSql("ALTER TABLE AggregateTokens ADD CONSTRAINT FK_4232BC51A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_4232BC51A76ED395 ON AggregateTokens (user_id)"); + $this->addSql("ALTER TABLE FtpExports ADD CONSTRAINT FK_CFCEEE7AA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_CFCEEE7AA76ED395 ON FtpExports (user_id)"); + $this->addSql("ALTER TABLE UsrAuthProviders ADD CONSTRAINT FK_947F003FA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_947F003FA76ED395 ON UsrAuthProviders (user_id)"); + $this->addSql("ALTER TABLE FeedTokens ADD CONSTRAINT FK_9D1CA848A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_9D1CA848A76ED395 ON FeedTokens (user_id)"); + $this->addSql("ALTER TABLE UsrListsContent ADD CONSTRAINT FK_661B8B9A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("CREATE INDEX IDX_661B8B9A76ED395 ON UsrListsContent (user_id)"); + } + + public function doDownSql(Schema $schema) + { + $this->addSql("ALTER TABLE AggregateTokens DROP FOREIGN KEY FK_4232BC51A76ED395"); + $this->addSql("DROP INDEX IDX_4232BC51A76ED395 ON AggregateTokens"); + $this->addSql("ALTER TABLE Baskets DROP FOREIGN KEY FK_13461873A76ED395"); + $this->addSql("DROP INDEX IDX_13461873A76ED395 ON Baskets"); + $this->addSql("ALTER TABLE FeedPublishers DROP FOREIGN KEY FK_31AFAB2A76ED395"); + $this->addSql("DROP INDEX IDX_31AFAB2A76ED395 ON FeedPublishers"); + $this->addSql("ALTER TABLE FeedTokens DROP FOREIGN KEY FK_9D1CA848A76ED395"); + $this->addSql("DROP INDEX IDX_9D1CA848A76ED395 ON FeedTokens"); + $this->addSql("ALTER TABLE FtpExports DROP FOREIGN KEY FK_CFCEEE7AA76ED395"); + $this->addSql("DROP INDEX IDX_CFCEEE7AA76ED395 ON FtpExports"); + $this->addSql("ALTER TABLE LazaretSessions DROP FOREIGN KEY FK_40A81317A76ED395"); + $this->addSql("DROP INDEX IDX_40A81317A76ED395 ON LazaretSessions"); + $this->addSql("ALTER TABLE Orders DROP FOREIGN KEY FK_E283F8D8A76ED395"); + $this->addSql("DROP INDEX IDX_E283F8D8A76ED395 ON Orders"); + $this->addSql("ALTER TABLE Sessions DROP FOREIGN KEY FK_6316FF45A76ED395"); + $this->addSql("DROP INDEX IDX_6316FF45A76ED395 ON Sessions"); + $this->addSql("ALTER TABLE StoryWZ DROP FOREIGN KEY FK_E0D2CBAEA76ED395"); + $this->addSql("DROP INDEX IDX_E0D2CBAEA76ED395 ON StoryWZ"); + $this->addSql("ALTER TABLE UsrAuthProviders DROP FOREIGN KEY FK_947F003FA76ED395"); + $this->addSql("DROP INDEX IDX_947F003FA76ED395 ON UsrAuthProviders"); + $this->addSql("ALTER TABLE UsrListOwners DROP FOREIGN KEY FK_54E9FE23A76ED395"); + $this->addSql("DROP INDEX IDX_54E9FE23A76ED395 ON UsrListOwners"); + $this->addSql("ALTER TABLE UsrListsContent DROP FOREIGN KEY FK_661B8B9A76ED395"); + $this->addSql("DROP INDEX IDX_661B8B9A76ED395 ON UsrListsContent"); + $this->addSql("ALTER TABLE ValidationParticipants DROP FOREIGN KEY FK_17850D7BA76ED395"); + $this->addSql("DROP INDEX IDX_17850D7BA76ED395 ON ValidationParticipants"); + } +} diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserListMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserListMigration.php new file mode 100644 index 0000000000..cf2d487a29 --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserListMigration.php @@ -0,0 +1,45 @@ +tableExists('UsrLists'); + } + + public function doUpSql(Schema $schema) + { + $this->addSql("CREATE TABLE UsrListOwners (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, list_id INT DEFAULT NULL, role VARCHAR(255) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_54E9FE23A76ED395 (user_id), INDEX IDX_54E9FE233DAE168B (list_id), UNIQUE INDEX unique_owner (user_id, id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE UsrLists (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) 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 UsrListsContent (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, list_id INT DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_661B8B9A76ED395 (user_id), INDEX IDX_661B8B93DAE168B (list_id), UNIQUE INDEX unique_usr_per_list (user_id, list_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE UsrListOwners ADD CONSTRAINT FK_54E9FE23A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("ALTER TABLE UsrListOwners ADD CONSTRAINT FK_54E9FE233DAE168B FOREIGN KEY (list_id) REFERENCES UsrLists (id)"); + $this->addSql("ALTER TABLE UsrListsContent ADD CONSTRAINT FK_661B8B9A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("ALTER TABLE UsrListsContent ADD CONSTRAINT FK_661B8B93DAE168B FOREIGN KEY (list_id) REFERENCES UsrLists (id)"); + } + + public function doDownSql(Schema $schema) + { + $this->addSql("ALTER TABLE UsrListOwners DROP FOREIGN KEY FK_54E9FE233DAE168B"); + $this->addSql("ALTER TABLE UsrListsContent DROP FOREIGN KEY FK_661B8B93DAE168B"); + $this->addSql("DROP TABLE UsrListOwners"); + $this->addSql("DROP TABLE UsrLists"); + $this->addSql("DROP TABLE UsrListsContent"); + } +} diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserMigration.php index 15f3b8dbaf..6a750fb74f 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserMigration.php @@ -15,14 +15,21 @@ use Doctrine\DBAL\Schema\Schema; class UserMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('Users'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS Users (id INT AUTO_INCREMENT NOT NULL, model_of INT DEFAULT NULL, login VARCHAR(128) NOT NULL, email VARCHAR(128) DEFAULT NULL, password VARCHAR(128) DEFAULT NULL, nonce VARCHAR(16) DEFAULT NULL, salted_password TINYINT(1) NOT NULL, first_name VARCHAR(64) NOT NULL, last_name VARCHAR(64) NOT NULL, gender VARCHAR(8) DEFAULT NULL, address LONGTEXT NOT NULL, city VARCHAR(64) NOT NULL, country VARCHAR(64) NOT NULL, zip_code VARCHAR(32) NOT NULL, geoname_id INT DEFAULT NULL, locale VARCHAR(8) DEFAULT NULL, timezone VARCHAR(128) NOT NULL, job VARCHAR(128) NOT NULL, activity VARCHAR(256) NOT NULL, company VARCHAR(64) NOT NULL, phone VARCHAR(32) NOT NULL, fax VARCHAR(32) NOT NULL, admin TINYINT(1) NOT NULL, guest TINYINT(1) NOT NULL, mail_notifications TINYINT(1) NOT NULL, request_notifications TINYINT(1) NOT NULL, ldap_created TINYINT(1) NOT NULL, last_model VARCHAR(64) DEFAULT NULL, push_list LONGTEXT NOT NULL, can_change_profil TINYINT(1) NOT NULL, can_change_ftp_profil TINYINT(1) NOT NULL, last_connection DATETIME DEFAULT NULL, mail_locked TINYINT(1) NOT NULL, deleted TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, UNIQUE INDEX UNIQ_D5428AEDC121714D (model_of), INDEX salted_password (salted_password), INDEX admin (admin), INDEX guest (guest), UNIQUE INDEX email_unique (email), UNIQUE INDEX login_unique (login), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE Users (id INT AUTO_INCREMENT NOT NULL, last_model INT DEFAULT NULL, model_of INT DEFAULT NULL, login VARCHAR(128) NOT NULL, email VARCHAR(128) DEFAULT NULL, password VARCHAR(128) DEFAULT NULL, nonce VARCHAR(64) DEFAULT NULL, salted_password TINYINT(1) NOT NULL, first_name VARCHAR(64) NOT NULL, last_name VARCHAR(64) NOT NULL, gender SMALLINT DEFAULT NULL, address LONGTEXT NOT NULL, city VARCHAR(64) NOT NULL, country VARCHAR(64) DEFAULT NULL, zip_code VARCHAR(32) NOT NULL, geoname_id INT DEFAULT NULL, locale VARCHAR(8) DEFAULT NULL, timezone VARCHAR(128) NOT NULL, job VARCHAR(128) NOT NULL, activity VARCHAR(256) NOT NULL, company VARCHAR(64) NOT NULL, phone VARCHAR(32) NOT NULL, fax VARCHAR(32) NOT NULL, admin TINYINT(1) NOT NULL, guest TINYINT(1) NOT NULL, mail_notifications TINYINT(1) NOT NULL, request_notifications TINYINT(1) NOT NULL, ldap_created TINYINT(1) NOT NULL, push_list LONGTEXT NOT NULL, can_change_profil TINYINT(1) NOT NULL, can_change_ftp_profil TINYINT(1) NOT NULL, last_connection DATETIME DEFAULT NULL, mail_locked TINYINT(1) NOT NULL, deleted TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_D5428AEDB5DE44C2 (last_model), INDEX IDX_D5428AEDC121714D (model_of), INDEX salted_password (salted_password), INDEX admin (admin), INDEX guest (guest), UNIQUE INDEX email_unique (email), UNIQUE INDEX login_unique (login), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE Users ADD CONSTRAINT FK_D5428AEDB5DE44C2 FOREIGN KEY (last_model) REFERENCES Users (id)"); $this->addSql("ALTER TABLE Users ADD CONSTRAINT FK_D5428AEDC121714D FOREIGN KEY (model_of) REFERENCES Users (id)"); } public function doDownSql(Schema $schema) { + $this->addSql("ALTER TABLE Users DROP FOREIGN KEY FK_D5428AEDB5DE44C2"); $this->addSql("ALTER TABLE Users DROP FOREIGN KEY FK_D5428AEDC121714D"); $this->addSql("DROP TABLE Users"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserNotificationSettingMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserNotificationSettingMigration.php index 5221cd67f2..bef37fb370 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserNotificationSettingMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserNotificationSettingMigration.php @@ -15,9 +15,14 @@ use Doctrine\DBAL\Schema\Schema; class UserNotificationSettingMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('UserNotificationSettings'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS UserNotificationSettings (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, usr_id INT NOT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(128) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_CFF041AAA76ED395 (user_id), UNIQUE INDEX unique_index (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE UserNotificationSettings (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(128) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_CFF041AAA76ED395 (user_id), UNIQUE INDEX unique_index (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE UserNotificationSettings ADD CONSTRAINT FK_CFF041AAA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserQueryMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserQueryMigration.php index 7107edf452..05c404f97d 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserQueryMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserQueryMigration.php @@ -15,9 +15,14 @@ use Doctrine\DBAL\Schema\Schema; class UserQueryMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('UserQueries'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS UserQueries (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, usr_id INT NOT NULL, query VARCHAR(256) NOT NULL, created DATETIME NOT NULL, INDEX IDX_5FB80D87A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE UserQueries (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, query VARCHAR(256) NOT NULL, created DATETIME NOT NULL, INDEX IDX_5FB80D87A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE UserQueries ADD CONSTRAINT FK_5FB80D87A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserSettingMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserSettingMigration.php index 28710392b1..f6919f8dbb 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserSettingMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/UserSettingMigration.php @@ -15,9 +15,14 @@ use Doctrine\DBAL\Schema\Schema; class UserSettingMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('UserSettings'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS UserSettings (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, usr_id INT NOT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(128) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_2847E61CA76ED395 (user_id), UNIQUE INDEX unique_setting (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE UserSettings (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, name VARCHAR(64) NOT NULL, value VARCHAR(128) DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_2847E61CA76ED395 (user_id), UNIQUE INDEX unique_setting (user_id, name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); $this->addSql("ALTER TABLE UserSettings ADD CONSTRAINT FK_2847E61CA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } diff --git a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/WorkzoneMigration.php b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/WorkzoneMigration.php index 1f20b1f5c9..02aeb15e06 100644 --- a/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/WorkzoneMigration.php +++ b/lib/Alchemy/Phrasea/Setup/DoctrineMigrations/WorkzoneMigration.php @@ -15,24 +15,37 @@ use Doctrine\DBAL\Schema\Schema; class WorkzoneMigration extends AbstractMigration { + public function isAlreadyApplied() + { + return $this->tableExists('StoryWZ'); + } + public function doUpSql(Schema $schema) { - $this->addSql("CREATE TABLE IF NOT EXISTS Baskets (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(128) NOT NULL, description LONGTEXT DEFAULT NULL, usr_id INT NOT NULL, is_read TINYINT(1) NOT NULL, pusher_id INT DEFAULT NULL, archived 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 IF NOT EXISTS StoryWZ (id INT AUTO_INCREMENT NOT NULL, sbas_id INT NOT NULL, record_id INT NOT NULL, usr_id INT NOT NULL, created DATETIME NOT NULL, UNIQUE INDEX user_story (usr_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS ValidationSessions (id INT AUTO_INCREMENT NOT NULL, basket_id INT DEFAULT NULL, initiator_id INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, expires DATETIME DEFAULT NULL, UNIQUE INDEX UNIQ_5B9DFB061BE1FB52 (basket_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS ValidationDatas (id INT AUTO_INCREMENT NOT NULL, participant_id INT DEFAULT NULL, basket_element_id INT DEFAULT NULL, agreement TINYINT(1) DEFAULT NULL, note LONGTEXT DEFAULT NULL, updated DATETIME NOT NULL, INDEX IDX_70E84DDC9D1C3019 (participant_id), INDEX IDX_70E84DDCE989605 (basket_element_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS BasketElements (id INT AUTO_INCREMENT NOT NULL, basket_id INT DEFAULT NULL, record_id INT NOT NULL, sbas_id INT NOT NULL, ord INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_C0B7ECB71BE1FB52 (basket_id), UNIQUE INDEX unique_recordcle (basket_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); - $this->addSql("CREATE TABLE IF NOT EXISTS ValidationParticipants (id INT AUTO_INCREMENT NOT NULL, usr_id INT NOT NULL, is_aware TINYINT(1) NOT NULL, is_confirmed TINYINT(1) NOT NULL, can_agree TINYINT(1) NOT NULL, can_see_others TINYINT(1) NOT NULL, reminded DATETIME DEFAULT NULL, ValidationSession_id INT DEFAULT NULL, INDEX IDX_17850D7BF25B0F5B (ValidationSession_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + + $this->addSql("CREATE TABLE Baskets (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, pusher_id INT DEFAULT NULL, name VARCHAR(128) NOT NULL, description LONGTEXT DEFAULT NULL, is_read TINYINT(1) NOT NULL, archived TINYINT(1) NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_13461873A76ED395 (user_id), INDEX IDX_13461873C2D98306 (pusher_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE StoryWZ (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, sbas_id INT NOT NULL, record_id INT NOT NULL, created DATETIME NOT NULL, INDEX IDX_E0D2CBAEA76ED395 (user_id), UNIQUE INDEX user_story (user_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE ValidationSessions (id INT AUTO_INCREMENT NOT NULL, initiator_id INT NOT NULL, basket_id INT DEFAULT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, expires DATETIME DEFAULT NULL, INDEX IDX_5B9DFB067DB3B714 (initiator_id), UNIQUE INDEX UNIQ_5B9DFB061BE1FB52 (basket_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE ValidationDatas (id INT AUTO_INCREMENT NOT NULL, participant_id INT DEFAULT NULL, basket_element_id INT DEFAULT NULL, agreement TINYINT(1) DEFAULT NULL, note LONGTEXT DEFAULT NULL, updated DATETIME NOT NULL, INDEX IDX_70E84DDC9D1C3019 (participant_id), INDEX IDX_70E84DDCE989605 (basket_element_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE BasketElements (id INT AUTO_INCREMENT NOT NULL, basket_id INT DEFAULT NULL, record_id INT NOT NULL, sbas_id INT NOT NULL, ord INT NOT NULL, created DATETIME NOT NULL, updated DATETIME NOT NULL, INDEX IDX_C0B7ECB71BE1FB52 (basket_id), UNIQUE INDEX unique_recordcle (basket_id, sbas_id, record_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("CREATE TABLE ValidationParticipants (id INT AUTO_INCREMENT NOT NULL, user_id INT NOT NULL, is_aware TINYINT(1) NOT NULL, is_confirmed TINYINT(1) NOT NULL, can_agree TINYINT(1) NOT NULL, can_see_others TINYINT(1) NOT NULL, reminded DATETIME DEFAULT NULL, ValidationSession_id INT DEFAULT NULL, INDEX IDX_17850D7BF25B0F5B (ValidationSession_id), INDEX IDX_17850D7BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB"); + $this->addSql("ALTER TABLE Baskets ADD CONSTRAINT FK_13461873A76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("ALTER TABLE Baskets ADD CONSTRAINT FK_13461873C2D98306 FOREIGN KEY (pusher_id) REFERENCES Users (id)"); + $this->addSql("ALTER TABLE StoryWZ ADD CONSTRAINT FK_E0D2CBAEA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); + $this->addSql("ALTER TABLE ValidationSessions ADD CONSTRAINT FK_5B9DFB067DB3B714 FOREIGN KEY (initiator_id) REFERENCES Users (id)"); $this->addSql("ALTER TABLE ValidationSessions ADD CONSTRAINT FK_5B9DFB061BE1FB52 FOREIGN KEY (basket_id) REFERENCES Baskets (id)"); $this->addSql("ALTER TABLE ValidationDatas ADD CONSTRAINT FK_70E84DDC9D1C3019 FOREIGN KEY (participant_id) REFERENCES ValidationParticipants (id)"); $this->addSql("ALTER TABLE ValidationDatas ADD CONSTRAINT FK_70E84DDCE989605 FOREIGN KEY (basket_element_id) REFERENCES BasketElements (id)"); $this->addSql("ALTER TABLE BasketElements ADD CONSTRAINT FK_C0B7ECB71BE1FB52 FOREIGN KEY (basket_id) REFERENCES Baskets (id)"); $this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BF25B0F5B FOREIGN KEY (ValidationSession_id) REFERENCES ValidationSessions (id)"); + $this->addSql("ALTER TABLE ValidationParticipants ADD CONSTRAINT FK_17850D7BA76ED395 FOREIGN KEY (user_id) REFERENCES Users (id)"); } public function doDownSql(Schema $schema) { + $this->addSql("ALTER TABLE ValidationSessions DROP FOREIGN KEY FK_5B9DFB061BE1FB52"); + $this->addSql("ALTER TABLE Orders DROP FOREIGN KEY FK_E283F8D81BE1FB52"); $this->addSql("ALTER TABLE BasketElements DROP FOREIGN KEY FK_C0B7ECB71BE1FB52"); $this->addSql("ALTER TABLE ValidationParticipants DROP FOREIGN KEY FK_17850D7BF25B0F5B"); $this->addSql("ALTER TABLE ValidationDatas DROP FOREIGN KEY FK_70E84DDCE989605"); diff --git a/lib/Alchemy/Phrasea/Setup/Installer.php b/lib/Alchemy/Phrasea/Setup/Installer.php index 91f1ccbe59..86a4e42fbf 100644 --- a/lib/Alchemy/Phrasea/Setup/Installer.php +++ b/lib/Alchemy/Phrasea/Setup/Installer.php @@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Setup; use Alchemy\Phrasea\Application; use Doctrine\ORM\Tools\SchemaTool; +use Alchemy\Phrasea\Model\Entities\User; class Installer { @@ -34,6 +35,7 @@ class Installer $this->createAB(); $this->populateRegistryData($serverName, $dataPath, $binaryData); $user = $this->createUser($email, $password); + $this->createDefaultUsers(); if (null !== $dbConn) { $this->createDB($dbConn, $template); } @@ -71,8 +73,8 @@ class Installer ->give_access_to_sbas([$databox->get_sbas_id()]) ->update_rights_to_sbas( $databox->get_sbas_id(), [ - 'bas_manage' => 1, 'bas_modify_struct' => 1, - 'bas_modif_th' => 1, 'bas_chupub' => 1 + 'bas_manage' => 1, 'bas_modify_struct' => 1, + 'bas_modif_th' => 1, 'bas_chupub' => 1 ] ); @@ -101,12 +103,18 @@ class Installer private function createUser($email, $password) { - $user = \User_Adapter::create($this->app, $email, $password, $email, true); + $user = $this->app['manipulator.user']->createUser($email, $password, $email, true); $this->app['authentication']->openAccount($user); return $user; } + private function createDefaultUsers() + { + $this->app['manipulator.user']->createUser(User::USER_AUTOREGISTER, User::USER_AUTOREGISTER); + $this->app['manipulator.user']->createUser(User::USER_GUEST, User::USER_GUEST); + } + private function rollbackInstall(\connection_interface $abConn, \connection_interface $dbConn = null) { $structure = simplexml_load_file(__DIR__ . "/../../../conf.d/bases_structure.xml"); @@ -148,8 +156,6 @@ class Installer private function createAB() { - $this->app['phraseanet.appbox']->insert_datas(); - $metadatas = $this->app['EM']->getMetadataFactory()->getAllMetadata(); if (!empty($metadatas)) { @@ -159,6 +165,8 @@ class Installer $tool->dropSchema($metadatas); $tool->createSchema($metadatas); } + + $this->app['phraseanet.appbox']->insert_datas($this->app); } private function createConfigFile($abConn, $serverName, $binaryData) diff --git a/lib/Alchemy/Phrasea/Setup/Version/MailChecker.php b/lib/Alchemy/Phrasea/Setup/Version/MailChecker.php index 5ac5faf66c..ca6cd114de 100644 --- a/lib/Alchemy/Phrasea/Setup/Version/MailChecker.php +++ b/lib/Alchemy/Phrasea/Setup/Version/MailChecker.php @@ -26,7 +26,7 @@ class MailChecker * @param \Application $app * @param string $table The table name where to look * - * @return array An array of User_Adapter + * @return array An array of User */ public static function getWrongEmailUsers(Application $app, $table = 'usr') { diff --git a/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeCollection.php b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeCollection.php new file mode 100644 index 0000000000..3bbaa2237c --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeCollection.php @@ -0,0 +1,65 @@ +upgrades = $upgrades; + } + + /** + * Applies all applyable upgrades + * + * @param Application $app + */ + public function apply(Application $app) + { + $applied = []; + + foreach ($this->upgrades as $upgrade) { + if ($upgrade->isApplyable($app)) { + try { + $upgrade->apply( + $app['EM'], + $app['phraseanet.appbox'], + $app['doctrine-migration.configuration'] + ); + $applied[] = $upgrade; + } catch (\Exception $e) { + $upgrade->rollback( + $app['EM'], + $app['phraseanet.appbox'], + $app['doctrine-migration.configuration'] + ); + foreach (array_reverse($applied) as $done) { + $done->rollback( + $app['EM'], + $app['phraseanet.appbox'], + $app['doctrine-migration.configuration'] + ); + } + throw $e; + } + } + } + } +} diff --git a/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeInterface.php b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeInterface.php new file mode 100644 index 0000000000..7dded6e5c1 --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/PreSchemaUpgradeInterface.php @@ -0,0 +1,51 @@ +doBackupFeedsTable($em); + } + + /** + * {@inheritdoc} + */ + public function isApplyable(Application $app) + { + return $this->tableExists($app['EM'], 'feeds'); + } + + /** + * {@inheritdoc} + */ + public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf) + { + if ($this->tableExists($em, 'feeds_backup')) { + $em->getConnection()->executeUpdate('RENAME TABLE `feeds_backup` TO `feeds`'); + } + } + + /** + * Checks whether the table exists or not. + * + * @param $tableName + * + * @return boolean + */ + + private function tableExists(EntityManager $em, $table) + { + return (Boolean) $em->createNativeQuery( + 'SHOW TABLE STATUS WHERE Name="'.$table.'"', (new ResultSetMapping())->addScalarResult('Name', 'Name') + )->getOneOrNullResult(); + } + + /** + * Renames feed table. + * + * @param EntityManager $em + */ + private function doBackupFeedsTable(EntityManager $em) + { + $em->getConnection()->executeUpdate('RENAME TABLE `feeds` TO `feeds_backup`'); + } +} diff --git a/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php new file mode 100644 index 0000000000..699e5ab3db --- /dev/null +++ b/lib/Alchemy/Phrasea/Setup/Version/PreSchemaUpgrade/Upgrade39Users.php @@ -0,0 +1,473 @@ +sanitizeUsrTable($em); + // Creates User schema + $version = $conf->getVersion('user'); + if (false === $version->isMigrated()) { + $version->execute('up'); + } + $version = $conf->getVersion('ftp-credential'); + if (false === $version->isMigrated()) { + $version->execute('up'); + } + $this->alterTablesUp($em); + + try { + $em->getConnection()->beginTransaction(); + $em->getConnection()->query('SET FOREIGN_KEY_CHECKS=0'); + // Creates user entities + $this->updateUsers($em); + $this->updateFtpSettings($em); + // Creates user model references + $this->updateTemplateOwner($em); + $this->updateLastAppliedModels($em); + $this->cleanForeignKeyReferences($em); + $em->getConnection()->query('SET FOREIGN_KEY_CHECKS=1'); + $em->getConnection()->commit(); + $this->renameTable($em, 'up'); + } catch (\Exception $e) { + $em->getConnection()->rollback(); + $em->close(); + throw $e; + } + } + + /** + * {@inheritdoc} + */ + public function isApplyable(Application $app) + { + return false === $this->tableExists($app['EM'], 'Users'); + } + + /** + * {@inheritdoc} + */ + public function rollback(EntityManager $em, \appbox $appbox, Configuration $conf) + { + $this->renameTable($em, 'down'); + // truncate created tables + $this->emptyTables($em); + // rollback schema + $this->alterTablesDown($em); + $version = $conf->getVersion('ftp-credential'); + if ($version->isMigrated()) { + $version->execute('down'); + } + $version = $conf->getVersion('user'); + if ($version->isMigrated()) { + $version->execute('down'); + } + } + + private function renameTable(EntityManager $em, $direction) + { + switch ($direction) { + case 'up': + $sql = 'RENAME TABLE usr TO usr_backup'; + break; + case 'down': + $sql = 'RENAME TABLE usr_backup TO usr'; + break; + default: + throw new \InvalidArgumentException(sprintf('Direction %s is not recognized.', $direction)); + } + $em->getConnection()->executeUpdate($sql); + } + + private function alterTablesUp(EntityManager $em) + { + foreach ([ + 'UsrListOwners' => "ALTER TABLE UsrListOwners CHANGE usr_id user_id INT DEFAULT NULL", + 'Sessions' => "ALTER TABLE Sessions CHANGE usr_id user_id INT DEFAULT NULL", + 'Baskets' => "ALTER TABLE Baskets CHANGE usr_id user_id INT DEFAULT NULL", + 'StoryWZ' => "ALTER TABLE StoryWZ CHANGE usr_id user_id INT DEFAULT NULL", + 'LazaretSessions' => "ALTER TABLE LazaretSessions CHANGE usr_id user_id INT DEFAULT NULL", + 'ValidationParticipants' => "ALTER TABLE ValidationParticipants CHANGE usr_id user_id INT DEFAULT NULL", + 'UsrAuthProviders' => "ALTER TABLE UsrAuthProviders CHANGE usr_id user_id INT DEFAULT NULL", + 'UsrListsContent' => "ALTER TABLE UsrListsContent CHANGE usr_id user_id INT DEFAULT NULL", + ] as $table => $sql) { + if ($this->tableExists($em, $table)) { + $em->getConnection()->executeUpdate($sql); + } + } + } + + private function alterTablesDown(EntityManager $em) + { + foreach ([ + 'Baskets' => "ALTER TABLE Baskets CHANGE user_id usr_id", + 'LazaretSessions' => "ALTER TABLE LazaretSessions CHANGE user_id usr_id", + 'Sessions' => "ALTER TABLE Sessions CHANGE user_id usr_id", + 'StoryWZ' => "ALTER TABLE StoryWZ CHANGE user_id usr_id", + 'UsrAuthProviders' => "ALTER TABLE UsrAuthProviders CHANGE user_id usr_id", + 'UsrListOwners' => "ALTER TABLE UsrListOwners CHANGE user_id usr_id", + 'UsrListsContent' => "ALTER TABLE UsrListsContent CHANGE user_id usr_id", + 'ValidationParticipants' => "ALTER TABLE ValidationParticipants CHANGE user_id usr_id", + ] as $table => $sql) { + if ($this->tableExists($em, $table)) { + $em->getConnection()->executeUpdate($sql); + } + } + } + + /** + * Checks whether the table exists or not. + * + * @param $tableName + * + * @return boolean + */ + private function tableExists(EntityManager $em, $table) + { + return (Boolean) $em->createNativeQuery( + 'SHOW TABLE STATUS WHERE Name = :table', (new ResultSetMapping())->addScalarResult('Name', 'Name') + )->setParameter(':table', $table)->getOneOrNullResult(); + } + + /** + * Fix character set in usr table. + * + * @param $em + */ + private function sanitizeUsrTable($em) + { + $rs = $em->createNativeQuery( + "SHOW FIELDS FROM usr WHERE Field = 'usr_login';", + (new ResultSetMapping())->addScalarResult('Type', 'Type') + )->getSingleResult(); + + if (0 !== strpos(strtolower($rs['Type']), 'varbinary')) { + return; + } + + // As 'usr_login' field type is varbinary it can contain any charset (utf8 or latin1). + // Compare usr_login to usr_login converted to utf8>utf32>utf8 will detect broken char for latin1 encoded string. + // Detected 'usr_login' fields must be updated using CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8) + $rs = $em->createNativeQuery( + 'SELECT t.usr_id, t.login_utf8 FROM ( + SELECT usr_id, + usr_login AS login_unknown_charset, + CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8) login_utf8, + CONVERT(CONVERT(CAST(usr_login AS CHAR CHARACTER SET utf8) USING utf32) USING utf8) AS login_utf8_utf32_utf8 + FROM usr + ) AS t + WHERE t.login_utf8_utf32_utf8 != t.login_unknown_charset', + (new ResultSetMapping()) + ->addScalarResult('usr_id', 'usr_id') + ->addScalarResult('login_utf8', 'login_utf8') + )->getResult(); + + foreach ($rs as $row) { + $em->getConnection()->executeUpdate(sprintf('UPDATE usr SET usr_login="%s" WHERE usr_id=%d', $row['login_utf8'], $row['usr_id'])); + } + + foreach ([ + // drop index + "ALTER TABLE usr DROP INDEX usr_login;", + // change field type + "ALTER TABLE usr MODIFY usr_login VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin;", + // recreate index + "CREATE UNIQUE INDEX usr_login ON usr (usr_login);" + ] as $sql) { + $em->getConnection()->executeUpdate($sql); + } + } + + private function cleanForeignKeyReferences(EntityManager $em) + { + $schemas = [ + "Baskets"=> [ + "referenced_by" => [ + "Orders" => "basket_id", + "BasketElements" => "basket_id", + "ValidationSessions" => "basket_id", + ], + 'field' => ['user_id', 'pusher_id'], + ], + "LazaretSessions" => [ + "referenced_by" => [ + "LazaretFiles" => "lazaret_session_id" + ], + 'field' => ['user_id'], + ], + "Sessions" => [ + "referenced_by" => [ + "SessionModules" => "session_id" + ], + 'field' => ['user_id'], + ], + "StoryWZ" => [ + "referenced_by" => [], + 'field' => ['user_id'], + ], + "UsrAuthProviders" => [ + "referenced_by" => [], + 'field' => ['user_id'], + ], + "UsrListsContent" => [ + "referenced_by" => [], + 'field' => ['user_id'], + ], + "UsrListOwners" => [ + "referenced_by" => [], + 'field' => ['user_id'], + ], + "ValidationParticipants" => [ + "referenced_by" => [ + "ValidationDatas" => "participant_id" + ], + 'field' => ['user_id'], + ], + "ValidationSessions" => [ + "referenced_by" => [ + "ValidationParticipants" => "ValidationSession_id" + ], + 'field' => ['initiator_id'], + ], + ]; + + foreach ($schemas as $tableName => $data) { + foreach ($data['field'] as $field) { + $this->deleteForeignKey($em, $schemas, $field, $tableName); + } + } + } + + private function deleteForeignKey(EntityManager $em, $schemas, $field, $tableName, $wrongIds = ' NOT IN (SELECT id FROM Users WHERE deleted = 0 )') + { + if (false === $this->tableExists($em, $tableName)) { + return; + } + + $sql = sprintf('SELECT id FROM %s WHERE %s %s', $tableName, $field, $wrongIds); + $rs = $em->getConnection()->executeQuery($sql)->fetchAll(\PDO::FETCH_COLUMN); + + if (count($rs) === 0) { + return; + } + + if (isset($schemas[$tableName])) { + array_walk($schemas[$tableName]['referenced_by'], function ($field, $tableName) use ($em, $schemas, $rs) { + $this->deleteForeignKey($em, $schemas, $field, $tableName, ' IN ('.implode(', ', $rs).')'); + }); + } + + array_walk($rs, function ($value) use ($em, $schemas, $tableName, $field) { + $sql = sprintf('DELETE FROM %s WHERE id = :value', $tableName); + $em->getConnection()->executeUpdate($sql, [':value' => $value]); + }); + } + + /** + * Empty User & migration table. + * + * @param EntityManager $em + */ + private function emptyTables(EntityManager $em) + { + $meta = $em->getClassMetadata('Alchemy\Phrasea\Model\Entities\User'); + $connection = $em->getConnection(); + $dbPlatform = $connection->getDatabasePlatform(); + $connection->beginTransaction(); + try { + $connection->query('SET FOREIGN_KEY_CHECKS=0'); + $connection->executeUpdate($dbPlatform->getTruncateTableSql($meta->getTableName())); + $connection->query('SET FOREIGN_KEY_CHECKS=1'); + $connection->commit(); + } catch (\Exception $e) { + $connection->rollback(); + throw $e; + } + } + + /** + * Check whether the usr table has a nonce column or not. + * + * @param EntityManager $em + * + * @return boolean + */ + private function hasField(EntityManager $em, $fieldName) + { + return (Boolean) $em->createNativeQuery( + "SHOW FIELDS FROM usr WHERE Field = :field", + (new ResultSetMapping())->addScalarResult('Field', 'Field') + )->setParameter(':field', $fieldName)->getOneOrNullResult(); + } + + /** + * Sets user entity from usr table. + */ + private function updateUsers(EntityManager $em) + { + $em->getConnection()->executeUpdate( + 'INSERT INTO Users + ( + id, activity, address, admin, + can_change_ftp_profil, can_change_profil, city, company, + country, email, fax, first_name, + geoname_id, guest, job, last_connection, + last_name, ldap_created, locale, login, + mail_locked, last_model, mail_notifications, nonce, + password, push_list, request_notifications, salted_password, + gender, phone, timezone, zip_code, + created, updated + ) + ( + SELECT + usr_id, activite, adresse, create_db, + canchgftpprofil, canchgprofil, ville, societe, + pays, usr_mail, fax, usr_prenom, + geonameid, invite, fonction, last_conn, + usr_nom, ldap_created, locale, usr_login, + mail_locked, NULL AS lastModel, mail_notifications, '.($this->hasField($em, 'nonce') ? 'nonce' : 'NULL AS nonce').', + usr_password, push_list, request_notifications, '.($this->hasField($em, 'salted_password') ? 'salted_password' : '0 AS salted_password').', + usr_sexe, tel, timezone, cpostal, + usr_creationdate, usr_modificationdate + FROM usr + )' + ); + + $em->getConnection()->executeUpdate('UPDATE Users SET geoname_id=NULL WHERE geoname_id=0'); + $em->getConnection()->executeUpdate('UPDATE Users SET locale=NULL WHERE locale NOT IN ("'.implode('", "', array_keys(Application::getAvailableLanguages())).'")'); + $em->getConnection()->executeUpdate('UPDATE Users SET deleted=1, login=SUBSTRING(login, 11) WHERE login LIKE "(#deleted_%"'); + } + + private function updateFtpSettings(EntityManager $em) + { + $offset = 0; + $perBatch = 100; + + do { + $sql = 'SELECT usr_id, activeFTP, addrFTP, loginFTP, + retryFTP, passifFTP, pwdFTP, destFTP, prefixFTPfolder + FROM usr + WHERE + usr_login NOT LIKE "(#deleted_%" + AND model_of = 0 + AND addrFTP != ""' + .sprintf(' LIMIT %d, %d', $offset, $perBatch); + + $rs = $em->getConnection()->fetchAll($sql); + + foreach ($rs as $row) { + try { + $user = $em->createQuery('SELECT PARTIAL u.{id} FROM Phraseanet:User u WHERE u.id = :id') + ->setParameters(['id' => $row['usr_id']]) + ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) + ->getSingleResult(); + } catch (NoResultException $e) { + continue; + } + + $credential = new FtpCredential(); + $credential->setActive($row['activeFTP']); + $credential->setAddress($row['addrFTP']); + $credential->setLogin($row['loginFTP']); + $credential->setMaxRetry((Integer) $row['retryFTP']); + $credential->setPassive($row['passifFTP']); + $credential->setPassword($row['pwdFTP']); + $credential->setReceptionFolder($row['destFTP']); + $credential->setRepositoryPrefixName($row['prefixFTPfolder']); + $credential->setUser($user); + + $em->persist($credential); + } + + $em->flush(); + $em->clear(); + + $offset += $perBatch; + } while (count($rs) > 0); + + return true; + } + + /** + * Sets last_model from usr table. + */ + private function updateLastAppliedModels(EntityManager $em) + { + $em->getConnection()->executeUpdate(' + UPDATE Users + INNER JOIN usr ON ( + usr.usr_id = Users.id + AND Users.deleted=0 + AND usr.lastModel IS NOT NULL + AND usr.lastModel != "" + ) + LEFT JOIN Users TableTemp ON (usr.lastModel = TableTemp.login) + SET Users.last_model = TableTemp.id + '); + } + + /** + * Sets model from usr table. + */ + private function updateTemplateOwner(EntityManager $em) + { + + $em->getConnection()->executeUpdate(' + UPDATE Users + INNER JOIN usr ON ( + usr.usr_id = Users.id + AND usr.model_of IS NOT NULL + AND usr.model_of>0 + ) + SET Users.model_of = usr.model_of + '); + + $em->getConnection()->executeUpdate(' + DELETE from Users + WHERE id IN ( + SELECT id FROM ( + SELECT templates.id + FROM Users users, Users templates + WHERE templates.model_of = users.id AND (users.deleted = 1 OR users.model_of IS NOT NULL) + ) as temporaryTable + ) + '); + + $em->getConnection()->executeUpdate(' + DELETE from Users + WHERE id IN ( + SELECT id FROM ( + SELECT templates.id + FROM Users templates + WHERE templates.model_of NOT IN (SELECT id FROM Users) + ) as temporaryTable + ) + '); + + $em->getConnection()->executeUpdate(' DELETE from Users WHERE deleted = 1 AND model_of IS NOT NULL'); + } +} diff --git a/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php b/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php index 0eb7b006b8..a9bc1b04e7 100644 --- a/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php +++ b/lib/Alchemy/Phrasea/TaskManager/Job/BridgeJob.php @@ -155,7 +155,7 @@ class BridgeJob extends AbstractJob case \Bridge_Element::STATUS_ERROR: $params = [ - 'usr_id' => $account->get_user()->get_id(), + 'usr_id' => $account->get_user()->getId(), 'reason' => $error_message, 'account_id' => $account->get_id(), 'sbas_id' => $element->get_record()->get_sbas_id(), diff --git a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php index ed8b3c2de9..858e594f0c 100644 --- a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php +++ b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/ControlProviderInterface.php @@ -11,6 +11,8 @@ namespace Alchemy\Phrasea\Vocabulary\ControlProvider; +use Alchemy\Phrasea\Model\Entities\User; + interface ControlProviderInterface { @@ -47,11 +49,11 @@ interface ControlProviderInterface /** * Find matching Term in the vocabulary repository * - * @param string $query A scalar quaery - * @param \User_Adapter $for_user The user doing the query - * @param \databox $on_databox The databox where vocabulary should be requested + * @param string $query A scalar quaery + * @param User $for_user The user doing the query + * @param \databox $on_databox The databox where vocabulary should be requested * * @return Doctrine\Common\Collections\ArrayCollection */ - public function find($query, \User_Adapter $for_user, \databox $on_databox); + public function find($query, User $for_user, \databox $on_databox); } diff --git a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php index 344dc89344..e9dfe3e400 100644 --- a/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php +++ b/lib/Alchemy/Phrasea/Vocabulary/ControlProvider/UserProvider.php @@ -12,6 +12,7 @@ namespace Alchemy\Phrasea\Vocabulary\ControlProvider; use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; use Doctrine\Common\Collections\ArrayCollection; use Alchemy\Phrasea\Vocabulary\Term; @@ -45,11 +46,11 @@ class UserProvider implements ControlProviderInterface /** * * @param string $query - * @param \User_Adapter $for_user + * @param User $for_user * @param \databox $on_databox * @return \Doctrine\Common\Collections\ArrayCollection */ - public function find($query, \User_Adapter $for_user, \databox $on_databox = null) + public function find($query, User $for_user,\databox $on_databox = null) { $user_query = new \User_Query($this->app); @@ -67,7 +68,7 @@ class UserProvider implements ControlProviderInterface foreach ($users as $user) { $results->add( - new Term($user->get_display_name(), '', $this, $user->get_id()) + new Term($user->getDisplayName(), '', $this, $user->getId()) ); } @@ -81,15 +82,7 @@ class UserProvider implements ControlProviderInterface */ public function validate($id) { - try { - \User_Adapter::getInstance($id, $this->app); - - return true; - } catch (\Exception $e) { - - } - - return false; + return (Boolean) $this->app['manipulator.user']->getRepository()->find($id); } /** @@ -99,9 +92,13 @@ class UserProvider implements ControlProviderInterface */ public function getValue($id) { - $user = \User_Adapter::getInstance($id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($id); - return $user->get_display_name(); + if (null === $user) { + throw new \Exception('User unknown'); + } + + return $user->getDisplayName(); } /** @@ -111,6 +108,6 @@ class UserProvider implements ControlProviderInterface */ public function getRessource($id) { - return \User_Adapter::getInstance($id, $this->app); + return $this->app['manipulator.user']->getRepository()->find($id); } } diff --git a/lib/classes/ACL.php b/lib/classes/ACL.php index 4f19600fe9..b8df075007 100644 --- a/lib/classes/ACL.php +++ b/lib/classes/ACL.php @@ -10,6 +10,7 @@ */ use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; class ACL implements cache_cacheableInterface { @@ -100,12 +101,12 @@ class ACL implements cache_cacheableInterface /** * Constructor * - * @param User_Interface $user - * @param Application $app + * @param User $user + * @param Application $app * * @return \ACL */ - public function __construct(User_Interface $user, Application $app) + public function __construct(User $user, Application $app) { $this->user = $user; $this->app = $app; @@ -113,11 +114,6 @@ class ACL implements cache_cacheableInterface return $this; } - public function set_app(Application $app) - { - $this->app = $app; - } - /** * Check if a hd grant has been received for a record * @@ -138,7 +134,7 @@ class ACL implements cache_cacheableInterface return false; } - public function grant_hd_on(record_adapter $record, User_Adapter $pusher, $action) + public function grant_hd_on(record_adapter $record, User $pusher, $action) { $sql = 'REPLACE INTO records_rights (id, usr_id, sbas_id, record_id, document, `case`, pusher_usr_id) @@ -146,11 +142,11 @@ class ACL implements cache_cacheableInterface (null, :usr_id, :sbas_id, :record_id, 1, :case, :pusher)'; $params = [ - ':usr_id' => $this->user->get_id() + ':usr_id' => $this->user->getId() , ':sbas_id' => $record->get_sbas_id() , ':record_id' => $record->get_record_id() , ':case' => $action - , ':pusher' => $pusher->get_id() + , ':pusher' => $pusher->getId() ]; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -162,7 +158,7 @@ class ACL implements cache_cacheableInterface return $this; } - public function grant_preview_on(record_adapter $record, User_Adapter $pusher, $action) + public function grant_preview_on(record_adapter $record, User $pusher, $action) { $sql = 'REPLACE INTO records_rights (id, usr_id, sbas_id, record_id, preview, `case`, pusher_usr_id) @@ -170,11 +166,11 @@ class ACL implements cache_cacheableInterface (null, :usr_id, :sbas_id, :record_id, 1, :case, :pusher)'; $params = [ - ':usr_id' => $this->user->get_id() + ':usr_id' => $this->user->getId() , ':sbas_id' => $record->get_sbas_id() , ':record_id' => $record->get_record_id() , ':case' => $action - , ':pusher' => $pusher->get_id() + , ':pusher' => $pusher->getId() ]; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -194,7 +190,6 @@ class ACL implements cache_cacheableInterface */ public function has_preview_grant(record_Interface $record) { - $this->load_hd_grant(); $key = $record->get_serialize_key(); @@ -262,11 +257,11 @@ class ACL implements cache_cacheableInterface /** * Apply a template on user * - * @param User_Interface $template_user - * @param array $base_ids + * @param User $template_user + * @param array $base_ids * @return ACL */ - public function apply_model(User_Interface $template_user, Array $base_ids) + public function apply_model(User $template_user, Array $base_ids) { if (count($base_ids) == 0) { return $this; @@ -391,12 +386,12 @@ class ACL implements cache_cacheableInterface $this->apply_template_time_limits($template_user, $base_ids); - $this->user->set_last_template($template_user); + $this->user->setLastModel($template_user); return $this; } - private function apply_template_time_limits(User_Interface $template_user, Array $base_ids) + private function apply_template_time_limits(User $template_user, Array $base_ids) { foreach ($base_ids as $base_id) { $limited = $this->app['acl']->get($template_user)->get_limits($base_id); @@ -448,7 +443,7 @@ class ACL implements cache_cacheableInterface */ public function get_cache_key($option = null) { - return '_ACL_' . $this->user->get_id() . ($option ? '_' . $option : ''); + return '_ACL_' . $this->user->getId() . ($option ? '_' . $option : ''); } /** @@ -751,25 +746,16 @@ class ACL implements cache_cacheableInterface public function is_admin() { - $this->load_is_admin(); - - return $this->is_admin; + return $this->user->isAdmin(); } public function set_admin($boolean) { - $sql = 'UPDATE usr SET create_db = :create_db WHERE usr_id = :usr_id'; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([ - ':create_db' => $boolean ? '1' : '0', - ':usr_id' => $this->user->get_id() - ]); - $stmt->closeCursor(); - - $this->delete_data_from_cache(self::CACHE_IS_ADMIN); - - $this->is_admin = null; + if ($boolean) { + $this->app['manipulator.user']->promote($this->user); + } else { + $this->app['manipulator.user']->demote($this->user); + } return $this; } @@ -799,7 +785,7 @@ class ACL implements cache_cacheableInterface FROM records_rights WHERE usr_id = :usr_id'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); unset($stmt); @@ -824,34 +810,6 @@ class ACL implements cache_cacheableInterface return $this; } - protected function load_is_admin() - { - if (null !== $this->is_admin) { - return $this; - } - - try { - $this->is_admin = $this->get_data_from_cache(self::CACHE_IS_ADMIN); - - return $this; - } catch (\Exception $e) { - - } - $sql = 'SELECT create_db - FROM usr WHERE usr_id = :usr_id'; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - unset($stmt); - $this->is_admin = !!$row['create_db']; - - $this->set_data_to_cache($this->is_admin, self::CACHE_IS_ADMIN); - - return $this; - } - /** * Loads rights of specified user for all sbas * @@ -878,7 +836,7 @@ class ACL implements cache_cacheableInterface AND sbas.sbas_id = sbasusr.sbas_id'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -939,7 +897,7 @@ class ACL implements cache_cacheableInterface AND s.sbas_id = b.sbas_id '; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -1116,7 +1074,7 @@ class ACL implements cache_cacheableInterface $sql_del = 'DELETE FROM basusr WHERE base_id = :base_id AND usr_id = :usr_id'; $stmt_del = $this->app['phraseanet.appbox']->get_connection()->prepare($sql_del); - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); foreach ($base_ids as $base_id) { if (!$stmt_del->execute([':base_id' => $base_id, ':usr_id' => $usr_id])) { @@ -1138,7 +1096,7 @@ class ACL implements cache_cacheableInterface $sql_ins = 'INSERT INTO basusr (id, base_id, usr_id, actif) VALUES (null, :base_id, :usr_id, "1")'; $stmt_ins = $this->app['phraseanet.appbox']->get_connection()->prepare($sql_ins); - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); $to_update = []; $this->load_rights_bas(); @@ -1175,7 +1133,7 @@ class ACL implements cache_cacheableInterface $sql_ins = 'INSERT INTO sbasusr (sbasusr_id, sbas_id, usr_id) VALUES (null, :sbas_id, :usr_id)'; $stmt_ins = $this->app['phraseanet.appbox']->get_connection()->prepare($sql_ins); - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); foreach ($sbas_ids as $sbas_id) { if (!$this->has_access_to_sbas($sbas_id)) @@ -1221,7 +1179,7 @@ class ACL implements cache_cacheableInterface return $this; } - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); $sql_up .= implode(', ', $sql_args) . ' WHERE base_id = :base_id AND usr_id = :usr_id'; @@ -1252,7 +1210,7 @@ class ACL implements cache_cacheableInterface (SELECT distinct sbas_id FROM basusr bu, bas b WHERE usr_id = :usr_id_2 AND b.base_id = bu.base_id)'; - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); $params = [':usr_id_1' => $usr_id, ':usr_id_2' => $usr_id]; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -1278,7 +1236,7 @@ class ACL implements cache_cacheableInterface $sql_up = "UPDATE sbasusr SET "; $sql_args = []; - $usr_id = $this->user->get_id(); + $usr_id = $this->user->getId(); $params = [':sbas_id' => $sbas_id, ':usr_id' => $usr_id]; foreach ($rights as $right => $v) { @@ -1315,7 +1273,7 @@ class ACL implements cache_cacheableInterface WHERE usr_id = :usr_id AND base_id = :base_id '; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id(), ':base_id' => $base_id]); + $stmt->execute([':usr_id' => $this->user->getId(), ':base_id' => $base_id]); $stmt->closeCursor(); unset($stmt); @@ -1331,13 +1289,13 @@ class ACL implements cache_cacheableInterface AND usr_id = :usr_id AND MONTH(lastconn) != MONTH(NOW()) AND restrict_dwnld = 1'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $stmt->closeCursor(); $sql = "UPDATE basusr SET lastconn=now() WHERE usr_id = :usr_id AND actif = 1"; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $stmt->closeCursor(); unset($stmt); @@ -1360,7 +1318,7 @@ class ACL implements cache_cacheableInterface WHERE usr_id = :usr_id AND base_id = :base_id '; $params = [ - ':usr_id' => $this->user->get_id(), + ':usr_id' => $this->user->getId(), ':base_id' => $base_id, ':restes' => $restes, ':droits' => $droits @@ -1383,7 +1341,7 @@ class ACL implements cache_cacheableInterface $params = [ ':base_from' => $base_id_from, - ':usr_id' => $this->user->get_id() + ':usr_id' => $this->user->getId() ]; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -1470,7 +1428,7 @@ class ACL implements cache_cacheableInterface foreach ($this->get_granted_base([], [$databox->get_sbas_id()]) as $collection) { $stmt->execute([ ':site_id' => $this->app['conf']->get(['main', 'key']), - ':usr_id' => $this->user->get_id(), + ':usr_id' => $this->user->getId(), ':coll_id' => $collection->get_coll_id(), ':mask_and' => $this->get_mask_and($collection->get_base_id()), ':mask_xor' => $this->get_mask_xor($collection->get_base_id()), @@ -1496,7 +1454,7 @@ class ACL implements cache_cacheableInterface { $sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site'; $params = [ - ':usr_id' => $this->user->get_id() + ':usr_id' => $this->user->getId() , ':site' => $this->app['conf']->get(['main', 'key']) ]; $stmt = $databox->get_connection()->prepare($sql); @@ -1536,7 +1494,7 @@ class ACL implements cache_cacheableInterface WHERE usr_id = :usr_id and base_id = :base_id"; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':base_id' => $base_id, ':usr_id' => $this->user->get_id()]); + $stmt->execute([':base_id' => $base_id, ':usr_id' => $this->user->getId()]); $stmt->closeCursor(); unset($stmt); @@ -1590,7 +1548,7 @@ class ACL implements cache_cacheableInterface } $params = [ - ':usr_id' => $this->user->get_id() + ':usr_id' => $this->user->getId() , ':base_id' => $base_id , 'limited_from' => ($limit_from ? $limit_from->format(DATE_ISO8601) : null) , 'limited_to' => ($limit_to ? $limit_to->format(DATE_ISO8601) : null) @@ -1616,7 +1574,7 @@ class ACL implements cache_cacheableInterface { $sql = 'SELECT base_id FROM basusr WHERE order_master="1" AND usr_id= :usr_id '; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->user->get_id()]); + $stmt->execute([':usr_id' => $this->user->getId()]); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -1645,7 +1603,7 @@ class ACL implements cache_cacheableInterface $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute([ ':master' => $bool ? 1 : 0, - ':usr_id' => $this->user->get_id(), + ':usr_id' => $this->user->getId(), ':base_id' => $collection->get_base_id() ]); $stmt->closeCursor(); diff --git a/lib/classes/API/OAuth2/Account.php b/lib/classes/API/OAuth2/Account.php index 13cc69b6f3..c20ae3d263 100644 --- a/lib/classes/API/OAuth2/Account.php +++ b/lib/classes/API/OAuth2/Account.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Application; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Alchemy\Phrasea\Model\Entities\User; class API_OAuth2_Account { @@ -28,7 +29,7 @@ class API_OAuth2_Account /** * - * @var User_Adapter + * @var User */ protected $user; @@ -83,7 +84,7 @@ class API_OAuth2_Account $stmt->closeCursor(); $this->application_id = (int) $row['application_id']; - $this->user = User_Adapter::getInstance($row['usr_id'], $app); + $this->user = $app['manipulator.user']->getRepository()->find($row['usr_id']); $this->api_version = $row['api_version']; $this->revoked = ! ! $row['revoked']; @@ -103,7 +104,7 @@ class API_OAuth2_Account /** * - * @return User_Adapter + * @return User */ public function get_user() { @@ -214,7 +215,7 @@ class API_OAuth2_Account return; } - public static function create(Application $app, User_Adapter $user, API_OAuth2_Application $application) + public static function create(Application $app, User $user, API_OAuth2_Application $application) { $sql = 'INSERT INTO api_accounts (api_account_id, usr_id, revoked, api_version, application_id, created) @@ -222,7 +223,7 @@ class API_OAuth2_Account $datetime = new Datetime(); $params = [ - ':usr_id' => $user->get_id() + ':usr_id' => $user->getId() , ':application_id' => $application->get_id() , ':api_version' => API_OAuth2_Adapter::API_VERSION , ':revoked' => 0 @@ -238,13 +239,13 @@ class API_OAuth2_Account return new self($app, $account_id); } - public static function load_with_user(Application $app, API_OAuth2_Application $application, User_Adapter $user) + public static function load_with_user(Application $app, API_OAuth2_Application $application, User $user) { $sql = 'SELECT api_account_id FROM api_accounts WHERE usr_id = :usr_id AND application_id = :application_id'; $params = [ - ":usr_id" => $user->get_id(), + ":usr_id" => $user->getId(), ":application_id" => $application->get_id() ]; diff --git a/lib/classes/API/OAuth2/Adapter.php b/lib/classes/API/OAuth2/Adapter.php index b0afbd086a..c216b641f7 100644 --- a/lib/classes/API/OAuth2/Adapter.php +++ b/lib/classes/API/OAuth2/Adapter.php @@ -222,7 +222,7 @@ class API_OAuth2_Adapter extends OAuth2 , 'client_id' => $token->get_account()->get_application()->get_client_id() , 'session_id' => $token->get_session_id() , 'revoked' => ($token->get_account()->is_revoked() ? '1' : '0') - , 'usr_id' => $token->get_account()->get_user()->get_id() + , 'usr_id' => $token->get_account()->get_user()->getId() , 'oauth_token' => $token->get_value() ]; @@ -506,7 +506,7 @@ class API_OAuth2_Adapter extends OAuth2 throw new logicalException("Client property must be set before update an account"); try { - $user = User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); $account = API_OAuth2_Account::load_with_user($this->app, $this->client, $user); } catch (\Exception $e) { $account = $this->createAccount($usr_id); @@ -522,7 +522,7 @@ class API_OAuth2_Adapter extends OAuth2 */ private function createAccount($usr_id) { - $user = User_Adapter::getInstance($usr_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($usr_id); return API_OAuth2_Account::create($this->app, $user, $this->client); } diff --git a/lib/classes/API/OAuth2/Application.php b/lib/classes/API/OAuth2/Application.php index 4c0d6ee67e..59e60c1e46 100644 --- a/lib/classes/API/OAuth2/Application.php +++ b/lib/classes/API/OAuth2/Application.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Application; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Alchemy\Phrasea\Model\Entities\User; class API_OAuth2_Application { @@ -41,7 +42,7 @@ class API_OAuth2_Application /** * - * @var User_Adapter + * @var User */ protected $creator; @@ -145,7 +146,7 @@ class API_OAuth2_Application $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); - $this->creator = ! $row['creator'] ? null : User_Adapter::getInstance($row['creator'], $this->app); + $this->creator = ! $row['creator'] ? null : $this->app['manipulator.user']->getRepository()->find($row['creator']); $this->type = $row['type']; $this->name = $row['name']; $this->description = $row['description']; @@ -173,7 +174,7 @@ class API_OAuth2_Application /** * - * @return User_Adapter + * @return User */ public function get_creator() { @@ -518,16 +519,16 @@ class API_OAuth2_Application /** * - * @param User_Adapter $user + * @param User $user * @return API_OAuth2_Account */ - public function get_user_account(user_adapter $user) + public function get_user_account(User $user) { $sql = 'SELECT api_account_id FROM api_accounts WHERE usr_id = :usr_id AND application_id = :id'; $params = [ - ':usr_id' => $user->get_id() + ':usr_id' => $user->getId() , ':id' => $this->id ]; @@ -588,11 +589,11 @@ class API_OAuth2_Application /** * * @param Application $app - * @param User_Adapter $user + * @param User $user * @param type $name * @return API_OAuth2_Application */ - public static function create(Application $app, User_Adapter $user = null, $name) + public static function create(Application $app, User $user = null, $name) { $sql = ' INSERT INTO api_applications ( @@ -609,7 +610,7 @@ class API_OAuth2_Application $client_token = API_OAuth2_Token::generate_token(); $params = [ - ':usr_id' => $user ? $user->get_id() : null, + ':usr_id' => $user ? $user->getId() : null, ':name' => $name, ':client_id' => $client_token, ':client_secret' => $client_secret, @@ -655,14 +656,14 @@ class API_OAuth2_Application return new self($app, $row['application_id']); } - public static function load_dev_app_by_user(Application $app, User_Adapter $user) + public static function load_dev_app_by_user(Application $app, User $user) { $sql = 'SELECT a.application_id FROM api_applications a, api_accounts b WHERE a.creator = :usr_id AND a.application_id = b.application_id'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $user->get_id()]); + $stmt->execute([':usr_id' => $user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -674,14 +675,14 @@ class API_OAuth2_Application return $apps; } - public static function load_app_by_user(Application $app, user_adapter $user) + public static function load_app_by_user(Application $app, User $user) { $sql = 'SELECT a.application_id FROM api_accounts a, api_applications c WHERE usr_id = :usr_id AND c.application_id = a.application_id'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $user->get_id()]); + $stmt->execute([':usr_id' => $user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -693,7 +694,7 @@ class API_OAuth2_Application return $apps; } - public static function load_authorized_app_by_user(Application $app, user_adapter $user) + public static function load_authorized_app_by_user(Application $app, User $user) { $sql = ' SELECT a.application_id @@ -702,7 +703,7 @@ class API_OAuth2_Application AND revoked = 0'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $user->get_id()]); + $stmt->execute([':usr_id' => $user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); diff --git a/lib/classes/API/V1/Interface.php b/lib/classes/API/V1/Interface.php index 846571091d..c9fd4ceb76 100644 --- a/lib/classes/API/V1/Interface.php +++ b/lib/classes/API/V1/Interface.php @@ -10,6 +10,7 @@ */ use Alchemy\Phrasea\Model\Entities\Basket; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\HttpFoundation\Request; use Silex\Application; @@ -242,7 +243,7 @@ interface API_V1_Interface * Parameters : * */ - public function search_publications(Request $request, User_Adapter $user); + public function search_publications(Request $request, User $user); /** * Route : /publications/PUBLICATION_ID/remove/FORMAT/ @@ -264,11 +265,11 @@ interface API_V1_Interface * PUBLICATION_ID : required INT * */ - public function get_publication(Request $request, $publication_id, User_Adapter $user); + public function get_publication(Request $request, $publication_id, User $user); - public function get_publications(Request $request, User_Adapter $user); + public function get_publications(Request $request, User $user); - public function get_feed_entry(Request $request, $entry, User_Adapter $user); + public function get_feed_entry(Request $request, $entry, User $user); /** * Route : /users/search/FORMAT/ * diff --git a/lib/classes/API/V1/adapter.php b/lib/classes/API/V1/adapter.php index 6e9f86d1ce..ac0d12f9a4 100644 --- a/lib/classes/API/V1/adapter.php +++ b/lib/classes/API/V1/adapter.php @@ -23,6 +23,7 @@ use Alchemy\Phrasea\Model\Entities\FeedEntry; use Alchemy\Phrasea\Model\Entities\FeedItem; use Alchemy\Phrasea\Model\Entities\LazaretFile; use Alchemy\Phrasea\Model\Entities\Task; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\UserQuery; use Alchemy\Phrasea\Model\Entities\ValidationData; use Alchemy\Phrasea\Model\Entities\ValidationParticipant; @@ -658,7 +659,7 @@ class API_V1_adapter extends API_V1_Abstract } $session = new Alchemy\Phrasea\Model\Entities\LazaretSession(); - $session->setUsrId($app['authentication']->getUser()->get_id()); + $session->setUser($app['authentication']->getUser()); $app['EM']->persist($session); $app['EM']->flush(); @@ -783,8 +784,8 @@ class API_V1_adapter extends API_V1_Abstract } $usr_id = null; - if ($file->getSession()->getUser($this->app)) { - $usr_id = $file->getSession()->getUser($this->app)->get_id(); + if ($file->getSession()->getUser()) { + $usr_id = $file->getSession()->getUser()->getId(); } $session = [ @@ -876,7 +877,7 @@ class API_V1_adapter extends API_V1_Abstract $search_result = $this->app['phraseanet.SE']->query($query, $offsetStart, $perPage, $options); $userQuery = new UserQuery(); - $userQuery->setUsrId($this->app['authentication']->getUser()->get_id()); + $userQuery->setUser($this->app['authentication']->getUser()); $userQuery->setQuery($query); $this->app['EM']->persist($userQuery); @@ -1226,7 +1227,7 @@ class API_V1_adapter extends API_V1_Abstract { $result = new API_V1_result($this->app, $request, $this); - $usr_id = $this->app['authentication']->getUser()->get_id(); + $usr_id = $this->app['authentication']->getUser()->getId(); $result->set_datas(['baskets' => $this->list_baskets($usr_id)]); @@ -1271,7 +1272,7 @@ class API_V1_adapter extends API_V1_Abstract } $Basket = new Basket(); - $Basket->setOwner($this->app['authentication']->getUser()); + $Basket->setUser($this->app['authentication']->getUser()); $Basket->setName($name); $this->app['EM']->persist($Basket); @@ -1309,10 +1310,10 @@ class API_V1_adapter extends API_V1_Abstract $result = new API_V1_result($this->app, $request, $this); $result->set_datas( - [ - "basket" => $this->list_basket($basket), - "basket_elements" => $this->list_basket_content($basket) - ] + [ + "basket" => $this->list_basket($basket), + "basket_elements" => $this->list_basket_content($basket) + ] ); return $result; @@ -1357,23 +1358,23 @@ class API_V1_adapter extends API_V1_Abstract foreach ($basket_element->getValidationDatas() as $validation_datas) { $participant = $validation_datas->getParticipant(); - $user = $participant->getUser($this->app); + $user = $participant->getUser(); /* @var $validation_datas ValidationData */ $choices[] = [ 'validation_user' => [ - 'usr_id' => $user->get_id(), - 'usr_name' => $user->get_display_name(), + 'usr_id' => $user->getId(), + 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), - 'readonly' => $user->get_id() != $this->app['authentication']->getUser()->get_id(), + 'readonly' => $user->getId() != $this->app['authentication']->getUser()->getId(), ], 'agreement' => $validation_datas->getAgreement(), 'updated_on' => $validation_datas->getUpdated()->format(DATE_ATOM), 'note' => null === $validation_datas->getNote() ? '' : $validation_datas->getNote(), ]; - if ($user->get_id() == $this->app['authentication']->getUser()->get_id()) { + if ($user->getId() == $this->app['authentication']->getUser()->getId()) { $agreement = $validation_datas->getAgreement(); $note = null === $validation_datas->getNote() ? '' : $validation_datas->getNote(); } @@ -1434,10 +1435,10 @@ class API_V1_adapter extends API_V1_Abstract * List all avalaible feeds * * @param Request $request - * @param User_Adapter $user + * @param User $user * @return API_V1_result */ - public function search_publications(Request $request, User_Adapter $user) + public function search_publications(Request $request, User $user) { $result = new API_V1_result($this->app, $request, $this); @@ -1467,10 +1468,10 @@ class API_V1_adapter extends API_V1_Abstract * * @param Request $request * @param int $publication_id - * @param User_Adapter $user + * @param User $user * @return API_V1_result */ - public function get_publication(Request $request, $publication_id, User_Adapter $user) + public function get_publication(Request $request, $publication_id, User $user) { $result = new API_V1_result($this->app, $request, $this); @@ -1495,7 +1496,7 @@ class API_V1_adapter extends API_V1_Abstract return $result; } - public function get_publications(Request $request, User_Adapter $user) + public function get_publications(Request $request, User $user) { $result = new API_V1_result($this->app, $request, $this); @@ -1518,7 +1519,7 @@ class API_V1_adapter extends API_V1_Abstract return $result; } - public function get_feed_entry(Request $request, $entry_id, User_Adapter $user) + public function get_feed_entry(Request $request, $entry_id, User $user) { $result = new API_V1_result($this->app, $request, $this); @@ -1777,7 +1778,7 @@ class API_V1_adapter extends API_V1_Abstract 'created_on' => $basket->getCreated()->format(DATE_ATOM), 'description' => (string) $basket->getDescription(), 'name' => $basket->getName(), - 'pusher_usr_id' => $basket->getPusherId(), + 'pusher_usr_id' => $basket->getPusher() ? $basket->getPusher()->getId() : null, 'updated_on' => $basket->getUpdated()->format(DATE_ATOM), 'unread' => !$basket->getIsRead(), 'validation_basket' => !!$basket->getValidation() @@ -1788,15 +1789,15 @@ class API_V1_adapter extends API_V1_Abstract foreach ($basket->getValidation()->getParticipants() as $participant) { /* @var $participant ValidationParticipant */ - $user = $participant->getUser($this->app); + $user = $participant->getUser(); $users[] = [ - 'usr_id' => $user->get_id(), - 'usr_name' => $user->get_display_name(), + 'usr_id' => $user->getId(), + 'usr_name' => $user->getDisplayName(), 'confirmed' => $participant->getIsConfirmed(), 'can_agree' => $participant->getCanAgree(), 'can_see_others' => $participant->getCanSeeOthers(), - 'readonly' => $user->get_id() != $this->app['authentication']->getUser()->get_id(), + 'readonly' => $user->getId() != $this->app['authentication']->getUser()->getId(), ]; } @@ -1811,7 +1812,7 @@ class API_V1_adapter extends API_V1_Abstract 'validation_users' => $users, 'expires_on' => $expires_on_atom, 'validation_infos' => $basket->getValidation()->getValidationString($this->app, $this->app['authentication']->getUser()), - 'validation_confirmed' => $basket->getValidation()->getParticipant($this->app['authentication']->getUser(), $this->app)->getIsConfirmed(), + 'validation_confirmed' => $basket->getValidation()->getParticipant($this->app['authentication']->getUser())->getIsConfirmed(), 'validation_initiator' => $basket->getValidation()->isInitiator($this->app['authentication']->getUser()), ], $ret ); diff --git a/lib/classes/Bridge/Account.php b/lib/classes/Bridge/Account.php index f2304c4136..8035596148 100644 --- a/lib/classes/Bridge/Account.php +++ b/lib/classes/Bridge/Account.php @@ -10,6 +10,7 @@ */ use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; class Bridge_Account { @@ -39,7 +40,7 @@ class Bridge_Account /** * - * @var User_Adapter + * @var User */ protected $user; @@ -94,7 +95,7 @@ class Bridge_Account throw new Bridge_Exception_AccountNotFound('Account Not Found'); $this->dist_id = $row['dist_id']; - $this->user = User_Adapter::getInstance($row['usr_id'], $this->app); + $this->user = $this->app['manipulator.user']->getRepository()->find($row['usr_id']); $this->name = $row['name']; $this->updated_on = new DateTime($row['updated_on']); $this->created_on = new DateTime($row['created_on']); @@ -143,7 +144,7 @@ class Bridge_Account /** * - * @return User_Adapter + * @return User */ public function get_user() { @@ -253,18 +254,18 @@ class Bridge_Account * * @param Application $app * @param Bridge_Api $api - * @param User_Adapter $user + * @param User $user * @param string $distant_id * @return Bridge_Account */ - public static function load_account_from_distant_id(Application $app, Bridge_Api $api, User_Adapter $user, $distant_id) + public static function load_account_from_distant_id(Application $app, Bridge_Api $api, User $user, $distant_id) { $sql = 'SELECT id FROM bridge_accounts WHERE api_id = :api_id AND usr_id = :usr_id AND dist_id = :dist_id'; $params = [ ':api_id' => $api->get_id() - , ':usr_id' => $user->get_id() + , ':usr_id' => $user->getId() , ':dist_id' => $distant_id ]; @@ -308,15 +309,15 @@ class Bridge_Account /** * * @param Application $app - * @param user_adapter $user + * @param User $user * @return Bridge_Account */ - public static function get_accounts_by_user(Application $app, user_adapter $user) + public static function get_accounts_by_user(Application $app, User $user) { $sql = 'SELECT id, api_id FROM bridge_accounts WHERE usr_id = :usr_id'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $user->get_id()]); + $stmt->execute([':usr_id' => $user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -340,15 +341,15 @@ class Bridge_Account /** * - * @param Application $app - * @param Bridge_Api $api - * @param User_Adapter $user - * @param string $dist_id - * @param string $name + * @param Application $app + * @param Bridge_Api $api + * @param User $user + * @param string $dist_id + * @param string $name * * @return Bridge_Account */ - public static function create(Application $app, Bridge_Api $api, User_Adapter $user, $dist_id, $name) + public static function create(Application $app, Bridge_Api $api, User $user, $dist_id, $name) { $sql = 'INSERT INTO bridge_accounts (id, api_id, dist_id, usr_id, name, created_on, updated_on) @@ -357,7 +358,7 @@ class Bridge_Account $params = [ ':api_id' => $api->get_id() , ':dist_id' => $dist_id - , ':usr_id' => $user->get_id() + , ':usr_id' => $user->getId() , ':name' => $name ]; diff --git a/lib/classes/Session/Logger.php b/lib/classes/Session/Logger.php index e51cc480f9..4bf1f83eb2 100644 --- a/lib/classes/Session/Logger.php +++ b/lib/classes/Session/Logger.php @@ -118,9 +118,9 @@ class Session_Logger $params = [ ':ses_id' => $app['session']->get('session_id'), - ':usr_login' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_login() : null, + ':usr_login' => $app['authentication']->getUser() ? $app['authentication']->getUser()->getLogin() : null, ':site_id' => $app['conf']->get(['main', 'key']), - ':usr_id' => $app['authentication']->isAuthenticated() ? $app['authentication']->getUser()->get_id() : null, + ':usr_id' => $app['authentication']->isAuthenticated() ? $app['authentication']->getUser()->getId() : null, ':browser' => $browser->getBrowser(), ':browser_version' => $browser->getExtendedVersion(), ':platform' => $browser->getPlatform(), @@ -128,10 +128,10 @@ class Session_Logger ':ip' => $browser->getIP(), ':user_agent' => $browser->getUserAgent(), ':appli' => serialize([]), - ':fonction' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_job() : null, - ':company' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_company() : null, - ':activity' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_position() : null, - ':country' => $app['authentication']->getUser() ? $app['authentication']->getUser()->get_country() : null + ':fonction' => $app['authentication']->getUser() ? $app['authentication']->getUser()->getJob() : null, + ':company' => $app['authentication']->getUser() ? $app['authentication']->getUser()->getCompany() : null, + ':activity' => $app['authentication']->getUser() ? $app['authentication']->getUser()->getActivity() : null, + ':country' => $app['authentication']->getUser() ? $app['authentication']->getUser()->getCountry() : null ]; $stmt = $conn->prepare($sql); @@ -205,10 +205,6 @@ class Session_Logger $app['EM']->flush(); } - $usrId = $app['authentication']->getUser()->get_id(); - - $user = User_Adapter::getInstance($usrId, $app); - $appName = [ '1' => 'Prod', '2' => 'Client', @@ -222,7 +218,7 @@ class Session_Logger ]; if (isset($appName[$appId])) { - $sbas_ids = array_keys($app['acl']->get($user)->get_granted_sbas()); + $sbas_ids = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_sbas()); foreach ($sbas_ids as $sbas_id) { try { diff --git a/lib/classes/User/Adapter.php b/lib/classes/User/Adapter.php deleted file mode 100644 index 5d1be742f4..0000000000 --- a/lib/classes/User/Adapter.php +++ /dev/null @@ -1,1354 +0,0 @@ - 'العربية' - , 'de' => 'Deutsch' - , 'nl' => 'Dutch' - , 'en' => 'English' - , 'es' => 'Español' - , 'fr' => 'Français' - ]; - - /** - * - * @var array - */ - protected static $_instance = []; - - /** - * - * @var array - */ - protected $_prefs = []; - - /** - * - * @var array - */ - protected $_updated_prefs = []; - - /** - * - * @var array - */ - public static $def_values = [ - 'view' => 'thumbs', - 'images_per_page' => 20, - 'images_size' => 120, - 'editing_images_size' => 134, - 'editing_top_box' => 30, - 'editing_right_box' => 48, - 'editing_left_box' => 33, - 'basket_sort_field' => 'name', - 'basket_sort_order' => 'ASC', - 'warning_on_delete_story' => 'true', - 'client_basket_status' => '1', - 'css' => '000000', - 'advanced_search_reload' => '1', - 'start_page_query' => 'last', - 'start_page' => 'QUERY', - 'rollover_thumbnail' => 'caption', - 'technical_display' => '1', - 'doctype_display' => '1', - 'bask_val_order' => 'nat', - 'basket_caption_display' => '0', - 'basket_status_display' => '0', - 'basket_title_display' => '0' - ]; - - /** - * - * @var array - */ - protected static $available_values = [ - 'view' => ['thumbs', 'list'], - 'basket_sort_field' => ['name', 'date'], - 'basket_sort_order' => ['ASC', 'DESC'], - 'start_page' => ['PUBLI', 'QUERY', 'LAST_QUERY', 'HELP'], - 'technical_display' => ['0', '1', 'group'], - 'rollover_thumbnail' => ['caption', 'preview'], - 'bask_val_order' => ['nat', 'asc', 'desc'] - ]; - - /** - * - * @var Application - */ - protected $app; - - /** - * - * @var int - */ - protected $id; - - /** - * - * @var string - */ - protected $email; - - /** - * - * @var string - */ - protected $login; - /** - * - * @var string - */ - protected $locale; - - /** - * - * @var string - */ - protected $firstname; - - /** - * - * @var string - */ - protected $lastname; - - /** - * - * @var string - */ - protected $address; - - /** - * - * @var string - */ - protected $city; - - /** - * - * @var int - */ - protected $geonameid; - - /** - * - * @var string - */ - protected $zip; - - /** - * - * @var int - */ - protected $gender; - - /** - * - * @var string - */ - protected $tel; - - /** - * - * @var int - */ - protected $lastModel; - - /** - * - * @var DateTime - */ - protected $creationdate; - - /** - * - * @var DateTime - */ - protected $modificationdate; - - /** - * - * @var string - */ - protected $fax; - - /** - * - * @var string - */ - protected $job; - - /** - * - * @var string - */ - protected $position; - - /** - * - * @var string - */ - protected $company; - - /** - * - * @var boolean - */ - protected $ldap_created; - - /** - * - * @var boolean - */ - protected $is_guest; - - /** - * - * @var boolean - */ - protected $mail_locked; - - /** - * - * @var FtpCredential - */ - protected $ftpCredential; - /** - * - * @var string - */ - protected $mail_notifications; - - /** - * - * @var string - */ - protected $country; - - /** - * - * @var boolean - */ - protected $is_template; - - /** - * - * @var User_Adapter - */ - protected $template_owner; - - protected $password; - - protected $preferences_loaded = false; - protected $notifications_preferences_loaded = false; - - /** - * - * @param Integer $id - * @param Application $app - * - * @return User_Adapter - */ - public function __construct($id, Application $app) - { - - $this->app = $app; - $this->load($id); - - return $this; - } - - public static function unsetInstances() - { - foreach (self::$_instance as $id => $user) { - self::unsetInstance($id); - } - } - - public static function unsetInstance($id) - { - if (isset(self::$_instance[$id])) { - self::$_instance[$id] = null; - unset(self::$_instance[$id]); - } - } - - /** - * - * @param type $id - * @param Application $app - * @return User_Adapter - */ - public static function getInstance($id, Application $app) - { - if (is_int((int) $id) && (int) $id > 0) { - $id = (int) $id; - } else - throw new Exception('Invalid usr_id'); - - if (!isset(self::$_instance[$id])) { - try { - self::$_instance[$id] = $app['phraseanet.appbox']->get_data_from_cache('_user_' . $id); - self::$_instance[$id]->set_app($app); - } catch (\Exception $e) { - self::$_instance[$id] = new self($id, $app); - $app['phraseanet.appbox']->set_data_to_cache(self::$_instance[$id], '_user_' . $id); - } - } else { - self::$_instance[$id]->set_app($app); - } - - return array_key_exists($id, self::$_instance) ? self::$_instance[$id] : false; - } - - /** - * - * @param Application $app - */ - protected function set_app(Application $app) - { - $this->app = $app; - if (null !== $app['acl']->get($this)) { - $app['acl']->get($this)->set_app($app); - } - } - - /** - * - * @param type $pasword - * @return User_Adapter - */ - public function set_password($pasword) - { - $sql = 'UPDATE usr SET usr_password = :password, salted_password = "1" - WHERE usr_id = :usr_id'; - - $password = $this->app['auth.password-encoder']->encodePassword($pasword, $this->get_nonce()); - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':password' => $password, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $this->password = $password; - - return $this; - } - - /** - * - * @param string $email - * @return User_Adapter - */ - public function set_email($email) - { - if (trim($email) == '') { - $email = null; - } - - $test_user = User_Adapter::get_usr_id_from_email($this->app, $email); - - if ($test_user && $test_user != $this->get_id()) { - throw new Exception_InvalidArgument($this->app->trans('A user already exists with email addres %email%', ['%email%' => $email])); - } - - $sql = 'UPDATE usr SET usr_mail = :new_email WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':new_email' => $email, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->email = $email; - $this->delete_data_from_cache(); - - return $this; - } - - /** - * - * @return string - */ - public function get_country() - { - if ($this->geonameid) { - try { - $country = $this->app['geonames.connector'] - ->geoname($this->geonameid) - ->get('country'); - - if (isset($country['name'])) { - return $country['name']; - } - } catch (GeonamesExceptionInterface $e) { - - } - } - - return ''; - } - - /** - * - * @param Application $app - * @param string $login - * - * @return integer - */ - public static function get_usr_id_from_login(Application $app, $login) - { - $conn = connection::getPDOConnection($app); - $sql = 'SELECT usr_id FROM usr WHERE usr_login = :login'; - $stmt = $conn->prepare($sql); - $stmt->execute([':login' => trim($login)]); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $usr_id = $row ? (int) $row['usr_id'] : false; - - return $usr_id; - } - - /** - * - * @param bollean $boolean - * @return User_Adapter - */ - public function set_mail_notifications($boolean) - { - $value = $boolean ? '1' : '0'; - $sql = 'UPDATE usr SET mail_notifications = :mail_notifications WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':mail_notifications' => $value, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->mail_notifications = !!$boolean; - $this->delete_data_from_cache(); - - return $this; - } - - /** - * - * @param boolean $boolean - * @return User_Adapter - */ - public function set_ldap_created($boolean) - { - $value = $boolean ? '1' : '0'; - $sql = 'UPDATE usr SET ldap_created = :ldap_created WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':ldap_created' => $value, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->ldap_created = $boolean; - - return $this; - } - - public function set_firstname($firstname) - { - $sql = 'UPDATE usr SET usr_prenom = :usr_prenom WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_prenom' => $firstname, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->firstname = $firstname; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_lastname($lastname) - { - $sql = 'UPDATE usr SET usr_nom = :usr_nom WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_nom' => $lastname, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->lastname = $lastname; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_address($address) - { - $sql = 'UPDATE usr SET adresse = :adresse WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':adresse' => $address, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->address = $address; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_city($city) - { - $sql = 'UPDATE usr SET ville = :city WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':city' => $city, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->city = $city; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_geonameid($geonameid) - { - $country_code = null; - - try { - $country = $this->app['geonames.connector'] - ->geoname($this->geonameid) - ->get('country'); - - if (isset($country['code'])) { - $country_code = $country['code']; - } - } catch (GeonamesExceptionInterface $e) { - - } - - $sql = 'UPDATE usr SET geonameid = :geonameid, pays=:country_code WHERE usr_id = :usr_id'; - - $datas = [ - ':geonameid' => $geonameid, - ':usr_id' => $this->get_id(), - ':country_code' => $country_code - ]; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute($datas); - $stmt->closeCursor(); - $this->geonameid = $geonameid; - $this->country = $country_code; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_zip($zip) - { - $sql = 'UPDATE usr SET cpostal = :cpostal WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':cpostal' => $zip, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->zip = $zip; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_gender($gender) - { - $sql = 'UPDATE usr SET usr_sexe = :usr_sexe WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_sexe' => $gender, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->gender = $gender; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_tel($tel) - { - $sql = 'UPDATE usr SET tel = :tel WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':tel' => $tel, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->tel = $tel; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_fax($fax) - { - $sql = 'UPDATE usr SET fax = :fax WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':fax' => $fax, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->fax = $fax; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_job($job) - { - $sql = 'UPDATE usr SET fonction = :fonction WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':fonction' => $job, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->job = $job; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_position($position) - { - $sql = 'UPDATE usr SET activite = :activite WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':activite' => $position, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->position = $position; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_company($company) - { - $sql = 'UPDATE usr SET societe = :company WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':company' => $company, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->company = $company; - $this->delete_data_from_cache(); - - return $this; - } - - public function set_template(User_Adapter $owner) - { - $this->is_template = true; - $this->template_owner = $owner; - - if ($owner->get_id() == $this->get_id()) - throw new Exception_InvalidArgument (); - - $sql = 'UPDATE usr SET model_of = :owner_id WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':owner_id' => $owner->get_id(), ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $this - ->set_city('') - ->set_company('') - ->set_email(null) - ->set_fax('') - ->set_firstname('') - ->set_gender('') - ->set_geonameid('') - ->set_job('') - ->set_lastname('') - ->set_mail_locked(false) - ->set_mail_notifications(true) - ->set_position('') - ->set_zip('') - ->set_tel(''); - - $this->ftpCredential = new FtpCredential(); - $this->ftpCredential->setUsrId($this->get_id()); - $this->app['EM']->persist($this->ftpCredential); - $this->app['EM']->flush(); - - $this->delete_data_from_cache(); - - return $this; - } - - /** - * @return FtpCredential - */ - public function getFtpCredential() - { - if (null === $this->ftpCredential) { - $this->ftpCredential = $this->app['EM']->getRepository('Phraseanet:FtpCredential')->findOneBy([ - 'usrId' => $this->get_id() - ]); - - if (null === $this->ftpCredential) { - $this->ftpCredential = new FtpCredential(); - $this->ftpCredential->setUsrId($this->get_id()); - } - } - - return $this->ftpCredential; - } - - public function is_template() - { - return $this->is_template; - } - - public function is_special() - { - return in_array($this->login, ['invite', 'autoregister']); - } - - public function get_template_owner() - { - return $this->template_owner; - } - - public static function get_usr_id_from_email(Application $app, $email) - { - if (is_null($email)) { - return false; - } - - $conn = connection::getPDOConnection($app); - $sql = 'SELECT usr_id FROM usr - WHERE usr_mail = :email - AND usr_login NOT LIKE "(#deleted_%" - AND invite="0" AND usr_login != "autoregister"'; - $stmt = $conn->prepare($sql); - $stmt->execute([':email' => trim($email)]); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $usr_id = $row ? $row['usr_id'] : false; - - return $usr_id; - } - - /** - * @todo close all open session - * @return type - */ - public function delete() - { - $repo = $this->app['EM']->getRepository('Phraseanet:UsrAuthProvider'); - foreach ($repo->findByUser($this) as $provider) { - $this->app['EM']->remove($provider); - } - - $repo = $this->app['EM']->getRepository('Phraseanet:FtpExport'); - foreach ($repo->findByUser($this) as $export) { - $this->app['EM']->remove($export); - } - - $repo = $this->app['EM']->getRepository('Phraseanet:Order'); - foreach ($repo->findByUser($this) as $order) { - $this->app['EM']->remove($order); - } - - $repo = $this->app['EM']->getRepository('Phraseanet:Session'); - - foreach ($repo->findByUser($this) as $session) { - $this->app['EM']->remove($session); - } - - $this->app['EM']->flush(); - - $sql = 'UPDATE usr SET usr_login = :usr_login , usr_mail = null - WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_login' => '(#deleted_' . $this->get_login() . '_' . $this->get_id(), ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM basusr WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM sbasusr WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM dsel WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM edit_presets WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM tokens WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - $sql = 'DELETE FROM usr_settings WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - - unset(self::$_instance[$this->get_id()]); - - return; - } - public function get_mail_notifications() - { - return $this->mail_notifications; - } - - /** - * - * @param $id - * @return user - */ - public function load($id) - { - $sql = 'SELECT usr_id, ldap_created, create_db, usr_login, usr_password, usr_nom, activite, - usr_prenom, usr_sexe as gender, usr_mail, adresse, usr_creationdate, usr_modificationdate, - ville, cpostal, tel, fax, fonction, societe, geonameid, lastModel, invite, - mail_notifications, mail_locked, model_of, locale - FROM usr WHERE usr_id= :id '; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':id' => $id]); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if (!$row) { - throw new \Exception('User unknown'); - } - - $this->id = (int) $row['usr_id']; - $this->email = $row['usr_mail']; - $this->login = $row['usr_login']; - $this->password = $row['usr_password']; - - $this->ldap_created = $row['ldap_created']; - - $this->mail_notifications = $row['mail_notifications']; - - $this->mail_locked = !!$row['mail_locked']; - - $this->firstname = $row['usr_prenom']; - $this->lastname = $row['usr_nom']; - $this->address = $row['adresse']; - $this->city = $row['ville']; - $this->geonameid = $row['geonameid']; - $this->zip = $row['cpostal']; - $this->gender = $row['gender']; - $this->tel = $row['tel']; - $this->locale = $row['locale']; - $this->fax = $row['fax']; - $this->job = $row['fonction']; - $this->position = $row['activite']; - $this->company = $row['societe']; - $this->creationdate = new DateTime($row['usr_creationdate']); - $this->modificationdate = new DateTime($row['usr_modificationdate']); - $this->applied_template = $row['lastModel']; - - $this->country = $this->get_country(); - - $this->is_guest = ($row['invite'] == '1'); - - if ($row['model_of'] > 0) { - $this->is_template = true; - $this->template_owner = self::getInstance($row['model_of'], $this->app); - } - - return $this; - } - - public function set_last_template(User_Interface $template) - { - $sql = 'UPDATE usr SET lastModel = :template_id WHERE usr_id = :usr_id'; - - $params = [ - ':usr_id' => $this->get_id() - , ':template_id' => $template->get_login() - ]; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute($params); - $stmt->closeCursor(); - $this->delete_data_from_cache(); - - return $this; - } - - public function set_mail_locked($boolean) - { - $sql = 'UPDATE usr SET mail_locked = :mail_locked WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id(), ':mail_locked' => ($boolean ? '1' : '0')]); - $stmt->closeCursor(); - $this->mail_locked = !!$boolean; - - return $this; - } - - public function get_mail_locked() - { - return $this->mail_locked; - } - - /** - * - * @return int - */ - public function get_id() - { - return $this->id; - } - - public function get_ldap_created() - { - return $this->ldap_created; - } - - public function is_guest() - { - return $this->is_guest; - } - - public function get_login() - { - return $this->login; - } - - public function get_password() - { - return $this->password; - } - - public function get_email() - { - return $this->email; - } - - public function get_firstname() - { - return $this->firstname; - } - - public function get_lastname() - { - return $this->lastname; - } - - public function get_company() - { - return $this->company; - } - - public function get_tel() - { - return $this->tel; - } - - public function get_fax() - { - return $this->fax; - } - - public function get_job() - { - return $this->job; - } - - public function get_position() - { - return $this->position; - } - - public function get_zipcode() - { - return $this->zip; - } - - public function get_city() - { - return $this->city; - } - - public function get_address() - { - return $this->address; - } - - public function get_gender() - { - return $this->gender; - } - - public function get_geonameid() - { - return $this->geonameid; - } - - public function get_last_connection() - { - $sql = 'SELECT last_conn FROM usr WHERE usr_id = :usr_id'; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - - $stmt->execute([':usr_id' => $this->get_id()]); - - $row = $stmt->fetch(PDO::FETCH_ASSOC); - - $stmt->closeCursor(); - - $date_obj = new DateTime($row['last_conn']); - - return $date_obj; - } - - public function get_applied_template() - { - return $this->applied_template; - } - - public function get_creation_date() - { - return $this->creationdate; - } - - public function get_modification_date() - { - return $this->modificationdate; - } - - protected function load_preferences() - { - if ($this->preferences_loaded) { - return $this; - } - - foreach (self::$def_values as $k => $v) { - if (!isset($this->_prefs[$k])) { - if ($k == 'start_page_query' && $this->app['conf']->get(['registry', 'searchengine', 'default-query'])) { - $v = $this->app['conf']->get(['registry', 'searchengine', 'default-query']); - } - - $this->_prefs[$k] = $v; - } - } - - if ($this->app['conf']->has('user-settings')) { - $this->_prefs = array_replace( - $this->_prefs, - // remove keys that are not defined in default values - array_intersect_key( - $this->app['conf']->get('user-settings'), - self::$def_values - ) - ); - } - - $sql = 'SELECT prop, value FROM usr_settings WHERE usr_id= :id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':id' => $this->id]); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($rs as $row) { - $this->_prefs[$row['prop']] = $row['value']; - } - - $this->preferences_loaded = true; - - return $this; - } - - public function purgePreferences() - { - $this->notifications_preferences_loaded = $this->preferences_loaded = false; - } - - protected function load_notifications_preferences(Application $app) - { - $this->load_preferences(); - - $notifications = $app['events-manager']->list_notifications_available($this->id); - - foreach ($notifications as $notification_group => $nots) { - foreach ($nots as $notification) { - if (!isset($this->_prefs['notification_' . $notification['id']])) { - $this->_prefs['notification_' . $notification['id']] = '1'; - } - } - } - $this->notifications_preferences_loaded = true; - } - - public function get_notifications_preference(Application $app, $notification_id) - { - if (!$this->notifications_preferences_loaded) - $this->load_notifications_preferences($app); - - return isset($this->_prefs['notification_' . $notification_id]) ? $this->_prefs['notification_' . $notification_id] : '0'; - } - - public function set_notification_preference(Application $app, $notification_id, $value) - { - if (!$this->notifications_preferences_loaded) - $this->load_notifications_preferences($app); - - $prop = 'notification_' . $notification_id; - $value = $value ? '1' : '0'; - - $this->setPrefs($prop, $value); - - return ; - } - - public function get_display_name() - { - if ($this->is_template()) - $display_name = $this->app->trans('modele %name%', ['%name%' => $this->get_login()]); - elseif (trim($this->lastname) !== '' || trim($this->firstname) !== '') - $display_name = $this->firstname . ' ' . $this->lastname; - elseif (trim($this->email) !== '') - $display_name = $this->email; - else - $display_name = $this->app->trans('phraseanet::utilisateur inconnu'); - - return $display_name; - } - - protected function update_pref($prop, $value) - { - try { - $sql = 'REPLACE INTO usr_settings (usr_id, prop, value) - VALUES (:usr_id, :prop, :value)'; - - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([ - ':usr_id' => $this->id, - ':prop' => $prop, - ':value' => $value - ]); - $this->delete_data_from_cache(); - } catch (\Exception $e) { - - } - - return $this; - } - - public function get_cache_key($option = null) - { - return '_user_' . $this->get_id() . ($option ? '_' . $option : ''); - } - - public function delete_data_from_cache($option = null) - { - $this->app['phraseanet.appbox']->delete_data_from_cache($this->get_cache_key($option)); - - return $this; - } - - public function get_data_from_cache($option = null) - { - $this->app['phraseanet.appbox']->get_data_from_cache($this->get_cache_key($option)); - - return $this; - } - - public function set_data_to_cache($value, $option = null, $duration = 0) - { - $this->app['phraseanet.appbox']->set_data_to_cache($value, $this->get_cache_key($option), $duration); - - return $this; - } - - public function setPrefs($prop, $value) - { - $this->load_preferences(); - if (isset($this->_prefs[$prop]) && $this->_prefs[$prop] === $value) { - return $this->_prefs[$prop]; - } - - $ok = true; - - if (isset(self::$available_values[$prop])) { - $ok = false; - if (in_array($value, self::$available_values[$prop])) - $ok = true; - } - - if ($ok) { - $this->_prefs[$prop] = $value; - $this->update_pref($prop, $value); - } - - return $this->_prefs[$prop]; - } - - public function getPrefs($prop, $default = null) - { - $this->load_preferences(); - - return array_key_exists($prop, $this->_prefs) ? $this->_prefs[$prop] : $default; - } - - public static function get_sys_admins(Application $app) - { - $sql = 'SELECT usr_id, usr_login FROM usr - WHERE create_db="1" - AND model_of="0" - AND usr_login NOT LIKE "(#deleted%"'; - $conn = connection::getPDOConnection($app); - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $users = []; - - foreach ($rs as $row) - $users[$row['usr_id']] = $row['usr_login']; - - return $users; - } - - public static function set_sys_admins(Application $app, $admins) - { - try { - $sql = "UPDATE usr SET create_db='0' WHERE create_db='1' AND usr_id != :usr_id"; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $app['authentication']->getUser()->get_id()]); - $stmt->closeCursor(); - - $sql = "UPDATE usr SET create_db='1' WHERE usr_id IN (" . implode(',', $admins) . ")"; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - return true; - } catch (\Exception $e) { - - } - - return false; - } - - public function get_locale() - { - return $this->locale ?: $this->app['conf']->get(['languages', 'default'], 'en'); - } - - public function set_locale($locale) - { - if (!array_key_exists($locale, $this->app['locales.available'])) { - throw new \InvalidArgumentException(sprintf('Locale %s is not recognized', $locale)); - } - - $sql = 'UPDATE usr SET locale = :locale WHERE usr_id = :usr_id'; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':locale' => $locale, ':usr_id' => $this->get_id()]); - $stmt->closeCursor(); - $this->delete_data_from_cache(); - - $this->locale = $locale; - - return $this->locale; - } - - public static function create(Application $app, $login, $password, $email, $admin, $invite = false) - { - $conn = $app['phraseanet.appbox']->get_connection(); - - if (trim($login) == '') { - throw new \InvalidArgumentException('Invalid username'); - } - - if (strlen($login) > 100) { - throw new \InvalidArgumentException('Username is too long'); - } - - if (trim($password) == '') { - throw new \InvalidArgumentException('Invalid password'); - } - - $login = $invite ? 'invite' . random::generatePassword(16) : $login; - - $nonce = random::generatePassword(16); - - $sql = 'INSERT INTO usr - (usr_id, usr_login, usr_password, usr_creationdate, usr_mail, create_db, nonce, salted_password, invite) - VALUES (null, :login, :password, NOW(), :email, :admin, :nonce, 1, :invite)'; - - $stmt = $conn->prepare($sql); - $stmt->execute([ - ':login' => $login, - ':nonce' => $nonce, - ':password' => $app['auth.password-encoder']->encodePassword($password, $nonce), - ':email' => ($email ? $email : null), - ':admin' => ($admin ? '1' : '0'), - ':invite' => ($invite ? '1' : '0') - ]); - $stmt->closeCursor(); - - $usr_id = $conn->lastInsertId(); - - $ftpCredential = new FtpCredential(); - $ftpCredential->setUsrId($usr_id); - $app['EM']->persist($ftpCredential); - $app['EM']->flush(); - - if ($invite) { - $sql = 'UPDATE usr SET usr_login = :login - WHERE usr_id = :usr_id'; - $stmt = $conn->prepare($sql); - $stmt->execute([':login' => 'invite'.$usr_id, ':usr_id' => $usr_id]); - $stmt->closeCursor(); - } - - return self::getInstance($usr_id, $app); - } - - protected $nonce; - - public function get_nonce() - { - if ($this->nonce) { - return $this->nonce; - } - - $nonce = false; - - $sql = 'SELECT nonce FROM usr WHERE usr_id = :usr_id '; - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->get_id()]); - $row = $stmt->fetch(PDO::FETCH_ASSOC); - $stmt->closeCursor(); - unset($stmt); - - $nonce = $row['nonce']; - - $this->nonce = $nonce; - - return $this->nonce; - } - - public function __sleep() - { - $vars = []; - foreach ($this as $key => $value) { - if (in_array($key, ['ACL', 'app'])) - continue; - $vars[] = $key; - } - - return $vars; - } - - public static function purge() - { - self::$_instance = []; - } -} diff --git a/lib/classes/User/Interface.php b/lib/classes/User/Interface.php deleted file mode 100644 index 68dd164d30..0000000000 --- a/lib/classes/User/Interface.php +++ /dev/null @@ -1,124 +0,0 @@ -sql_params = []; $sql = ' - FROM usr LEFT JOIN basusr ON (usr.usr_id = basusr.usr_id) - LEFT JOIN sbasusr ON (usr.usr_id = sbasusr.usr_id) + FROM Users LEFT JOIN basusr ON (Users.id = basusr.usr_id) + LEFT JOIN sbasusr ON (Users.id = sbasusr.usr_id) WHERE 1 '; if (! $this->include_special_users) { - $sql .= ' AND usr_login != "autoregister" - AND usr_login != "invite" '; + $sql .= ' AND Users.login != "autoregister" + AND Users.login != "invite" '; } - $sql .= ' AND usr_login NOT LIKE "(#deleted_%" '; + $sql .= ' AND Users.deleted="0" '; if (! $this->include_invite) { - $sql .= ' AND usr.invite=0 '; + $sql .= ' AND Users.guest="0" '; } if ($this->email_not_null) { - $sql .= ' AND usr.usr_mail IS NOT NULL '; + $sql .= ' AND Users.email IS NOT NULL '; } if ($this->only_templates === true) { if (!$this->app['authentication']->getUser()) { throw new InvalidArgumentException('Unable to load templates while disconnected'); } - $sql .= ' AND model_of = ' . $this->app['authentication']->getUser()->get_id(); + $sql .= ' AND model_of = ' . $this->app['authentication']->getUser()->getId(); } elseif ($this->include_templates === false) { - $sql .= ' AND model_of=0'; + $sql .= ' AND model_of IS NULL'; } elseif ($this->app['authentication']->getUser()) { - $sql .= ' AND (model_of=0 OR model_of = ' . $this->app['authentication']->getUser()->get_id() . ' ) '; + $sql .= ' AND (model_of IS NULL OR model_of = ' . $this->app['authentication']->getUser()->getId() . ' ) '; } else { - $sql .= ' AND model_of=0'; + $sql .= ' AND model_of IS NULL'; } if ($this->activities) { @@ -299,7 +300,7 @@ class User_Query implements User_QueryInterface } if ($this->in_ids) { - $sql .= 'AND (usr.usr_id = ' . implode(' OR usr.usr_id = ', $this->in_ids) . ')'; + $sql .= 'AND (Users.id = ' . implode(' OR Users.id = ', $this->in_ids) . ')'; } if ($this->have_rights) { @@ -315,7 +316,7 @@ class User_Query implements User_QueryInterface } if ($this->last_model) { - $sql .= ' AND usr.lastModel = ' . $this->app['phraseanet.appbox']->get_connection()->quote($this->last_model) . ' '; + $sql .= ' AND Users.lastModel = ' . $this->app['phraseanet.appbox']->get_connection()->quote($this->last_model) . ' '; } $sql_like = []; @@ -329,8 +330,8 @@ class User_Query implements User_QueryInterface continue; $qrys[] = sprintf( - ' (usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci - OR usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci) ' + ' (Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci + OR Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci) ' , self::LIKE_FIRSTNAME , str_replace(['"', '%'], ['\"', '\%'], $like_val) , self::LIKE_LASTNAME @@ -349,7 +350,7 @@ class User_Query implements User_QueryInterface case self::LIKE_LOGIN: case self::LIKE_COUNTRY: $sql_like[] = sprintf( - ' usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci ' + ' Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci ' , $like_field , str_replace(['"', '%'], ['\"', '\%'], $like_value) ); @@ -396,7 +397,7 @@ class User_Query implements User_QueryInterface public function last_model_is($login = null) { - $this->last_model = $login instanceof \User_Adapter ? $login->get_login() : $login; + $this->last_model = $login instanceof User ? $login->getLogin() : $login; return $this; } @@ -489,7 +490,7 @@ class User_Query implements User_QueryInterface public function execute() { $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.usr_id ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.id ' . $this->generate_sql_constraints(); if ('' !== $sorter = $this->generate_sort_constraint()) { $sql .= ' ORDER BY ' . $sorter; @@ -511,7 +512,7 @@ class User_Query implements User_QueryInterface $users = new ArrayCollection(); foreach ($rs as $row) { - $users[] = User_Adapter::getInstance($row['usr_id'], $this->app); + $users[] = $this->app['manipulator.user']->getRepository()->find($row['id']); } $this->results = $users; @@ -531,7 +532,7 @@ class User_Query implements User_QueryInterface $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql_count = 'SELECT COUNT(DISTINCT usr.usr_id) as total ' + $sql_count = 'SELECT COUNT(DISTINCT Users.id) as total ' . $this->generate_sql_constraints(); $stmt = $conn->prepare($sql_count); @@ -864,9 +865,9 @@ class User_Query implements User_QueryInterface { $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.activite ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.activity ' . $this->generate_sql_constraints(); - $sql .= ' ORDER BY usr.activite'; + $sql .= ' ORDER BY Users.activity'; $stmt = $conn->prepare($sql); $stmt->execute($this->sql_params); @@ -876,7 +877,7 @@ class User_Query implements User_QueryInterface $activities = []; foreach ($rs as $row) { - if (trim($row['activite']) === '') + if (trim($row['activity']) === '') continue; $activities[] = $row['activite']; @@ -889,9 +890,9 @@ class User_Query implements User_QueryInterface { $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.fonction ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.job ' . $this->generate_sql_constraints(); - $sql .= ' ORDER BY usr.fonction'; + $sql .= ' ORDER BY Users.job'; $stmt = $conn->prepare($sql); $stmt->execute($this->sql_params); @@ -901,10 +902,10 @@ class User_Query implements User_QueryInterface $fonction = []; foreach ($rs as $row) { - if (trim($row['fonction']) === '') + if (trim($row['job']) === '') continue; - $fonction[] = $row['fonction']; + $fonction[] = $row['job']; } return $fonction; @@ -916,9 +917,9 @@ class User_Query implements User_QueryInterface $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.pays ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.country ' . $this->generate_sql_constraints(); - $sql .= ' ORDER BY usr.pays'; + $sql .= ' ORDER BY Users.country'; $stmt = $conn->prepare($sql); $stmt->execute($this->sql_params); @@ -930,11 +931,11 @@ class User_Query implements User_QueryInterface $ctry = \getCountries($this->app['locale']); foreach ($rs as $row) { - if (trim($row['pays']) === '') + if (trim($row['country']) === '') continue; - if (isset($ctry[$row['pays']])) - $pays[$row['pays']] = $ctry[$row['pays']]; + if (isset($ctry[$row['country']])) + $pays[$row['country']] = $ctry[$row['country']]; } return $pays; @@ -944,9 +945,9 @@ class User_Query implements User_QueryInterface { $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.societe ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.company ' . $this->generate_sql_constraints(); - $sql .= ' ORDER BY usr.societe'; + $sql .= ' ORDER BY Users.company'; $stmt = $conn->prepare($sql); $stmt->execute($this->sql_params); @@ -956,10 +957,10 @@ class User_Query implements User_QueryInterface $societe = []; foreach ($rs as $row) { - if (trim($row['societe']) === '') + if (trim($row['company']) === '') continue; - $societe[] = $row['societe']; + $societe[] = $row['company']; } return $societe; @@ -969,9 +970,9 @@ class User_Query implements User_QueryInterface { $conn = $this->app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT DISTINCT usr.lastModel ' . $this->generate_sql_constraints(); + $sql = 'SELECT DISTINCT Users.last_model ' . $this->generate_sql_constraints(); - $sql .= ' ORDER BY usr.lastModel'; + $sql .= ' ORDER BY Users.last_model'; $stmt = $conn->prepare($sql); $stmt->execute($this->sql_params); @@ -981,10 +982,10 @@ class User_Query implements User_QueryInterface $lastModel = []; foreach ($rs as $row) { - if (trim($row['lastModel']) === '') + if (trim($row['last_model']) === '') continue; - $lastModel[] = $row['lastModel']; + $lastModel[] = $row['last_model']; } return $lastModel; @@ -1004,13 +1005,13 @@ class User_Query implements User_QueryInterface case self::SORT_COMPANY: case self::SORT_LOGIN: case self::SORT_EMAIL: - $sorter[$k] = ' usr.`' . $sort . '` COLLATE utf8_unicode_ci '; + $sorter[$k] = ' Users.`' . $sort . '` COLLATE utf8_unicode_ci '; break; case self::SORT_ID: case self::SORT_CREATIONDATE: case self::SORT_COUNTRY: case self::SORT_LASTMODEL: - $sorter[$k] = ' usr.`' . $sort . '` '; + $sorter[$k] = ' Users.`' . $sort . '` '; break; default: break; diff --git a/lib/classes/appbox.php b/lib/classes/appbox.php index b63d6db145..3bb6d00a39 100644 --- a/lib/classes/appbox.php +++ b/lib/classes/appbox.php @@ -295,6 +295,9 @@ class appbox extends base $upgrader->set_current_message($this->app->trans('Creating new tables')); + // Executes stuff before applying patches + $app['phraseanet.pre-schema-upgrader']->apply($app); + $upgrader->add_steps_complete(1); /** diff --git a/lib/classes/appbox/register.php b/lib/classes/appbox/register.php index 4591d534e1..89442dc565 100644 --- a/lib/classes/appbox/register.php +++ b/lib/classes/appbox/register.php @@ -10,6 +10,7 @@ */ use Alchemy\Phrasea\Application; +use Alchemy\Phrasea\Model\Entities\User; class appbox_register { @@ -36,16 +37,16 @@ class appbox_register /** * Add a registration request for a user on a collection * - * @param User_Interface $user + * @param User $user * @param collection $collection * @return appbox_register */ - public function add_request(User_Interface $user, collection $collection) + 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->get_id(), ':base_id' => $collection->get_base_id()]); + $stmt->execute([':usr_id' => $user->getId(), ':base_id' => $collection->get_base_id()]); $stmt->closeCursor(); return $this; @@ -55,16 +56,16 @@ class appbox_register * Return an array of collection objects where provided * user is waiting for approbation * - * @param Application $app - * @param User_Interface $user + * @param Application $app + * @param User $user * * @return array */ - public function get_collection_awaiting_for_user(Application $app, User_Interface $user) + 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->get_id()]); + $stmt->execute([':usr_id' => $user->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $ret = []; diff --git a/lib/classes/base.php b/lib/classes/base.php index fe41b81d1e..da2eb2cd58 100644 --- a/lib/classes/base.php +++ b/lib/classes/base.php @@ -12,6 +12,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Core\Version as PhraseaVersion; use vierbergenlars\SemVer\version; +use Alchemy\Phrasea\Model\Entities\User; abstract class base implements cache_cacheableInterface { @@ -143,19 +144,6 @@ abstract class base implements cache_cacheableInterface return $this->connection; } - /** - * Replaces the connection - * - * @param \connection_pdo $connection - * @return \base - */ - public function set_connection(\connection_pdo $connection) - { - $this->connection = $connection; - - return $this; - } - public function get_cache() { return $this->app['cache']; @@ -830,12 +818,27 @@ abstract class base implements cache_cacheableInterface $success = true; foreach ($list_patches as $patch) { + // Gets doctrine migrations required for current patch foreach ($patch->getDoctrineMigrations() as $doctrineVersion) { $version = $app['doctrine-migration.configuration']->getVersion($doctrineVersion); - $version->getMigration()->setEntityManager($app['EM']); - if (false === $version->isMigrated()) { - $version->execute('up'); + // Skip if already migrated + if ($version->isMigrated()) { + continue; } + + $migration = $version->getMigration(); + + // Inject entity manager + $migration->setEntityManager($app['EM']); + + // Execute migration if not marked as migrated and not already applied by an older patch + if (!$migration->isAlreadyApplied()) { + $version->execute('up'); + continue; + } + + // Or mark it as migrated + $version->markMigrated(); } if (false === $patch->apply($this, $app)) { diff --git a/lib/classes/collection.php b/lib/classes/collection.php index 6d3d013b57..e2d2cccf26 100644 --- a/lib/classes/collection.php +++ b/lib/classes/collection.php @@ -12,6 +12,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Exception\InvalidArgumentException; +use Alchemy\Phrasea\Model\Entities\User; class collection implements cache_cacheableInterface { @@ -557,7 +558,7 @@ class collection implements cache_cacheableInterface return $ord['ord'] ?: 1; } - public static function create(Application $app, databox $databox, appbox $appbox, $name, User_Adapter $user = null) + public static function create(Application $app, databox $databox, appbox $appbox, $name, User $user = null) { $sbas_id = $databox->get_sbas_id(); $connbas = $databox->get_connection(); @@ -613,7 +614,7 @@ class collection implements cache_cacheableInterface return $collection; } - public function set_admin($base_id, user_adapter $user) + public function set_admin($base_id, User $user) { $rights = [ @@ -641,7 +642,7 @@ class collection implements cache_cacheableInterface return true; } - public static function mount_collection(Application $app, databox $databox, $coll_id, User_Adapter $user) + public static function mount_collection(Application $app, databox $databox, $coll_id, User $user) { $sql = "INSERT INTO bas (base_id, active, server_coll_id, sbas_id, aliases, ord) diff --git a/lib/classes/databox.php b/lib/classes/databox.php index d6de47733e..dbe52b8861 100644 --- a/lib/classes/databox.php +++ b/lib/classes/databox.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Application; use Symfony\Component\Filesystem\Filesystem; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Exception\InvalidArgumentException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Translation\TranslatorInterface; @@ -967,10 +968,10 @@ class databox extends base /** * - * @param User_Interface $user + * @param User $user * @return databox */ - public function registerAdmin(User_Interface $user) + public function registerAdmin(User $user) { $conn = connection::getPDOConnection($this->app); diff --git a/lib/classes/databox/cgu.php b/lib/classes/databox/cgu.php index 31ce60e79f..4a54b836af 100644 --- a/lib/classes/databox/cgu.php +++ b/lib/classes/databox/cgu.php @@ -62,7 +62,7 @@ class databox_cgu if ( ! $app['acl']->get($app['authentication']->getUser())->has_access_to_sbas($databox->get_sbas_id())) { continue; } - $userValidation = ($app['authentication']->getUser()->getPrefs('terms_of_use_' . $databox->get_sbas_id()) !== $update && trim($value) !== ''); + $userValidation = ($app['settings']->getUserSetting($app['authentication']->getUser(), 'terms_of_use_' . $databox->get_sbas_id()) !== $update && trim($value) !== ''); } if ($userValidation) diff --git a/lib/classes/deprecated/inscript.api.php b/lib/classes/deprecated/inscript.api.php index 65be0fa179..f0c266dcc1 100644 --- a/lib/classes/deprecated/inscript.api.php +++ b/lib/classes/deprecated/inscript.api.php @@ -21,18 +21,20 @@ function giveMeBases(Application $app, $usr = 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, - usr.usr_id, basusr.actif, demand.en_cours, demand.refuser - FROM (usr, bas, sbas) - LEFT JOIN basusr - ON ( usr.usr_id = basusr.usr_id - AND bas.base_id = basusr.base_id ) - LEFT JOIN demand - ON ( demand.usr_id = usr.usr_id - AND bas.base_id = demand.base_id ) - WHERE bas.active >0 AND bas.sbas_id = sbas.sbas_id - AND usr.usr_id = :usr_id AND model_of = 0'; + $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]); diff --git a/lib/classes/eventsmanager/broker.php b/lib/classes/eventsmanager/broker.php index 695a4a4702..cc4eadc340 100644 --- a/lib/classes/eventsmanager/broker.php +++ b/lib/classes/eventsmanager/broker.php @@ -127,7 +127,7 @@ class eventsmanager_broker FROM notifications WHERE usr_id = :usr_id'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->getId()]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -145,7 +145,7 @@ class eventsmanager_broker $data = ['notifications' => [], 'next' => '']; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -195,7 +195,7 @@ class eventsmanager_broker FROM notifications WHERE usr_id = :usr_id AND unread="1"'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->getId()]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -214,7 +214,7 @@ class eventsmanager_broker FROM notifications WHERE usr_id = :usr_id'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->getId()]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $stmt->closeCursor(); @@ -232,7 +232,7 @@ class eventsmanager_broker $ret = []; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->get_id()]); + $stmt->execute([':usr_id' => $this->app['authentication']->getUser()->getId()]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); diff --git a/lib/classes/eventsmanager/notify/autoregister.php b/lib/classes/eventsmanager/notify/autoregister.php index 687a9cd676..43e35995c6 100644 --- a/lib/classes/eventsmanager/notify/autoregister.php +++ b/lib/classes/eventsmanager/notify/autoregister.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Mail\MailInfoSomebodyAutoregistered; +use Alchemy\Phrasea\Model\Entities\User; class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract { @@ -38,11 +39,7 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract */ public function fire($event, $params, &$object) { - $default = [ - 'usr_id' => '' - , 'autoregister' => [] - ]; - + $default = ['usr_id' => '' , 'autoregister' => []]; $params = array_merge($default, $params); $base_ids = array_keys($params['autoregister']); @@ -52,29 +49,19 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract $mailColl = []; - $sql = 'SELECT u.usr_id, b.base_id FROM usr u, basusr b - WHERE u.usr_id = b.usr_id - AND b.base_id - IN (' . implode(', ', array_keys($base_ids)) . ') - AND model_of="0" - AND b.actif="1" - AND b.canadmin="1" - AND u.usr_login NOT LIKE "(#deleted%"'; - try { - $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $rs = $this->app['EM.native-query']->getAdminsOfBases(array_keys($base_ids)); foreach ($rs as $row) { - if ( ! isset($mailColl[$row['usr_id']])) - $mailColl[$row['usr_id']] = []; + $user = $row[0]; - $mailColl[$row['usr_id']][] = $row['base_id']; + if (!isset($mailColl[$user->getId()])) { + $mailColl[$user->getId()] = []; + } + + $mailColl[$user->getId()][] = $row['base_id']; } } catch (\Exception $e) { - } $dom_xml = new DOMDocument('1.0', 'UTF-8'); @@ -102,9 +89,7 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract $datas = $dom_xml->saveXml(); - try { - $registered_user = User_Adapter::getInstance($params['usr_id'], $this->app); - } catch (\Exception $e) { + if (null === $registered_user = $this->app['manipulator.user']->getRepository()->find($params['usr_id'])) { return; } @@ -113,9 +98,7 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract $mailed = false; if ($this->shouldSendNotificationFor($usr_id)) { - try { - $admin_user = User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $admin_user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { continue; } @@ -140,16 +123,13 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract $sx = simplexml_load_string($datas); $usr_id = (string) $sx->usr_id; - try { - User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return []; } - $sender = User_Adapter::getInstance($usr_id, $this->app)->get_display_name(); - $ret = [ - 'text' => $this->app->trans('%user% s\'est enregistre sur une ou plusieurs %before_link% scollections %after_link%', ['%user%' => $sender, '%before_link%' => '', '%after_link%' => '']) + 'text' => $this->app->trans('%user% s\'est enregistre sur une ou plusieurs %before_link% scollections %after_link%', ['%user%' => $user->getDisplayName(), '%before_link%' => '', '%after_link%' => '']) , 'class' => '' ]; @@ -176,18 +156,19 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract /** * - * @param \User_Adapter $to - * @param \User_Adapter $registeredUser + * @param User $to + * @param User $registeredUser * * @return boolean */ - public function mail(\User_Adapter $to, \User_Adapter $registeredUser) + public function mail(User $to, User $registeredUser) { - $body .= sprintf("Login : %s\n", $registeredUser->get_login()); - $body .= sprintf("%s : %s\n", $this->app->trans('admin::compte-utilisateur nom'), $registeredUser->get_firstname()); - $body .= sprintf("%s : %s\n", $this->app->trans('admin::compte-utilisateur prenom'), $registeredUser->get_lastname()); - $body .= sprintf("%s : %s\n", $this->app->trans('admin::compte-utilisateur email'), $registeredUser->get_email()); - $body .= sprintf("%s/%s\n", $registeredUser->get_job(), $registeredUser->get_company()); + $body = ''; + $body .= sprintf("Login : %s\n", $registeredUser->getLogin()); + $body .= sprintf("%s : %s\n", _('admin::compte-utilisateur nom'), $registeredUser->getFirstName()); + $body .= sprintf("%s : %s\n", _('admin::compte-utilisateur prenom'), $registeredUser->getLastName()); + $body .= sprintf("%s : %s\n", _('admin::compte-utilisateur email'), $registeredUser->getEmail()); + $body .= sprintf("%s/%s\n", $registeredUser->get_job(), $registeredUser->getCompany()); $readyToSend = false; try { @@ -216,9 +197,7 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract return false; } - try { - $user = \User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return false; } diff --git a/lib/classes/eventsmanager/notify/bridgeuploadfail.php b/lib/classes/eventsmanager/notify/bridgeuploadfail.php index 0b07e37526..ccfd61979a 100644 --- a/lib/classes/eventsmanager/notify/bridgeuploadfail.php +++ b/lib/classes/eventsmanager/notify/bridgeuploadfail.php @@ -79,7 +79,7 @@ class eventsmanager_notify_bridgeuploadfail extends eventsmanager_notifyAbstract $readyToSend = false; try { - $user = User_Adapter::getInstance($params['usr_id'], $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($params['usr_id']); $account = Bridge_Account::load_account($this->app, $params['account_id']); $receiver = Receiver::fromUser($user); $readyToSend = true; diff --git a/lib/classes/eventsmanager/notify/feed.php b/lib/classes/eventsmanager/notify/feed.php index 1a1a9400e2..b41888e9cd 100644 --- a/lib/classes/eventsmanager/notify/feed.php +++ b/lib/classes/eventsmanager/notify/feed.php @@ -83,15 +83,14 @@ class eventsmanager_notify_feed extends eventsmanager_notifyAbstract $results = $Query->limit($start, $perLoop)->execute()->get_results(); foreach ($results as $user_to_notif) { - /* @var $user_to_notif \User_Adapter */ $mailed = false; - if ($params['notify_email'] && $this->shouldSendNotificationFor($user_to_notif->get_id())) { + if ($params['notify_email'] && $this->shouldSendNotificationFor($user_to_notif->getId())) { $readyToSend = false; try { $token = $this->app['tokens']->getUrlToken( \random::TYPE_FEED_ENTRY - , $user_to_notif->get_id() + , $user_to_notif->getId() , null , $entry->getId() ); @@ -115,7 +114,7 @@ class eventsmanager_notify_feed extends eventsmanager_notifyAbstract } } - $this->broker->notify($user_to_notif->get_id(), __CLASS__, $datas, $mailed); + $this->broker->notify($user_to_notif->getId(), __CLASS__, $datas, $mailed); } $start += $perLoop; } while (count($results) > 0); diff --git a/lib/classes/eventsmanager/notify/order.php b/lib/classes/eventsmanager/notify/order.php index 02f8f8e71c..9c1700ee09 100644 --- a/lib/classes/eventsmanager/notify/order.php +++ b/lib/classes/eventsmanager/notify/order.php @@ -92,16 +92,14 @@ class eventsmanager_notify_order extends eventsmanager_notifyAbstract $datas = $dom_xml->saveXml(); - try { - $orderInitiator = User_Adapter::getInstance($params['usr_id'], $this->app); - } catch (\Exception $e) { + if (null === $orderInitiator = $this->app['manipulator.user']->getRepository()->find($params['usr_id'])) { return; } foreach ($users as $user) { $mailed = false; - if ($this->shouldSendNotificationFor($user->get_id())) { + if ($this->shouldSendNotificationFor($user->getId())) { $readyToSend = false; try { $receiver = Receiver::fromUser($user); @@ -119,7 +117,7 @@ class eventsmanager_notify_order extends eventsmanager_notifyAbstract } } - $this->broker->notify($user->get_id(), __CLASS__, $datas, $mailed); + $this->broker->notify($user->getId(), __CLASS__, $datas, $mailed); } return; @@ -138,13 +136,11 @@ class eventsmanager_notify_order extends eventsmanager_notifyAbstract $usr_id = (string) $sx->usr_id; $order_id = (string) $sx->order_id; - try { - User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return []; } - $sender = User_Adapter::getInstance($usr_id, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); $ret = [ 'text' => $this->app->trans('%user% a passe une %opening_link% commande %end_link%', [ @@ -182,9 +178,7 @@ class eventsmanager_notify_order extends eventsmanager_notifyAbstract */ public function is_available($usr_id) { - try { - $user = \User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return false; } diff --git a/lib/classes/eventsmanager/notify/orderdeliver.php b/lib/classes/eventsmanager/notify/orderdeliver.php index 9ddc59e934..580e052112 100644 --- a/lib/classes/eventsmanager/notify/orderdeliver.php +++ b/lib/classes/eventsmanager/notify/orderdeliver.php @@ -92,8 +92,8 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract if ($this->shouldSendNotificationFor($params['to'])) { $readyToSend = false; try { - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); $receiver = Receiver::fromUser($user_to); $emitter = Emitter::fromUser($user_from); @@ -111,7 +111,7 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract 'basket' => $basket->getId(), 'LOG' => $this->app['tokens']->getUrlToken( \random::TYPE_VIEW, - $user_to->get_id(), + $user_to->getId(), null, $basket->getId() ) @@ -144,16 +144,16 @@ class eventsmanager_notify_orderdeliver extends eventsmanager_notifyAbstract $ssel_id = (string) $sx->ssel_id; $n = (int) $sx->n; - try { - User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $user= $this->app['manipulator.user']->getRepository()->find(($from))) { return []; } - $sender = User_Adapter::getInstance($from, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); try { - $basket = $this->app['converter.basket']->convert($ssel_id); + $repository = $this->app['EM']->getRepository('Phraseanet:Basket'); + + $basket = $repository->findUserBasket($ssel_id, $this->app['authentication']->getUser(), false); } catch (\Exception $e) { return []; } diff --git a/lib/classes/eventsmanager/notify/ordernotdelivered.php b/lib/classes/eventsmanager/notify/ordernotdelivered.php index 2619997e88..5c88ea52ad 100644 --- a/lib/classes/eventsmanager/notify/ordernotdelivered.php +++ b/lib/classes/eventsmanager/notify/ordernotdelivered.php @@ -75,8 +75,8 @@ class eventsmanager_notify_ordernotdelivered extends eventsmanager_notifyAbstrac $readyToSend = false; try { - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); $receiver = Receiver::fromUser($user_to); $emitter = Emitter::fromUser($user_from); @@ -107,13 +107,11 @@ class eventsmanager_notify_ordernotdelivered extends eventsmanager_notifyAbstrac $from = (string) $sx->from; $n = (int) $sx->n; - try { - User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($from)) { return []; } - $sender = User_Adapter::getInstance($from, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); $ret = [ 'text' => $this->app->trans('%user% a refuse la livraison de %quantity% document(s) pour votre commande', ['%user%' => $sender, '%quantity%' => $n]) diff --git a/lib/classes/eventsmanager/notify/push.php b/lib/classes/eventsmanager/notify/push.php index f6236cedaa..a9faa1ea28 100644 --- a/lib/classes/eventsmanager/notify/push.php +++ b/lib/classes/eventsmanager/notify/push.php @@ -83,8 +83,8 @@ class eventsmanager_notify_push extends eventsmanager_notifyAbstract $repository = $this->app['EM']->getRepository('Phraseanet:Basket'); $basket = $repository->find($params['ssel_id']); - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); $receiver = Receiver::fromUser($user_to); $emitter = Emitter::fromUser($user_from); @@ -119,13 +119,11 @@ class eventsmanager_notify_push extends eventsmanager_notifyAbstract $from = (string) $sx->from; - try { - User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($from)) { return []; } - $sender = User_Adapter::getInstance($from, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); $ret = [ 'text' => $this->app->trans('%user% vous a envoye un %before_link% panier %after_link%', ['%user%' => $sender, '%before_link%' => 'app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $rs = $this->app['EM.native-query']->getAdminsOfBases(array_keys($base_ids)); foreach ($rs as $row) { - if ( ! isset($mailColl[$row['usr_id']])) - $mailColl[$row['usr_id']] = []; + $user = $row[0]; - $mailColl[$row['usr_id']][] = $row['base_id']; + if (!isset($mailColl[$user->getId()])) { + $mailColl[$user->getId()] = []; + } + + $mailColl[$user->getId()][] = $row['base_id']; } } catch (\Exception $e) { - } $dom_xml = new DOMDocument('1.0', 'UTF-8'); @@ -103,10 +92,8 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract $datas = $dom_xml->saveXml(); - try { - $registeredUser = \User_Adapter::getInstance($params['usr_id'], $this->app); - } catch (\Exception $e) { - return; + if (null === $registeredUser = $this->app['manipulator.user']->getRepository()->find($params['usr_id'])) { + return; } foreach ($mailColl as $usr_id => $base_ids) { @@ -115,7 +102,7 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract if ($this->shouldSendNotificationFor($usr_id)) { $readyToSend = false; try { - $admin_user = User_Adapter::getInstance($usr_id, $this->app); + $admin_user = $this->app['manipulator.user']->getRepository()->find($usr_id); $receiver = Receiver::fromUser($admin_user); $readyToSend = true; } catch (\Exception $e) { @@ -150,13 +137,11 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract $usr_id = (string) $sx->usr_id; - try { - User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return []; } - $sender = User_Adapter::getInstance($usr_id, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); $ret = [ 'text' => $this->app->trans('%user% demande votre approbation sur une ou plusieurs %before_link% collections %after_link%', ['%user%' => $sender, '%before_link%' => '', '%after_link%' => '']) @@ -195,9 +180,7 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract return false; } - try { - $user = \User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return false; } diff --git a/lib/classes/eventsmanager/notify/uploadquarantine.php b/lib/classes/eventsmanager/notify/uploadquarantine.php index e42e2fc15c..a5d2ea32bd 100644 --- a/lib/classes/eventsmanager/notify/uploadquarantine.php +++ b/lib/classes/eventsmanager/notify/uploadquarantine.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Model\Entities\LazaretCheck; use Alchemy\Phrasea\Model\Entities\LazaretFile; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Mail\MailInfoRecordQuarantined; @@ -71,9 +72,9 @@ class eventsmanager_notify_uploadquarantine extends eventsmanager_notifyAbstract $datas = $domXML->saveXml(); //Sender - if (null !== $user = $lazaretFile->getSession()->getUser($this->app)) { + if (null !== $user = $lazaretFile->getSession()->getUser()) { $sender = $domXML->createElement('sender'); - $sender->appendChild($domXML->createTextNode($user->get_display_name())); + $sender->appendChild($domXML->createTextNode($user->getDisplayName())); $root->appendChild($sender); $this->notifyUser($user, $datas); @@ -98,14 +99,14 @@ class eventsmanager_notify_uploadquarantine extends eventsmanager_notifyAbstract /** * Notifiy an user using the specified datas * - * @param \User_Adapter $user - * @param string $datas + * @param User $user + * @param string $datas */ - private function notifyUser(\User_Adapter $user, $datas) + private function notifyUser(User $user, $datas) { $mailed = false; - if ($this->shouldSendNotificationFor($user->get_id())) { + if ($this->shouldSendNotificationFor($user->getId())) { $readyToSend = false; try { $receiver = Receiver::fromUser($user); @@ -121,7 +122,7 @@ class eventsmanager_notify_uploadquarantine extends eventsmanager_notifyAbstract } } - $this->broker->notify($user->get_id(), __CLASS__, $datas, $mailed); + $this->broker->notify($user->getId(), __CLASS__, $datas, $mailed); } /** @@ -182,9 +183,7 @@ class eventsmanager_notify_uploadquarantine extends eventsmanager_notifyAbstract */ public function is_available($usr_id) { - try { - $user = \User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return false; } diff --git a/lib/classes/eventsmanager/notify/validate.php b/lib/classes/eventsmanager/notify/validate.php index 2d513b0a8f..2433f494bd 100644 --- a/lib/classes/eventsmanager/notify/validate.php +++ b/lib/classes/eventsmanager/notify/validate.php @@ -93,8 +93,8 @@ class eventsmanager_notify_validate extends eventsmanager_notifyAbstract $readyToSend = false; try { - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); $basket = $this->app['EM'] ->getRepository('Phraseanet:Basket') @@ -137,13 +137,11 @@ class eventsmanager_notify_validate extends eventsmanager_notifyAbstract $from = (string) $sx->from; $ssel_id = (string) $sx->ssel_id; - try { - User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($from)) { return []; } - $sender = User_Adapter::getInstance($from, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); try { $basket = $this->app['converter.basket']->convert($ssel_id); diff --git a/lib/classes/eventsmanager/notify/validationdone.php b/lib/classes/eventsmanager/notify/validationdone.php index 2b3f3b4d7f..91c84e3d8e 100644 --- a/lib/classes/eventsmanager/notify/validationdone.php +++ b/lib/classes/eventsmanager/notify/validationdone.php @@ -88,8 +88,8 @@ class eventsmanager_notify_validationdone extends eventsmanager_notifyAbstract if ($this->shouldSendNotificationFor($params['to'])) { $readyToSend = false; try { - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); $basket = $this->app['EM'] ->getRepository('Phraseanet:Basket') @@ -131,16 +131,16 @@ class eventsmanager_notify_validationdone extends eventsmanager_notifyAbstract $from = (string) $sx->from; $ssel_id = (string) $sx->ssel_id; - try { - $registered_user = User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $registered_user = $this->app['manipulator.user']->getRepository()->find($from)) { return []; } - $sender = $registered_user->get_display_name(); + $sender = $registered_user->getDisplayName(); try { - $basket = $this->app['converter.basket']->convert($ssel_id); + $repository = $this->app['EM']->getRepository('Phraseanet:Basket'); + + $basket = $repository->findUserBasket($ssel_id, $this->app['authentication']->getUser(), false); } catch (\Exception $e) { return []; } @@ -181,9 +181,7 @@ class eventsmanager_notify_validationdone extends eventsmanager_notifyAbstract */ public function is_available($usr_id) { - try { - $user = \User_Adapter::getInstance($usr_id, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($usr_id)) { return false; } diff --git a/lib/classes/eventsmanager/notify/validationreminder.php b/lib/classes/eventsmanager/notify/validationreminder.php index 10b3ac9f3a..1611579753 100644 --- a/lib/classes/eventsmanager/notify/validationreminder.php +++ b/lib/classes/eventsmanager/notify/validationreminder.php @@ -86,10 +86,10 @@ class eventsmanager_notify_validationreminder extends eventsmanager_notifyAbstra $mailed = false; - try { - $user_from = User_Adapter::getInstance($params['from'], $this->app); - $user_to = User_Adapter::getInstance($params['to'], $this->app); - } catch (\Exception $e) { + $user_from = $this->app['manipulator.user']->getRepository()->find($params['from']); + $user_to = $this->app['manipulator.user']->getRepository()->find($params['to']); + + if (null === $user_from || null === $user_to) { return false; } @@ -136,13 +136,11 @@ class eventsmanager_notify_validationreminder extends eventsmanager_notifyAbstra $from = (string) $sx->from; $ssel_id = (string) $sx->ssel_id; - try { - User_Adapter::getInstance($from, $this->app); - } catch (\Exception $e) { + if (null === $user = $this->app['manipulator.user']->getRepository()->find($from)) { return []; } - $sender = User_Adapter::getInstance($from, $this->app)->get_display_name(); + $sender = $user->getDisplayName(); try { $basket = $this->app['converter.basket']->convert($ssel_id); diff --git a/lib/classes/eventsmanager/notifyAbstract.php b/lib/classes/eventsmanager/notifyAbstract.php index caa43cc599..5e7e9385a5 100644 --- a/lib/classes/eventsmanager/notifyAbstract.php +++ b/lib/classes/eventsmanager/notifyAbstract.php @@ -32,16 +32,10 @@ abstract class eventsmanager_notifyAbstract extends eventsmanager_eventAbstract abstract public function icon_url(); - protected function get_prefs($class, $usr_id) + protected function shouldSendNotificationFor($usrId) { - $user = User_Adapter::getInstance($usr_id, $this->app); - $pref = $user->get_notifications_preference($this->app, $class); + $user = $this->app['manipulator.user']->getRepository()->find($usrId); - return null !== $pref ? $pref : 1; - } - - protected function shouldSendNotificationFor($usr_id) - { - return 0 !== (int) $this->get_prefs(get_class($this), $usr_id); + return $this->app['settings']->getUserNotificationSetting($user, get_class($this)); } } diff --git a/lib/classes/module/console/checkExtension.php b/lib/classes/module/console/checkExtension.php index 6848722dc1..993c8812eb 100644 --- a/lib/classes/module/console/checkExtension.php +++ b/lib/classes/module/console/checkExtension.php @@ -41,9 +41,7 @@ class module_console_checkExtension extends Command $usrId = $input->getArgument('usr_id'); - try { - $TestUser = \User_Adapter::getInstance($usrId, $this->container); - } catch (\Exception $e) { + if (null === $TestUser = $this->container['manipulator.user']->getRepository()->find($usrId)) { $output->writeln("Wrong user !"); return 1; @@ -52,8 +50,8 @@ class module_console_checkExtension extends Command $output->writeln( sprintf( "\nWill do the check with user %s (%s)\n" - , $TestUser->get_display_name() - , $TestUser->get_email() + , $TestUser->getDisplayName() + , $TestUser->getEmail() ) ); @@ -93,7 +91,7 @@ class module_console_checkExtension extends Command $output->writeln("\n-- phrasea_create_session --"); - $sessid = phrasea_create_session((string) $TestUser->get_id()); + $sessid = phrasea_create_session((string) $TestUser->getId()); if (ctype_digit((string) $sessid)) { $output->writeln("Succes ! got session id $sessid"); diff --git a/lib/classes/module/console/systemMailCheck.php b/lib/classes/module/console/systemMailCheck.php index b0ba27ca1b..d3cec60c4b 100644 --- a/lib/classes/module/console/systemMailCheck.php +++ b/lib/classes/module/console/systemMailCheck.php @@ -81,13 +81,13 @@ class module_console_systemMailCheck extends Command $id = $dialog->ask($output, 'Which id ?', ''); try { - $tmp_user = User_Adapter::getInstance($id, $this->container); + $tmp_user = $this->container['manipulator.user']->getRepository()->find($id); - if ($tmp_user->get_email() != $email) { + if ($tmp_user->getEmail() != $email) { throw new Exception('Invalid user'); } - $tmp_user->set_email(null); + $tmp_user->setEmail(null); unset($users[$id]); } catch (\Exception $e) { diff --git a/lib/classes/module/report.php b/lib/classes/module/report.php index 82a58abcbe..9dcc6c5cf7 100644 --- a/lib/classes/module/report.php +++ b/lib/classes/module/report.php @@ -251,7 +251,7 @@ class module_report $this->dmax = $d2; $this->sbas_id = $sbas_id; $this->list_coll_id = $collist; - $this->user_id = $this->app['authentication']->getUser()->get_id(); + $this->user_id = $this->app['authentication']->getUser()->getId(); $this->periode = sprintf( '%s - %s ', $this->app['date-formatter']->getPrettyString(new \DateTime($d1)), diff --git a/lib/classes/module/report/activity.php b/lib/classes/module/report/activity.php index ed60a03cf2..2fdef6aee9 100644 --- a/lib/classes/module/report/activity.php +++ b/lib/classes/module/report/activity.php @@ -295,7 +295,7 @@ class module_report_activity extends module_report $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - $login = User_Adapter::getInstance($usr, $this->app)->get_display_name(); + $login = $this->app['manipulator.user']->getRepository()->find($usr)->getDisplayName(); $this->setChamp($rs); diff --git a/lib/classes/module/report/add.php b/lib/classes/module/report/add.php index 344e20c462..2835f20e91 100644 --- a/lib/classes/module/report/add.php +++ b/lib/classes/module/report/add.php @@ -77,11 +77,8 @@ class module_report_add extends module_report $value = $row['val']; $caption = $value; if ($field == "getter") { - try { - $user = User_Adapter::getInstance($value, $this->app); - $caption = $user->get_display_name(); - } catch (\Exception $e) { - + if (null !== $user = $this->app['manipulator.user']->getRepository()->find($value)) { + $caption = $user->getDisplayName(); } } elseif ($field == 'date') $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); diff --git a/lib/classes/module/report/edit.php b/lib/classes/module/report/edit.php index 3476de21de..97b94320de 100644 --- a/lib/classes/module/report/edit.php +++ b/lib/classes/module/report/edit.php @@ -77,11 +77,8 @@ class module_report_edit extends module_report $value = $row['val']; $caption = $value; if ($field == "getter") { - try { - $user = User_Adapter::getInstance($value, $this->app); - $caption = $user->get_display_name(); - } catch (\Exception $e) { - + if (null !== $user = $this->app['manipulator.user']->getRepository()->find($value)) { + $caption = $user->getDisplayName(); } } elseif ($field == 'date') { $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); diff --git a/lib/classes/module/report/nav.php b/lib/classes/module/report/nav.php index 03e4c5bb5e..3b7f6bfa51 100644 --- a/lib/classes/module/report/nav.php +++ b/lib/classes/module/report/nav.php @@ -434,22 +434,23 @@ class module_report_nav extends module_report $sql = " SELECT - usr_login as identifiant, - usr_nom as nom, - usr_mail as mail, - adresse, tel - FROM usr + login as identifiant, + last_name as nom, + email as mail, + address AS adresse, + phone AS tel + FROM Users WHERE $on = :value " . (('' !== $filter_id_apbox) ? "AND (" . $filter_id_apbox . ")" : ''); } else { $sql = ' SELECT - usr_login AS identifiant, - usr_nom AS nom, - usr_mail AS mail, - adresse, - tel - FROM usr - WHERE (usr_id = :value)'; + login AS identifiant, + last_name AS nom, + email AS mail, + address AS adresse, + phone AS tel + FROM Users + WHERE (id = :value)'; } $params2 = [':value' => $val]; diff --git a/lib/classes/module/report/push.php b/lib/classes/module/report/push.php index 218090222e..fdae8ecc96 100644 --- a/lib/classes/module/report/push.php +++ b/lib/classes/module/report/push.php @@ -78,11 +78,8 @@ class module_report_push extends module_report $value = $row['val']; $caption = $value; if ($field == "getter") { - try { - $user = User_Adapter::getInstance($value, $this->app); - $caption = $user->get_display_name(); - } catch (\Exception $e) { - + if (null !== $user = $this->app['manipulator.user']->getRepository()->find($value)) { + $caption = $user->getDisplayName(); } } elseif ($field == 'date') { $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); diff --git a/lib/classes/module/report/sent.php b/lib/classes/module/report/sent.php index 77ff15b5e1..539841519b 100644 --- a/lib/classes/module/report/sent.php +++ b/lib/classes/module/report/sent.php @@ -78,11 +78,8 @@ class module_report_sent extends module_report $value = $row['val']; $caption = $value; if ($field == "getter") { - try { - $user = User_Adapter::getInstance($value, $this->app); - $caption = $user->get_display_name(); - } catch (\Exception $e) { - + if (null !== $user = $this->app['manipulator.user']->getRepository()->find($value)) { + $caption = $user->getDisplayName(); } } elseif ($field == 'date') { $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); diff --git a/lib/classes/module/report/validate.php b/lib/classes/module/report/validate.php index ed2db855a2..6063552db4 100644 --- a/lib/classes/module/report/validate.php +++ b/lib/classes/module/report/validate.php @@ -78,11 +78,8 @@ class module_report_validate extends module_report $value = $row['val']; $caption = $value; if ($field == "getter") { - try { - $user = User_Adapter::getInstance($value, $this->app); - $caption = $user->get_display_name(); - } catch (\Exception $e) { - + if (null !== $user = $this->app['manipulator.user']->getRepository()->find($value)) { + $caption = $user->getDisplayName(); } } elseif ($field == 'date') { $caption = $this->app['date-formatter']->getPrettyString(new DateTime($value)); diff --git a/lib/classes/patch/320alpha2a.php b/lib/classes/patch/320alpha2a.php index 7bcb9855d5..a5a468ae2c 100644 --- a/lib/classes/patch/320alpha2a.php +++ b/lib/classes/patch/320alpha2a.php @@ -10,6 +10,7 @@ */ use Alchemy\Phrasea\Application; +use Doctrine\ORM\Query; class patch_320alpha2a implements patchInterface { @@ -56,20 +57,22 @@ class patch_320alpha2a implements patchInterface */ public function apply(base $appbox, Application $app) { - $sql = 'SELECT * FROM usr WHERE nonce IS NULL'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); - $stmt->closeCursor(); + $dql = 'SELECT u FROM Phraseanet:User u WHERE u.nonce IS NULL'; + $q = $app['EM']->createQuery($dql); + $q->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); + $users = $q->getResult(); - $sql = 'UPDATE usr SET nonce = :nonce WHERE usr_id = :usr_id'; - $stmt = $appbox->get_connection()->prepare($sql); - foreach ($rs as $row) { - $nonce = random::generatePassword(16); - $params = [':usr_id' => $row['usr_id'], ':nonce' => $nonce]; - $stmt->execute($params); + $n = 0; + foreach ($users as $user) { + $user->setNonce(random::generatePassword(16)); + $app['EM']->persist($user); + $n++; + if ($n %100 === 0) { + $app['EM']->flush(); + } } - $stmt->closeCursor(); + + $app['EM']->flush(); $sql = 'SELECT task_id, `class` FROM task2'; $stmt = $appbox->get_connection()->prepare($sql); diff --git a/lib/classes/patch/320alpha4a.php b/lib/classes/patch/320alpha4a.php index 5229b21093..c37ff9cdec 100644 --- a/lib/classes/patch/320alpha4a.php +++ b/lib/classes/patch/320alpha4a.php @@ -97,7 +97,6 @@ class patch_320alpha4a implements patchInterface $xp_struct = $databox->get_xpath_structure(); foreach ($sxe->description->children() as $fname => $field) { - $src = trim(isset($field['src']) ? $field['src'] : ''); if (array_key_exists($src, $phrasea_maps)) { $src = $phrasea_maps[$src]; diff --git a/lib/classes/patch/320alpha4b.php b/lib/classes/patch/320alpha4b.php index 0a6c0b7f78..9f55e83a2f 100644 --- a/lib/classes/patch/320alpha4b.php +++ b/lib/classes/patch/320alpha4b.php @@ -17,7 +17,7 @@ use Alchemy\Phrasea\Model\Entities\FeedPublisher; use Gedmo\Timestampable\TimestampableListener; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -class patch_320alpha4b implements patchInterface +class patch_320alpha4b extends patchAbstract { /** @var string */ private $release = '3.2.0-alpha.4'; @@ -38,7 +38,7 @@ class patch_320alpha4b implements patchInterface */ public function getDoctrineMigrations() { - return ['feed']; + return ['user', 'feed']; } /** @@ -46,7 +46,7 @@ class patch_320alpha4b implements patchInterface */ public function require_all_upgrades() { - return true; + return false; } /** @@ -62,8 +62,6 @@ class patch_320alpha4b implements patchInterface */ public function apply(base $appbox, Application $app) { - $feeds = []; - try { $sql = 'ALTER TABLE `ssel` ADD `migrated` INT NOT NULL DEFAULT "0"'; $stmt = $appbox->get_connection()->prepare($sql); @@ -88,8 +86,9 @@ class patch_320alpha4b implements patchInterface $app['EM']->getEventManager()->removeEventSubscriber(new TimestampableListener()); foreach ($rs as $row) { - $user = User_Adapter::getInstance($row['usr_id'], $app); - + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } $feed = $this->get_feed($appbox, $user, $row['pub_restrict'], $row['homelink'], $app); if (! $feed instanceof Feed) { @@ -99,8 +98,8 @@ class patch_320alpha4b implements patchInterface $publishers = $feed->getPublishers(); $entry = new FeedEntry(); - $entry->setAuthorEmail($user->get_email()); - $entry->setAuthorName($user->get_display_name()); + $entry->setAuthorEmail($user->getEmail()); + $entry->setAuthorName($user->getDisplayName()); $entry->setFeed($feed); $entry->setPublisher($publishers->first()); $entry->setTitle($row['name']); @@ -175,9 +174,9 @@ class patch_320alpha4b implements patchInterface } protected static $feeds = []; - protected function get_feed(appbox $appbox, User_Adapter $user, $pub_restrict, $homelink, Application $app) + protected function get_feed(appbox $appbox, User $user, $pub_restrict, $homelink, Application $app) { - $user_key = 'user_' . $user->get_id(); + $user_key = 'user_' . $user->getId(); if ($homelink == '1') { $feed_key = 'feed_homelink'; } elseif ($pub_restrict == '1') { @@ -188,11 +187,11 @@ class patch_320alpha4b implements patchInterface if ( ! array_key_exists($user_key, self::$feeds) || ! isset(self::$feeds[$user_key][$feed_key])) { if ($homelink == '1') - $title = $user->get_display_name() . ' - ' . 'homelink Feed'; + $title = $user->getDisplayName() . ' - ' . 'homelink Feed'; elseif ($pub_restrict == '1') - $title = $user->get_display_name() . ' - ' . 'private Feed'; + $title = $user->getDisplayName() . ' - ' . 'private Feed'; else - $title = $user->get_display_name() . ' - ' . 'public Feed'; + $title = $user->getDisplayName() . ' - ' . 'public Feed'; $feed = new Feed(); $publisher = new FeedPublisher(); @@ -201,7 +200,7 @@ class patch_320alpha4b implements patchInterface $feed->addPublisher($publisher); $publisher->setFeed($feed); $publisher->setOwner(true); - $publisher->setUsrId($user->get_id()); + $publisher->setUser($user); if ($homelink) { $feed->setPublic(true); diff --git a/lib/classes/patch/360alpha1a.php b/lib/classes/patch/360alpha1a.php index 7f027e12d9..27269b352e 100644 --- a/lib/classes/patch/360alpha1a.php +++ b/lib/classes/patch/360alpha1a.php @@ -214,7 +214,7 @@ class patch_360alpha1a implements patchInterface $stmt->execute(); $stmt->closeCursor(); - $sql = 'SELECT usr_id, basket_id, p.id as participant_id + $sql = 'SELECT user_id, basket_id, p.id as participant_id FROM ValidationParticipants p, ValidationSessions s WHERE p.ValidationSession_Id = s.id'; @@ -236,7 +236,7 @@ class patch_360alpha1a implements patchInterface $params = [ ':participant_id' => $row['participant_id'], ':basket_id' => $row['basket_id'], - ':usr_id' => $row['usr_id'], + ':usr_id' => $row['user_id'], ]; $stmt->execute($params); } diff --git a/lib/classes/patch/360alpha2a.php b/lib/classes/patch/360alpha2a.php index 66674b2d01..c6ced6d827 100644 --- a/lib/classes/patch/360alpha2a.php +++ b/lib/classes/patch/360alpha2a.php @@ -56,13 +56,7 @@ class patch_360alpha2a implements patchInterface */ public function apply(base $appbox, Application $app) { - - $sql = 'UPDATE usr SET usr_mail = NULL - WHERE usr_mail IS NOT NULL - AND usr_login LIKE "(#deleted%"'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); + $app['EM']->getConnection()->executeUpdate('UPDATE Users u SET u.email = NULL WHERE u.email IS NOT NULL AND u.deleted = 1'); return true; } diff --git a/lib/classes/patch/370alpha4a.php b/lib/classes/patch/370alpha4a.php index bfacc72d90..3947696338 100644 --- a/lib/classes/patch/370alpha4a.php +++ b/lib/classes/patch/370alpha4a.php @@ -68,7 +68,6 @@ class patch_370alpha4a implements patchInterface $tagBasename = new \Alchemy\Phrasea\Metadata\Tag\TfBasename(); foreach ($rs as $row) { - if (strpos(strtolower($row['src']), 'tf-parentdir') !== false) { $update[] = ['id' => $row['id'], 'src' => $tagDirname->getTagname()]; } diff --git a/lib/classes/patch/370alpha5a.php b/lib/classes/patch/370alpha5a.php index 997f7c532f..79c5a538db 100644 --- a/lib/classes/patch/370alpha5a.php +++ b/lib/classes/patch/370alpha5a.php @@ -56,7 +56,6 @@ class patch_370alpha5a implements patchInterface */ public function apply(base $databox, Application $app) { - $sql = 'SELECT id, src FROM metadatas_structure'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); diff --git a/lib/classes/patch/370alpha6a.php b/lib/classes/patch/370alpha6a.php index 85c57c4075..8d56e2f88b 100644 --- a/lib/classes/patch/370alpha6a.php +++ b/lib/classes/patch/370alpha6a.php @@ -76,13 +76,10 @@ class patch_370alpha6a implements patchInterface $subdefgroups = $databox->get_subdef_structure(); foreach ($subdefgroups as $groupname => $subdefs) { - foreach ($subdefs as $name => $subdef) { - $this->addScreenDeviceOption($subdefgroups, $subdef, $groupname); if (in_array($name, ['preview', 'thumbnail'])) { - if ($name == 'thumbnail' || $subdef->getSubdefType()->getType() != \Alchemy\Phrasea\Media\Subdef\Subdef::TYPE_VIDEO) { $this->addMobileSubdefImage($subdefgroups, $subdef, $groupname); } else { diff --git a/lib/classes/patch/370alpha7a.php b/lib/classes/patch/370alpha7a.php index 7536131603..fbe13f784e 100644 --- a/lib/classes/patch/370alpha7a.php +++ b/lib/classes/patch/370alpha7a.php @@ -15,7 +15,7 @@ use Alchemy\Phrasea\Model\Entities\LazaretSession; use MediaAlchemyst\Exception\ExceptionInterface as MediaAlchemystException; use MediaAlchemyst\Specification\Image as ImageSpec; -class patch_370alpha7a implements patchInterface +class patch_370alpha7a extends patchAbstract { /** @var string */ private $release = '3.7.0-alpha.7'; @@ -36,7 +36,7 @@ class patch_370alpha7a implements patchInterface */ public function require_all_upgrades() { - return false; + return true; } /** @@ -52,7 +52,7 @@ class patch_370alpha7a implements patchInterface */ public function getDoctrineMigrations() { - return ['lazaret']; + return ['user', 'lazaret']; } /** @@ -87,11 +87,12 @@ class patch_370alpha7a implements patchInterface $i = 0; foreach ($rs as $row) { - $filePath = $app['root.path'] . '/tmp/lazaret/' . $row['filepath']; + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } if (file_exists($filePath)) { - $spec = new ImageSpec(); $spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO); @@ -112,7 +113,7 @@ class patch_370alpha7a implements patchInterface $borderFile = new \Alchemy\Phrasea\Border\File($app, $media, $collection); $lazaretSession = new LazaretSession(); - $lazaretSession->setUsrId($row['usr_id']); + $lazaretSession->setUser($user); $lazaretFile = new LazaretFile(); $lazaretFile->setBaseId($row['base_id']); diff --git a/lib/classes/patch/380alpha11a.php b/lib/classes/patch/380alpha11a.php index af4ae93417..581ed6e401 100644 --- a/lib/classes/patch/380alpha11a.php +++ b/lib/classes/patch/380alpha11a.php @@ -13,7 +13,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\Session; use Alchemy\Phrasea\Model\Entities\SessionModule; -class patch_380alpha11a implements patchInterface +class patch_380alpha11a extends patchAbstract { /** @var string */ private $release = '3.8.0-alpha.11'; @@ -50,7 +50,7 @@ class patch_380alpha11a implements patchInterface */ public function getDoctrineMigrations() { - return ['session']; + return ['user', 'session']; } /** @@ -72,6 +72,10 @@ class patch_380alpha11a implements patchInterface } foreach ($rs as $row) { + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } + $created = $updated = null; if ('0000-00-00 00:00:00' !== $row['created_on']) { $created = \DateTime::createFromFormat('Y-m-d H:i:s', $row['created_on']); @@ -82,7 +86,7 @@ class patch_380alpha11a implements patchInterface $session = new Session(); $session - ->setUsrId($row['usr_id']) + ->setUser($user) ->setUserAgent($row['user_agent']) ->setUpdated($updated) ->setToken($row['token']) diff --git a/lib/classes/patch/381alpha3a.php b/lib/classes/patch/381alpha3a.php index 389c87bb95..46c2761c46 100644 --- a/lib/classes/patch/381alpha3a.php +++ b/lib/classes/patch/381alpha3a.php @@ -59,7 +59,7 @@ class patch_381alpha3a implements patchInterface $propSql = $propArgs = []; $n = 0; - foreach (\User_Adapter::$def_values as $prop => $value) { + foreach ($app['settings']->getUsersSettings() as $prop => $value) { if ('start_page_query' === $prop) { continue; } diff --git a/lib/classes/patch/383alpha1a.php b/lib/classes/patch/383alpha1a.php index 269f8c1279..659f804aea 100644 --- a/lib/classes/patch/383alpha1a.php +++ b/lib/classes/patch/383alpha1a.php @@ -62,7 +62,7 @@ class patch_383alpha1a implements patchInterface } // Remove deleted users sessions - $sql = 'SELECT s.id FROM `Sessions` s, usr u WHERE u.usr_login LIKE "(#deleted%" AND u.usr_id = s.usr_id'; + $sql = 'SELECT s.id FROM `Sessions` s INNER JOIN Users u ON (u.id = s.user_id) WHERE u.deleted = 1'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); diff --git a/lib/classes/patch/383alpha2a.php b/lib/classes/patch/383alpha2a.php index af2fc321a2..ae41104d8d 100644 --- a/lib/classes/patch/383alpha2a.php +++ b/lib/classes/patch/383alpha2a.php @@ -10,8 +10,9 @@ */ use Alchemy\Phrasea\Application; +use Doctrine\ORM\NoResultException; -class patch_383alpha2a implements patchInterface +class patch_383alpha2a extends patchAbstract { /** @var string */ private $release = '3.8.3-alpha.2'; @@ -57,15 +58,21 @@ class patch_383alpha2a implements patchInterface public function apply(base $appbox, Application $app) { // Clean validation sessions where initiator_id does not exist anymore - $sql = 'SELECT DISTINCT(v.id) AS validation_session_id FROM `ValidationSessions` v LEFT JOIN usr u ON (v.initiator_id = u.usr_id) WHERE u.usr_id IS NULL'; + $sql = 'SELECT DISTINCT(v.id) AS validation_session_id FROM `ValidationSessions` v LEFT JOIN Users u ON (v.initiator_id = u.id) WHERE u.id IS NULL'; $stmt = $appbox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); foreach ($rows as $row) { - if (null !== $vsession = $app['EM']->find('Phraseanet:ValidationSession', $row['validation_session_id'])) { + try { + $vsession = $app['EM']->createQuery('SELECT PARTIAL s.{id} FROM Phraseanet:ValidationSession s WHERE s.id = :id') + ->setParameters(['id' => $row['validation_session_id']]) + ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) + ->getSingleResult(); $app['EM']->remove($vsession); + } catch (NoResultException $e) { + } } diff --git a/lib/classes/patch/383alpha4a.php b/lib/classes/patch/383alpha4a.php deleted file mode 100644 index 670b702691..0000000000 --- a/lib/classes/patch/383alpha4a.php +++ /dev/null @@ -1,105 +0,0 @@ -release; - } - - /** - * {@inheritdoc} - */ - public function require_all_upgrades() - { - return false; - } - - /** - * {@inheritdoc} - */ - public function concern() - { - return $this->concern; - } - - /** - * {@inheritdoc} - */ - public function getDoctrineMigrations() - { - return []; - } - - /** - * {@inheritdoc} - */ - public function apply(base $appbox, Application $app) - { - $em = $app['EM']; - $mappingFieldType = $mappingFieldResult = new ResultSetMapping(); - - $rs = $em->createNativeQuery( - "SHOW FIELDS FROM usr WHERE Field = 'usr_login';", - $mappingFieldType->addScalarResult('Type', 'Type') - )->getSingleResult(); - - if (0 !== strpos(strtolower($rs['Type']), 'varbinary')) { - return; - } - - // As 'usr_login' field type is varbinary it can contain any charset (utf8 or latin1). - // Compare usr_login to usr_login converted to utf8>utf32>utf8 - // will detect broken char for latin1 encoded string. - // Then detected 'usr_login' fields must be converted from latin1 to utf8. - $rs = $em->createNativeQuery( - 'SELECT t.usr_id, t.login_utf8 FROM ( - SELECT usr_id, - usr_login AS login_unknown_charset, - CONVERT(CAST(usr_login AS CHAR CHARACTER SET latin1) USING utf8) AS login_utf8, - CONVERT(CONVERT(CAST(usr_login AS CHAR CHARACTER SET utf8) USING utf32) USING utf8) AS login_utf8_utf32_utf8 - FROM usr - ) AS t - WHERE t.login_utf8_utf32_utf8 != t.login_unknown_charset', - $mappingFieldResult->addScalarResult('usr_id', 'usr_id')->addScalarResult('login_utf8', 'login_utf8') - )->getResult(); - - foreach ($rs as $row) { - $em->getConnection()->executeQuery(sprintf('UPDATE usr SET usr_login="%s" WHERE usr_id=%d', $row['login_utf8'], $row['usr_id'])); - } - - foreach ([ - // drop index - "ALTER TABLE usr DROP INDEX usr_login;", - // change field type - "ALTER TABLE usr MODIFY usr_login VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin;", - // recreate index - "CREATE UNIQUE INDEX usr_login ON usr (usr_login);" - ] as $sql) { - $em->getConnection()->executeQuery($sql); - } - - return true; - } -} diff --git a/lib/classes/patch/390alpha1a.php b/lib/classes/patch/390alpha1a.php index d18a67da4a..b43f976107 100644 --- a/lib/classes/patch/390alpha1a.php +++ b/lib/classes/patch/390alpha1a.php @@ -10,9 +10,12 @@ */ use Alchemy\Phrasea\Application; -use Alchemy\Phrasea\Model\Entities\FtpCredential; +use Alchemy\Phrasea\Model\Entities\Order; +use Alchemy\Phrasea\Model\Entities\OrderElement; +use Doctrine\ORM\NoResultException; +use Gedmo\Timestampable\TimestampableListener; -class patch_390alpha1a implements patchInterface +class patch_390alpha1a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.1'; @@ -49,7 +52,7 @@ class patch_390alpha1a implements patchInterface */ public function getDoctrineMigrations() { - return ['ftp-credential']; + return ['user', 'order']; } /** @@ -57,10 +60,18 @@ class patch_390alpha1a implements patchInterface */ public function apply(base $appbox, Application $app) { + $sql = 'DELETE FROM Orders'; + $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + + $sql = 'DELETE FROM OrderElements'; + $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); + $stmt->execute(); + $stmt->closeCursor(); + $conn = $app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT usr_id, activeFTP, addrFTP, loginFTP, - retryFTP, passifFTP, pwdFTP, destFTP, prefixFTPfolder - FROM usr'; + $sql = 'SELECT id, usr_id, created_on, `usage`, deadline, ssel_id FROM `order`'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); @@ -68,22 +79,61 @@ class patch_390alpha1a implements patchInterface $n = 0; $em = $app['EM']; + $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); foreach ($rs as $row) { - $credential = new FtpCredential(); - $credential->setActive($row['activeFTP']); - $credential->setAddress($row['addrFTP']); - $credential->setLogin($row['loginFTP']); - $credential->setMaxRetry((Integer) $row['retryFTP']); - $credential->setPassive($row['passifFTP']); - $credential->setPassword($row['pwdFTP']); - $credential->setReceptionFolder($row['destFTP']); - $credential->setRepositoryPrefixName($row['prefixFTPfolder']); - $credential->setUsrId($row['usr_id']); + $sql = 'SELECT count(id) as todo + FROM order_elements + WHERE deny = NULL + AND order_id = :id'; - $em->persist($credential); + $stmt = $conn->prepare($sql); + $stmt->execute([':id' => $row['id']]); + $todo = $stmt->fetch(\PDO::FETCH_ASSOC); + $stmt->closeCursor(); - $n++; + $user = $this->loadUser($app['EM'], $row['usr_id']); + + try { + $basket = $app['EM']->createQuery('SELECT PARTIAL b.{id} FROM Phraseanet:Basket b WHERE b.id = :id') + ->setParameters(['id' => $row['ssel_id']]) + ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) + ->getSingleResult(); + } catch (NoResultException $e) { + continue; + } + + $order = new Order(); + $order->setUser($user) + ->setTodo($todo['todo']) + ->setOrderUsage($row['usage']) + ->setDeadline(new \DateTime($row['deadline'])) + ->setCreatedOn(new \DateTime($row['created_on'])) + ->setBasket($basket); + + $em->persist($order); + + $sql = 'SELECT base_id, record_id, order_master_id, deny + FROM order_elements + WHERE order_id = :id'; + + $stmt = $conn->prepare($sql); + $stmt->execute([':id' => $row['id']]); + $elements = $stmt->fetchAll(\PDO::FETCH_ASSOC); + $stmt->closeCursor(); + + foreach ($elements as $element) { + $orderElement = new OrderElement(); + $user = $this->loadUser($app['EM'], $row['usr_id']); + $orderElement->setBaseId($element['base_id']) + ->setDeny($element['deny'] === null ? null : (Boolean) $element['deny']) + ->setOrder($order) + ->setOrderMaster($user) + ->setRecordId($element['record_id']); + + $order->addElement($orderElement); + $em->persist($orderElement); + } if ($n % 100 === 0) { $em->flush(); @@ -94,6 +144,8 @@ class patch_390alpha1a implements patchInterface $em->flush(); $em->clear(); + $em->getEventManager()->addEventSubscriber(new TimestampableListener()); + return true; } } diff --git a/lib/classes/patch/390alpha1b.php b/lib/classes/patch/390alpha1b.php deleted file mode 100644 index 8cfeac42ee..0000000000 --- a/lib/classes/patch/390alpha1b.php +++ /dev/null @@ -1,139 +0,0 @@ -release; - } - - /** - * {@inheritdoc} - */ - public function require_all_upgrades() - { - return true; - } - - /** - * {@inheritdoc} - */ - public function concern() - { - return $this->concern; - } - - /** - * {@inheritdoc} - */ - public function getDoctrineMigrations() - { - return ['order']; - } - - /** - * {@inheritdoc} - */ - public function apply(base $appbox, Application $app) - { - $sql = 'DELETE FROM Orders'; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $sql = 'DELETE FROM OrderElements'; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $conn = $app['phraseanet.appbox']->get_connection(); - $sql = 'SELECT id, usr_id, created_on, `usage`, deadline, ssel_id FROM `order`'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $n = 0; - $em = $app['EM']; - $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); - $basketRepository = $em->getRepository('Phraseanet:Basket'); - - foreach ($rs as $row) { - $sql = 'SELECT count(id) as todo - FROM order_elements - WHERE deny = NULL - AND order_id = :id'; - - $stmt = $conn->prepare($sql); - $stmt->execute([':id' => $row['id']]); - $todo = $stmt->fetch(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $order = new Order(); - $order->setUsrId($row['usr_id']) - ->setTodo($todo['todo']) - ->setOrderUsage($row['usage']) - ->setDeadline(new \DateTime($row['deadline'])) - ->setCreatedOn(new \DateTime($row['created_on'])) - ->setBasket($basketRepository->find($row['ssel_id'])); - - $em->persist($order); - - $sql = 'SELECT base_id, record_id, order_master_id, deny - FROM order_elements - WHERE order_id = :id'; - - $stmt = $conn->prepare($sql); - $stmt->execute([':id' => $row['id']]); - $elements = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - foreach ($elements as $element) { - $orderElement = new OrderElement(); - $orderElement->setBaseId($element['base_id']) - ->setDeny($element['deny'] === null ? null : (Boolean) $element['deny']) - ->setOrder($order) - ->setOrderMasterId($element['order_master_id']) - ->setRecordId($element['record_id']); - - $order->addElement($orderElement); - $em->persist($orderElement); - } - - if ($n % 100 === 0) { - $em->flush(); - $em->clear(); - } - } - - $em->flush(); - $em->clear(); - - $em->getEventManager()->addEventSubscriber(new TimestampableListener()); - - return true; - } -} diff --git a/lib/classes/patch/390alpha2a.php b/lib/classes/patch/390alpha2a.php deleted file mode 100644 index 0360b9da4e..0000000000 --- a/lib/classes/patch/390alpha2a.php +++ /dev/null @@ -1,234 +0,0 @@ -release; - } - - /** - * {@inheritdoc} - */ - public function require_all_upgrades() - { - return false; - } - - /** - * {@inheritdoc} - */ - public function concern() - { - return $this->concern; - } - - /** - * {@inheritdoc} - */ - public function getDoctrineMigrations() - { - return ['user']; - } - - /** - * {@inheritdoc} - */ - public function apply(base $appbox, Application $app) - { - $sql = 'DELETE FROM Users'; - $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); - $stmt->execute(); - $stmt->closeCursor(); - - $conn = $app['phraseanet.appbox']->get_connection(); - $em = $app['EM']; - - $em->getEventManager()->removeEventSubscriber(new TimestampableListener()); - - $this->updateUsers($em, $conn); - $this->updateModels($em, $conn); - - $em->getEventManager()->addEventSubscriber(new TimestampableListener()); - - return true; - } - - /** - * Sets user entity from usr table. - */ - private function updateUsers(EntityManager $em, $conn) - { - $sql = 'SELECT activite, adresse, create_db, canchgftpprofil, canchgprofil, ville, - societe, pays, usr_mail, fax, usr_prenom, geonameid, invite, fonction, last_conn, lastModel, - usr_nom, ldap_created, locale, usr_login, mail_locked, mail_notifications, nonce, usr_password, push_list, - request_notifications, salted_password, usr_sexe, tel, timezone, cpostal, usr_creationdate, usr_modificationdate - FROM usr'; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $n = 0; - - foreach ($rows as $row) { - $user = new User(); - $user->setActivity($row['activite']); - $user->setAddress($row['adresse']); - $user->setAdmin(!!$row['create_db']); - $user->setCanChangeFtpProfil(!!$row['canchgftpprofil']); - $user->setCanChangeProfil(!!$row['canchgprofil']); - $user->setCity($row['ville']); - $user->setCompany($row['societe']); - $user->setCountry((string) $row['pays']); - $user->setEmail($row['usr_mail']); - $user->setFax($row['fax']); - $user->setFirstName($row['usr_prenom']); - if ($row['geonameid'] > 0) { - $user->setGeonameId($row['geonameid']); - } - $user->setGuest(!!$row['invite']); - $user->setJob($row['fonction']); - $user->setLastConnection(new \DateTime($row['last_conn'])); - $user->setLastModel($row['lastModel']); - $user->setLastName($row['usr_nom']); - $user->setLdapCreated(!!$row['ldap_created']); - try { - $user->setLocale($row['locale']); - } catch (\InvalidArgumentException $e ) { - - } - $user->setLogin($row['usr_login']); - - if (substr($row['usr_login'], 0, 10) === '(#deleted_') { - $user->setDeleted(true); - } - - $user->setMailLocked(!!$row['mail_locked']); - $user->setMailNotificationsActivated(!!$row['mail_notifications']); - $user->setNonce($row['nonce']); - $user->setPassword($row['usr_password']); - $user->setPushList($row['push_list']); - $user->setRequestNotificationsActivated(!!$row['request_notifications']); - $user->setSaltedPassword(!!$row['salted_password']); - - switch ($row['usr_sexe']) { - case 0: - $gender = User::GENDER_MISS; - break; - case 1: - $gender = User::GENDER_MRS; - break; - case 2: - $gender = User::GENDER_MR; - break; - default: - $gender = null; - } - - $user->setGender($gender); - $user->setPhone($row['tel']); - $user->setTimezone($row['timezone']); - $user->setZipCode($row['cpostal']); - $user->setCreated(new \DateTime($row['usr_creationdate'])); - $user->setupdated(new \DateTime($row['usr_modificationdate'])); - - $em->persist($user); - - $n++; - - if ($n % 100 === 0) { - $em->flush(); - $em->clear(); - } - } - - $em->flush(); - $em->clear(); - } - - /** - * Sets model from usr table. - */ - private function updateModels(EntityManager $em, $conn) - { - $sql = "SELECT model_of, usr_login - FROM usr - WHERE model_of > 0"; - $stmt = $conn->prepare($sql); - $stmt->execute(); - $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $n = 0; - - $repository = $em->getRepository('Phraseanet:User'); - - foreach ($rows as $row) { - $template = $repository->findOneByLogin($row['usr_login']); - - if (null === $loginOwner = $this->getLoginFromId($conn, $row['model_of'])) { - // remove template with no owner - $em->remove($template); - } else { - $owner = $repository->findOneByLogin($loginOwner); - $template->setModelOf($owner); - $em->persist($owner); - } - - $n++; - - if ($n % 100 === 0) { - $em->flush(); - $em->clear(); - } - } - - $em->flush(); - $em->clear(); - } - - /** - * Returns user login from its id. - */ - private function getLoginFromId($conn, $id) - { - $sql = "SELECT usr_login - FROM usr - WHERE usr_id = :id"; - - $stmt = $conn->prepare($sql); - $stmt->execute([':id' => $id]); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - if (count($row) === 0) { - return null; - } - - return $row['usr_login']; - } -} diff --git a/lib/classes/patch/390alpha3a.php b/lib/classes/patch/390alpha3a.php index 8d6ac8d39f..0a90796cf8 100644 --- a/lib/classes/patch/390alpha3a.php +++ b/lib/classes/patch/390alpha3a.php @@ -12,7 +12,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\UserQuery; -class patch_390alpha3a implements patchInterface +class patch_390alpha3a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.3'; @@ -49,7 +49,7 @@ class patch_390alpha3a implements patchInterface */ public function getDoctrineMigrations() { - return ['user-query']; + return ['user', 'user-query']; } /** @@ -73,9 +73,13 @@ class patch_390alpha3a implements patchInterface $em = $app['EM']; foreach ($rs as $row) { + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } + $userQuery = new UserQuery(); $userQuery->setQuery($row['query']); - $userQuery->setUsrId($row['usr_id']); + $userQuery->setUser($user); $em->persist($userQuery); diff --git a/lib/classes/patch/390alpha4a.php b/lib/classes/patch/390alpha4a.php index dd359d5928..341ae9b9f7 100644 --- a/lib/classes/patch/390alpha4a.php +++ b/lib/classes/patch/390alpha4a.php @@ -12,7 +12,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\UserSetting; -class patch_390alpha4a implements patchInterface +class patch_390alpha4a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.4'; @@ -77,10 +77,14 @@ class patch_390alpha4a implements patchInterface continue; } + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } + $userSetting = new UserSetting(); $userSetting->setName($row['prop']); $userSetting->setValue($row['value']); - $userSetting->setUsrId($row['usr_id']); + $userSetting->setUser($user); $em->persist($userSetting); diff --git a/lib/classes/patch/390alpha5a.php b/lib/classes/patch/390alpha5a.php index b94bd15406..85743d89ae 100644 --- a/lib/classes/patch/390alpha5a.php +++ b/lib/classes/patch/390alpha5a.php @@ -12,7 +12,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\UserNotificationSetting; -class patch_390alpha5a implements patchInterface +class patch_390alpha5a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.5'; @@ -74,10 +74,14 @@ class patch_390alpha5a implements patchInterface $em = $app['EM']; foreach ($rs as $row) { + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { + continue; + } + $userSetting = new UserNotificationSetting(); $userSetting->setName($row['prop']); $userSetting->setValue($row['value']); - $userSetting->setUsrId($row['usr_id']); + $userSetting->setUser($user); $em->persist($userSetting); diff --git a/lib/classes/patch/390alpha6a.php b/lib/classes/patch/390alpha6a.php index a6fd3b62d5..18868b0fdd 100644 --- a/lib/classes/patch/390alpha6a.php +++ b/lib/classes/patch/390alpha6a.php @@ -13,8 +13,9 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\FtpExport; use Alchemy\Phrasea\Model\Entities\FtpExportElement; use Gedmo\Timestampable\TimestampableListener; +use Doctrine\ORM\NoResultException; -class patch_390alpha6a implements patchInterface +class patch_390alpha6a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.6'; @@ -93,9 +94,7 @@ class patch_390alpha6a implements patchInterface $n = 0; foreach ($rs as $row) { - try { - $user = \User_Adapter::getInstance($row['usr_id'], $app); - } catch (\Exception $e) { + if (null === $user = $this->loadUser($app['EM'], $row['usr_id'])) { continue; } diff --git a/lib/classes/patch/390alpha7a.php b/lib/classes/patch/390alpha7a.php index cbd6a99f0e..ecdb7e931e 100644 --- a/lib/classes/patch/390alpha7a.php +++ b/lib/classes/patch/390alpha7a.php @@ -18,7 +18,7 @@ use Alchemy\Phrasea\Model\Entities\FeedPublisher; use Alchemy\Phrasea\Model\Entities\FeedToken; use Doctrine\ORM\Query\ResultSetMapping; -class patch_390alpha7a implements patchInterface +class patch_390alpha7a extends patchAbstract { /** @var string */ private $release = '3.9.0-alpha.7'; @@ -133,12 +133,16 @@ class patch_390alpha7a implements patchInterface $fpRes = $fpStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fpRes as $fpRow) { + if (null === $user = $this->loadUser($app['EM'], $fpRow['usr_id'])) { + continue; + } + $feedPublisher = new FeedPublisher(); $feedPublisher->setFeed($feed); $feed->addPublisher($feedPublisher); $feedPublisher->setCreatedOn(new \DateTime($fpRow['created_on'])); $feedPublisher->setIsOwner((Boolean) $fpRow['owner']); - $feedPublisher->setUsrId($fpRow['usr_id']); + $feedPublisher->setUser($user); $feStmt->execute([':feed_id' => $row['id'], ':publisher_id' => $fpRow['id']]); $feRes = $feStmt->fetchAll(\PDO::FETCH_ASSOC); @@ -177,10 +181,14 @@ class patch_390alpha7a implements patchInterface $ftRes = $ftStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($ftRes as $ftRow) { + if (null === $user = $this->loadUser($app['EM'], $ftRow['usr_id'])) { + continue; + } + $token = new FeedToken(); $token->setFeed($feed); $feed->addToken($token); - $token->setUsrId($ftRow['usr_id']); + $token->setUser($user); $token->setValue($ftRow['token']); $em->persist($token); @@ -204,8 +212,12 @@ class patch_390alpha7a implements patchInterface $faRes = $faStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($faRes as $faRow) { + if (null === $user = $this->loadUser($app['EM'], $faRow['usr_id'])) { + continue; + } + $token = new AggregateToken(); - $token->setUsrId($faRow['usr_id']); + $token->setUser($user); $token->setValue($faRow['token']); $em->persist($token); diff --git a/lib/classes/patch/390alpha9a.php b/lib/classes/patch/390alpha9a.php index 83ff830465..d804188b2e 100644 --- a/lib/classes/patch/390alpha9a.php +++ b/lib/classes/patch/390alpha9a.php @@ -57,7 +57,6 @@ class patch_390alpha9a implements patchInterface public function apply(base $appbox, Application $app) { $this->updateRegistry($app); - $this->updateUsers($appbox); $this->updateDoctrineUsers($app); $this->updateDataboxPrefs($appbox); } @@ -78,27 +77,6 @@ class patch_390alpha9a implements patchInterface $stmt->closeCursor(); } - private function updateUsers(\appbox $appbox) - { - $sql = 'SELECT usr_id, locale FROM usr WHERE locale IS NOT NULL'; - $stmt = $appbox->get_connection()->prepare($sql); - $stmt->execute(); - $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); - $stmt->closeCursor(); - - $sql = 'UPDATE usr SET locale = :locale WHERE usr_id = :usr_id'; - $stmt = $appbox->get_connection()->prepare($sql); - - foreach ($rows as $row) { - $stmt->execute([ - ':locale' => $this->extractLocale($row['locale']), - ':usr_id' => $row['usr_id'], - ]); - } - - $stmt->closeCursor(); - } - private function updateDoctrineUsers(Application $app) { $dql = 'SELECT u FROM Phraseanet:User u WHERE u.locale IS NOT NULL'; diff --git a/lib/classes/patch/390alpha10a.php b/lib/classes/patch/390alpha9b.php similarity index 98% rename from lib/classes/patch/390alpha10a.php rename to lib/classes/patch/390alpha9b.php index a91eac55cb..0c6b91bcf0 100644 --- a/lib/classes/patch/390alpha10a.php +++ b/lib/classes/patch/390alpha9b.php @@ -12,10 +12,10 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Entities\Task; -class patch_390alpha10a implements patchInterface +class patch_390alpha9b implements patchInterface { /** @var string */ - private $release = '3.9.0-alpha.10'; + private $release = '3.9.0-alpha.9b'; /** @var array */ private $concern = [base::APPLICATION_BOX]; @@ -33,7 +33,7 @@ class patch_390alpha10a implements patchInterface */ public function require_all_upgrades() { - return false; + return true; } /** diff --git a/lib/classes/patchAbstract.php b/lib/classes/patchAbstract.php new file mode 100644 index 0000000000..ec094e4f10 --- /dev/null +++ b/lib/classes/patchAbstract.php @@ -0,0 +1,28 @@ +createQuery('SELECT PARTIAL u.{id} FROM Phraseanet:User u WHERE u.id = :id') + ->setParameters(['id' => $usrId]) + ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) + ->getSingleResult(); + } catch (NoResultException $e) { + + } + } +} diff --git a/lib/classes/queries.php b/lib/classes/queries.php index 626c6dfcf6..fed56676f8 100644 --- a/lib/classes/queries.php +++ b/lib/classes/queries.php @@ -190,7 +190,7 @@ class queries $queries = $app['EM'] ->getRepository('Phraseanet:UserQuery') - ->findBy(['usrId' => $usrId], ['created' => 'ASC'], 25, 0); + ->findBy(['user' => $usrId], ['created' => 'ASC'], 25, 0); foreach ($queries as $query) { $history .= '
  • getQuery()) . '\')">' . $query->getQuery() . '
  • '; diff --git a/lib/classes/record/Interface.php b/lib/classes/record/Interface.php index 7d457eff91..b88880691a 100644 --- a/lib/classes/record/Interface.php +++ b/lib/classes/record/Interface.php @@ -9,6 +9,7 @@ * file that was distributed with this source code. */ +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\SearchEngine\SearchEngineInterface; use Doctrine\ORM\EntityManager; @@ -95,5 +96,5 @@ interface record_Interface public function log_view($log_id, $referrer, $gv_sit); - public function get_container_baskets(EntityManager $em, User_Adapter $user); + public function get_container_baskets(EntityManager $em, User $user); } diff --git a/lib/classes/record/adapter.php b/lib/classes/record/adapter.php index 6d756ae8f2..2088a2547e 100644 --- a/lib/classes/record/adapter.php +++ b/lib/classes/record/adapter.php @@ -13,6 +13,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Border\File; use Alchemy\Phrasea\Metadata\Tag\TfFilename; use Alchemy\Phrasea\Metadata\Tag\TfBasename; +use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Serializer\CaptionSerializer; use Alchemy\Phrasea\SearchEngine\SearchEngineInterface; use Alchemy\Phrasea\SearchEngine\SearchEngineOptions; @@ -1131,9 +1132,10 @@ class record_adapter implements record_Interface, cache_cacheableInterface { $connbas = connection::getPDOConnection($this->app, $this->get_sbas_id()); - $sql = 'UPDATE record SET status = :status WHERE record_id= :record_id'; + $sql = 'UPDATE record SET status = 0b' . $status . ' + WHERE record_id= :record_id'; $stmt = $connbas->prepare($sql); - $stmt->execute([':record_id' => $this->record_id, ':status' => bindec($status)]); + $stmt->execute([':record_id' => $this->record_id]); $stmt->closeCursor(); $sql = 'REPLACE INTO status (id, record_id, name, value) VALUES (null, :record_id, :name, :value)'; @@ -1610,7 +1612,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface * @todo de meme avec stories * @return Array */ - public function get_container_baskets(EntityManager $em, User_Adapter $user) + public function get_container_baskets(EntityManager $em, User $user) { return $em ->getRepository('Phraseanet:Basket') @@ -1677,7 +1679,7 @@ class record_adapter implements record_Interface, cache_cacheableInterface $params = [ ':site' => $this->app['conf']->get(['main', 'key']), - ':usr_id' => $this->app['authentication']->getUser()->get_id(), + ':usr_id' => $this->app['authentication']->getUser()->getId(), ':record_id' => $this->get_record_id(), ]; } else { @@ -1726,14 +1728,12 @@ class record_adapter implements record_Interface, cache_cacheableInterface ON (g.rid_parent = r.record_id) WHERE rid_child = :record_id'; - $params = [ - ':site' => $this->app['conf']->get(['main', 'key']) - , ':usr_id' => $this->app['authentication']->getUser()->get_id() - , ':record_id' => $this->get_record_id() - ]; - $stmt = $this->get_databox()->get_connection()->prepare($sql); - $stmt->execute($params); + $stmt->execute([ + ':site' => $this->app['conf']->get(['main', 'key']), + ':usr_id' => $this->app['authentication']->getUser()->getId(), + ':record_id' => $this->get_record_id(), + ]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); diff --git a/lib/classes/record/orderElement.php b/lib/classes/record/orderElement.php index 200e018685..1b372d7dda 100644 --- a/lib/classes/record/orderElement.php +++ b/lib/classes/record/orderElement.php @@ -52,9 +52,9 @@ class record_orderElement extends record_adapter public function get_order_master_name() { if ($this->order_master_id) { - $user = User_Adapter::getInstance($this->order_master_id, $this->app); + $user = $this->app['manipulator.user']->getRepository()->find($this->order_master_id); - return $user->get_display_name(); + return $user->getDisplayName(); } return ''; diff --git a/lib/classes/record/preview.php b/lib/classes/record/preview.php index 311263ff0b..a24a7fbd0a 100644 --- a/lib/classes/record/preview.php +++ b/lib/classes/record/preview.php @@ -338,7 +338,7 @@ class record_preview extends record_adapter if (! $report) { $sql .= ' AND ((l.usrid = :usr_id AND l.site= :site) OR action="add")'; - $params[':usr_id'] = $this->app['authentication']->getUser()->get_id(); + $params[':usr_id'] = $this->app['authentication']->getUser()->getId(); $params[':site'] = $this->app['conf']->get(['main', 'key']); } @@ -366,19 +366,11 @@ class record_preview extends record_adapter $tab[$hour][$site][$action] = []; if ( ! isset($tab[$hour][$site][$action][$row['usr_id']])) { - $user = null; - - try { - $user = \User_Adapter::getInstance($row['usr_id'], $this->app); - } catch (\Exception $e) { - - } - $tab[$hour][$site][$action][$row['usr_id']] = [ 'final' => [] , 'comment' => [] - , 'user' => $user + , 'user' => $this->app['manipulator.user']->getRepository()->find($row['usr_id']) ]; } diff --git a/lib/classes/set/export.php b/lib/classes/set/export.php index 0a850ba7ea..b9e1e2321f 100644 --- a/lib/classes/set/export.php +++ b/lib/classes/set/export.php @@ -11,6 +11,7 @@ use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Model\Serializer\CaptionSerializer; +use Alchemy\Phrasea\Model\Entities\User; use Symfony\Component\Filesystem\Filesystem; class set_export extends set_abstract @@ -53,9 +54,10 @@ class set_export extends set_abstract } if ($sstid != "") { - $Basket = $app['converter.basket']->convert($sstid); - $app['acl.basket']->hasAccess($Basket, $app['authentication']->getUser()); + $repository = $app['EM']->getRepository('Phraseanet:Basket'); + /* @var $repository Alchemy\Phrasea\Model\Repositories\BasketRepository */ + $Basket = $repository->findUserBasket($sstid, $app['authentication']->getUser(), false); $this->exportName = str_replace([' ', '\\', '/'], '_', $Basket->getName()) . "_" . date("Y-n-d"); foreach ($Basket->getElements() as $basket_element) { @@ -228,34 +230,34 @@ class set_export extends set_abstract $lst_base_id = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base()); if ($hasadminright) { - $sql = "SELECT usr.usr_id,usr_login,usr.usr_mail, FtpCredential.* + $sql = "SELECT Users.id AS usr_id ,Users.login AS usr_login ,Users.email AS usr_mail, FtpCredential.* FROM ( - FtpCredential INNER JOIN usr ON ( - FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id + FtpCredential INNER JOIN Users ON ( + FtpCredential.active = 1 AND FtpCredential.user_id = Users.id ) INNER JOIN basusr ON ( - usr.usr_id=basusr.usr_id + Users.id=basusr.usr_id AND (basusr.base_id= '" . implode("' OR basusr.base_id='", $lst_base_id) . "' ) ) ) - GROUP BY usr_id "; + GROUP BY Users.id "; $params = []; } elseif ($this->app['conf']->get(['registry', 'ftp', 'ftp-user-access'])) { - $sql = "SELECT usr.usr_id,usr_login,usr.usr_mail, FtpCredential.* + $sql = "SELECT Users.id AS usr_id ,Users.login AS usr_login ,Users.email AS usr_mail, FtpCredential.* FROM ( - FtpCredential INNER JOIN usr ON ( - FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id + FtpCredential INNER JOIN Users ON ( + FtpCredential.active = 1 AND FtpCredential.id = Users.id ) INNER JOIN basusr ON ( - usr.usr_id=basusr.usr_id - AND usr.usr_id = :usr_id + Users.id=basusr.usr_id + AND Users.id = :usr_id AND (basusr.base_id= '" . implode("' OR basusr.base_id='", $lst_base_id) . "' ) ) ) - GROUP BY usr_id "; - $params = [':usr_id' => $app['authentication']->getUser()->get_id()]; + GROUP BY Users.id "; + $params = [':usr_id' => $app['authentication']->getUser()->getId()]; } $datas[] = [ @@ -269,7 +271,7 @@ class set_export extends set_abstract 'prefix_folder' => 'Export_' . date("Y-m-d_H.i.s"), 'passive' => false, 'max_retry' => 5, - 'sendermail' => $app['authentication']->getUser()->get_email() + 'sendermail' => $app['authentication']->getUser()->getEmail() ]; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); @@ -293,7 +295,7 @@ class set_export extends set_abstract 'passive' => !! $row['passive'], 'max_retry' => $row['max_retry'], 'usr_mail' => $row['usr_mail'], - 'sender_mail' => $app['authentication']->getUser()->get_email() + 'sender_mail' => $app['authentication']->getUser()->getEmail() ]; } @@ -387,15 +389,15 @@ class set_export extends set_abstract /** * - * @param User_Adapter $user - * @param Filesystem $filesystem - * @param Array $subdefs - * @param boolean $rename_title - * @param boolean $includeBusinessFields + * @param User $user + * @param Filesystem $filesystem + * @param Array $subdefs + * @param boolean $rename_title + * @param boolean $includeBusinessFields * * @return Array */ - public function prepare_export(User_Adapter $user, Filesystem $filesystem, Array $subdefs, $rename_title, $includeBusinessFields) + public function prepare_export(User $user, Filesystem $filesystem, Array $subdefs, $rename_title, $includeBusinessFields) { if (!is_array($subdefs)) { throw new Exception('No subdefs given'); @@ -629,7 +631,7 @@ class set_export extends set_abstract if (in_array('caption', $subdefs)) { $caption_dir = $this->app['root.path'] . '/tmp/desc_tmp/' - . time() . $this->app['authentication']->getUser()->get_id() . '/'; + . time() . $this->app['authentication']->getUser()->getId() . '/'; $filesystem->mkdir($caption_dir, 0750); @@ -651,7 +653,7 @@ class set_export extends set_abstract if (in_array('caption-yaml', $subdefs)) { $caption_dir = $this->app['root.path'] . '/tmp/desc_tmp/' - . time() . $this->app['authentication']->getUser()->get_id() . '/'; + . time() . $this->app['authentication']->getUser()->getId() . '/'; $filesystem->mkdir($caption_dir, 0750); @@ -808,7 +810,7 @@ class set_export extends set_abstract $params = [ ':remain_dl' => $app['acl']->get($app['authentication']->getUser())->remaining_download($base_id) , ':base_id' => $base_id - , ':usr_id' => $app['acl']->get($app['authentication']->getUser())->get_id() + , ':usr_id' => $app['acl']->get($app['authentication']->getUser())->getId() ]; $stmt->execute($params); diff --git a/lib/classes/set/exportftp.php b/lib/classes/set/exportftp.php index acc26685c2..a667d4a498 100644 --- a/lib/classes/set/exportftp.php +++ b/lib/classes/set/exportftp.php @@ -33,13 +33,13 @@ class set_exportftp extends set_export { $email_dest = ''; if ($usr_to) { - $user_t = User_Adapter::getInstance($usr_to, $this->app); - $email_dest = $user_t->get_email(); + $user_t = $this->app['manipulator.user']->getRepository()->find($usr_to); + $email_dest = $user_t->getEmail(); } $text_mail_receiver = "Bonjour,\n" . "L'utilisateur " - . $this->app['authentication']->getUser()->get_display_name() . " (login : " . $this->app['authentication']->getUser()->get_login() . ") " + . $this->app['authentication']->getUser()->getDisplayName() . " (login : " . $this->app['authentication']->getUser()->getLogin() . ") " . "a fait un transfert FTP sur le serveur ayant comme adresse \"" . $host . "\" avec le login \"" . $login . "\" " . "et pour repertoire de destination \"" @@ -61,7 +61,7 @@ class set_exportftp extends set_export ->setUser($this->app['authentication']->getUser()) ->setTextMailSender($text_mail_sender) ->setTextMailReceiver($text_mail_receiver) - ->setSendermail($this->app['authentication']->getUser()->get_email()) + ->setSendermail($this->app['authentication']->getUser()->getEmail()) ->setDestfolder($destfolder) ->setPassif($passif == '1') ->setPwd($password) diff --git a/lib/conf.d/bases_structure.xml b/lib/conf.d/bases_structure.xml index 6a9dfccd33..b0ebea2227 100644 --- a/lib/conf.d/bases_structure.xml +++ b/lib/conf.d/bases_structure.xml @@ -1485,65 +1485,6 @@ InnoDB - - - - - id - int(11) unsigned - - auto_increment - - - - - key - char(32) - - - - - ascii_bin - - - value - varchar(1024) - - - - - - - type - enum('string','boolean','array','integer','text','binary','timezone','enum_multi','enum') - - - string - - - - - - PRIMARY - PRIMARY - - id - - - - UNIQUE - UNIQUE - - key - - - - InnoDB -
    - - - - @@ -2401,499 +2342,6 @@ InnoDB
    - - - - usr_id - - int(11) unsigned - - auto_increment - - - - - - ldap_created - int(1) unsigned - - - - 0 - - - - - usr_sexe - int(1) unsigned - YES - - - - - - usr_nom - varchar(50) - - - - - - - - - usr_prenom - - varchar(50) - - - - - - - - - usr_login - varchar(128) - - - - - - utf8_bin - - - - usr_password - varchar(128) - - - - - - - utf8_bin - - - usr_mail - - varchar(64) - YES - - - - - - - - usr_creationdate - datetime - - - - 0000-00-00 00:00:00 - - - - - usr_modificationdate - datetime - - - - 0000-00-00 00:00:00 - - - - - adresse - text - - - - - - - - - ville - varchar(64) - - - - - - - - - cpostal - varchar(32) - - - - - - - - - tel - varchar(32) - - - - - - - - - fax - - varchar(32) - - - - - - - - - fonction - varchar(64) - - - - - - - - - societe - varchar(64) - - - - - - - - - activite - varchar(200) - - - - - - - - - code8 - int(10) unsigned - - - - - 0 - - - - pays - varchar(64) - - YES - - - - - - - - last_conn - datetime - - - - 0000-00-00 00:00:00 - - - - - model_of - int(11) unsigned - - - - 0 - - - - - create_db - tinyint(3) - - - - - 0 - - - - lastModel - varchar(50) - - - - - - - canchgprofil - tinyint(1) - - - - - 1 - - - - canchgftpprofil - tinyint(1) unsigned - - - - - 1 - - - - invite - - tinyint(1) unsigned - - - - 0 - - - - mail_locked - - tinyint(1) unsigned - - - - 0 - - - - geonameid - - int(7) unsigned - YES - - - - - - - updated - - tinyint(1) unsigned - - - - 0 - - - - locale - enum('fr','en','ar','de','es','zh','nb','nl') - YES - - - - ascii_bin - - - mail_notifications - tinyint(1) unsigned - - - 1 - - - - request_notifications - tinyint(1) unsigned - - - 1 - - - - push_list - text - - - - - - - timezone - varchar(128) - - - - - - - salted_password - tinyint(1) unsigned - - - 0 - - - - nonce - char(16) - YES - - utf8_bin - - - - - - PRIMARY - PRIMARY - - usr_id - - - - usr_login - UNIQUE - - usr_login - - - - usr_mail - INDEX - - usr_mail - - - - unique_usr_mail - UNIQUE - - usr_mail - - - - model_of - INDEX - - model_of - - - - salted_password - INDEX - - salted_password - - - - invite - INDEX - - invite - - - - - - null - 2 - null - autoregister - autoregister - NOW() - NOW() - 0000-00-00 00:00:00 - 0 - 0 - 0 - 0 - - - - null - 2 - null - invite - invite - NOW() - NOW() - 0000-00-00 00:00:00 - 0 - 0 - 0 - 0 - - - - InnoDB -
    - - - - usr_id - int(11) unsigned - - - - - - - prop - char(128) - - - 0 - - - - value - varbinary(32768) - YES - - 0 - - - - - - couple - UNIQUE - - prop - usr_id - - - - usr_id - INDEX - - usr_id - - - - InnoDB -
    diff --git a/lib/conf.d/migrations.yml b/lib/conf.d/migrations.yml index 27f488abe2..341bd40e73 100644 --- a/lib/conf.d/migrations.yml +++ b/lib/conf.d/migrations.yml @@ -42,3 +42,15 @@ migrations: migration13: version: ftp-export class: Alchemy\Phrasea\Setup\DoctrineMigrations\FtpExportMigration + migration14: + version: user-field + class: Alchemy\Phrasea\Setup\DoctrineMigrations\UserFieldMigration + migration15: + version: user-id-field-delete + class: Alchemy\Phrasea\Setup\DoctrineMigrations\DeleteUsrIdFieldMigration + migration16: + version: user-list + class: Alchemy\Phrasea\Setup\DoctrineMigrations\UserListMigration + migration17: + version: user-auth-provider + class: Alchemy\Phrasea\Setup\DoctrineMigrations\UserAuthProviderMigration diff --git a/templates/mobile/api/auth/end_user_authorization.html.twig b/templates/mobile/api/auth/end_user_authorization.html.twig index cd70513e63..c4f018345d 100644 --- a/templates/mobile/api/auth/end_user_authorization.html.twig +++ b/templates/mobile/api/auth/end_user_authorization.html.twig @@ -55,7 +55,7 @@ {% else %} {% if app['authentication'].getUser() is not none %} - {% set username = '' ~ app['authentication'].getUser().get_display_name() ~ '' %} + {% set username = '' ~ app['authentication'].getUser().getDisplayName() ~ '' %}
    {% if app['authentication'].getUser() is not none %} - {% set username = '' ~ app['authentication'].getUser().get_display_name() ~ '' %} + {% set username = '' ~ app['authentication'].getUser().getDisplayName() ~ '' %}
    {{ thumbnail.format100percent(record.get_preview()) }} {% if basket_element.getBasket().getValidation() %} - {% if basket_element.getBasket().getValidation().getParticipant(app['authentication'].getUser(), app).getCanAgree() %} + {% if basket_element.getBasket().getValidation().getParticipant(app['authentication'].getUser()).getCanAgree() %}
    - + - +
    {% endif %} diff --git a/templates/mobile/lightbox/note_form.html.twig b/templates/mobile/lightbox/note_form.html.twig index 2305266399..0cedce20d1 100644 --- a/templates/mobile/lightbox/note_form.html.twig +++ b/templates/mobile/lightbox/note_form.html.twig @@ -19,7 +19,7 @@
    + {% if basket_element.getUserValidationDatas(app['authentication'].getUser()).getNote() == '' %}placeholder="Note"{% endif %}>{{basket_element.getUserValidationDatas(app['authentication'].getUser()).getNote()}}
    diff --git a/templates/mobile/lightbox/sc_note.html.twig b/templates/mobile/lightbox/sc_note.html.twig index 40b07e2563..0114bd0b9d 100644 --- a/templates/mobile/lightbox/sc_note.html.twig +++ b/templates/mobile/lightbox/sc_note.html.twig @@ -1,5 +1,5 @@ {% for validationDatas in basket_element.getValidationDatas() %} - {% set is_mine = validationDatas.getParticipant().getUser(app).get_id() == app['authentication'].getUser().get_id() %} + {% set is_mine = validationDatas.getParticipant().getUser().getId() == app['authentication'].getUser().getId() %} {% if validationDatas.getNote() != '' or (validationDatas.getAgreement() is not null and is_mine) %}
  • @@ -7,7 +7,7 @@ {% endif %} - {{ validationDatas.getParticipant().getUser(app).get_display_name() }} + {{ validationDatas.getParticipant().getUser().getDisplayName() }}

    {% if validationDatas.getNote() != '' %}

    {{ 'validation:: note' | trans }} : {{ validationDatas.getNote()|nl2br }}

    diff --git a/templates/mobile/lightbox/validate.html.twig b/templates/mobile/lightbox/validate.html.twig index 0caa81edec..5a6dc9463a 100644 --- a/templates/mobile/lightbox/validate.html.twig +++ b/templates/mobile/lightbox/validate.html.twig @@ -4,7 +4,7 @@ {% block javascript %} @@ -30,8 +30,8 @@
      {% for basket_element in basket.getElements() %}
    • - {% if basket_element.getBasket().getValidation() and basket_element.getBasket().getValidation().getParticipant(app['authentication'].getUser(), app).getCanAgree() %} -
      + {% if basket_element.getBasket().getValidation() and basket_element.getBasket().getValidation().getParticipant(app['authentication'].getUser()).getCanAgree() %} +
      {% endif %} @@ -43,7 +43,7 @@
  • - {% if basket.getValidation() and basket.getValidation().getParticipant(app['authentication'].getUser(), app).getCanAgree() %} + {% if basket.getValidation() and basket.getValidation().getParticipant(app['authentication'].getUser()).getCanAgree() %}