Merge branch 'replace_users' of https://github.com/nlegoff/Phraseanet into nlegoff-replace_users

Conflicts:
	lib/classes/ACL.php
	lib/classes/User/Adapter.php
	lib/classes/eventsmanager/notify/autoregister.php
	lib/classes/eventsmanager/notify/order.php
	lib/classes/eventsmanager/notify/orderdeliver.php
	lib/classes/eventsmanager/notify/ordernotdelivered.php
	lib/classes/eventsmanager/notify/push.php
	lib/classes/eventsmanager/notify/register.php
	lib/classes/eventsmanager/notify/validate.php
	lib/classes/eventsmanager/notify/validationdone.php
	lib/classes/eventsmanager/notify/validationreminder.php
	lib/classes/module/report/add.php
	lib/classes/module/report/edit.php
	lib/classes/module/report/push.php
	lib/classes/module/report/sent.php
	lib/classes/module/report/validate.php
	lib/classes/record/preview.php
This commit is contained in:
Romain Neutron
2014-02-20 18:02:27 +01:00
393 changed files with 30866 additions and 7165 deletions

View File

@@ -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" - 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 mkdir -p /var/sphinx/datas
- sudo chmod -R 0777 /var/sphinx - 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 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" - 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.sql_mode= "";'
- mysql -e 'SET @@global.max_allowed_packet= 33554432;'
- mysql -e 'SET @@global.wait_timeout= 999999;' - mysql -e 'SET @@global.wait_timeout= 999999;'
- git clone git://github.com/alchemy-fr/Phraseanet-Extension.git - git clone git://github.com/alchemy-fr/Phraseanet-Extension.git
- sh -c "cd Phraseanet-Extension && phpize && ./configure --quiet && make -j --quiet && sudo make install" - sh -c "cd Phraseanet-Extension && phpize && ./configure --quiet && make -j --quiet && sudo make install"

View File

@@ -10,8 +10,8 @@ then
else else
echo "Dependencies retrieval discarded" echo "Dependencies retrieval discarded"
fi 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 '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 ab_test;create database db_test; create database ab_unitTests; create 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 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 "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 sudo mysql -e "source `pwd`/hudson/fixtures.sql" || exit 1

View File

@@ -14,6 +14,7 @@ require_once __DIR__ . '/../../vendor/autoload.php';
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Behat\Behat\Exception\PendingException; use Behat\Behat\Exception\PendingException;
use Behat\MinkExtension\Context\MinkContext; use Behat\MinkExtension\Context\MinkContext;
use Alchemy\Phrasea\Model\Entities\User;
class GuiContext extends MinkContext class GuiContext extends MinkContext
{ {
@@ -65,14 +66,12 @@ class GuiContext extends MinkContext
*/ */
public function aUserDoesNotExist($login) public function aUserDoesNotExist($login)
{ {
if (false !== $userId = \User_Adapter::get_usr_id_from_login($this->app, $login)) { if (null !== $user = $this->app['manipulator.user']->getRepository()->findByLogin($login)) {
$user = \User_Adapter::getInstance($userId, $this->app); $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->ACL()->revoke_access_from_bases(array_keys(
$this->app['authentication']->getUser()->ACL()->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) public function aUserExistsWithAsPassword($login, $password)
{ {
if (false === \User_Adapter::get_usr_id_from_login($this->app, $login)) { if (null === $user = $this->app['manipulator.user']->getRepository()->findByLogin($login)) {
\User_Adapter::create( $this->app['manipulator.user']->create($login, $password, null, false);
$this->app,
$login,
$password,
$login,
false
);
} }
} }
@@ -168,24 +161,15 @@ class GuiContext extends MinkContext
*/ */
public function userGuestAccessIsEnable() public function userGuestAccessIsEnable()
{ {
if (false === $usrId = \User_Adapter::get_usr_id_from_login($this->app, 'invite')) { if (null === $user = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) {
$user = \User_Adapter::create( $user = $this->app['manipulator.user']->create(User::USER_GUEST, '');
$this->app,
'invite',
'',
null,
false,
true
);
} else {
$user = \User_Adapter::getInstance($usrId, $this->app);
} }
$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 ($this->app['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) { 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() public function userGuestAccessIsDisable()
{ {
if (false !== $usrId = \User_Adapter::get_usr_id_from_login($this->app, 'invite')) { if (null !== $user = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) {
$user = \User_Adapter::getInstance($usrId, $this->app);
foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) { 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) 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)); 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); $this->app['authentication']->openAccount($user);
throw new PendingException(); throw new PendingException();

View File

@@ -12,11 +12,11 @@
namespace Alchemy\Phrasea\ACL; namespace Alchemy\Phrasea\ACL;
use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Model\Entities\Basket;
use User_Adapter; use Alchemy\Phrasea\Model\Entities\User;
class BasketACL class BasketACL
{ {
public function hasAccess(Basket $basket, User_Adapter $user) public function hasAccess(Basket $basket, User $user)
{ {
if ($this->isOwner($basket, $user)) { if ($this->isOwner($basket, $user)) {
return true; return true;
@@ -24,7 +24,7 @@ class BasketACL
if ($basket->getValidation()) { if ($basket->getValidation()) {
foreach ($basket->getValidation()->getParticipants() as $participant) { foreach ($basket->getValidation()->getParticipants() as $participant) {
if ($participant->getUsrId() === $user->get_id()) { if ($participant->getUser()->getId() === $user->getId()) {
return true; return true;
} }
} }
@@ -33,8 +33,8 @@ class BasketACL
return false; 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();
} }
} }

View File

@@ -111,6 +111,7 @@ use Alchemy\Phrasea\Core\Provider\TokensServiceProvider;
use Alchemy\Phrasea\Core\Provider\TranslationServiceProvider; use Alchemy\Phrasea\Core\Provider\TranslationServiceProvider;
use Alchemy\Phrasea\Core\Provider\UnicodeServiceProvider; use Alchemy\Phrasea\Core\Provider\UnicodeServiceProvider;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Form\Extension\HelpTypeExtension; use Alchemy\Phrasea\Form\Extension\HelpTypeExtension;
use Alchemy\Phrasea\Twig\JSUniqueID; use Alchemy\Phrasea\Twig\JSUniqueID;
use Alchemy\Phrasea\Twig\Camelize; use Alchemy\Phrasea\Twig\Camelize;
@@ -773,13 +774,11 @@ class Application extends SilexApplication
*/ */
public function isGuestAllowed() public function isGuestAllowed()
{ {
$usrId = \User_Adapter::get_usr_id_from_login($this, 'invite'); if (null === $user = $this['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) {
if (!$usrId) {
return false; 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;
} }
/** /**

View File

@@ -37,7 +37,7 @@ class ACLProvider
* *
* @return \ACL * @return \ACL
*/ */
public function get(\User_Adapter $user) public function get(User $user)
{ {
if (null !== $acl = $this->fetchFromCache($user)) { if (null !== $acl = $this->fetchFromCache($user)) {
return $acl; return $acl;
@@ -61,9 +61,9 @@ class ACLProvider
* *
* @return null || \ACL * @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 * @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 * @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);
} }
} }

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Authentication;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\Entities\User;
class AccountCreator class AccountCreator
{ {
@@ -56,7 +57,7 @@ class AccountCreator
* @param string $email The email * @param string $email The email
* @param array $templates Some extra templates to apply with the ones of this creator * @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 RuntimeException In case the AccountCreator is disabled
* @throws InvalidArgumentException In case a user with the same email already exists * @throws InvalidArgumentException In case a user with the same email already exists
@@ -70,16 +71,16 @@ class AccountCreator
$login = $id; $login = $id;
$n = 1; $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.'); 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; $login = $id . '#' . $n;
$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 = []; $base_ids = [];
foreach ($this->appbox->get_databoxes() as $databox) { foreach ($this->appbox->get_databoxes() as $databox) {

View File

@@ -13,11 +13,11 @@ namespace Alchemy\Phrasea\Authentication;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\Entities\User;
use Browser; use Browser;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Alchemy\Phrasea\Model\Entities\Session; use Alchemy\Phrasea\Model\Entities\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Authenticator class Authenticator
{ {
@@ -43,7 +43,7 @@ class Authenticator
return $this->user; return $this->user;
} }
public function setUser(\User_Adapter $user = null) public function setUser(User $user = null)
{ {
$this->user = $user; $this->user = $user;
@@ -53,13 +53,13 @@ class Authenticator
/** /**
* Open user session * Open user session
* *
* @param \User_Adapter $user * @param User $user
* *
* @return Session * @return Session
* *
* @throws \Exception_InternalServerError * @throws \Exception_InternalServerError
*/ */
public function openAccount(\User_Adapter $user) public function openAccount(User $user)
{ {
$this->session->remove('usr_id'); $this->session->remove('usr_id');
$this->session->remove('session_id'); $this->session->remove('session_id');
@@ -69,7 +69,7 @@ class Authenticator
->setBrowserVersion($this->browser->getVersion()) ->setBrowserVersion($this->browser->getVersion())
->setPlatform($this->browser->getPlatform()) ->setPlatform($this->browser->getPlatform())
->setUserAgent($this->browser->getUserAgent()) ->setUserAgent($this->browser->getUserAgent())
->setUsrId($user->get_id()); ->setUser($user);
$this->em->persist($session); $this->em->persist($session);
$this->em->flush(); $this->em->flush();
@@ -93,7 +93,7 @@ class Authenticator
$rights[] = 'task-manager'; $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('websockets_rights', $rights);
$this->session->set('session_id', $session->getId()); $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'); throw new RuntimeException('Unable to refresh the session, it does not exist anymore');
} }
try { if (null === $user = $session->getUser()) {
$user = \User_Adapter::getInstance($session->getUsrId(), $this->app); throw new RuntimeException('Unable to refresh the session');
} catch (NotFoundHttpException $e) {
throw new RuntimeException('Unable to refresh the session', $e->getCode(), $e);
} }
$this->session->clear(); $this->session->clear();
@@ -145,7 +143,7 @@ class Authenticator
public function reinitUser() public function reinitUser()
{ {
if ($this->isAuthenticated()) { 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 { } else {
$this->user = null; $this->user = null;
} }

View File

@@ -12,6 +12,7 @@
namespace Alchemy\Phrasea\Authentication; namespace Alchemy\Phrasea\Authentication;
use Alchemy\Phrasea\Model\Entities\Session; use Alchemy\Phrasea\Model\Entities\Session;
use Alchemy\Phrasea\Model\Entities\User;
class Manager class Manager
{ {
@@ -26,11 +27,11 @@ class Manager
/** /**
* *
* @param \User_Adapter $user * @param User $user
* *
* @return Session * @return Session
*/ */
public function openAccount(\User_Adapter $user) public function openAccount(User $user)
{ {
return $this->authenticator->openAccount($user); return $this->authenticator->openAccount($user);
} }

View File

@@ -13,20 +13,22 @@ namespace Alchemy\Phrasea\Authentication\Phrasea;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Authentication\Exception\AccountLockedException; use Alchemy\Phrasea\Authentication\Exception\AccountLockedException;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
class NativeAuthentication implements PasswordAuthenticationInterface class NativeAuthentication implements PasswordAuthenticationInterface
{ {
/** @var \connection_interface */ /** @var UserManipulator */
private $conn; private $userManipulator;
/** @var PasswordEncoder */ /** @var PasswordEncoder */
private $encoder; private $encoder;
/** @var OldPasswordEncoder */ /** @var OldPasswordEncoder */
private $oldEncoder; 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->encoder = $encoder;
$this->oldEncoder = $oldEncoder; $this->oldEncoder = $oldEncoder;
} }
@@ -36,55 +38,31 @@ class NativeAuthentication implements PasswordAuthenticationInterface
*/ */
public function getUsrId($username, $password, Request $request) public function getUsrId($username, $password, Request $request)
{ {
if (in_array($username, ['invite', 'autoregister'])) { if (null === $user = $this->userManipulator->getRepository()->findRealUserByLogin($username)) {
return null; return null;
} }
$sql = 'SELECT nonce, salted_password, mail_locked, usr_id, usr_login, usr_password if ($user->isSpecial()) {
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) {
return null; return null;
} }
// check locked account // check locked account
if ('1' == $row['mail_locked']) { if ($user->isMailLocked()) {
throw new AccountLockedException('The account is locked', $row['usr_id']); 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 // we need a quick update and continue
if ($this->oldEncoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) { if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) {
$this->userManipulator->setPassword($user, $password);
$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->encoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) { if (false === $this->encoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) {
return null; return null;
} }
return $row['usr_id']; return $user->getId();
} }
/** /**

View File

@@ -15,6 +15,7 @@ use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Authentication\Exception\NotAuthenticatedException; use Alchemy\Phrasea\Authentication\Exception\NotAuthenticatedException;
use Alchemy\Phrasea\Authentication\Provider\Token\Token; use Alchemy\Phrasea\Authentication\Provider\Token\Token;
use Alchemy\Phrasea\Authentication\Provider\Token\Identity; use Alchemy\Phrasea\Authentication\Provider\Token\Identity;
use Alchemy\Phrasea\Model\Entities\User;
class SuggestionFinder class SuggestionFinder
{ {
@@ -30,7 +31,7 @@ class SuggestionFinder
* *
* @param Token $token * @param Token $token
* *
* @return null|\User_Adapter * @return null|User
* *
* @throws NotAuthenticatedException In case the token is not authenticated. * @throws NotAuthenticatedException In case the token is not authenticated.
*/ */
@@ -39,16 +40,7 @@ class SuggestionFinder
$infos = $token->getIdentity(); $infos = $token->getIdentity();
if ($infos->has(Identity::PROPERTY_EMAIL)) { if ($infos->has(Identity::PROPERTY_EMAIL)) {
return $this->app['manipulator.user']->getRepository()->findByEmail($infos->get(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 null; return null;

View File

@@ -18,6 +18,7 @@ use Alchemy\Phrasea\Exception\RuntimeException;
use Symfony\Component\Console; use Symfony\Component\Console;
use Alchemy\Phrasea\Core\CLIProvider\CLIDriversServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\CLIDriversServiceProvider;
use Alchemy\Phrasea\Core\CLIProvider\ComposerSetupServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\ComposerSetupServiceProvider;
use Alchemy\Phrasea\Core\CLIProvider\DoctrineMigrationServiceProvider;
use Alchemy\Phrasea\Core\CLIProvider\LessBuilderServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\LessBuilderServiceProvider;
use Alchemy\Phrasea\Core\CLIProvider\PluginServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\PluginServiceProvider;
use Alchemy\Phrasea\Core\CLIProvider\SignalHandlerServiceProvider; use Alchemy\Phrasea\Core\CLIProvider\SignalHandlerServiceProvider;
@@ -31,7 +32,6 @@ use Alchemy\Phrasea\Core\CLIProvider\TaskManagerServiceProvider;
*/ */
class CLI extends Application class CLI extends Application
{ {
/** /**
* Registers the autoloader and necessary components. * Registers the autoloader and necessary components.
* *
@@ -63,6 +63,7 @@ class CLI extends Application
$this->register(new SignalHandlerServiceProvider()); $this->register(new SignalHandlerServiceProvider());
$this->register(new TaskManagerServiceProvider()); $this->register(new TaskManagerServiceProvider());
$this->register(new TranslationExtractorServiceProvider()); $this->register(new TranslationExtractorServiceProvider());
$this->register(new DoctrineMigrationServiceProvider());
$this->bindRoutes(); $this->bindRoutes();
} }

View File

@@ -60,9 +60,7 @@ class CreateCollection extends Command
} }
$app = $this->container; $app = $this->container;
$this->container['manipulator.acl']->resetAdminRights(array_map(function ($id) use ($app) { $this->container['manipulator.acl']->resetAdminRights($this->container['manipulator.user']->getRepository()->findAdmins());
return \User_Adapter::getInstance($id, $app);
}, array_keys(\User_Adapter::get_sys_admins($this->container))));
$this->container['dispatcher']->dispatch(PhraseaEvents::COLLECTION_CREATE, new CollectionCreateEvent($new_collection)); $this->container['dispatcher']->dispatch(PhraseaEvents::COLLECTION_CREATE, new CollectionCreateEvent($new_collection));
} }

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Command\Developer;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Command\Command; use Alchemy\Phrasea\Command\Command;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\Client; use Symfony\Component\HttpKernel\Client;
@@ -36,17 +37,10 @@ class JsFixtures extends Command
copy($dbRefPath, '/tmp/db.sqlite'); copy($dbRefPath, '/tmp/db.sqlite');
$user = $this->createUser($this->container);
$sbasId = current($this->container['phraseanet.appbox']->get_databoxes())->get_sbas_id(); $sbasId = current($this->container['phraseanet.appbox']->get_databoxes())->get_sbas_id();
$this->writeResponse($output, 'GET', '/login/', '/home/login/index.html');
try { $this->writeResponse($output, 'GET', '/admin/fields/'.$sbasId , '/admin/fields/index.html', true);
$this->writeResponse($output, 'GET', '/login/', '/home/login/index.html'); $this->writeResponse($output, 'GET', '/admin/task-manager/tasks', '/admin/task-manager/index.html', true);
$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->copy($output, [ $this->copy($output, [
['source' => 'login/common/templates.html.twig', 'target' => 'home/login/templates.html'], ['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'], ['source' => 'admin/task-manager/templates.html.twig', 'target' => 'admin/task-manager/templates.html'],
]); ]);
$user->delete();
return 0; return 0;
} }
private function deleteUser(User $user)
{
$this->container['manipulator.user']->delete($user);
}
private function copy(OutputInterface $output, $data) private function copy(OutputInterface $output, $data)
{ {
foreach ($data as $paths) { foreach ($data as $paths) {
@@ -82,7 +79,7 @@ class JsFixtures extends Command
private function createUser(Application $app) 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['acl']->get($user)->set_admin(true);
$app['manipulator.acl']->resetAdminRights($user); $app['manipulator.acl']->resetAdminRights($user);
@@ -90,7 +87,7 @@ class JsFixtures extends Command
return $user; return $user;
} }
private function loginUser(Application $app, \User_Adapter $user) private function loginUser(Application $app, User $user)
{ {
$app['authentication']->openAccount($user); $app['authentication']->openAccount($user);
} }
@@ -100,10 +97,13 @@ class JsFixtures extends Command
$app['authentication']->closeAccount(); $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; $environment = Application::ENV_TEST;
$app = require __DIR__ . '/../../Application/Root.php'; $app = require __DIR__ . '/../../Application/Root.php';
$user = $this->createUser($app);
// force load of non cached template // force load of non cached template
$app['twig']->enableAutoReload(); $app['twig']->enableAutoReload();
$client = new Client($app); $client = new Client($app);
@@ -111,19 +111,21 @@ class JsFixtures extends Command
$target = sprintf('%s/%s/%s', $app['root.path'],$fixturePath, $to); $target = sprintf('%s/%s/%s', $app['root.path'],$fixturePath, $to);
$output->writeln(sprintf("Generating %s", $target)); $output->writeln(sprintf("Generating %s", $target));
if (null !== $user) { if ($authenticateUser) {
$this->loginUser($app, $user); $this->loginUser($app, $user);
} }
$client->request($method, $path); $client->request($method, $path);
$response = $client->getResponse(); $response = $client->getResponse();
if (null !== $user) { if ($authenticateUser) {
$this->logoutUser($app); $this->logoutUser($app);
} }
if (false === $response->isOk()) { if (false === $response->isOk()) {
$this->deleteUser($user);
throw new RuntimeException(sprintf('Request %s %s returns %d code error', $method, $path, $response->getStatusCode())); 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']->mkdir(str_replace(basename($target), '', $target));
$this->container['filesystem']->dumpFile($target, $this->removeHeadTag($this->removeScriptTags($response->getContent()))); $this->container['filesystem']->dumpFile($target, $this->removeHeadTag($this->removeScriptTags($response->getContent())));
$this->deleteUser($user);
} }
} }

View File

@@ -61,7 +61,7 @@ class RegenerateSqliteDb extends Command
if (is_file($source)) { if (is_file($source)) {
$renamed = true; $renamed = true;
$fs->rename($source, $target); $fs->rename($source, $target, true);
} }
try { try {
@@ -92,10 +92,11 @@ class RegenerateSqliteDb extends Command
$this->insertLazaretFiles($this->container['EM'], $DI); $this->insertLazaretFiles($this->container['EM'], $DI);
$this->insertAuthFailures($this->container['EM'], $DI); $this->insertAuthFailures($this->container['EM'], $DI);
$fixtures['user']['test_phpunit'] = $DI['user']->get_id(); $fixtures['user']['test_phpunit'] = $DI['user']->getId();
$fixtures['user']['test_phpunit_not_admin'] = $DI['user_notAdmin']->get_id(); $fixtures['user']['test_phpunit_not_admin'] = $DI['user_notAdmin']->getId();
$fixtures['user']['test_phpunit_alt1'] = $DI['user_alt1']->get_id(); $fixtures['user']['test_phpunit_alt1'] = $DI['user_alt1']->getId();
$fixtures['user']['test_phpunit_alt2'] = $DI['user_alt2']->get_id(); $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'] = $DI['app-user']->get_id();
$fixtures['oauth']['user_notAdmin'] = $DI['app-user_notAdmin']->get_id(); $fixtures['oauth']['user_notAdmin'] = $DI['app-user_notAdmin']->get_id();
@@ -134,9 +135,7 @@ class RegenerateSqliteDb extends Command
} catch (\Exception $e) { } catch (\Exception $e) {
$output->writeln("<error>".$e->getMessage()."</error>"); $output->writeln("<error>".$e->getMessage()."</error>");
if ($renamed) { if ($renamed) {
if (is_file($source)) { $fs->remove($source);
unlink($source);
}
$fs->rename($target, $source); $fs->rename($target, $source);
} }
throw $e; throw $e;
@@ -187,6 +186,7 @@ class RegenerateSqliteDb extends Command
private function insertLazaretFiles(EntityManager $em, \Pimple $DI) private function insertLazaretFiles(EntityManager $em, \Pimple $DI)
{ {
$session = new LazaretSession(); $session = new LazaretSession();
$session->setUser($DI['user']);
$em->persist($session); $em->persist($session);
$em->flush(); $em->flush();
@@ -205,6 +205,7 @@ class RegenerateSqliteDb extends Command
$DI['user_alt1'] = $this->getUserAlt1(); $DI['user_alt1'] = $this->getUserAlt1();
$DI['user_alt2'] = $this->getUserAlt2(); $DI['user_alt2'] = $this->getUserAlt2();
$DI['user_notAdmin'] = $this->getUserNotAdmin(); $DI['user_notAdmin'] = $this->getUserNotAdmin();
$DI['user_guest'] = $this->getUserGuest();
$user1 = $this->insertOneUser('user1'); $user1 = $this->insertOneUser('user1');
$user2 = $this->insertOneUser('user2', 'user2@phraseanet.com'); $user2 = $this->insertOneUser('user2', 'user2@phraseanet.com');
@@ -322,44 +323,53 @@ class RegenerateSqliteDb extends Command
private function getUser() private function getUser()
{ {
if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit')) { if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit')) {
return \User_Adapter::create($this->container, 'test_phpunit', \random::generatePassword(), 'noone@example.com', false); $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() private function getUserAlt1()
{ {
if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_alt1')) { if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_alt1')) {
return \User_Adapter::create($this->container, 'test_phpunit_alt1', \random::generatePassword(), 'noonealt1@example.com', false); $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() private function getUserAlt2()
{ {
if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_alt2')) { if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_alt2')) {
return \User_Adapter::create($this->container, 'test_phpunit_alt2', \random::generatePassword(), 'noonealt2@example.com', false); $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() public function getUserNotAdmin()
{ {
if (false === $usr_id = \User_Adapter::get_usr_id_from_login($this->container, 'test_phpunit_not_admin')) { if (null === $user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_not_admin')) {
return \User_Adapter::create($this->container, 'test_phpunit_not_admin', \random::generatePassword(), 'noone_not_admin@example.com', false); $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) private function insertTwoBasket(EntityManager $em, \Pimple $DI)
{ {
$basket1 = new Basket(); $basket1 = new Basket();
$basket1->setOwner($this->getUser()); $basket1->setUser($this->getUser());
$basket1->setName('test'); $basket1->setName('test');
$basket1->setDescription('description test'); $basket1->setDescription('description test');
@@ -369,12 +379,12 @@ class RegenerateSqliteDb extends Command
$element->setBasket($basket1); $element->setBasket($basket1);
$basket2 = new Basket(); $basket2 = new Basket();
$basket2->setOwner($this->getUser()); $basket2->setUser($this->getUser());
$basket2->setName('test'); $basket2->setName('test');
$basket2->setDescription('description test'); $basket2->setDescription('description test');
$basket3 = new Basket(); $basket3 = new Basket();
$basket3->setOwner($this->getUserAlt1()); $basket3->setUser($this->getUserAlt1());
$basket3->setName('test'); $basket3->setName('test');
$basket3->setDescription('description test'); $basket3->setDescription('description test');
@@ -386,7 +396,7 @@ class RegenerateSqliteDb extends Command
$basket4 = new Basket(); $basket4 = new Basket();
$basket4->setName('test'); $basket4->setName('test');
$basket4->setDescription('description'); $basket4->setDescription('description');
$basket4->setOwner($this->getUser()); $basket4->setUser($this->getUser());
foreach ([$DI['record_1'], $DI['record_2']] as $record) { foreach ([$DI['record_1'], $DI['record_2']] as $record) {
$basketElement = new BasketElement(); $basketElement = new BasketElement();
@@ -490,7 +500,7 @@ class RegenerateSqliteDb extends Command
$user = $DI['user']; $user = $DI['user'];
$publisher->setUsrId($user->get_id()); $publisher->setUser($user);
$publisher->setIsOwner(true); $publisher->setIsOwner(true);
$publisher->setFeed($feed); $publisher->setFeed($feed);
@@ -513,7 +523,7 @@ class RegenerateSqliteDb extends Command
$user = $DI['user']; $user = $DI['user'];
$publisher->setUsrId($user->get_id()); $publisher->setUser($user);
$publisher->setIsOwner(true); $publisher->setIsOwner(true);
$publisher->setFeed($feed); $publisher->setFeed($feed);
@@ -536,7 +546,7 @@ class RegenerateSqliteDb extends Command
$user = $DI['user_alt1']; $user = $DI['user_alt1'];
$publisher->setUsrId($user->get_id()); $publisher->setUser($user);
$publisher->setIsOwner(true); $publisher->setIsOwner(true);
$publisher->setFeed($feed); $publisher->setFeed($feed);
@@ -580,7 +590,7 @@ class RegenerateSqliteDb extends Command
$token = new FeedToken(); $token = new FeedToken();
$token->setValue($this->container['tokens']->generatePassword(12)); $token->setValue($this->container['tokens']->generatePassword(12));
$token->setFeed($feed); $token->setFeed($feed);
$token->setUsrId($DI['user']->get_id()); $token->setUser($DI['user']);
$feed->addToken($token); $feed->addToken($token);
@@ -594,7 +604,7 @@ class RegenerateSqliteDb extends Command
$token = new AggregateToken(); $token = new AggregateToken();
$token->setValue($this->container['tokens']->generatePassword(12)); $token->setValue($this->container['tokens']->generatePassword(12));
$token->setUsrId($user->get_id()); $token->setUser($user);
$em->persist($token); $em->persist($token);
} }

View File

@@ -11,6 +11,7 @@
namespace Alchemy\Phrasea\Controller\Admin; namespace Alchemy\Phrasea\Controller\Admin;
use Alchemy\Phrasea\Exception\RuntimeException;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
@@ -176,40 +177,45 @@ class Collection implements ControllerProviderInterface
public function setOrderAdmins(Application $app, Request $request, $bas_id) public function setOrderAdmins(Application $app, Request $request, $bas_id)
{ {
$success = false; $success = false;
$admins = array_values($request->request->get('admins', []));
if (count($admins = $request->request->get('admins', [])) > 0) { if (count($admins) === 0) {
$newAdmins = []; $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) { foreach ($admins as $admin) {
$newAdmins[] = $admin; $app['acl']->get($admin)->update_rights_to_base($bas_id, ['order_master' => true]);
}
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();
}
} }
$conn->commit();
$success = true;
} catch (\Exception $e) {
$conn->rollBack();
throw $e;
} }
return $app->redirectPath('admin_display_collection', [ return $app->redirectPath('admin_display_collection', [

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Admin;
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
use Alchemy\Phrasea\Notification\Mail\MailTest; use Alchemy\Phrasea\Notification\Mail\MailTest;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Exception\RuntimeException;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -69,7 +70,7 @@ class Dashboard implements ControllerProviderInterface
$parameters = [ $parameters = [
'cache_flushed' => $request->query->get('flush_cache') === 'ok', 'cache_flushed' => $request->query->get('flush_cache') === 'ok',
'admins' => \User_Adapter::get_sys_admins($app), 'admins' => $app['manipulator.user']->getRepository()->findAdmins(),
'email_status' => $emailStatus, 'email_status' => $emailStatus,
]; ];
@@ -132,9 +133,7 @@ class Dashboard implements ControllerProviderInterface
*/ */
public function resetAdminRights(Application $app, Request $request) public function resetAdminRights(Application $app, Request $request)
{ {
$app['manipulator.acl']->resetAdminRights(array_map(function ($id) use ($app) { $app['manipulator.acl']->resetAdminRights($app['manipulator.user']->getRepository()->findAdmins());
return \User_Adapter::getInstance($id, $app);
}, array_keys(\User_Adapter::get_sys_admins($app))));
return $app->redirectPath('admin_dashbord'); return $app->redirectPath('admin_dashbord');
} }
@@ -148,19 +147,24 @@ class Dashboard implements ControllerProviderInterface
*/ */
public function addAdmins(Application $app, Request $request) public function addAdmins(Application $app, Request $request)
{ {
if (count($admins = $request->request->get('admins', [])) > 0) { $admins = $request->request->get('admins', []);
if (count($admins) === 0 || !is_array($admins)) {
if (!in_array($app['authentication']->getUser()->get_id(), $admins)) { $app->abort(400, '"admins" parameter must contains at least one value.');
$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))));
}
} }
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'); return $app->redirectPath('admin_dashbord');
} }

View File

@@ -52,7 +52,7 @@ class Publications implements ControllerProviderInterface
$feed = new Feed(); $feed = new Feed();
$publisher->setFeed($feed); $publisher->setFeed($feed);
$publisher->setUsrId($app['authentication']->getUser()->get_id()); $publisher->setUser($app['authentication']->getUser());
$publisher->setIsOwner(true); $publisher->setIsOwner(true);
$feed->addPublisher($publisher); $feed->addPublisher($publisher);
@@ -193,11 +193,11 @@ class Publications implements ControllerProviderInterface
$error = ''; $error = '';
try { try {
$request = $app['request']; $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); $feed = $app["EM"]->find('Phraseanet:Feed', $id);
$publisher = new FeedPublisher(); $publisher = new FeedPublisher();
$publisher->setUsrId($user->get_id()); $publisher->setUser($user);
$publisher->setFeed($feed); $publisher->setFeed($feed);
$feed->addPublisher($publisher); $feed->addPublisher($publisher);
@@ -226,7 +226,7 @@ class Publications implements ControllerProviderInterface
$app->abort(404, "Feed Publisher not found"); $app->abort(404, "Feed Publisher not found");
} }
$user = $publisher->getUser($app); $user = $publisher->getUser();
if ($feed->isPublisher($user) && !$feed->isOwner($user)) { if ($feed->isPublisher($user) && !$feed->isOwner($user)) {
$feed->removePublisher($publisher); $feed->removePublisher($publisher);

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Controller\Admin;
use Alchemy\Phrasea\Helper\User as UserHelper; use Alchemy\Phrasea\Helper\User as UserHelper;
use Alchemy\Phrasea\Model\Entities\FtpCredential; use Alchemy\Phrasea\Model\Entities\FtpCredential;
use Alchemy\Phrasea\Model\Entities\User;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -173,24 +174,23 @@ class Users implements ControllerProviderInterface
]; ];
foreach ($users->export() as $user) { foreach ($users->export() as $user) {
/* @var $user \User_Adapter */
$userTable[] = [ $userTable[] = [
$user->get_id(), $user->getId(),
$user->get_login(), $user->getLogin(),
$user->get_lastname(), $user->getLastName(),
$user->get_firstname(), $user->getFirstName(),
$user->get_email(), $user->getEmail(),
$user->get_creation_date()->format(DATE_ATOM), $user->getCreated()->format(DATE_ATOM),
$user->get_modification_date()->format(DATE_ATOM), $user->getUpdated()->format(DATE_ATOM),
$user->get_address(), $user->getAddress(),
$user->get_city(), $user->getCity(),
$user->get_zipcode(), $user->getZipCode(),
$user->get_country(), $user->getCountry(),
$user->get_tel(), $user->getPhone(),
$user->get_fax(), $user->getFax(),
$user->get_job(), $user->getJob(),
$user->get_company(), $user->getCompany(),
$user->get_position() $user->getActivity()
]; ];
} }
@@ -241,10 +241,10 @@ class Users implements ControllerProviderInterface
foreach ($elligible_users as $user) { foreach ($elligible_users as $user) {
$datas[] = [ $datas[] = [
'email' => $user->get_email() ? : '' 'email' => $user->getEmail() ? : '',
, 'login' => $user->get_login() ? : '' 'login' => $user->getLogin() ? : '',
, 'name' => $user->get_display_name() ? : '' 'name' => $user->getDisplayName(),
, 'id' => $user->get_id() 'id' => $user->getId(),
]; ];
} }
@@ -252,7 +252,6 @@ class Users implements ControllerProviderInterface
}); });
$controllers->post('/create/', function (Application $app) { $controllers->post('/create/', function (Application $app) {
$datas = ['error' => false, 'message' => '', 'data' => null]; $datas = ['error' => false, 'message' => '', 'data' => null];
try { try {
$request = $app['request']; $request = $app['request'];
@@ -262,10 +261,11 @@ class Users implements ControllerProviderInterface
} else { } else {
$user = $module->create_newuser(); $user = $module->create_newuser();
} }
if (!($user instanceof \User_Adapter)) if (!$user instanceof User) {
throw new \Exception('Unknown error'); throw new \Exception('Unknown error');
}
$datas['data'] = $user->get_id(); $datas['data'] = $user->getId();
} catch (\Exception $e) { } catch (\Exception $e) {
$datas['error'] = true; $datas['error'] = true;
if ($request->request->get('template') == '1') { if ($request->request->get('template') == '1') {
@@ -296,22 +296,22 @@ class Users implements ControllerProviderInterface
$buffer = []; $buffer = [];
$buffer[] = [ $buffer[] = [
'ID' 'ID',
, 'Login' 'Login',
, $app->trans('admin::compte-utilisateur nom') $app->trans('admin::compte-utilisateur nom'),
, $app->trans('admin::compte-utilisateur prenom') $app->trans('admin::compte-utilisateur prenom'),
, $app->trans('admin::compte-utilisateur email') $app->trans('admin::compte-utilisateur email'),
, 'CreationDate' 'CreationDate',
, 'ModificationDate' 'ModificationDate',
, $app->trans('admin::compte-utilisateur adresse') $app->trans('admin::compte-utilisateur adresse'),
, $app->trans('admin::compte-utilisateur ville') $app->trans('admin::compte-utilisateur ville'),
, $app->trans('admin::compte-utilisateur code postal') $app->trans('admin::compte-utilisateur code postal'),
, $app->trans('admin::compte-utilisateur pays') $app->trans('admin::compte-utilisateur pays'),
, $app->trans('admin::compte-utilisateur telephone') $app->trans('admin::compte-utilisateur telephone'),
, $app->trans('admin::compte-utilisateur fax') $app->trans('admin::compte-utilisateur fax'),
, $app->trans('admin::compte-utilisateur poste') $app->trans('admin::compte-utilisateur poste'),
, $app->trans('admin::compte-utilisateur societe') $app->trans('admin::compte-utilisateur societe'),
, $app->trans('admin::compte-utilisateur activite') $app->trans('admin::compte-utilisateur activite'),
]; ];
do { do {
$elligible_users->limit($offset, 20); $elligible_users->limit($offset, 20);
@@ -321,22 +321,22 @@ class Users implements ControllerProviderInterface
foreach ($results as $user) { foreach ($results as $user) {
$buffer[] = [ $buffer[] = [
$user->get_id() $user->getId(),
, $user->get_login() $user->getLogin(),
, $user->get_lastname() $user->getLastName(),
, $user->get_firstname() $user->getFirstName(),
, $user->get_email() $user->getEmail(),
, $app['date-formatter']->format_mysql($user->get_creation_date()) $app['date-formatter']->format_mysql($user->getCreated()),
, $app['date-formatter']->format_mysql($user->get_modification_date()) $app['date-formatter']->format_mysql($user->getUpdated()),
, $user->get_address() $user->getAddress(),
, $user->get_city() $user->getCity(),
, $user->get_zipcode() $user->getZipCode(),
, $user->get_country() $user->getCountry(),
, $user->get_tel() $user->getPhone(),
, $user->get_fax() $user->getFax(),
, $user->get_job() $user->getJob(),
, $user->get_company() $user->getCompany(),
, $user->get_position() $user->getActivity(),
]; ];
} }
} while (count($results) > 0); } while (count($results) > 0);
@@ -354,51 +354,35 @@ class Users implements ControllerProviderInterface
})->bind('admin_users_export_csv'); })->bind('admin_users_export_csv');
$controllers->get('/demands/', function (Application $app) { $controllers->get('/demands/', function (Application $app) {
$lastMonth = time() - (3 * 4 * 7 * 24 * 60 * 60); $lastMonth = time() - (3 * 4 * 7 * 24 * 60 * 60);
$sql = "DELETE FROM demand WHERE date_modif < :date"; $sql = "DELETE FROM demand WHERE date_modif < :date";
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':date' => date('Y-m-d', $lastMonth)]); $stmt->execute([':date' => date('Y-m-d', $lastMonth)]);
$stmt->closeCursor(); $stmt->closeCursor();
$baslist = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])); $basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin']));
$models = $app['manipulator.user']->getRepository()->findModelOf($app['authentication']->getUser());
$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();
$currentUsr = null; $currentUsr = null;
$table = ['user' => [], 'coll' => []]; $table = ['users' => [], 'coll' => []];
foreach ($rs as $row) { foreach ($app['EM.native-query']->getUsersRegistrationDemand($basList) as $row) {
if ($row['usr_id'] != $currentUsr) { $user = $row[0];
$currentUsr = $row['usr_id'];
$row['date_modif'] = new \DateTime($row['date_modif']); if ($user->getId() !== $currentUsr) {
$table['user'][$row['usr_id']] = $row; $currentUsr = $user->getId();
$table['users'][$currentUsr] = [
'user' => $user,
'date_demand' => $row['date_demand'],
];
} }
if (!isset($table['coll'][$row['usr_id']])) { if (!isset($table['coll'][$user->getId()])) {
$table['coll'][$row['usr_id']] = []; $table['coll'][$user->getId()] = [];
} }
if (!in_array($row['base_id'], $table['coll'][$row['usr_id']])) { if (!in_array($row['base_demand'], $table['coll'][$user->getId()])) {
$table['coll'][$row['usr_id']][] = $row['base_id']; $table['coll'][$user->getId()][] = $row['base_demand'];
} }
} }
@@ -458,10 +442,10 @@ class Users implements ControllerProviderInterface
$cache_to_update = []; $cache_to_update = [];
foreach ($templates as $usr => $template_id) { foreach ($templates as $usr => $template_id) {
$user = \User_Adapter::getInstance($usr, $app); $user = $app['manipulator.user']->getRepository()->find($usr);
$cache_to_update[$usr] = true; $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()); $base_ids = array_keys($app['acl']->get($user_template)->get_granted_base());
$app['acl']->get($user)->apply_model($user_template, $base_ids); $app['acl']->get($user)->apply_model($user_template, $base_ids);
@@ -507,18 +491,18 @@ class Users implements ControllerProviderInterface
$stmt->closeCursor(); $stmt->closeCursor();
foreach ($accept as $usr => $bases) { foreach ($accept as $usr => $bases) {
$user = \User_Adapter::getInstance($usr, $app); $user = $app['manipulator.user']->getRepository()->find($usr);
$cache_to_update[$usr] = true; $cache_to_update[$usr] = true;
foreach ($bases as $bas) { foreach ($bases as $bas) {
$app['acl']->get($user)->give_access_to_sbas([\phrasea::sbasFromBas($app, $bas)]); $app['acl']->get($user)->give_access_to_sbas([\phrasea::sbasFromBas($app, $bas)]);
$rights = [ $rights = [
'canputinalbum' => '1' 'canputinalbum' => '1',
, 'candwnldhd' => ($options[$usr][$bas]['HD'] ? '1' : '0') 'candwnldhd' => ($options[$usr][$bas]['HD'] ? '1' : '0'),
, 'nowatermark' => ($options[$usr][$bas]['WM'] ? '0' : '1') 'nowatermark' => ($options[$usr][$bas]['WM'] ? '0' : '1'),
, 'candwnldpreview' => '1' 'candwnldpreview' => '1',
, 'actif' => '1' 'actif' => '1',
]; ];
$app['acl']->get($user)->give_access_to_base([$bas]); $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) { 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(); $app['acl']->get($user)->delete_data_from_cache();
unset($user); unset($user);
} }
foreach ($done as $usr => $bases) { 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 = []; $acceptColl = $denyColl = [];
if (null !== $user = $app['manipulator.user']->getRepository()->find($usr)) {
if ($row) { if (\Swift_Validate::email($user->getEmail())) {
if (\Swift_Validate::email($row['usr_mail'])) {
foreach ($bases as $bas => $isok) { foreach ($bases as $bas => $isok) {
if ($isok) { if ($isok) {
$acceptColl[] = \phrasea::bas_labels($bas, $app); $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"; $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); $mail = MailSuccessEmailUpdate::create($app, $receiver, null, $message);
$app['notification.deliverer']->deliver($mail); $app['notification.deliverer']->deliver($mail);
@@ -667,7 +643,7 @@ class Users implements ControllerProviderInterface
} elseif (in_array($loginToAdd, $loginNew)) { } elseif (in_array($loginToAdd, $loginNew)) {
$out['errors'][] = $app->trans("Login %login% is already defined in the file at line %line%", ['%login%' => $loginToAdd, '%line%' => $nbLine]); $out['errors'][] = $app->trans("Login %login% is already defined in the file at line %line%", ['%login%' => $loginToAdd, '%line%' => $nbLine]);
} else { } 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]); $out['errors'][] = $app->trans("Login %login% already exists in database", ['%login%' => $loginToAdd]);
} else { } else {
$loginValid = true; $loginValid = true;
@@ -680,7 +656,7 @@ class Users implements ControllerProviderInterface
if ($mailToAdd === "") { if ($mailToAdd === "") {
$out['errors'][] = $app->trans("Mail line %line% is empty", ['%line%' => $nbLine + 1]); $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]); $out['errors'][] = $app->trans("Email '%email%' for login '%login%' already exists in database", ['%email%' => $mailToAdd, '%login%' => $loginToAdd]);
} else { } else {
$mailValid = true; $mailValid = true;
@@ -716,20 +692,8 @@ class Users implements ControllerProviderInterface
]); ]);
} }
$sql = " $basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']));
SELECT usr.usr_id,usr.usr_login $models = $app['EM.native-query']->getModelForUser($app['authentication']->getUser(), $basList);
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();
return $app['twig']->render('/admin/user/import/view.html.twig', [ return $app['twig']->render('/admin/user/import/view.html.twig', [
'nb_user_to_add' => $nbUsrToAdd, 'nb_user_to_add' => $nbUsrToAdd,
@@ -807,12 +771,13 @@ class Users implements ControllerProviderInterface
if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== '' if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== ''
&& isset($curUser['usr_password']) && trim($curUser['usr_password']) !== '' && isset($curUser['usr_password']) && trim($curUser['usr_password']) !== ''
&& isset($curUser['usr_mail']) && trim($curUser['usr_mail']) !== '') { && isset($curUser['usr_mail']) && trim($curUser['usr_mail']) !== '') {
if (false === \User_Adapter::get_usr_id_from_login($app, $curUser['usr_login']) if (null === $app['manipulator.user']->getRepository()->findByLogin($curUser['usr_login'])
&& false === \User_Adapter::get_usr_id_from_email($app, $curUser['usr_mail'])) { && false === $app['manipulator.user']->getRepository()->findByEmail($curUser['usr_mail'])) {
$NewUser = \User_Adapter::create($app, $curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail'], false);
$newUser = $app['manipulator.user']->createUser($curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail']);
$ftpCredential = new FtpCredential(); $ftpCredential = new FtpCredential();
$ftpCredential->setUsrId($NewUser->get_id()); $ftpCredential->setUser($newUser);
if (isset($curUser['activeFTP'])) { if (isset($curUser['activeFTP'])) {
$ftpCredential->setActive((int) $curUser['activeFTP']); $ftpCredential->setActive((int) $curUser['activeFTP']);
@@ -830,38 +795,38 @@ class Users implements ControllerProviderInterface
$ftpCredential->setRepositoryPrefixName($curUser['prefixFTPfolder']); $ftpCredential->setRepositoryPrefixName($curUser['prefixFTPfolder']);
} }
if (isset($curUser['usr_prenom'])) { if (isset($curUser['usr_prenom'])) {
$NewUser->set_firstname($curUser['usr_prenom']); $newUser->setFirstName($curUser['usr_prenom']);
} }
if (isset($curUser['usr_nom'])) { if (isset($curUser['usr_nom'])) {
$NewUser->set_lastname($curUser['usr_nom']); $newUser->setLastName($curUser['usr_nom']);
} }
if (isset($curUser['adresse'])) { if (isset($curUser['adresse'])) {
$NewUser->set_address($curUser['adresse']); $newUser->setAdress($curUser['adresse']);
} }
if (isset($curUser['cpostal'])) { if (isset($curUser['cpostal'])) {
$NewUser->set_zip($curUser['cpostal']); $newUser->setZipCode($curUser['cpostal']);
} }
if (isset($curUser['usr_sexe'])) { if (isset($curUser['usr_sexe'])) {
$NewUser->set_gender((int) ($curUser['usr_sexe'])); $newUser->setGender((int) ($curUser['usr_sexe']));
} }
if (isset($curUser['tel'])) { if (isset($curUser['tel'])) {
$NewUser->set_tel($curUser['tel']); $newUser->setPhone($curUser['tel']);
} }
if (isset($curUser['fax'])) { if (isset($curUser['fax'])) {
$NewUser->set_fax($curUser['fax']); $newUser->setFax($curUser['fax']);
} }
if (isset($curUser['activite'])) { if (isset($curUser['activite'])) {
$NewUser->set_job($curUser['activite']); $newUser->setJob($curUser['activite']);
} }
if (isset($curUser['fonction'])) { if (isset($curUser['fonction'])) {
$NewUser->set_position($curUser['fonction']); $newUser->setPosition($curUser['fonction']);
} }
if (isset($curUser['societe'])) { if (isset($curUser['societe'])) {
$NewUser->set_company($curUser['societe']); $newUser->setCompany($curUser['societe']);
} }
$app['acl']->get($NewUser)->apply_model( $app['acl']->get($newUser)->apply_model(
\User_Adapter::getInstance($model, $app), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage'])) $app['manipulator.user']->getRepository()->find($model), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))
); );
$nbCreation++; $nbCreation++;

View File

@@ -91,7 +91,7 @@ class Oauth2 implements ControllerProviderInterface
return $app->redirectPath('oauth2_authorize', ['error' => 'account-locked']); 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])); 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(); $params['account_id'] = $account->get_id();

View File

@@ -82,7 +82,7 @@ class V1 implements ControllerProviderInterface
return; 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); $app['authentication']->openAccount($user);
$oauth2_adapter->remember_this_ses_id($app['session']->get('session_id')); $oauth2_adapter->remember_this_ses_id($app['session']->get('session_id'));

View File

@@ -111,7 +111,7 @@ class Baskets implements ControllerProviderInterface
try { try {
$basket = new Basket(); $basket = new Basket();
$basket->setName($request->request->get('p0')); $basket->setName($request->request->get('p0'));
$basket->setOwner($app['authentication']->getUser()); $basket->setUser($app['authentication']->getUser());
$app['EM']->persist($basket); $app['EM']->persist($basket);
$app['EM']->flush(); $app['EM']->flush();
@@ -180,7 +180,7 @@ class Baskets implements ControllerProviderInterface
} }
$basketCollections = $baskets->partition(function ($key, $basket) { $basketCollections = $baskets->partition(function ($key, $basket) {
return (Boolean) $basket->getPusherId(); return null !== $basket->getPusher();
}); });
return $app['twig']->render('client/baskets.html.twig', [ return $app['twig']->render('client/baskets.html.twig', [

View File

@@ -91,14 +91,14 @@ class Root implements ControllerProviderInterface
$result = $app['phraseanet.SE']->query($query, ($currentPage - 1) * $perPage, $perPage, $options); $result = $app['phraseanet.SE']->query($query, ($currentPage - 1) * $perPage, $perPage, $options);
$userQuery = new UserQuery(); $userQuery = new UserQuery();
$userQuery->setUsrId($app['authentication']->getUser()->get_id()); $userQuery->setUser($app['authentication']->getUser());
$userQuery->setQuery($query); $userQuery->setQuery($query);
$app['EM']->persist($userQuery); $app['EM']->persist($userQuery);
$app['EM']->flush(); $app['EM']->flush();
if ($app['authentication']->getUser()->getPrefs('start_page') === 'LAST_QUERY') { if ($app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page') === 'LAST_QUERY') {
$app['authentication']->getUser()->setPrefs('start_page_query', $query); $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), 'start_page_query', $query);
} }
foreach ($options->getDataboxes() as $databox) { foreach ($options->getDataboxes() as $databox) {
@@ -171,7 +171,7 @@ class Root implements ControllerProviderInterface
'per_page' => $perPage, 'per_page' => $perPage,
'search_engine' => $app['phraseanet.SE'], 'search_engine' => $app['phraseanet.SE'],
'search_engine_option' => $options->serialize(), 'search_engine_option' => $options->serialize(),
'history' => \queries::history($app, $app['authentication']->getUser()->get_id()), 'history' => \queries::history($app, $app['authentication']->getUser()->getId()),
'result' => $result, 'result' => $result,
'proposals' => $currentPage === 1 ? $result->getProposals() : null, 'proposals' => $currentPage === 1 ? $result->getProposals() : null,
'help' => count($resultData) === 0 ? $this->getHelpStartPage($app) : '', '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', [ 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), 'phrasea_home' => $this->getDefaultClientStartPage($app),
'render_topics' => $renderTopics, 'render_topics' => $renderTopics,
'grid_properties' => $this->getGridProperty(), 'grid_properties' => $this->getGridProperty(),
@@ -261,12 +261,12 @@ class Root implements ControllerProviderInterface
'storage_access' => $this->getDocumentStorageAccess($app), 'storage_access' => $this->getDocumentStorageAccess($app),
'tabs_setup' => $this->getTabSetup($app), 'tabs_setup' => $this->getTabSetup($app),
'module' => 'client', '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), 'css_file' => $this->getCssFile($app),
'basket_status' => null !== $app['authentication']->getUser()->getPrefs('client_basket_status') ? $app['authentication']->getUser()->getPrefs('client_basket_status') : "1", 'basket_status' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_basket_status', '1'),
'mod_pres' => null !== $app['authentication']->getUser()->getPrefs('client_view') ? $app['authentication']->getUser()->getPrefs('client_view') : '', 'mod_pres' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_view', '' ),
'start_page' => $app['authentication']->getUser()->getPrefs('start_page'), 'start_page' => $app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page'),
'start_page_query' => null !== $app['authentication']->getUser()->getPrefs('start_page_query') ? $app['authentication']->getUser()->getPrefs('start_page_query') : '' '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/'; $cssPath = __DIR__ . '/../../../../../www/skins/client/';
$css = []; $css = [];
$cssFile = $app['authentication']->getUser()->getPrefs('client_css'); $cssFile = $app['settings']->getUserSetting($app['authentication']->getUser(), 'client_css');
$finder = new Finder(); $finder = new Finder();
@@ -418,7 +418,7 @@ class Root implements ControllerProviderInterface
*/ */
private function getDefaultClientStartPage(Application $app) 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') { if ($startPage === 'PUBLI') {
return $this->getPublicationStartPage($app); return $this->getPublicationStartPage($app);
@@ -441,7 +441,7 @@ class Root implements ControllerProviderInterface
{ {
$collections = $queryParameters = []; $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)) { if ($searchSet && isset($searchSet->bases)) {
foreach ($searchSet->bases as $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()); $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["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["pag"] = 0;
$queryParameters["search_type"] = SearchEngineOptions::RECORD_RECORD; $queryParameters["search_type"] = SearchEngineOptions::RECORD_RECORD;
$queryParameters["qryAdv"] = ''; $queryParameters["qryAdv"] = '';
@@ -479,7 +479,7 @@ class Root implements ControllerProviderInterface
{ {
return $app['twig']->render('client/home_inter_pub_basket.html.twig', [ return $app['twig']->render('client/home_inter_pub_basket.html.twig', [
'feeds' => Aggregate::createFromUser($app, $app['authentication']->getUser()), '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')
]); ]);
} }

View File

@@ -44,7 +44,7 @@ class Lightbox implements ControllerProviderInterface
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
} }
$app['authentication']->openAccount(\User_Adapter::getInstance($usr_id, $app)); $app['authentication']->openAccount($app['manipulator.user']->getRepository()->find($usr_id));
try { try {
$datas = $app['tokens']->helloToken($request->query->get('LOG')); $datas = $app['tokens']->helloToken($request->query->get('LOG'));
@@ -221,9 +221,9 @@ class Lightbox implements ControllerProviderInterface
$app['EM']->flush(); $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 = $app['EM']->merge($basket);
$basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush(); $app['EM']->flush();
} }
@@ -268,9 +268,9 @@ class Lightbox implements ControllerProviderInterface
$app['EM']->flush(); $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 = $app['EM']->merge($basket);
$basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush(); $app['EM']->flush();
} }
@@ -350,7 +350,7 @@ class Lightbox implements ControllerProviderInterface
$basket_element = $repository->findUserElement($sselcont_id, $app['authentication']->getUser()); $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); $validationDatas->setNote($note);
@@ -400,11 +400,11 @@ class Lightbox implements ControllerProviderInterface
, $app['authentication']->getUser() , $app['authentication']->getUser()
); );
/* @var $basket_element BasketElement */ /* @var $basket_element BasketElement */
$validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser(), $app); $validationDatas = $basket_element->getUserValidationDatas($app['authentication']->getUser());
if (!$basket_element->getBasket() if (!$basket_element->getBasket()
->getValidation() ->getValidation()
->getParticipant($app['authentication']->getUser(), $app)->getCanAgree()) { ->getParticipant($app['authentication']->getUser())->getCanAgree()) {
throw new ControllerException('You can not agree on this'); throw new ControllerException('You can not agree on this');
} }
@@ -412,7 +412,7 @@ class Lightbox implements ControllerProviderInterface
$participant = $basket_element->getBasket() $participant = $basket_element->getBasket()
->getValidation() ->getValidation()
->getParticipant($app['authentication']->getUser(), $app); ->getParticipant($app['authentication']->getUser());
$app['EM']->merge($basket_element); $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'); 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'); throw new ControllerException('You have not right to agree');
} }
$agreed = false; $agreed = false;
/* @var $basket Basket */ /* @var $basket Basket */
foreach ($basket->getElements() as $element) { foreach ($basket->getElements() as $element) {
if (null !== $element->getUserValidationDatas($app['authentication']->getUser(), $app)->getAgreement()) { if (null !== $element->getUserValidationDatas($app['authentication']->getUser())->getAgreement()) {
$agreed = true; $agreed = true;
} }
} }
@@ -463,20 +463,20 @@ class Lightbox implements ControllerProviderInterface
} }
/* @var $basket Basket */ /* @var $basket Basket */
$participant = $basket->getValidation()->getParticipant($app['authentication']->getUser(), $app); $participant = $basket->getValidation()->getParticipant($app['authentication']->getUser());
$expires = new \DateTime('+10 days'); $expires = new \DateTime('+10 days');
$url = $app->url('lightbox', ['LOG' => $app['tokens']->getUrlToken( $url = $app->url('lightbox', ['LOG' => $app['tokens']->getUrlToken(
\random::TYPE_VALIDATE \random::TYPE_VALIDATE
, $basket->getValidation()->getInitiator($app)->get_id() , $basket->getValidation()->getInitiator($app)->getId()
, $expires , $expires
, $basket->getId() , $basket->getId()
)]); )]);
$to = $basket->getValidation()->getInitiator($app)->get_id(); $to = $basket->getValidation()->getInitiator($app)->getId();
$params = [ $params = [
'ssel_id' => $basket->getId(), 'ssel_id' => $basket->getId(),
'from' => $app['authentication']->getUser()->get_id(), 'from' => $app['authentication']->getUser()->getId(),
'url' => $url, 'url' => $url,
'to' => $to 'to' => $to
]; ];

View File

@@ -154,16 +154,14 @@ class Permalink extends AbstractDelivery
$watermark = $stamp = false; $watermark = $stamp = false;
if ($app['authentication']->isAuthenticated()) { if ($app['authentication']->isAuthenticated()) {
$user = \User_Adapter::getInstance($app['authentication']->getUser()->get_id(), $app); $watermark = !$app['acl']->get($app['authentication']->getUser())->has_right_on_base($record->get_base_id(), 'nowatermark');
$watermark = !$app['acl']->get($user)->has_right_on_base($record->get_base_id(), 'nowatermark');
if ($watermark) { if ($watermark) {
$repository = $app['EM']->getRepository('Phraseanet:BasketElement'); $repository = $app['EM']->getRepository('Phraseanet:BasketElement');
if (count($repository->findReceivedValidationElementsByRecord($record, $user)) > 0) { if (count($repository->findReceivedValidationElementsByRecord($record, $app['authentication']->getUser())) > 0) {
$watermark = false; $watermark = false;
} elseif (count($repository->findReceivedElementsByRecord($record, $user)) > 0) { } elseif (count($repository->findReceivedElementsByRecord($record, $app['authentication']->getUser())) > 0) {
$watermark = false; $watermark = false;
} }
} }

View File

@@ -99,8 +99,8 @@ class BasketController implements ControllerProviderInterface
} }
if ($basket->getValidation()) { if ($basket->getValidation()) {
if ($basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->getIsAware() === false) { if ($basket->getValidation()->getParticipant($app['authentication']->getUser())->getIsAware() === false) {
$basket->getValidation()->getParticipant($app['authentication']->getUser(), $app)->setIsAware(true); $basket->getValidation()->getParticipant($app['authentication']->getUser())->setIsAware(true);
$app['EM']->flush(); $app['EM']->flush();
} }
} }
@@ -118,7 +118,7 @@ class BasketController implements ControllerProviderInterface
$Basket = new BasketEntity(); $Basket = new BasketEntity();
$Basket->setName($request->request->get('name', '')); $Basket->setName($request->request->get('name', ''));
$Basket->setOwner($app['authentication']->getUser()); $Basket->setUser($app['authentication']->getUser());
$Basket->setDescription($request->request->get('desc')); $Basket->setDescription($request->request->get('desc'));
$app['EM']->persist($Basket); $app['EM']->persist($Basket);

View File

@@ -173,7 +173,7 @@ class Bridge implements ControllerProviderInterface
try { try {
$account = \Bridge_Account::load_account($app, $account_id); $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'); throw new HttpException(403, 'Access forbiden');
} }

View File

@@ -66,7 +66,7 @@ class Download implements ControllerProviderInterface
$token = $app['tokens']->getUrlToken( $token = $app['tokens']->getUrlToken(
\random::TYPE_DOWNLOAD, \random::TYPE_DOWNLOAD,
$app['authentication']->getUser()->get_id(), $app['authentication']->getUser()->getId(),
new \DateTime('+3 hours'), // Token lifetime new \DateTime('+3 hours'), // Token lifetime
serialize($list) serialize($list)
); );
@@ -77,7 +77,7 @@ class Download implements ControllerProviderInterface
$app['events-manager']->trigger('__DOWNLOAD__', [ $app['events-manager']->trigger('__DOWNLOAD__', [
'lst' => $lst, 'lst' => $lst,
'downloader' => $app['authentication']->getUser()->get_id(), 'downloader' => $app['authentication']->getUser()->getId(),
'subdefs' => $subdefs, 'subdefs' => $subdefs,
'from_basket' => $ssttid, 'from_basket' => $ssttid,
'export_file' => $download->getExportName() 'export_file' => $download->getExportName()

View File

@@ -206,7 +206,7 @@ class Export implements ControllerProviderInterface
$destMails[] = $mail; $destMails[] = $mail;
} else { } else {
$app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [
'usr_id' => $app['authentication']->getUser()->get_id(), 'usr_id' => $app['authentication']->getUser()->getId(),
'lst' => $lst, 'lst' => $lst,
'ssttid' => $ssttid, 'ssttid' => $ssttid,
'dest' => $mail, 'dest' => $mail,
@@ -232,7 +232,7 @@ class Export implements ControllerProviderInterface
$url = $app->url('prepare_download', ['token' => $token, 'anonymous']); $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) { foreach ($destMails as $key => $mail) {
try { try {
@@ -253,7 +253,7 @@ class Export implements ControllerProviderInterface
if (count($remaingEmails) > 0) { if (count($remaingEmails) > 0) {
foreach ($remaingEmails as $mail) { foreach ($remaingEmails as $mail) {
$app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [
'usr_id' => $app['authentication']->getUser()->get_id(), 'usr_id' => $app['authentication']->getUser()->getId(),
'lst' => $lst, 'lst' => $lst,
'ssttid' => $ssttid, 'ssttid' => $ssttid,
'dest' => $mail, 'dest' => $mail,
@@ -264,7 +264,7 @@ class Export implements ControllerProviderInterface
} elseif (!$token && count($destMails) > 0) { //couldn't generate token } elseif (!$token && count($destMails) > 0) { //couldn't generate token
foreach ($destMails as $mail) { foreach ($destMails as $mail) {
$app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [ $app['events-manager']->trigger('__EXPORT_MAIL_FAIL__', [
'usr_id' => $app['authentication']->getUser()->get_id(), 'usr_id' => $app['authentication']->getUser()->getId(),
'lst' => $lst, 'lst' => $lst,
'ssttid' => $ssttid, 'ssttid' => $ssttid,
'dest' => $mail, 'dest' => $mail,

View File

@@ -49,7 +49,7 @@ class Feed implements ControllerProviderInterface
$app->abort(404, "Feed not found"); $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', ''))) { if ('' === $title = trim($request->request->get('title', ''))) {
$app->abort(400, "Bad request"); $app->abort(400, "Bad request");

View File

@@ -94,7 +94,7 @@ class Order implements ControllerProviderInterface
if (!$records->isEmpty()) { if (!$records->isEmpty()) {
$order = new OrderEntity(); $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->setDeadline((null !== $deadLine = $request->request->get('deadline')) ? new \DateTime($deadLine) : $deadLine);
$order->setOrderUsage($request->request->get('use', '')); $order->setOrderUsage($request->request->get('use', ''));
foreach ($records as $key => $record) { foreach ($records as $key => $record) {
@@ -144,7 +144,7 @@ class Order implements ControllerProviderInterface
try { try {
$app['events-manager']->trigger('__NEW_ORDER__', [ $app['events-manager']->trigger('__NEW_ORDER__', [
'order_id' => $order->getId(), 'order_id' => $order->getId(),
'usr_id' => $order->getUsrId() 'usr_id' => $order->getUser()->getId()
]); ]);
$success = true; $success = true;
@@ -237,19 +237,15 @@ class Order implements ControllerProviderInterface
public function sendOrder(Application $app, Request $request, $order_id) public function sendOrder(Application $app, Request $request, $order_id)
{ {
$success = false; $success = false;
$order = $app['EM']->getRepository('Phraseanet:Order')->find($order_id); if (null === $order = $app['EM']->getRepository('Phraseanet:Order')->find($order_id)) {
if (null === $order) {
throw new NotFoundHttpException('Order not found'); throw new NotFoundHttpException('Order not found');
} }
$dest_user = \User_Adapter::getInstance($order->getUsrId(), $app);
$basket = $order->getBasket(); $basket = $order->getBasket();
if (null === $basket) { if (null === $basket) {
$basket = new Basket(); $basket = new Basket();
$basket->setName($app->trans('Commande du %date%', ['%date%' => $order->getCreatedOn()->format('Y-m-d')])); $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()); $basket->setPusher($app['authentication']->getUser());
$app['EM']->persist($basket); $app['EM']->persist($basket);
@@ -267,14 +263,14 @@ class Order implements ControllerProviderInterface
$basketElement->setRecord($record); $basketElement->setRecord($record);
$basketElement->setBasket($basket); $basketElement->setBasket($basket);
$orderElement->setOrderMasterId($app['authentication']->getUser()->get_id()); $orderElement->setOrderMaster($app['authentication']->getUser());
$orderElement->setDeny(false); $orderElement->setDeny(false);
$orderElement->getOrder()->setBasket($basket); $orderElement->getOrder()->setBasket($basket);
$basket->addElement($basketElement); $basket->addElement($basketElement);
$n++; $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__', [ $app['events-manager']->trigger('__ORDER_DELIVER__', [
'ssel_id' => $order->getBasket()->getId(), 'ssel_id' => $order->getBasket()->getId(),
'from' => $app['authentication']->getUser()->get_id(), 'from' => $app['authentication']->getUser()->getId(),
'to' => $dest_user->get_id(), 'to' => $order->getUser()->getId(),
'n' => $n 'n' => $n
]); ]);
} }
@@ -333,7 +329,7 @@ class Order implements ControllerProviderInterface
$elements = $request->request->get('elements', []); $elements = $request->request->get('elements', []);
foreach ($order->getElements() as $orderElement) { foreach ($order->getElements() as $orderElement) {
if (in_array($orderElement->getId(),$elements)) { if (in_array($orderElement->getId(),$elements)) {
$orderElement->setOrderMasterId($app['authentication']->getUser()->get_id()); $orderElement->setOrderMaster($app['authentication']->getUser());
$orderElement->setDeny(true); $orderElement->setDeny(true);
$app['EM']->persist($orderElement); $app['EM']->persist($orderElement);
@@ -346,8 +342,8 @@ class Order implements ControllerProviderInterface
$order->setTodo($order->getTodo() - $n); $order->setTodo($order->getTodo() - $n);
$app['events-manager']->trigger('__ORDER_NOT_DELIVERED__', [ $app['events-manager']->trigger('__ORDER_NOT_DELIVERED__', [
'from' => $app['authentication']->getUser()->get_id(), 'from' => $app['authentication']->getUser()->getId(),
'to' => $order->getUsrId(), 'to' => $order->getUser()->getId(),
'n' => $n 'n' => $n
]); ]);
} }

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Controller\Prod;
use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Model\Entities\Basket;
use Alchemy\Phrasea\Model\Entities\BasketElement; use Alchemy\Phrasea\Model\Entities\BasketElement;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Model\Entities\UsrList; use Alchemy\Phrasea\Model\Entities\UsrList;
use Alchemy\Phrasea\Model\Entities\UsrListEntry; use Alchemy\Phrasea\Model\Entities\UsrListEntry;
use Alchemy\Phrasea\Model\Entities\ValidationSession; use Alchemy\Phrasea\Model\Entities\ValidationSession;
@@ -28,26 +29,26 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Push implements ControllerProviderInterface class Push implements ControllerProviderInterface
{ {
protected function getUserFormatter() protected function getUserFormatter(Application $app)
{ {
return function (\User_Adapter $user) { return function (User $user) use ($app) {
$subtitle = array_filter([$user->get_job(), $user->get_company()]); $subtitle = array_filter([$user->getJob(), $user->getCompany()]);
return [ return [
'type' => 'USER' 'type' => 'USER',
, 'usr_id' => $user->get_id() 'usr_id' => $user->getId(),
, 'firstname' => $user->get_firstname() 'firstname' => $user->getFirstName(),
, 'lastname' => $user->get_lastname() 'lastname' => $user->getLastName(),
, 'email' => $user->get_email() 'email' => $user->getEmail(),
, 'display_name' => $user->get_display_name() 'display_name' => $user->getDisplayName(),
, 'subtitle' => implode(', ', $subtitle) 'subtitle' => implode(', ', $subtitle),
]; ];
}; };
} }
protected function getListFormatter($app) protected function getListFormatter($app)
{ {
$userFormatter = $this->getUserFormatter(); $userFormatter = $this->getUserFormatter($app);
return function (UsrList $List) use ($userFormatter, $app) { return function (UsrList $List) use ($userFormatter, $app) {
$entries = []; $entries = [];
@@ -56,16 +57,16 @@ class Push implements ControllerProviderInterface
/* @var $entry UsrListEntry */ /* @var $entry UsrListEntry */
$entries[] = [ $entries[] = [
'Id' => $entry->getId(), 'Id' => $entry->getId(),
'User' => $userFormatter($entry->getUser($app)) 'User' => $userFormatter($entry->getUser())
]; ];
} }
return [ return [
'type' => 'LIST' 'type' => 'LIST',
, 'list_id' => $List->getId() 'list_id' => $List->getId(),
, 'name' => $List->getName() 'name' => $List->getName(),
, 'length' => count($entries) 'length' => count($entries),
, 'entries' => $entries 'entries' => $entries,
]; ];
}; };
} }
@@ -87,7 +88,7 @@ class Push implements ControllerProviderInterface
$user = $value->getRessource(); $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'); $app['firewall']->requireRight('push');
}); });
$userFormatter = $this->getUserFormatter(); $userFormatter = $this->getUserFormatter($app);
$listFormatter = $this->getListFormatter($app); $listFormatter = $this->getListFormatter($app);
@@ -161,7 +162,7 @@ class Push implements ControllerProviderInterface
try { try {
$pusher = new RecordHelper\Push($app, $app['request']); $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'); $push_description = $request->request->get('push_description');
$receivers = $request->request->get('participants'); $receivers = $request->request->get('participants');
@@ -176,7 +177,7 @@ class Push implements ControllerProviderInterface
foreach ($receivers as $receiver) { foreach ($receivers as $receiver) {
try { try {
$user_receiver = \User_Adapter::getInstance($receiver['usr_id'], $app); $user_receiver = $app['manipulator.user']->getRepository()->find($receiver['usr_id']);
} catch (\Exception $e) { } catch (\Exception $e) {
throw new ControllerException($app->trans('Unknown user %user_id%', ['%user_id%' => $receiver['usr_id']])); 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 = new Basket();
$Basket->setName($push_name); $Basket->setName($push_name);
$Basket->setDescription($push_description); $Basket->setDescription($push_description);
$Basket->setOwner($user_receiver); $Basket->setUser($user_receiver);
$Basket->setPusher($app['authentication']->getUser()); $Basket->setPusher($app['authentication']->getUser());
$Basket->setIsRead(false); $Basket->setIsRead(false);
@@ -220,31 +221,31 @@ class Push implements ControllerProviderInterface
'basket' => $Basket->getId(), 'basket' => $Basket->getId(),
'LOG' => $app['tokens']->getUrlToken( 'LOG' => $app['tokens']->getUrlToken(
\random::TYPE_VIEW, \random::TYPE_VIEW,
$user_receiver->get_id(), $user_receiver->getId(),
null, null,
$Basket->getId() $Basket->getId()
) )
]); ]);
$receipt = $request->get('recept') ? $app['authentication']->getUser()->get_email() : ''; $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : '';
$params = [ $params = [
'from' => $app['authentication']->getUser()->get_id() 'from' => $app['authentication']->getUser()->getId(),
, 'from_email' => $app['authentication']->getUser()->get_email() 'from_email' => $app['authentication']->getUser()->getEmail(),
, 'to' => $user_receiver->get_id() 'to' => $user_receiver->getId(),
, 'to_email' => $user_receiver->get_email() 'to_email' => $user_receiver->getEmail(),
, 'to_name' => $user_receiver->get_display_name() 'to_name' => $user_receiver->getDisplayName(),
, 'url' => $url 'url' => $url,
, 'accuse' => $receipt 'accuse' => $receipt,
, 'message' => $request->request->get('message') 'message' => $request->request->get('message'),
, 'ssel_id' => $Basket->getId() 'ssel_id' => $Basket->getId(),
]; ];
$app['events-manager']->trigger('__PUSH_DATAS__', $params); $app['events-manager']->trigger('__PUSH_DATAS__', $params);
} }
$app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox()) $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(); $app['EM']->flush();
@@ -277,9 +278,7 @@ class Push implements ControllerProviderInterface
try { try {
$pusher = new RecordHelper\Push($app, $app['request']); $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()->getDisplayName()]));
$validation_name = $request->request->get('name', $app->trans('Validation from %user%', ['%user%' => $app['authentication']->getUser()->get_display_name()]));
$validation_description = $request->request->get('validation_description'); $validation_description = $request->request->get('validation_description');
$participants = $request->request->get('participants'); $participants = $request->request->get('participants');
@@ -298,7 +297,7 @@ class Push implements ControllerProviderInterface
$Basket = new Basket(); $Basket = new Basket();
$Basket->setName($validation_name); $Basket->setName($validation_name);
$Basket->setDescription($validation_description); $Basket->setDescription($validation_description);
$Basket->setOwner($app['authentication']->getUser()); $Basket->setUser($app['authentication']->getUser());
$Basket->setIsRead(false); $Basket->setIsRead(false);
$app['EM']->persist($Basket); $app['EM']->persist($Basket);
@@ -336,17 +335,17 @@ class Push implements ControllerProviderInterface
} }
$found = false; $found = false;
foreach ($participants as $key => $participant) { foreach ($participants as $participant) {
if ($participant['usr_id'] == $app['authentication']->getUser()->get_id()) { if ($participant['usr_id'] === $app['authentication']->getUser()->getId()) {
$found = true; $found = true;
break; break;
} }
} }
if (!$found) { if (!$found) {
$participants[$app['authentication']->getUser()->get_id()] = [ $participants[] = [
'see_others' => 1, 'see_others' => 1,
'usr_id' => $app['authentication']->getUser()->get_id(), 'usr_id' => $app['authentication']->getUser()->getId(),
'agree' => 0, 'agree' => 0,
'HD' => 0 'HD' => 0
]; ];
@@ -359,13 +358,13 @@ class Push implements ControllerProviderInterface
} }
try { try {
$participant_user = \User_Adapter::getInstance($participant['usr_id'], $app); $participant_user = $app['manipulator.user']->getRepository()->find($participant['usr_id']);
} catch (\Exception $e) { } catch (\Exception $e) {
throw new ControllerException($app->trans('Unknown user %usr_id%', ['%usr_id%' => $participant['usr_id']])); throw new ControllerException($app->trans('Unknown user %usr_id%', ['%usr_id%' => $participant['usr_id']]));
} }
try { try {
$Participant = $Validation->getParticipant($participant_user, $app); $Participant = $Validation->getParticipant($participant_user);
continue; continue;
} catch (NotFoundHttpException $e) { } catch (NotFoundHttpException $e) {
@@ -404,7 +403,7 @@ class Push implements ControllerProviderInterface
$app['EM']->persist($ValidationData); $app['EM']->persist($ValidationData);
$app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox()) $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); $Participant->addData($ValidationData);
} }
@@ -417,20 +416,20 @@ class Push implements ControllerProviderInterface
'basket' => $Basket->getId(), 'basket' => $Basket->getId(),
'LOG' => $app['tokens']->getUrlToken( 'LOG' => $app['tokens']->getUrlToken(
\random::TYPE_VALIDATE, \random::TYPE_VALIDATE,
$participant_user->get_id(), $participant_user->getId(),
null, null,
$Basket->getId() $Basket->getId()
) )
]); ]);
$receipt = $request->get('recept') ? $app['authentication']->getUser()->get_email() : ''; $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : '';
$params = [ $params = [
'from' => $app['authentication']->getUser()->get_id(), 'from' => $app['authentication']->getUser()->getId(),
'from_email' => $app['authentication']->getUser()->get_email(), 'from_email' => $app['authentication']->getUser()->getEmail(),
'to' => $participant_user->get_id(), 'to' => $participant_user->getId(),
'to_email' => $participant_user->get_email(), 'to_email' => $participant_user->getEmail(),
'to_name' => $participant_user->get_display_name(), 'to_name' => $participant_user->getDisplayName(),
'url' => $url, 'url' => $url,
'accuse' => $receipt, 'accuse' => $receipt,
'message' => $request->request->get('message'), 'message' => $request->request->get('message'),
@@ -494,7 +493,7 @@ class Push implements ControllerProviderInterface
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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) { if ($list) {
$datas = $listFormatter($list); $datas = $listFormatter($list);
@@ -533,8 +532,7 @@ class Push implements ControllerProviderInterface
$email = $request->request->get('email'); $email = $request->request->get('email');
try { try {
$usr_id = \User_Adapter::get_usr_id_from_email($app, $email); $user = $app['manipulator.user']->getRepository()->findByEmail($email);
$user = \User_Adapter::getInstance($usr_id, $app);
$result['message'] = $app->trans('User already exists'); $result['message'] = $app->trans('User already exists');
$result['success'] = true; $result['success'] = true;
@@ -543,21 +541,24 @@ class Push implements ControllerProviderInterface
} }
if (!$user instanceof \User_Adapter) { if (!$user instanceof User) {
try { try {
$password = \random::generatePassword(); $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')) $user->setFirstName($request->request->get('firstname'))
->set_lastname($request->request->get('lastname')); ->setLastName($request->request->get('lastname'));
if ($request->request->get('company')) if ($request->request->get('company')) {
$user->set_company($request->request->get('company')); $user->setCompany($request->request->get('company'));
if ($request->request->get('job')) }
$user->set_company($request->request->get('job')); if ($request->request->get('job')) {
if ($request->request->get('form_geonameid')) $user->setCompany($request->request->get('job'));
$user->set_geonameid($request->request->get('form_geonameid')); }
if ($request->request->get('form_geonameid')) {
$app['manipulator.user']->setGeonameId($user, $request->request->get('form_geonameid'));
}
$result['message'] = $app->trans('User successfully created'); $result['message'] = $app->trans('User successfully created');
$result['success'] = true; $result['success'] = true;
@@ -617,7 +618,7 @@ class Push implements ControllerProviderInterface
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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); $query = new \User_Query($app);

View File

@@ -12,7 +12,6 @@
namespace Alchemy\Phrasea\Controller\Prod; namespace Alchemy\Phrasea\Controller\Prod;
use Alchemy\Phrasea\SearchEngine\SearchEngineOptions; use Alchemy\Phrasea\SearchEngine\SearchEngineOptions;
use Alchemy\Phrasea\Model\Entities\UserQuery;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
@@ -52,7 +51,7 @@ class Query implements ControllerProviderInterface
{ {
$query = (string) $request->request->get('qry'); $query = (string) $request->request->get('qry');
$mod = $app['authentication']->getUser()->getPrefs('view'); $mod = $app['settings']->getUserSetting($app['authentication']->getUser(), 'view');
$json = []; $json = [];
@@ -60,7 +59,7 @@ class Query implements ControllerProviderInterface
$form = $options->serialize(); $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'); $page = (int) $request->request->get('pag');
$firstPage = $page < 1; $firstPage = $page < 1;
@@ -72,15 +71,10 @@ class Query implements ControllerProviderInterface
$result = $app['phraseanet.SE']->query($query, (($page - 1) * $perPage), $perPage, $options); $result = $app['phraseanet.SE']->query($query, (($page - 1) * $perPage), $perPage, $options);
$userQuery = new UserQuery(); $app['manipulator.user']->logQuery($app['authentication']->getUser(), $result->getQuery());
$userQuery->setUsrId($app['authentication']->getUser()->get_id());
$userQuery->setQuery($result->getQuery());
$app['EM']->persist($userQuery); if ($app['settings']->getUserSetting($app['authentication']->getUser(), 'start_page') === 'LAST_QUERY') {
$app['EM']->flush(); $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), 'start_page_query', $result->getQuery());
if ($app['authentication']->getUser()->getPrefs('start_page') === 'LAST_QUERY') {
$app['authentication']->getUser()->setPrefs('start_page_query', $result->getQuery());
} }
foreach ($options->getDataboxes() as $databox) { foreach ($options->getDataboxes() as $databox) {

View File

@@ -65,7 +65,7 @@ class Root implements ControllerProviderInterface
$css[$baseName] = $baseName; $css[$baseName] = $baseName;
} }
$cssfile = $app['authentication']->getUser()->getPrefs('css'); $cssfile = $app['settings']->getUserSetting($app['authentication']->getUser(), 'css');
if (!$cssfile && isset($css['000000'])) { if (!$cssfile && isset($css['000000'])) {
$cssfile = '000000'; $cssfile = '000000';
@@ -119,7 +119,7 @@ class Root implements ControllerProviderInterface
'GV_google_api' => $app['conf']->get(['registry', 'webservices', 'google-charts-enabled']), 'GV_google_api' => $app['conf']->get(['registry', 'webservices', 'google-charts-enabled']),
'queries_topics' => $queries_topics, 'queries_topics' => $queries_topics,
'search_status' => \databox_status::getSearchStatus($app), '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_js_list' => $thjslist,
'thesau_json_sbas' => json_encode($sbas), 'thesau_json_sbas' => json_encode($sbas),
'thesau_json_bas2sbas' => json_encode($bas2sbas), 'thesau_json_bas2sbas' => json_encode($bas2sbas),

View File

@@ -89,7 +89,7 @@ class Tooltip implements ControllerProviderInterface
public function displayUserBadge(Application $app, $usr_id) 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( return $app['twig']->render(
'prod/Tooltip/User.html.twig' 'prod/Tooltip/User.html.twig'

View File

@@ -158,7 +158,7 @@ class Upload implements ControllerProviderInterface
$collection = \collection::get_from_base_id($app, $base_id); $collection = \collection::get_from_base_id($app, $base_id);
$lazaretSession = new LazaretSession(); $lazaretSession = new LazaretSession();
$lazaretSession->setUsrId($app['authentication']->getUser()->get_id()); $lazaretSession->setUser($app['authentication']->getUser());
$app['EM']->persist($lazaretSession); $app['EM']->persist($lazaretSession);

View File

@@ -91,24 +91,24 @@ class UsrLists implements ControllerProviderInterface
foreach ($list->getOwners() as $owner) { foreach ($list->getOwners() as $owner) {
$owners[] = [ $owners[] = [
'usr_id' => $owner->getUser($app)->get_id(), 'usr_id' => $owner->getUser()->getId(),
'display_name' => $owner->getUser($app)->get_display_name(), 'display_name' => $owner->getUser()->getDisplayName(),
'position' => $owner->getUser($app)->get_position(), 'position' => $owner->getUser()->getActivity(),
'job' => $owner->getUser($app)->get_job(), 'job' => $owner->getUser()->getJob(),
'company' => $owner->getUser($app)->get_company(), 'company' => $owner->getUser()->getCompany(),
'email' => $owner->getUser($app)->get_email(), 'email' => $owner->getUser()->getEmail(),
'role' => $owner->getRole() 'role' => $owner->getRole()
]; ];
} }
foreach ($list->getEntries() as $entry) { foreach ($list->getEntries() as $entry) {
$entries[] = [ $entries[] = [
'usr_id' => $owner->getUser($app)->get_id(), 'usr_id' => $entry->getUser()->getId(),
'display_name' => $owner->getUser($app)->get_display_name(), 'display_name' => $entry->getUser()->getDisplayName(),
'position' => $owner->getUser($app)->get_position(), 'position' => $entry->getUser()->getActivity(),
'job' => $owner->getUser($app)->get_job(), 'job' => $entry->getUser()->getJob(),
'company' => $owner->getUser($app)->get_company(), 'company' => $entry->getUser()->getCompany(),
'email' => $owner->getUser($app)->get_email(), 'email' => $entry->getUser()->getEmail(),
]; ];
} }
@@ -195,31 +195,31 @@ class UsrLists implements ControllerProviderInterface
{ {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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(); $entries = new ArrayCollection();
$owners = new ArrayCollection(); $owners = new ArrayCollection();
foreach ($list->getOwners() as $owner) { foreach ($list->getOwners() as $owner) {
$owners[] = [ $owners[] = [
'usr_id' => $owner->getUser($app)->get_id(), 'usr_id' => $owner->getUser()->getId(),
'display_name' => $owner->getUser($app)->get_display_name(), 'display_name' => $owner->getUser()->getDisplayName(),
'position' => $owner->getUser($app)->get_position(), 'position' => $owner->getUser()->getActivity(),
'job' => $owner->getUser($app)->get_job(), 'job' => $owner->getUser()->getJob(),
'company' => $owner->getUser($app)->get_company(), 'company' => $owner->getUser()->getCompany(),
'email' => $owner->getUser($app)->get_email(), 'email' => $owner->getUser()->getEmail(),
'role' => $owner->getRole($app) 'role' => $owner->getRole()
]; ];
} }
foreach ($list->getEntries() as $entry) { foreach ($list->getEntries() as $entry) {
$entries[] = [ $entries[] = [
'usr_id' => $entry->getUser($app)->get_id(), 'usr_id' => $entry->getUser()->getId(),
'display_name' => $entry->getUser($app)->get_display_name(), 'display_name' => $entry->getUser()->getDisplayName(),
'position' => $entry->getUser($app)->get_position(), 'position' => $entry->getUser()->getActivity(),
'job' => $entry->getUser($app)->get_job(), 'job' => $entry->getUser()->getJob(),
'company' => $entry->getUser($app)->get_company(), 'company' => $entry->getUser()->getCompany(),
'email' => $entry->getUser($app)->get_email(), 'email' => $entry->getUser()->getEmail(),
]; ];
} }
@@ -253,7 +253,7 @@ class UsrLists implements ControllerProviderInterface
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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) { if ($list->getOwner($app['authentication']->getUser(), $app)->getRole() < UsrListOwner::ROLE_EDITOR) {
throw new ControllerException($app->trans('You are not authorized to do this')); throw new ControllerException($app->trans('You are not authorized to do this'));
@@ -284,9 +284,9 @@ class UsrLists implements ControllerProviderInterface
try { try {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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')); throw new ControllerException($app->trans('You are not authorized to do this'));
} }
@@ -318,10 +318,10 @@ class UsrLists implements ControllerProviderInterface
try { try {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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 */ /* @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')); 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'); $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 */ /* @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')); throw new ControllerException($app->trans('You are not authorized to do this'));
} }
$inserted_usr_ids = []; $inserted_usr_ids = [];
foreach ($request->request->get('usr_ids') as $usr_id) { 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; continue;
$entry = new UsrListEntry(); $entry = new UsrListEntry();
@@ -383,7 +383,7 @@ class UsrLists implements ControllerProviderInterface
$app['EM']->persist($entry); $app['EM']->persist($entry);
$inserted_usr_ids[] = $user_entry->get_id(); $inserted_usr_ids[] = $user_entry->getId();
} }
$app['EM']->flush(); $app['EM']->flush();
@@ -424,10 +424,10 @@ class UsrLists implements ControllerProviderInterface
try { try {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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 */ /* @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; $list = null;
throw new \Exception($app->trans('You are not authorized to do this')); throw new \Exception($app->trans('You are not authorized to do this'));
} }
@@ -454,21 +454,21 @@ class UsrLists implements ControllerProviderInterface
try { try {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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 */ /* @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')); 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 ($list->hasAccess($new_owner)) {
if ($new_owner->get_id() == $app['authentication']->getUser()->get_id()) { if ($new_owner->getId() == $app['authentication']->getUser()->getId()) {
throw new ControllerException('You can not downgrade your Admin right'); throw new ControllerException('You can not downgrade your Admin right');
} }
$owner = $list->getOwner($new_owner, $app); $owner = $list->getOwner($new_owner);
} else { } else {
$owner = new UsrListOwner(); $owner = new UsrListOwner();
$owner->setList($list); $owner->setList($list);
@@ -510,10 +510,10 @@ class UsrLists implements ControllerProviderInterface
try { try {
$repository = $app['EM']->getRepository('Phraseanet:UsrList'); $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 */ /* @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')); throw new \Exception($app->trans('You are not authorized to do this'));
} }

View File

@@ -242,7 +242,6 @@ class RecordsRequest extends ArrayCollection
$to_remove = []; $to_remove = [];
foreach ($elements as $id => $record) { foreach ($elements as $id => $record) {
if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_record($record)) { if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_record($record)) {
$to_remove[] = $id; $to_remove[] = $id;
continue; continue;

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Root;
use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface; use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface;
use Alchemy\Phrasea\Application as PhraseaApplication; use Alchemy\Phrasea\Application as PhraseaApplication;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\Entities\FtpCredential;
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
use Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate; use Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate;
use Alchemy\Phrasea\Form\Login\PhraseaRenewPasswordForm; use Alchemy\Phrasea\Form\Login\PhraseaRenewPasswordForm;
@@ -75,13 +76,6 @@ class Account implements ControllerProviderInterface
return $controllers; return $controllers;
} }
/**
* Reset Password
*
* @param Application $app
* @param Request $request
* @return Response
*/
public function resetPassword(Application $app, Request $request) public function resetPassword(Application $app, Request $request)
{ {
$form = $app->form(new PhraseaRenewPasswordForm()); $form = $app->form(new PhraseaRenewPasswordForm());
@@ -93,8 +87,8 @@ class Account implements ControllerProviderInterface
$data = $form->getData(); $data = $form->getData();
$user = $app['authentication']->getUser(); $user = $app['authentication']->getUser();
if ($app['auth.password-encoder']->isPasswordValid($user->get_password(), $data['oldPassword'], $user->get_nonce())) { if ($app['auth.password-encoder']->isPasswordValid($user->getPassword(), $data['oldPassword'], $user->getNonce())) {
$user->set_password($data['password']); $app['manipulator.user']->setPassword($user, $data['password']);
$app->addFlash('success', $app->trans('login::notification: Mise a jour du mot de passe avec succes')); $app->addFlash('success', $app->trans('login::notification: Mise a jour du mot de passe avec succes'));
return $app->redirectPath('account'); return $app->redirectPath('account');
@@ -126,7 +120,7 @@ class Account implements ControllerProviderInterface
$user = $app['authentication']->getUser(); $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')); $app->addFlash('error', $app->trans('admin::compte-utilisateur:ftp: Le mot de passe est errone'));
return $app->redirectPath('account_reset_email'); return $app->redirectPath('account_reset_email');
@@ -145,7 +139,7 @@ class Account implements ControllerProviderInterface
} }
$date = new \DateTime('1 day'); $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]); $url = $app->url('account_reset_email', ['token' => $token]);
try { try {
@@ -179,8 +173,8 @@ class Account implements ControllerProviderInterface
if (null !== $token = $request->query->get('token')) { if (null !== $token = $request->query->get('token')) {
try { try {
$datas = $app['tokens']->helloToken($token); $datas = $app['tokens']->helloToken($token);
$user = \User_Adapter::getInstance((int) $datas['usr_id'], $app); $user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id']);
$user->set_email($datas['datas']); $user->setEmail($datas['datas']);
$app['tokens']->removeToken($token); $app['tokens']->removeToken($token);
$app->addFlash('success', $app->trans('admin::compte-utilisateur: L\'email a correctement ete mis a jour')); $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'; require_once $app['root.path'] . '/lib/classes/deprecated/inscript.api.php';
return $app['twig']->render('account/access.html.twig', [ 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) public function accountSessionsAccess(Application $app, Request $request)
{ {
$dql = 'SELECT s FROM Phraseanet:Session s $dql = 'SELECT s FROM Phraseanet:Session s
WHERE s.usr_id = :usr_id WHERE s.user = :usr_id
ORDER BY s.created DESC'; ORDER BY s.created DESC';
$query = $app['EM']->createQuery($dql); $query = $app['EM']->createQuery($dql);
@@ -321,7 +315,7 @@ class Account implements ControllerProviderInterface
return $app['twig']->render('account/account.html.twig', [ return $app['twig']->render('account/account.html.twig', [
'user' => $app['authentication']->getUser(), 'user' => $app['authentication']->getUser(),
'evt_mngr' => $app['events-manager'], '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', []); $demands = (array) $request->request->get('demand', []);
if (0 !== count($demands)) { if (0 !== count($demands)) {
$register = new \appbox_register($app['phraseanet.appbox']);
foreach ($demands as $baseId) { foreach ($demands as $baseId) {
try { 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')); $app->addFlash('success', $app->trans('login::notification: Vos demandes ont ete prises en compte'));
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -370,53 +362,48 @@ class Account implements ControllerProviderInterface
]; ];
if (0 === count(array_diff($accountFields, array_keys($request->request->all())))) { 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['manipulator.user']->setGeonameId($app['authentication']->getUser(), $request->request->get("form_geonameid"));
$app['phraseanet.appbox']->get_connection()->beginTransaction();
$app['authentication']->getUser() $ftpCredential = $app['authentication']->getUser()->getFtpCredential();
->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(); if (null === $ftpCredential) {
$ftpCredential = new FtpCredential();
$ftpCredential->setActive($request->request->get("form_activeFTP")); $ftpCredential->setUser($app['authentication']->getUser());
$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();
} }
$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', []); $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) { foreach ($notifications as $notification) {
if (isset($requestedNotifications[$notification['id']])) { $app['manipulator.user']->setNotificationSetting($app['authentication']->getUser(), $notification['id'], 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');
}
} }
} }

View File

@@ -23,6 +23,7 @@ use Alchemy\Phrasea\Core\PhraseaEvents;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Exception\FormProcessingException; use Alchemy\Phrasea\Exception\FormProcessingException;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Model\Entities\ValidationParticipant; use Alchemy\Phrasea\Model\Entities\ValidationParticipant;
use Alchemy\Phrasea\Model\Entities\UsrAuthProvider; use Alchemy\Phrasea\Model\Entities\UsrAuthProvider;
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
@@ -308,7 +309,7 @@ class Login implements ControllerProviderInterface
->findWithProviderAndId($token->getProvider()->getId(), $token->getId()); ->findWithProviderAndId($token->getProvider()->getId(), $token->getId());
if (null !== $userAuthProvider) { if (null !== $userAuthProvider) {
$this->postAuthProcess($app, $userAuthProvider->getUser($app)); $this->postAuthProcess($app, $userAuthProvider->getUser());
if (null !== $redirect = $request->query->get('redirect')) { if (null !== $redirect = $request->query->get('redirect')) {
$redirection = '../' . $redirect; $redirection = '../' . $redirect;
@@ -339,7 +340,6 @@ class Login implements ControllerProviderInterface
$inscOK = []; $inscOK = [];
foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) { foreach ($databox->get_collections() as $collection) {
if (null !== $selected && !in_array($collection->get_base_id(), $selected)) { if (null !== $selected && !in_array($collection->get_base_id(), $selected)) {
continue; continue;
@@ -362,26 +362,32 @@ class Login implements ControllerProviderInterface
$data['login'] = $data['email']; $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 ([ foreach ([
'gender' => 'set_gender', 'gender' => 'setGender',
'firstname' => 'set_firstname', 'firstname' => 'setFirstName',
'lastname' => 'set_lastname', 'lastname' => 'setLastName',
'address' => 'set_address', 'address' => 'setAddress',
'zipcode' => 'set_zip', 'zipcode' => 'setZipCode',
'tel' => 'set_tel', 'tel' => 'setPhone',
'fax' => 'set_fax', 'fax' => 'setFax',
'job' => 'set_job', 'job' => 'setJob',
'company' => 'set_company', 'company' => 'setCompany',
'position' => 'set_position', 'position' => 'setActivity',
'geonameid' => 'set_geonameid',
] as $property => $method) { ] as $property => $method) {
if (isset($data[$property])) { if (isset($data[$property])) {
call_user_func([$user, $method], $data[$property]); call_user_func([$user, $method], $data[$property]);
} }
} }
$app['EM']->persist($user);
$app['EM']->flush();
if (null !== $provider) { if (null !== $provider) {
$this->attachProviderToUser($app['EM'], $provider, $user); $this->attachProviderToUser($app['EM'], $provider, $user);
$app['EM']->flush(); $app['EM']->flush();
@@ -390,43 +396,39 @@ class Login implements ControllerProviderInterface
$demandOK = []; $demandOK = [];
if ($app['conf']->get(['registry', 'registration', 'auto-register-enabled'])) { if ($app['conf']->get(['registry', 'registration', 'auto-register-enabled'])) {
$template_user = $app['manipulator.user']->getRepository()->findByLogin(User::USER_AUTOREGISTER);
$template_user_id = \User_Adapter::get_usr_id_from_login($app, 'autoregister');
$template_user = \User_Adapter::getInstance($template_user_id, $app);
$base_ids = []; $base_ids = [];
foreach (array_keys($inscOK) as $base_id) { foreach (array_keys($inscOK) as $base_id) {
$base_ids[] = $base_id; $base_ids[] = $base_id;
} }
$app['acl']->get($user)->apply_model($template_user, $base_ids); $app['acl']->get($user)->apply_model($template_user, $base_ids);
} }
$autoReg = $app['acl']->get($user)->get_granted_base(); $autoReg = $app['acl']->get($user)->get_granted_base();
$appbox_register = new \appbox_register($app['phraseanet.appbox']);
foreach ($inscOK as $base_id => $autorisation) { foreach ($inscOK as $base_id => $autorisation) {
if (false === $autorisation || $app['acl']->get($user)->has_access_to_base($base_id)) { if (false === $autorisation || $app['acl']->get($user)->has_access_to_base($base_id)) {
continue; continue;
} }
$collection = \collection::get_from_base_id($app, $base_id); $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; $demandOK[$base_id] = true;
} }
$params = [ $params = [
'demand' => $demandOK, 'demand' => $demandOK,
'autoregister' => $autoReg, 'autoregister' => $autoReg,
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
$app['events-manager']->trigger('__REGISTER_AUTOREGISTER__', $params); $app['events-manager']->trigger('__REGISTER_AUTOREGISTER__', $params);
$app['events-manager']->trigger('__REGISTER_APPROVAL__', $params); $app['events-manager']->trigger('__REGISTER_APPROVAL__', $params);
$user->set_mail_locked(true); $user->setMailLocked(true);
try { try {
$this->sendAccountUnlockEmail($app, $user); $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 = new UsrAuthProvider();
$usrAuthProvider->setDistantId($provider->getToken()->getId()); $usrAuthProvider->setDistantId($provider->getToken()->getId());
$usrAuthProvider->setProvider($provider->getId()); $usrAuthProvider->setProvider($provider->getId());
$usrAuthProvider->setUsrId($user->get_id()); $usrAuthProvider->setUser($user);
try { try {
$provider->logout(); $provider->logout();
@@ -491,9 +493,7 @@ class Login implements ControllerProviderInterface
$app->abort(400, 'Missing usr_id parameter.'); $app->abort(400, 'Missing usr_id parameter.');
} }
try { if (null === $user = $app['manipulator.user']->getRepository()->find((int) $usrId)) {
$user = \User_Adapter::getInstance((int) $usrId, $app);
} catch (\Exception $e) {
$app->addFlash('error', $app->trans('Invalid link.')); $app->addFlash('error', $app->trans('Invalid link.'));
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
@@ -514,17 +514,17 @@ class Login implements ControllerProviderInterface
* Sends an account unlock email. * Sends an account unlock email.
* *
* @param PhraseaApplication $app * @param PhraseaApplication $app
* @param \User_Adapter $user * @param User $user
* *
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @throws RuntimeException * @throws RuntimeException
*/ */
private function sendAccountUnlockEmail(PhraseaApplication $app, \User_Adapter $user) private function sendAccountUnlockEmail(PhraseaApplication $app, User $user)
{ {
$receiver = Receiver::fromUser($user); $receiver = Receiver::fromUser($user);
$expire = new \DateTime('+3 days'); $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 = MailRequestEmailConfirmation::create($app, $receiver);
$mail->setButtonUrl($app->url('login_register_confirm', ['code' => $token])); $mail->setButtonUrl($app->url('login_register_confirm', ['code' => $token]));
@@ -556,22 +556,20 @@ class Login implements ControllerProviderInterface
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
} }
try { if (null === $user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id'])) {
$user = \User_Adapter::getInstance((int) $datas['usr_id'], $app); $app->addFlash('error', _('Invalid unlock link.'));
} catch (\Exception $e) {
$app->addFlash('error', $app->trans('Invalid unlock link.'));
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
} }
if (!$user->get_mail_locked()) { if (!$user->isMailLocked()) {
$app->addFlash('info', $app->trans('Account is already unlocked, you can login.')); $app->addFlash('info', $app->trans('Account is already unlocked, you can login.'));
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
} }
$app['tokens']->removeToken($code); $app['tokens']->removeToken($code);
$user->set_mail_locked(false); $user->setMailLocked(false);
try { try {
$receiver = Receiver::fromUser($user); $receiver = Receiver::fromUser($user);
@@ -621,8 +619,8 @@ class Login implements ControllerProviderInterface
$datas = $app['tokens']->helloToken($token); $datas = $app['tokens']->helloToken($token);
$user = \User_Adapter::getInstance($datas['usr_id'], $app); $user = $app['manipulator.user']->getRepository()->find($datas['usr_id']);
$user->set_password($data['password']); $app['manipulator.user']->setPassword($user, $data['password']);
$app['tokens']->removeToken($token); $app['tokens']->removeToken($token);
@@ -659,10 +657,8 @@ class Login implements ControllerProviderInterface
if ($form->isValid()) { if ($form->isValid()) {
$data = $form->getData(); $data = $form->getData();
try { if (null === $user = $app['manipulator.user']->getRepository()->findByEmail($data['email'])) {
$user = \User_Adapter::getInstance(\User_Adapter::get_usr_id_from_email($app, $data['email']), $app); throw new FormProcessingException(_('phraseanet::erreur: Le compte n\'a pas ete trouve'));
} catch (\Exception $e) {
throw new FormProcessingException($app->trans('phraseanet::erreur: Le compte n\'a pas ete trouve'));
} }
try { try {
@@ -671,7 +667,7 @@ class Login implements ControllerProviderInterface
throw new FormProcessingException($app->trans('Invalid email address')); 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) { if (!$token) {
return $app->abort(500, 'Unable to generate a 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); $url = $app->url('login_renew_password', ['token' => $token], true);
$mail = MailRequestPasswordUpdate::create($app, $receiver); $mail = MailRequestPasswordUpdate::create($app, $receiver);
$mail->setLogin($user->get_login()); $mail->setLogin($user->getLogin());
$mail->setButtonUrl($url); $mail->setButtonUrl($url);
$app['notification.deliverer']->deliver($mail); $app['notification.deliverer']->deliver($mail);
@@ -807,11 +803,8 @@ class Login implements ControllerProviderInterface
$context = new Context(Context::CONTEXT_GUEST); $context = new Context(Context::CONTEXT_GUEST);
$app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context)); $app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
$password = \random::generatePassword(24); $user = $app['manipulator.user']->createUser(uniqid('guest'), \random::generatePassword(24));
$user = \User_Adapter::create($app, 'invite', $password, null, false, true); $invite_user = $app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST);
$inviteUsrid = \User_Adapter::get_usr_id_from_login($app, 'invite');
$invite_user = \User_Adapter::getInstance($inviteUsrid, $app);
$usr_base_ids = array_keys($app['acl']->get($user)->get_granted_base()); $usr_base_ids = array_keys($app['acl']->get($user)->get_granted_base());
$app['acl']->get($user)->revoke_access_from_bases($usr_base_ids); $app['acl']->get($user)->revoke_access_from_bases($usr_base_ids);
@@ -822,7 +815,7 @@ class Login implements ControllerProviderInterface
$this->postAuthProcess($app, $user); $this->postAuthProcess($app, $user);
$response = $this->generateAuthResponse($app, $app['browser'], $request->request->get('redirect')); $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); $event = new PostAuthenticate($request, $response, $user, $context);
$app['dispatcher']->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event); $app['dispatcher']->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
@@ -849,7 +842,7 @@ class Login implements ControllerProviderInterface
} }
// move this in an event // 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'); $date = new \DateTime('+' . (int) $app['conf']->get(['registry', 'actions', 'validation-reminder-days']) . ' days');
@@ -860,7 +853,7 @@ class Login implements ControllerProviderInterface
/* @var $participant ValidationParticipant */ /* @var $participant ValidationParticipant */
$validationSession = $participant->getSession(); $validationSession = $participant->getSession();
$participantId = $participant->getUsrId(); $participantId = $participant->getUser()->getId();
$basketId = $validationSession->getBasket()->getId(); $basketId = $validationSession->getBasket()->getId();
try { try {
@@ -872,7 +865,7 @@ class Login implements ControllerProviderInterface
$app['events-manager']->trigger('__VALIDATION_REMINDER__', [ $app['events-manager']->trigger('__VALIDATION_REMINDER__', [
'to' => $participantId, 'to' => $participantId,
'ssel_id' => $basketId, 'ssel_id' => $basketId,
'from' => $validationSession->getInitiatorId(), 'from' => $validationSession->getInitiator()->getId(),
'validate_id' => $validationSession->getId(), 'validate_id' => $validationSession->getId(),
'url' => $app->url('lightbox_validation', ['basket' => $basketId, 'LOG' => $token]), 'url' => $app->url('lightbox_validation', ['basket' => $basketId, 'LOG' => $token]),
]); ]);
@@ -885,8 +878,8 @@ class Login implements ControllerProviderInterface
$session = $app['authentication']->openAccount($user); $session = $app['authentication']->openAccount($user);
if ($user->get_locale() != $app['locale']) { if ($user->getLocale() != $app['locale']) {
$user->set_locale($app['locale']); $user->setLocale($app['locale']);
} }
$width = $height = null; $width = $height = null;
@@ -931,7 +924,7 @@ class Login implements ControllerProviderInterface
->findWithProviderAndId($token->getProvider()->getId(), $token->getId()); ->findWithProviderAndId($token->getProvider()->getId(), $token->getId());
if (null !== $userAuthProvider) { if (null !== $userAuthProvider) {
$this->postAuthProcess($app, $userAuthProvider->getUser($app)); $this->postAuthProcess($app, $userAuthProvider->getUser());
if (null !== $redirect = $request->query->get('redirect')) { if (null !== $redirect = $request->query->get('redirect')) {
$redirection = '../' . $redirect; $redirection = '../' . $redirect;
@@ -1047,7 +1040,7 @@ class Login implements ControllerProviderInterface
throw new AuthenticationException(call_user_func($redirector, $params)); 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); $session = $this->postAuthProcess($app, $user);
@@ -1055,14 +1048,14 @@ class Login implements ControllerProviderInterface
$response->headers->clearCookie('invite-usr-id'); $response->headers->clearCookie('invite-usr-id');
if ($request->cookies->has('postlog') && $request->cookies->get('postlog') == '1') { if ($request->cookies->has('postlog') && $request->cookies->get('postlog') == '1') {
if (!$user->is_guest() && $request->cookies->has('invite-usr_id')) { if (!$user->isGuest() && $request->cookies->has('invite-usr_id')) {
if ($user->get_id() != $inviteUsrId = $request->cookies->get('invite-usr_id')) { if ($user->getId() != $inviteUsrId = $request->cookies->get('invite-usr_id')) {
$repo = $app['EM']->getRepository('Phraseanet:Basket'); $repo = $app['EM']->getRepository('Phraseanet:Basket');
$baskets = $repo->findBy(['usr_id' => $inviteUsrId]); $baskets = $repo->findBy(['usr_id' => $inviteUsrId]);
foreach ($baskets as $basket) { foreach ($baskets as $basket) {
$basket->setUsrId($user->get_id()); $basket->setUser($user);
$app['EM']->persist($basket); $app['EM']->persist($basket);
} }
} }

View File

@@ -55,7 +55,7 @@ class RSSFeeds implements ControllerProviderInterface
$page = $page < 1 ? 1 : $page; $page = $page < 1 ? 1 : $page;
return $app['feed.formatter-strategy']($format) 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') ->bind('feed_user')
->assert('id', '\d+') ->assert('id', '\d+')
@@ -63,7 +63,8 @@ class RSSFeeds implements ControllerProviderInterface
$controllers->get('/userfeed/aggregated/{token}/{format}/', function (Application $app, $token, $format) { $controllers->get('/userfeed/aggregated/{token}/{format}/', function (Application $app, $token, $format) {
$token = $app['EM']->getRepository('Phraseanet:AggregateToken')->findOneBy(["value" => $token]); $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)); $feeds = $app['EM']->getRepository('Phraseanet:Feed')->getAllForUser($app['acl']->get($user));

View File

@@ -57,7 +57,7 @@ class Session implements ControllerProviderInterface
]; ];
if ($app['authentication']->isAuthenticated()) { 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 if ($usr_id != $request->request->get('usr')) { // I logged with another user
$ret['status'] = 'disconnected'; $ret['status'] = 'disconnected';
@@ -138,7 +138,11 @@ class Session implements ControllerProviderInterface
$app->abort(404, 'Unknown session'); $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'); $app->abort(403, 'Unauthorized');
} }

View File

@@ -765,10 +765,10 @@ class Thesaurus implements ControllerProviderInterface
sbasusr.bas_modify_struct AS bas_modify_struct, sbasusr.bas_modify_struct AS bas_modify_struct,
sbasusr.bas_modif_th AS bas_edit_thesaurus sbasusr.bas_modif_th AS bas_edit_thesaurus
FROM FROM
(usr INNER JOIN sbasusr (Users u INNER JOIN sbasusr
ON usr.usr_id = :usr_id ON u.id = :usr_id
AND usr.usr_id = sbasusr.usr_id AND u.id = sbasusr.usr_id
AND model_of = 0) AND u.model_of IS NULL)
INNER JOIN INNER JOIN
sbas ON sbas.sbas_id = sbasusr.sbas_id sbas ON sbas.sbas_id = sbasusr.sbas_id
HAVING bas_edit_thesaurus > 0 HAVING bas_edit_thesaurus > 0
@@ -777,7 +777,7 @@ class Thesaurus implements ControllerProviderInterface
$bases = $languages = []; $bases = $languages = [];
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $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); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor(); $stmt->closeCursor();

View File

@@ -358,7 +358,7 @@ class Xmlhttp implements ControllerProviderInterface
public function EditingPresetsJson(Application $app, Request $request) public function EditingPresetsJson(Application $app, Request $request)
{ {
$usr_id = $app['authentication']->getUser()->get_id(); $usr_id = $app['authentication']->getUser()->getId();
$ret = ['parm' => [ $ret = ['parm' => [
'act' => $request->get('act'), 'act' => $request->get('act'),

View File

@@ -59,7 +59,7 @@ class Notifications implements ControllerProviderInterface
try { try {
$app['events-manager']->read( $app['events-manager']->read(
explode('_', (string) $request->request->get('notifications')), explode('_', (string) $request->request->get('notifications')),
$app['authentication']->getUser()->get_id() $app['authentication']->getUser()->getId()
); );
return $app->json(['success' => true, 'message' => '']); return $app->json(['success' => true, 'message' => '']);

View File

@@ -85,7 +85,7 @@ class Preferences implements ControllerProviderInterface
$success = false; $success = false;
if (null !== $prop && null !== $value) { if (null !== $prop && null !== $value) {
$app['authentication']->getUser()->setPrefs($prop, $value); $app['manipulator.user']->setUserSetting($app['authentication']->getUser(), $prop, $value);
$success = true; $success = true;
$msg = $app->trans('Preference saved !'); $msg = $app->trans('Preference saved !');
} }

View File

@@ -91,6 +91,24 @@ class DisplaySettingService
return $user->getSettings()->get($name)->getValue(); 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. * Returns application setting value.
* *

View File

@@ -12,6 +12,7 @@
namespace Alchemy\Phrasea\Core\Event; namespace Alchemy\Phrasea\Core\Event;
use Alchemy\Phrasea\Authentication\Context; use Alchemy\Phrasea\Authentication\Context;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\Event as SfEvent; use Symfony\Component\EventDispatcher\Event as SfEvent;
@@ -23,7 +24,7 @@ class PostAuthenticate extends SfEvent
private $request; private $request;
private $response; 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->request = $request;
$this->response = $response; $this->response = $response;

View File

@@ -57,12 +57,11 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
$templates = array_filter(array_map(function ($templateId) use ($app) { $templates = array_filter(array_map(function ($templateId) use ($app) {
try { try {
if (is_int($templateId) || ctype_digit($templateId)) { if (is_int($templateId) || ctype_digit($templateId)) {
return \User_Adapter::getInstance($templateId, $app); return $app['manipulator.user']->getRepository()->find($templateId);
} else { }
$template = \User_Adapter::get_usr_id_from_login($app, $templateId);
if (false !== $template) { if (false !== $templateId) {
return \User_Adapter::getInstance($template, $app); return $app['manipulator.user']->getRepository()->find($templateId);
}
} }
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -108,7 +107,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
}); });
$app['auth.password-checker'] = $app->share(function (Application $app) { $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) { $app['auth.native'] = $app->share(function (Application $app) {

View File

@@ -13,6 +13,9 @@ namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Setup\ConfigurationTester; use Alchemy\Phrasea\Setup\ConfigurationTester;
use Alchemy\Phrasea\Application; 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\Application as SilexApplication;
use Silex\ServiceProviderInterface; use Silex\ServiceProviderInterface;
@@ -24,6 +27,14 @@ class ConfigurationTesterServiceProvider implements ServiceProviderInterface
$app['phraseanet.configuration-tester'] = $app->share(function (Application $app) { $app['phraseanet.configuration-tester'] = $app->share(function (Application $app) {
return new ConfigurationTester($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) public function boot(SilexApplication $app)

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Exception\RuntimeException; use Alchemy\Phrasea\Exception\RuntimeException;
use Alchemy\Phrasea\Model\MonologSQLLogger; use Alchemy\Phrasea\Model\MonologSQLLogger;
use Alchemy\Phrasea\Model\NativeQueryProvider;
use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry; use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\FileCacheReader; use Doctrine\Common\Annotations\FileCacheReader;
@@ -155,6 +156,10 @@ class ORMServiceProvider implements ServiceProviderInterface
return $em; return $em;
}); });
$app['EM.native-query'] = $app->share(function ($app) {
return new NativeQueryProvider($app['EM']);
});
} }
public function boot(Application $app) public function boot(Application $app)

View File

@@ -38,6 +38,10 @@ class PhraseanetServiceProvider implements ServiceProviderInterface
$app['acl'] = $app->share(function (SilexApplication $app) { $app['acl'] = $app->share(function (SilexApplication $app) {
return new ACLProvider($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) public function boot(SilexApplication $app)

View File

@@ -12,6 +12,7 @@
namespace Alchemy\Phrasea\Core\Provider; namespace Alchemy\Phrasea\Core\Provider;
use Alchemy\Phrasea\Form\Constraint\NewLogin; use Alchemy\Phrasea\Form\Constraint\NewLogin;
use Alchemy\Phrasea\Model\Entities\User;
use Silex\Application; use Silex\Application;
use Silex\ServiceProviderInterface; use Silex\ServiceProviderInterface;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
@@ -56,9 +57,9 @@ class RegistrationServiceProvider implements ServiceProviderInterface
'multiple' => false, 'multiple' => false,
'expanded' => false, 'expanded' => false,
'choices' => [ 'choices' => [
'0' => 'admin::compte-utilisateur:sexe: mademoiselle', User::GENDER_MISS => 'admin::compte-utilisateur:sexe: mademoiselle',
'1' => 'admin::compte-utilisateur:sexe: madame', User::GENDER_MRS => 'admin::compte-utilisateur:sexe: madame',
'2' => 'admin::compte-utilisateur:sexe: monsieur', User::GENDER_MR => 'admin::compte-utilisateur:sexe: monsieur',
] ]
], ],
'firstname' => [ 'firstname' => [

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Exception\LogicException; use Alchemy\Phrasea\Exception\LogicException;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Alchemy\Phrasea\Model\Entities\AggregateToken; 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. * Creates an aggregate from all the feeds available to a given user.
* *
* @param EntityManager $em * @param EntityManager $em
* @param \User_Adapter $user * @param User $user
* *
* @return Aggregate * @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)); $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); return new static($app['EM'], $feeds, $token);
} }

View File

@@ -16,6 +16,7 @@ use Alchemy\Phrasea\Model\Entities\FeedEntry;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Feed\Link\FeedLink; use Alchemy\Phrasea\Feed\Link\FeedLink;
use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterface class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterface
@@ -34,7 +35,7 @@ class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterf
/** /**
* {@inheritdoc} * {@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); $content = $this->format($feed, $page, $user, $generator, $app);
$response = new Response($content, 200, ['Content-Type' => 'application/atom+xml']); $response = new Response($content, 200, ['Content-Type' => 'application/atom+xml']);
@@ -45,7 +46,7 @@ class AtomFormatter extends FeedFormatterAbstract implements FeedFormatterInterf
/** /**
* {@inheritdoc} * {@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(); $updated_on = $feed->getUpdatedOn();

View File

@@ -17,6 +17,7 @@ use Alchemy\Phrasea\Model\Entities\FeedEntry;
use Alchemy\Phrasea\Model\Entities\FeedItem; use Alchemy\Phrasea\Model\Entities\FeedItem;
use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection;
use Alchemy\Phrasea\Feed\RSS\FeedRSSImage; use Alchemy\Phrasea\Feed\RSS\FeedRSSImage;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterInterface class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterInterface
@@ -36,7 +37,7 @@ class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterIn
/** /**
* {@inheritdoc} * {@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); $content = $this->format($feed, $page, $user, $generator, $app);
$response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']); $response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']);
@@ -47,7 +48,7 @@ class CoolirisFormatter extends FeedFormatterAbstract implements FeedFormatterIn
/** /**
* {@inheritdoc} * {@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(); $updated_on = $feed->getUpdatedOn();

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Formatter;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Model\Entities\User;
interface FeedFormatterInterface interface FeedFormatterInterface
{ {
@@ -21,24 +22,24 @@ interface FeedFormatterInterface
* *
* @param FeedInterface $feed * @param FeedInterface $feed
* @param type $page * @param type $page
* @param \User_Adapter $user * @param User $user
* @param type $generator * @param type $generator
* @param Application $app * @param Application $app
* *
* @return string * @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. * Returns an HTTP Response containing a string representation of the feed.
* *
* @param FeedInterface $feed * @param FeedInterface $feed
* @param type $page * @param type $page
* @param \User_Adapter $user * @param User $user
* @param type $generator * @param type $generator
* @param Application $app * @param Application $app
* *
* @return string * @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');
} }

View File

@@ -16,6 +16,7 @@ use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Feed\Link\FeedLink; use Alchemy\Phrasea\Feed\Link\FeedLink;
use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection; use Alchemy\Phrasea\Feed\Link\LinkGeneratorCollection;
use Alchemy\Phrasea\Feed\RSS\FeedRSSImage; use Alchemy\Phrasea\Feed\RSS\FeedRSSImage;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Alchemy\Phrasea\Model\Entities\FeedEntry; use Alchemy\Phrasea\Model\Entities\FeedEntry;
use Alchemy\Phrasea\Feed\Link\FeedLinkGenerator; use Alchemy\Phrasea\Feed\Link\FeedLinkGenerator;
@@ -37,7 +38,7 @@ class RssFormatter extends FeedFormatterAbstract implements FeedFormatterInterfa
/** /**
* {@inheritdoc} * {@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); $content = $this->format($feed, $page, $user, $generator, $app);
$response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']); $response = new Response($content, 200, ['Content-Type' => 'application/rss+xml']);
@@ -48,7 +49,7 @@ class RssFormatter extends FeedFormatterAbstract implements FeedFormatterInterfa
/** /**
* {@inheritdoc} * {@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(); $updated_on = $feed->getUpdatedOn();

View File

@@ -15,6 +15,7 @@ use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Feed\Aggregate; use Alchemy\Phrasea\Feed\Aggregate;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Model\Entities\AggregateToken; use Alchemy\Phrasea\Model\Entities\AggregateToken;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Symfony\Component\Routing\Generator\UrlGenerator; use Symfony\Component\Routing\Generator\UrlGenerator;
@@ -42,7 +43,7 @@ class AggregateLinkGenerator implements LinkGeneratorInterface
/** /**
* {@inheritdoc} * {@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)) { if (!$this->supports($aggregate)) {
throw new InvalidArgumentException('AggregateLinkGenerator only support aggregate feeds.'); 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 $token = $this->em
->getRepository('Phraseanet:AggregateToken') ->getRepository('Phraseanet:AggregateToken')
->findOneBy(['usrId' => $user->get_id()]); ->findOneBy(['user' => $user]);
if (null === $token || true === $renew) { if (null === $token || true === $renew) {
if (null === $token) { if (null === $token) {
$token = new AggregateToken(); $token = new AggregateToken();
$token->setUsrId($user->get_id()); $token->setUser($user);
} }
$token->setValue($this->random->generatePassword(12, \random::LETTERS_AND_NUMBERS)); $token->setValue($this->random->generatePassword(12, \random::LETTERS_AND_NUMBERS));

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Link;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Alchemy\Phrasea\Model\Entities\Feed; use Alchemy\Phrasea\Model\Entities\Feed;
use Alchemy\Phrasea\Model\Entities\FeedToken; use Alchemy\Phrasea\Model\Entities\FeedToken;
@@ -42,7 +43,7 @@ class FeedLinkGenerator implements LinkGeneratorInterface
/** /**
* {@inheritdoc} * {@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)) { if (!$this->supports($feed)) {
throw new InvalidArgumentException('FeedLinkGenerator only support aggregate feeds.'); 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 $token = $this->em
->getRepository('Phraseanet:FeedToken') ->getRepository('Phraseanet:FeedToken')
->findOneBy(['usrId' => $user->get_id(), 'feed' => $feed->getId()]); ->findOneBy(['user' => $user, 'feed' => $feed]);
if (null === $token || true === $renew) { if (null === $token || true === $renew) {
if (null === $token) { if (null === $token) {
$token = new FeedToken(); $token = new FeedToken();
$token->setFeed($feed); $token->setFeed($feed);
$token->setUsrId($user->get_id()); $token->setUser($user);
$feed->addToken($token); $feed->addToken($token);
$this->em->persist($feed); $this->em->persist($feed);

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Feed\Link;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\Entities\User;
class LinkGeneratorCollection implements LinkGeneratorInterface class LinkGeneratorCollection implements LinkGeneratorInterface
{ {
@@ -31,7 +32,7 @@ class LinkGeneratorCollection implements LinkGeneratorInterface
/** /**
* {@inheritdoc} * {@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)) { if (null === $generator = $this->findGenerator($feed)) {
throw new InvalidArgumentException(sprintf('Unable to find a valid generator for %s', get_class($feed))); throw new InvalidArgumentException(sprintf('Unable to find a valid generator for %s', get_class($feed)));

View File

@@ -12,14 +12,15 @@
namespace Alchemy\Phrasea\Feed\Link; namespace Alchemy\Phrasea\Feed\Link;
use Alchemy\Phrasea\Feed\FeedInterface; use Alchemy\Phrasea\Feed\FeedInterface;
use Alchemy\Phrasea\Model\Entities\User;
interface LinkGeneratorInterface 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 FeedInterface $feed
* @param \User_Adapter $user * @param User $user
* @param type $format * @param type $format
* @param type $page * @param type $page
* @param type $renew * @param type $renew
@@ -28,7 +29,7 @@ interface LinkGeneratorInterface
* *
* @throws InvalidArgumentException * @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. * Generates a public FeedLink based on given FeedInterface.

View File

@@ -27,9 +27,7 @@ class NewEmail extends Constraint
public function isAlreadyRegistered($email) public function isAlreadyRegistered($email)
{ {
$ret = (Boolean) \User_Adapter::get_usr_id_from_email($this->app, $email); return (Boolean) $this->app['manipulator.user']->getRepository()->findByEmail($email);
return $ret;
} }
public static function create(Application $app) public static function create(Application $app)

View File

@@ -27,9 +27,7 @@ class NewLogin extends Constraint
public function isAlreadyRegistered($login) public function isAlreadyRegistered($login)
{ {
$ret = (Boolean) \User_Adapter::get_usr_id_from_login($this->app, $login); return (Boolean) $this->app['manipulator.user']->getRepository()->findByLogin($login);
return $ret;
} }
public static function create(Application $app) public static function create(Application $app)

View File

@@ -11,6 +11,8 @@
namespace Alchemy\Phrasea\Helper; namespace Alchemy\Phrasea\Helper;
use Alchemy\Phrasea\Model\Entities\User;
class Prod extends Helper class Prod extends Helper
{ {
@@ -24,12 +26,12 @@ class Prod extends Helper
$bases = $fields = $dates = []; $bases = $fields = $dates = [];
if (! $this->app['authentication']->getUser() instanceof \User_Adapter) { if (! $this->app['authentication']->getUser() instanceof User) {
return $search_datas; return $search_datas;
} }
$searchSet = json_decode($this->app['authentication']->getUser()->getPrefs('search'), true); $searchSet = json_decode($this->app['settings']->getUserSetting($this->app['authentication']->getUser(), 'search'), true);
$saveSettings = $this->app['authentication']->getUser()->getPrefs('advanced_search_reload'); $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) { foreach ($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_sbas() as $databox) {
$sbas_id = $databox->get_sbas_id(); $sbas_id = $databox->get_sbas_id();

View File

@@ -13,6 +13,7 @@ namespace Alchemy\Phrasea\Helper\User;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Notification\Mail\MailSuccessEmailUpdate; use Alchemy\Phrasea\Notification\Mail\MailSuccessEmailUpdate;
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -60,24 +61,24 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
public function delete_users() public function delete_users()
{ {
foreach ($this->users as $usr_id) { 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; continue;
} }
$user = \User_Adapter::getInstance($usr_id, $this->app); $user = $this->app['manipulator.user']->getRepository()->find($usr_id);
$this->delete_user($user); $this->delete_user($user);
} }
return $this; 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'])); $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); $this->app['acl']->get($user)->revoke_access_from_bases($list);
if ($this->app['acl']->get($user)->is_phantom()) { if ($this->app['acl']->get($user)->is_phantom()) {
$user->delete(); $this->app['manipulator.user']->delete($user);
} }
return $this; return $this;
@@ -124,12 +125,12 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
sum(mask_and + mask_xor) as masks 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) 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 LEFT join sbasusr sbu
ON (sbu.sbas_id = b.sbas_id AND u.usr_id = sbu.usr_id) ON (sbu.sbas_id = b.sbas_id AND u.id = sbu.usr_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 = s.sbas_id AND b.sbas_id = s.sbas_id
AND (b.base_id = '" . implode("' OR b.base_id = '", $list) . "')) AND (b.base_id = '" . implode("' OR b.base_id = '", $list) . "'))
GROUP BY b.base_id GROUP BY b.base_id
@@ -180,7 +181,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
if (count($this->users) == 1) { if (count($this->users) == 1) {
$usr_id = array_pop($this->users); $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; return $out;
@@ -190,9 +191,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
{ {
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->request->get('base_id');
$sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max $sql = "SELECT u.id, restrict_dwnld, remain_dwnld, month_dwnld_max
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id) FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)
WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ") WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")
AND bu.base_id = :base_id"; AND bu.base_id = :base_id";
$conn = \connection::getPDOConnection($this->app); $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'); $this->base_id = (int) $this->request->get('base_id');
$sql = "SELECT u.usr_id, time_limited, limited_from, limited_to $sql = "SELECT u.id, time_limited, limited_from, limited_to
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id) FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)
WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ") WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")
AND bu.base_id = :base_id"; AND bu.base_id = :base_id";
$conn = \connection::getPDOConnection($this->app); $conn = \connection::getPDOConnection($this->app);
@@ -367,11 +368,11 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
{ {
$sbas_id = (int) $this->request->get('sbas_id'); $sbas_id = (int) $this->request->get('sbas_id');
$sql = "SELECT u.usr_id, time_limited, limited_from, limited_to $sql = "SELECT u.id, time_limited, limited_from, limited_to
FROM (usr u FROM (Users u
INNER JOIN basusr bu ON u.usr_id = bu.usr_id INNER JOIN basusr bu ON u.id = bu.usr_id
INNER JOIN bas b ON b.base_id = bu.base_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"; AND b.sbas_id = :sbas_id";
$conn = \connection::getPDOConnection($this->app); $conn = \connection::getPDOConnection($this->app);
@@ -531,7 +532,8 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
try { try {
$this->app['phraseanet.appbox']->get_connection()->beginTransaction(); $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) $this->app['acl']->get($user)->revoke_access_from_bases($delete)
->give_access_to_base($create) ->give_access_to_base($create)
->give_access_to_sbas($create_sbas); ->give_access_to_sbas($create_sbas);
@@ -565,9 +567,9 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
$users = $this->users; $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; return $this;
} }
@@ -586,28 +588,29 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
, 'fax' , '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'])) { if ($parm['email'] && !\Swift_Validate::email($parm['email'])) {
throw new \Exception_InvalidArgument('Email addess is not valid'); throw new \Exception_InvalidArgument('Email addess is not valid');
} }
$old_email = $user->get_email(); $old_email = $user->getEmail();
$user->set_firstname($parm['first_name']) $user->setFirstName($parm['first_name'])
->set_lastname($parm['last_name']) ->setLastName($parm['last_name'])
->set_gender($parm['gender']) ->setGender($parm['gender'])
->set_email($parm['email']) ->setEmail($parm['email'])
->set_address($parm['address']) ->setAddress($parm['address'])
->set_zip($parm['zip']) ->setZipCode($parm['zip'])
->set_geonameid($parm['geonameid']) ->setActivity($parm['function'])
->set_position($parm['function']) ->setJob($parm['activite'])
->set_job($parm['activite']) ->setCompany($parm['company'])
->set_company($parm['company']) ->setPhone($parm['telephone'])
->set_tel($parm['telephone']) ->setFax($parm['fax']);
->set_fax($parm['fax']);
$new_email = $user->get_email(); $this->app['manipulator.user']->setGeonameId($user, $parm['geonameid']);
$new_email = $user->getEmail();
if ($old_email != $new_email) { if ($old_email != $new_email) {
$oldReceiver = $newReceiver = null; $oldReceiver = $newReceiver = null;
@@ -639,18 +642,18 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
public function apply_template() 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'); 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'])); $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin']));
foreach ($this->users as $usr_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 ($user->is_template()) { if ($user->isTemplate()) {
continue; continue;
} }
@@ -665,7 +668,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
$this->base_id = (int) $this->request->get('base_id'); $this->base_id = (int) $this->request->get('base_id');
foreach ($this->users as $usr_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')) 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')); $this->app['acl']->get($user)->set_quotas_on_base($this->base_id, $this->request->get('droits'), $this->request->get('restes'));
else else
@@ -686,7 +689,7 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
if ($vand_and && $vand_or && $vxor_and && $vxor_or) { if ($vand_and && $vand_or && $vxor_and && $vxor_or) {
foreach ($this->users as $usr_id) { 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); $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'])); $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin']));
foreach ($this->users as $usr_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->base_id > 0) { if ($this->base_id > 0) {
$this->app['acl']->get($user)->set_limits($this->base_id, $activate, $dmin, $dmax); $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'])); $base_ids = array_keys($this->app['acl']->get($this->app['authentication']->getUser())->get_granted_base(['canadmin']));
foreach ($this->users as $usr_id) { 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); $ACL = $this->app['acl']->get($user);
if ($user->is_template()) { if ($user->isTemplate()) {
$template = $user; $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; continue;
} }
} }
@@ -755,7 +758,13 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
private function unserializedRequestData(Request $request, array $indexes, $requestIndex) private function unserializedRequestData(Request $request, array $indexes, $requestIndex)
{ {
$parameters = $data = []; $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) { if (count($data) > 0) {
foreach ($indexes as $index) { foreach ($indexes as $index) {

View File

@@ -16,6 +16,7 @@ use Alchemy\Phrasea\Helper\Helper;
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
use Alchemy\Phrasea\Notification\Mail\MailRequestPasswordSetup; use Alchemy\Phrasea\Notification\Mail\MailRequestPasswordSetup;
use Alchemy\Phrasea\Notification\Mail\MailRequestEmailConfirmation; use Alchemy\Phrasea\Notification\Mail\MailRequestEmailConfirmation;
use Alchemy\Phrasea\Model\Entities\User;
class Manage extends Helper class Manage extends Helper
{ {
@@ -110,18 +111,12 @@ class Manage extends Helper
->limit($offset_start, $results_quantity) ->limit($offset_start, $results_quantity)
->execute(); ->execute();
try { if (null === $invite = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_GUEST)) {
$invite_id = \User_Adapter::get_usr_id_from_login($this->app, 'invite'); $invite = $this->app['manipulator.user']->createUser(User::USER_GUEST, User::USER_GUEST);
$invite = \User_Adapter::getInstance($invite_id, $this->app);
} catch (\Exception $e) {
$invite = \User_Adapter::create($this->app, 'invite', 'invite', '', false);
} }
try { if (null == $autoregister = $this->app['manipulator.user']->getRepository()->findByLogin(User::USER_AUTOREGISTER)) {
$autoregister_id = \User_Adapter::get_usr_id_from_login($this->app, 'autoregister'); $autoregister = $this->app['manipulator.user']->createUser(User::USER_AUTOREGISTER, User::USER_AUTOREGISTER);
$autoregister = \User_Adapter::getInstance($autoregister_id, $this->app);
} catch (\Exception $e) {
$autoregister = \User_Adapter::create($this->app, 'autoregister', 'autoregister', '', false);
} }
foreach ($this->query_parms as $k => $v) { foreach ($this->query_parms as $k => $v) {
@@ -151,19 +146,11 @@ class Manage extends Helper
throw new \Exception_InvalidArgument('Invalid mail address'); throw new \Exception_InvalidArgument('Invalid mail address');
} }
$conn = $this->app['phraseanet.appbox']->get_connection(); if (null === $createdUser = $this->app['manipulator.user']->getRepository()->findByEmail($email)) {
$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) {
$sendCredentials = !!$this->request->get('send_credentials', false); $sendCredentials = !!$this->request->get('send_credentials', false);
$validateMail = !!$this->request->get('validate_mail', false); $validateMail = !!$this->request->get('validate_mail', false);
$createdUser = \User_Adapter::create($this->app, $email, \random::generatePassword(16), $email, false, false); $createdUser = $this->app['manipulator.user']->createUser($email, \random::generatePassword(16), $email);
/* @var $createdUser \User_Adapter */
$receiver = null; $receiver = null;
try { try {
@@ -173,35 +160,32 @@ class Manage extends Helper
} }
if ($sendCredentials) { 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) { if ($receiver && false !== $urlToken) {
$url = $this->app->url('login_renew_password', ['token' => $urlToken]); $url = $this->app->url('login_renew_password', ['token' => $urlToken]);
$mail = MailRequestPasswordSetup::create($this->app, $receiver, null, '', $url); $mail = MailRequestPasswordSetup::create($this->app, $receiver, null, '', $url);
$mail->setLogin($createdUser->get_login()); $mail->setLogin($createdUser->getLogin());
$this->app['notification.deliverer']->deliver($mail); $this->app['notification.deliverer']->deliver($mail);
} }
} }
if ($validateMail) { if ($validateMail) {
$createdUser->set_mail_locked(true); $createdUser->setMailLocked(true);
if ($receiver) { if ($receiver) {
$expire = new \DateTime('+3 days'); $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]); $url = $this->app->url('login_register_confirm', ['code' => $token]);
$mail = MailRequestEmailConfirmation::create($this->app, $receiver, null, '', $url, $expire); $mail = MailRequestEmailConfirmation::create($this->app, $receiver, null, '', $url, $expire);
$this->app['notification.deliverer']->deliver($mail); $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; return $createdUser;
} }
@@ -213,9 +197,9 @@ class Manage extends Helper
throw new \Exception_InvalidArgument('Invalid template name'); throw new \Exception_InvalidArgument('Invalid template name');
} }
$created_user = \User_Adapter::create($this->app, $name, \random::generatePassword(16), null, false, false); $created_user = $this->app['manipulator.user']->getRepository()->find($name, \random::generatePassword(16));
$created_user->set_template($this->app['authentication']->getUser()); $created_user->setModelOf($this->app['authentication']->getUser());
$this->usr_id = $this->app['authentication']->getUser()->get_id(); $this->usr_id = $this->app['authentication']->getUser()->getId();
return $created_user; return $created_user;
} }

View File

@@ -46,7 +46,7 @@ class WorkZone extends Helper
$basket = new BasketEntity(); $basket = new BasketEntity();
$basket->setName($this->app->trans('Default basket')); $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']->persist($basket);
$this->app['EM']->flush(); $this->app['EM']->flush();

View File

@@ -27,9 +27,12 @@ class AggregateToken
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usrId; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string", length=12, nullable=true) * @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 * @return AggregateToken
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**

View File

@@ -43,9 +43,12 @@ class Basket
private $description; private $description;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
@@ -53,9 +56,12 @@ class Basket
private $is_read = false; private $is_read = false;
/** /**
* @ORM\Column(type="integer", nullable=true) * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="pusher_id", referencedColumnName="id")
private $pusher_id; *
* @return User
**/
private $pusher;
/** /**
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
@@ -155,38 +161,23 @@ class Basket
} }
/** /**
* Set usr_id * @param User $user
* *
* @param integer $usrId
* @return Basket * @return Basket
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usr_id = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
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);
}
} }
/** /**
@@ -213,38 +204,23 @@ class Basket
} }
/** /**
* Set pusher_id * @param User $user
* *
* @param integer $pusherId * @return $this
* @return Basket
*/ */
public function setPusherId($pusherId) public function setPusher(User $user = null)
{ {
$this->pusher_id = $pusherId; $this->pusher = $user;
return $this; return $this;
} }
/** /**
* Get pusher_id * @return mixed
*
* @return integer
*/ */
public function getPusherId() public function getPusher()
{ {
return $this->pusher_id; return $this->pusher;
}
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);
}
} }
/** /**

View File

@@ -277,17 +277,16 @@ class BasketElement
/** /**
* *
* @param \User_Adapter $user
* @return ValidationData * @return ValidationData
*/ */
public function getUserValidationDatas(\User_Adapter $user, Application $app) public function getUserValidationDatas(User $user)
{ {
foreach ($this->validation_datas as $validationData) { 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; return $validationData;
} }
} }
throw new \Exception('There is no such participant ' . $user->get_email()); throw new \Exception('There is no such participant ' . $user->getEmail());
} }
} }

View File

@@ -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 * @return boolean
*/ */
public function isOwner(\User_Adapter $user) public function isOwner(User $user)
{ {
$owner = $this->getOwner(); $owner = $this->getOwner();
if ($owner !== null && $user->get_id() === $owner->getUsrId()) { if ($owner !== null && $user->getId() === $owner->getUser()->getId()) {
return true; 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 * @return boolean
*/ */
public function isPublisher(\User_Adapter $user) public function isPublisher(User $user)
{ {
foreach ($this->getPublishers() as $publisher) { foreach ($this->getPublishers() as $publisher) {
if ($publisher->getUsrId() == $user->get_id()) { if ($publisher->getUser()->getId() == $user->getId()) {
return true; 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 * @return FeedPublisher
*/ */
public function getPublisher(\User_Adapter $user) public function getPublisher(User $user)
{ {
foreach ($this->getPublishers() as $publisher) { foreach ($this->getPublishers() as $publisher) {
if ($publisher->getUsrId() == $user->get_id()) { if ($publisher->getUser()->getId() == $user->getId()) {
return $publisher; 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 User $user
* @param Application $app * @param Application $app
* *
* @return boolean * @return boolean
*/ */
public function hasAccess(\User_Adapter $user, Application $app) public function hasAccess(User $user, Application $app)
{ {
if ($this->getCollection($app) instanceof collection) { if ($this->getCollection($app) instanceof collection) {
return $app['acl']->get($user)->has_access_to_base($this->collection->get_base_id()); 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 * 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 * @param \Alchemy\Phrasea\Application $app
* *
* @return boolean * @return boolean
*/ */
public function isAccessible(\User_Adapter $user, Application $app) public function isAccessible(User $user, Application $app)
{ {
$coll = $this->getCollection($app); $coll = $this->getCollection($app);
if ($this->isPublic() if ($this->isPublic()

View File

@@ -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 * @return boolean
*/ */
public function isPublisher(\User_Adapter $user) public function isPublisher(User $user)
{ {
if ($this->publisher) { if ($this->publisher) {
if ($this->publisher->getUsrId() === $user->get_id()) { if ($this->publisher->getUser()->getId() === $user->getId()) {
return true; return true;
} }
} }

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
@@ -29,9 +28,12 @@ class FeedPublisher
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usrId; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
@@ -61,26 +63,23 @@ class FeedPublisher
} }
/** /**
* Set usr_id * @param User $user
* *
* @param integer $usrId
* @return FeedPublisher * @return FeedPublisher
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**
@@ -129,18 +128,6 @@ class FeedPublisher
return $this->feed; 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 * Set created_on
* *

View File

@@ -27,9 +27,12 @@ class FeedToken
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usrId; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string", length=12, nullable=true) * @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 * @return FeedToken
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**

View File

@@ -27,14 +27,9 @@ class FtpCredential
*/ */
private $id; private $id;
/**
* @ORM\Column(type="integer")
*/
private $usrId;
/** /**
* @ORM\OneToOne(targetEntity="User", inversedBy="ftpCredential") * @ORM\OneToOne(targetEntity="User", inversedBy="ftpCredential")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
**/ **/
private $user; private $user;
@@ -97,22 +92,6 @@ class FtpCredential
return $this->id; return $this->id;
} }
/**
* @return integer
*/
public function getUsrId()
{
return $this->usrId;
}
/**
* @param integer $usrId
*/
public function setUsrId($usrId)
{
$this->usrId = $usrId;
}
/** /**
* @return User * @return User
*/ */

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
@@ -90,9 +89,12 @@ class FtpExport
private $textMailReceiver; private $textMailReceiver;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usrId; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="text", nullable=true) * @ORM\Column(type="text", nullable=true)
@@ -141,6 +143,26 @@ class FtpExport
return $this->id; 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 * Set crash
* *
@@ -441,54 +463,6 @@ class FtpExport
return $this->textMailReceiver; 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 * Set foldertocreate
* *

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
@@ -28,10 +27,13 @@ class LazaretSession
*/ */
private $id; private $id;
/** /**
* @ORM\Column(type="integer", nullable=true) * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @Gedmo\Timestampable(on="create") * @Gedmo\Timestampable(on="create")
@@ -70,44 +72,23 @@ class LazaretSession
} }
/** /**
* Set usr_id * @param User $user
* *
* @param integer $usrId
* @return LazaretSession * @return LazaretSession
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usr_id = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
/**
* 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;
} }
/** /**

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
@@ -29,9 +28,12 @@ class Order
private $id; private $id;
/** /**
* @ORM\Column(type="integer", name="usr_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usrId; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string", length=2048, name="order_usage") * @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 * @return Order
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usrId = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usrId; return $this->user;
} }
/** /**
@@ -184,20 +183,6 @@ class Order
return $this->elements; 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 * Set todo
* *

View File

@@ -38,9 +38,12 @@ class OrderElement
private $recordId; private $recordId;
/** /**
* @ORM\Column(type="integer", nullable=true, name="order_master_id") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="order_master", referencedColumnName="id")
private $orderMasterId; *
* @return User
**/
private $orderMaster;
/** /**
* @ORM\Column(type="boolean", nullable=true) * @ORM\Column(type="boolean", nullable=true)
@@ -64,44 +67,23 @@ class OrderElement
} }
/** /**
* Set order_master_id * @param User $user
* *
* @param integer $orderMasterId * @return $this
* @return OrderElement
*/ */
public function setOrderMasterId($orderMasterId) public function setOrderMaster(User $user = null)
{ {
$this->orderMasterId = $orderMasterId; $this->orderMaster = $user;
return $this; return $this;
} }
/** /**
* Get order_master_id * @return mixed
*
* @return integer
*/ */
public function getOrderMasterId() public function getOrderMaster()
{ {
return $this->orderMasterId; return $this->orderMaster;
}
/**
*
* 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;
} }
/** /**

View File

@@ -11,12 +11,11 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; 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") * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\SessionRepository")
*/ */
class Session class Session
@@ -29,9 +28,12 @@ class Session
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string", length=512) * @ORM\Column(type="string", length=512)
@@ -114,39 +116,24 @@ class Session
return $this->id; 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 * @return Session
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usr_id = $usrId; $this->user = $user;
return $this; return $this;
} }
public function getUser(Application $app)
{
if ($this->getUsrId()) {
return \User_Adapter::getInstance($this->getUsrId(), $app);
}
}
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
} }
/** /**

View File

@@ -17,7 +17,7 @@ use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; 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") * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\StoryWZRepository")
*/ */
class StoryWZ class StoryWZ
@@ -40,9 +40,12 @@ class StoryWZ
private $record_id; private $record_id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @Gedmo\Timestampable(on="create") * @Gedmo\Timestampable(on="create")
@@ -116,40 +119,24 @@ class StoryWZ
$this->setRecordId($record->get_record_id()); $this->setRecordId($record->get_record_id());
$this->setSbasId($record->get_sbas_id()); $this->setSbasId($record->get_sbas_id());
} }
/** /**
* Set usr_id * @param User $user
* *
* @param integer $usrId
* @return StoryWZ * @return StoryWZ
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usr_id = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
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);
}
} }
/** /**

View File

@@ -16,7 +16,6 @@ use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Translation\TranslatorInterface;
/** /**
* @ORM\Table(name="Users", * @ORM\Table(name="Users",
@@ -37,9 +36,9 @@ use Symfony\Component\Translation\TranslatorInterface;
*/ */
class User class User
{ {
const GENDER_MR = 'mr'; const GENDER_MR = 2;
const GENDER_MRS = 'mrs'; const GENDER_MRS = 1;
const GENDER_MISS = 'miss'; const GENDER_MISS = 0;
const USER_GUEST = 'guest'; const USER_GUEST = 'guest';
const USER_AUTOREGISTER = 'autoregister'; const USER_AUTOREGISTER = 'autoregister';
@@ -67,14 +66,14 @@ class User
private $password; private $password;
/** /**
* @ORM\Column(type="string", length=16, nullable=true) * @ORM\Column(type="string", length=64, nullable=true)
*/ */
private $nonce; private $nonce;
/** /**
* @ORM\Column(type="boolean", name="salted_password") * @ORM\Column(type="boolean", name="salted_password")
*/ */
private $saltedPassword = false; private $saltedPassword = true;
/** /**
* @ORM\Column(type="string", length=64, name="first_name") * @ORM\Column(type="string", length=64, name="first_name")
@@ -87,7 +86,7 @@ class User
private $lastName = ''; private $lastName = '';
/** /**
* @ORM\Column(type="string", length=8, nullable=true) * @ORM\Column(type="smallint", nullable=true)
*/ */
private $gender; private $gender;
@@ -102,7 +101,7 @@ class User
private $city = ''; private $city = '';
/** /**
* @ORM\Column(type="string", length=64) * @ORM\Column(type="string", length=64, nullable=true)
*/ */
private $country = ''; private $country = '';
@@ -177,8 +176,9 @@ class User
private $ldapCreated = false; 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; private $lastModel;
/** /**
@@ -224,7 +224,7 @@ class User
private $updated; private $updated;
/** /**
* @ORM\OneToOne(targetEntity="User") * @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="model_of", referencedColumnName="id") * @ORM\JoinColumn(name="model_of", referencedColumnName="id")
* *
* @var User * @var User
@@ -291,6 +291,8 @@ class User
public function setLogin($login) public function setLogin($login)
{ {
$this->login = $login; $this->login = $login;
return $this;
} }
/** /**
@@ -307,6 +309,8 @@ class User
public function setEmail($email) public function setEmail($email)
{ {
$this->email = $email; $this->email = $email;
return $this;
} }
/** /**
@@ -324,6 +328,8 @@ class User
public function setPassword($password) public function setPassword($password)
{ {
$this->password = $password; $this->password = $password;
return $this;
} }
/** /**
@@ -340,6 +346,8 @@ class User
public function setNonce($nonce) public function setNonce($nonce)
{ {
$this->nonce = $nonce; $this->nonce = $nonce;
return $this;
} }
/** /**
@@ -356,6 +364,8 @@ class User
public function setSaltedPassword($saltedPassword) public function setSaltedPassword($saltedPassword)
{ {
$this->saltedPassword = (Boolean) $saltedPassword; $this->saltedPassword = (Boolean) $saltedPassword;
return $this;
} }
/** /**
@@ -372,6 +382,8 @@ class User
public function setFirstName($firstName) public function setFirstName($firstName)
{ {
$this->firstName = $firstName; $this->firstName = $firstName;
return $this;
} }
/** /**
@@ -389,6 +401,8 @@ class User
public function setLastName($lastName) public function setLastName($lastName)
{ {
$this->lastName = $lastName; $this->lastName = $lastName;
return $this;
} }
/** /**
@@ -410,11 +424,13 @@ class User
self::GENDER_MISS, self::GENDER_MISS,
self::GENDER_MR, self::GENDER_MR,
self::GENDER_MRS self::GENDER_MRS
])) { ], true)) {
throw new InvalidArgumentException(sprintf("Invalid gender %s.", $gender)); throw new InvalidArgumentException(sprintf("Invalid gender %s.", $gender));
} }
$this->gender = $gender; $this->gender = $gender;
return $this;
} }
/** /**
@@ -431,6 +447,8 @@ class User
public function setAddress($address) public function setAddress($address)
{ {
$this->address = $address; $this->address = $address;
return $this;
} }
/** /**
@@ -447,6 +465,8 @@ class User
public function setCity($city) public function setCity($city)
{ {
$this->city = $city; $this->city = $city;
return $this;
} }
/** /**
@@ -463,6 +483,8 @@ class User
public function setCountry($country) public function setCountry($country)
{ {
$this->country = $country; $this->country = $country;
return $this;
} }
/** /**
@@ -479,6 +501,8 @@ class User
public function setZipCode($zipCode) public function setZipCode($zipCode)
{ {
$this->zipCode = $zipCode; $this->zipCode = $zipCode;
return $this;
} }
/** /**
@@ -499,6 +523,8 @@ class User
} }
$this->geonameId = $geonameId; $this->geonameId = $geonameId;
return $this;
} }
/** /**
@@ -521,6 +547,8 @@ class User
} }
$this->locale = $locale; $this->locale = $locale;
return $this;
} }
/** /**
@@ -537,6 +565,8 @@ class User
public function setTimezone($timezone) public function setTimezone($timezone)
{ {
$this->timezone = $timezone; $this->timezone = $timezone;
return $this;
} }
/** /**
@@ -553,6 +583,8 @@ class User
public function setJob($job) public function setJob($job)
{ {
$this->job = $job; $this->job = $job;
return $this;
} }
/** /**
@@ -569,6 +601,8 @@ class User
public function setActivity($activity) public function setActivity($activity)
{ {
$this->activity = $activity; $this->activity = $activity;
return $this;
} }
/** /**
@@ -585,6 +619,8 @@ class User
public function setCompany($company) public function setCompany($company)
{ {
$this->company = $company; $this->company = $company;
return $this;
} }
/** /**
@@ -601,6 +637,8 @@ class User
public function setPhone($phone) public function setPhone($phone)
{ {
$this->phone = $phone; $this->phone = $phone;
return $this;
} }
/** /**
@@ -617,6 +655,8 @@ class User
public function setFax($fax) public function setFax($fax)
{ {
$this->fax = $fax; $this->fax = $fax;
return $this;
} }
/** /**
@@ -633,6 +673,8 @@ class User
public function setAdmin($admin) public function setAdmin($admin)
{ {
$this->admin = (Boolean) $admin; $this->admin = (Boolean) $admin;
return $this;
} }
/** /**
@@ -649,6 +691,8 @@ class User
public function setGuest($guest) public function setGuest($guest)
{ {
$this->guest = (Boolean) $guest; $this->guest = (Boolean) $guest;
return $this;
} }
/** /**
@@ -665,6 +709,8 @@ class User
public function setMailNotificationsActivated($mailNotifications) public function setMailNotificationsActivated($mailNotifications)
{ {
$this->mailNotificationsActivated = (Boolean) $mailNotifications; $this->mailNotificationsActivated = (Boolean) $mailNotifications;
return $this;
} }
/** /**
@@ -681,6 +727,8 @@ class User
public function setRequestNotificationsActivated($requestNotifications) public function setRequestNotificationsActivated($requestNotifications)
{ {
$this->requestNotificationsActivated = (Boolean) $requestNotifications; $this->requestNotificationsActivated = (Boolean) $requestNotifications;
return $this;
} }
/** /**
@@ -697,6 +745,8 @@ class User
public function setLdapCreated($ldapCreated) public function setLdapCreated($ldapCreated)
{ {
$this->ldapCreated = (Boolean) $ldapCreated; $this->ldapCreated = (Boolean) $ldapCreated;
return $this;
} }
/** /**
@@ -713,10 +763,12 @@ class User
public function setModelOf(User $owner) public function setModelOf(User $owner)
{ {
$this->modelOf = $owner; $this->modelOf = $owner;
return $this;
} }
/** /**
* @return string * @return User
*/ */
public function getLastModel() 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; $this->lastModel = $lastModel;
return $this;
} }
/** /**
@@ -745,6 +799,8 @@ class User
public function setPushList($pushList) public function setPushList($pushList)
{ {
$this->pushList = $pushList; $this->pushList = $pushList;
return $this;
} }
/** /**
@@ -761,6 +817,8 @@ class User
public function setCanChangeProfil($canChangeProfil) public function setCanChangeProfil($canChangeProfil)
{ {
$this->canChangeProfil = (Boolean) $canChangeProfil; $this->canChangeProfil = (Boolean) $canChangeProfil;
return $this;
} }
/** /**
@@ -777,6 +835,8 @@ class User
public function setCanChangeFtpProfil($canChangeFtpProfil) public function setCanChangeFtpProfil($canChangeFtpProfil)
{ {
$this->canChangeFtpProfil = (Boolean) $canChangeFtpProfil; $this->canChangeFtpProfil = (Boolean) $canChangeFtpProfil;
return $this;
} }
/** /**
@@ -793,6 +853,8 @@ class User
public function setLastConnection(\DateTime $lastConnection) public function setLastConnection(\DateTime $lastConnection)
{ {
$this->lastConnection = $lastConnection; $this->lastConnection = $lastConnection;
return $this;
} }
/** /**
@@ -809,6 +871,8 @@ class User
public function setMailLocked($mailLocked) public function setMailLocked($mailLocked)
{ {
$this->mailLocked = (Boolean) $mailLocked; $this->mailLocked = (Boolean) $mailLocked;
return $this;
} }
/** /**
@@ -853,6 +917,8 @@ class User
public function setCreated(\Datetime $created) public function setCreated(\Datetime $created)
{ {
$this->created = $created; $this->created = $created;
return $this;
} }
/** /**
@@ -861,6 +927,8 @@ class User
public function setUpdated(\Datetime $updated) public function setUpdated(\Datetime $updated)
{ {
$this->updated = $updated; $this->updated = $updated;
return $this;
} }
/** /**
@@ -962,10 +1030,10 @@ class User
/** /**
* @return string * @return string
*/ */
public function getDisplayName(TranslatorInterface $translator) public function getDisplayName()
{ {
if ($this->isTemplate()) { if ($this->isTemplate()) {
return $translator->trans('modele %name%', ['%name%' => $this->getLogin()]); return $this->getLogin();
} }
if (trim($this->lastName) !== '' || trim($this->firstName) !== '') { if (trim($this->lastName) !== '' || trim($this->firstName) !== '') {
@@ -976,6 +1044,10 @@ class User
return $this->email; return $this->email;
} }
return $translator->trans('Unnamed user'); if ('' !== trim($this->getLogin())) {
return $this->getLogin();
}
return 'Unnamed user';
} }
} }

View File

@@ -31,14 +31,9 @@ class UserNotificationSetting
*/ */
private $id; private $id;
/**
* @ORM\Column(type="integer", name="usr_id")
*/
private $usrId;
/** /**
* @ORM\ManyToOne(targetEntity="User", inversedBy="notificationSettings") * @ORM\ManyToOne(targetEntity="User", inversedBy="notificationSettings")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
**/ **/
private $user; private $user;
@@ -85,33 +80,13 @@ class UserNotificationSetting
* *
* @return UserNotificationSetting * @return UserNotificationSetting
*/ */
public function setUser(User $user = null) public function setUser(User $user)
{ {
$this->user = $user; $this->user = $user;
return $this; 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 * @return string
*/ */

View File

@@ -27,14 +27,9 @@ class UserQuery
*/ */
private $id; private $id;
/**
* @ORM\Column(type="integer", name="usr_id")
*/
private $usrId;
/** /**
* @ORM\ManyToOne(targetEntity="User", inversedBy="queries") * @ORM\ManyToOne(targetEntity="User", inversedBy="queries")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
**/ **/
private $user; private $user;
@@ -57,22 +52,6 @@ class UserQuery
return $this->id; return $this->id;
} }
/**
* @return integer
*/
public function getUsrId()
{
return $this->usrId;
}
/**
* @param integer $usrId
*/
public function setUsrId($usrId)
{
$this->usrId = $usrId;
}
/** /**
* @return User * @return User
*/ */
@@ -86,7 +65,7 @@ class UserQuery
* *
* @return UserQuery * @return UserQuery
*/ */
public function setUser(User $user = null) public function setUser(User $user)
{ {
$this->user = $user; $this->user = $user;

View File

@@ -31,14 +31,9 @@ class UserSetting
*/ */
private $id; private $id;
/**
* @ORM\Column(type="integer", name="usr_id")
*/
private $usrId;
/** /**
* @ORM\ManyToOne(targetEntity="User", inversedBy="settings") * @ORM\ManyToOne(targetEntity="User", inversedBy="settings")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
**/ **/
private $user; private $user;
@@ -85,33 +80,13 @@ class UserSetting
* *
* @return UserSetting * @return UserSetting
*/ */
public function setUser(User $user = null) public function setUser(User $user)
{ {
$this->user = $user; $this->user = $user;
return $this; 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 * @return string
*/ */

View File

@@ -11,13 +11,12 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
/** /**
* @ORM\Table(name="UsrAuthProviders", uniqueConstraints={ * @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\UniqueConstraint(name="provider_ids", columns={"provider", "distant_id"})
* }) * })
* @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrAuthProviderRepository") * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrAuthProviderRepository")
@@ -32,9 +31,12 @@ class UsrAuthProvider
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string", length=32) * @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; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->usr_id, $app);
} }
/** /**

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; use Gedmo\Mapping\Annotation as Gedmo;
@@ -209,10 +208,10 @@ class UsrList
return $this->entries; return $this->entries;
} }
public function hasAccess(\User_Adapter $user, Application $app) public function hasAccess(User $user)
{ {
foreach ($this->getOwners() as $owner) { foreach ($this->getOwners() as $owner) {
if ($owner->getUser($app)->get_id() == $user->get_id()) { if ($owner->getUser()->getId() == $user->getId()) {
return true; return true;
} }
} }
@@ -222,13 +221,13 @@ class UsrList
/** /**
* *
* @param \User_Adapter $user * @param User $user
* @return UsrListOwner * @return UsrListOwner
*/ */
public function getOwner(\User_Adapter $user, Application $app) public function getOwner(User $user)
{ {
foreach ($this->getOwners() as $owner) { foreach ($this->getOwners() as $owner) {
if ($owner->getUser($app)->get_id() == $user->get_id()) { if ($owner->getUser()->getId() == $user->getId()) {
return $owner; return $owner;
} }
} }
@@ -239,14 +238,14 @@ class UsrList
/** /**
* Return true if one of the entry is related to the given user * Return true if one of the entry is related to the given user
* *
* @param \User_Adapter $user * @param User $user
* @return boolean * @return boolean
*/ */
public function has(\User_Adapter $user, Application $app) public function has(User $user)
{ {
return $this->entries->exists( return $this->entries->exists(
function ($key, $entry) use ($user, $app) { function ($key, $entry) use ($user) {
return $entry->getUser($app)->get_id() === $user->get_id(); return $entry->getUser()->getId() === $user->getId();
} }
); );
} }

View File

@@ -11,12 +11,11 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; 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") * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrListEntryRepository")
*/ */
class UsrListEntry class UsrListEntry
@@ -29,9 +28,12 @@ class UsrListEntry
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @Gedmo\Timestampable(on="create") * @Gedmo\Timestampable(on="create")
@@ -62,36 +64,23 @@ class UsrListEntry
} }
/** /**
* Set usr_id * @param User $user
* *
* @param integer $usrId
* @return UsrListEntry * @return UsrListEntry
*/ */
public function setUsrId($usrId) public function setUser(User $user)
{ {
$this->usr_id = $usrId; $this->user = $user;
return $this; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->getUsrId(), $app);
}
public function setUser(\User_Adapter $user)
{
return $this->setUsrId($user->get_id());
} }
/** /**

View File

@@ -11,12 +11,11 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo; 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") * @ORM\Entity(repositoryClass="Alchemy\Phrasea\Model\Repositories\UsrListOwnerRepository")
*/ */
class UsrListOwner class UsrListOwner
@@ -33,9 +32,12 @@ class UsrListOwner
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
private $usr_id; *
* @return User
**/
private $user;
/** /**
* @ORM\Column(type="string") * @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; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
public function setUser(\User_Adapter $user)
{
return $this->setUsrId($user->get_id());
}
public function getUser(Application $app)
{
return \User_Adapter::getInstance($this->getUsrId(), $app);
} }
/** /**

View File

@@ -11,7 +11,6 @@
namespace Alchemy\Phrasea\Model\Entities; namespace Alchemy\Phrasea\Model\Entities;
use Alchemy\Phrasea\Application;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
@@ -27,11 +26,6 @@ class ValidationParticipant
*/ */
private $id; private $id;
/**
* @ORM\Column(type="integer")
*/
private $usr_id;
/** /**
* @ORM\Column(type="boolean") * @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 User
* @return ValidationParticipant **/
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; return $this;
} }
/** /**
* Get usr_id * @return User
*
* @return integer
*/ */
public function getUsrId() public function getUser()
{ {
return $this->usr_id; return $this->user;
}
/**
*
* @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);
} }
/** /**

View File

@@ -30,9 +30,12 @@ class ValidationSession
private $id; private $id;
/** /**
* @ORM\Column(type="integer") * @ORM\ManyToOne(targetEntity="User")
*/ * @ORM\JoinColumn(name="initiator_id", referencedColumnName="id", nullable=false)
private $initiator_id; *
* @return User
**/
private $initiator;
/** /**
* @Gedmo\Timestampable(on="create") * @Gedmo\Timestampable(on="create")
@@ -81,45 +84,35 @@ class ValidationSession
} }
/** /**
* Set initiator_id * @param User $user
* *
* @param integer $initiatorId * @return $this
* @return ValidationSession
*/ */
public function setInitiatorId($initiatorId) public function setInitiator(User $user)
{ {
$this->initiator_id = $initiatorId; $this->initiator = $user;
return $this; 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(); return $this->getInitiator()->getId() == $user->getId();
}
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);
}
} }
/** /**
@@ -258,21 +251,20 @@ class ValidationSession
return $date_obj > $this->getExpires(); 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->isInitiator($user)) {
if ($this->isFinished()) { if ($this->isFinished()) {
return $app->trans('Vous aviez envoye cette demande a %n% utilisateurs', ['%n%' => count($this->getParticipants()) - 1]); 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 { } else {
if ($this->getParticipant($user, $app)->getCanSeeOthers()) { if ($this->getParticipant($user)->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]); return $app->trans('Processus de validation recu de %user% et concernant %n% utilisateurs', ['%user%' => $this->getInitiator($app)->getDisplayName(), '%n%' => count($this->getParticipants()) - 1]);
} else {
return $app->trans('Processus de validation recu de %user%', ['%user%' => $this->getInitiator($app)->get_display_name()]);
} }
return $app->trans('Processus de validation recu de %user%', ['%user%' => $this->getInitiator($app)->getDisplayName()]);
} }
} }
@@ -281,14 +273,14 @@ class ValidationSession
* *
* @return ValidationParticipant * @return ValidationParticipant
*/ */
public function getParticipant(\User_Adapter $user, Application $app) public function getParticipant(User $user)
{ {
foreach ($this->getParticipants() as $participant) { foreach ($this->getParticipants() as $participant) {
if ($participant->getUser($app)->get_id() == $user->get_id()) { if ($participant->getUser()->getId() == $user->getId()) {
return $participant; return $participant;
} }
} }
throw new NotFoundHttpException('Participant not found ' . $user->get_email()); throw new NotFoundHttpException('Participant not found' . $user->getEmail());
} }
} }

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Model\Manager;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManager;
use Alchemy\Phrasea\Model\Entities\User; use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Model\Entities\UserSetting; use Alchemy\Phrasea\Model\Entities\UserSetting;
use Doctrine\ORM\UnitOfWork AS UOW;
class UserManager class UserManager
{ {
@@ -46,10 +47,6 @@ class UserManager
*/ */
public function delete(User $user, $flush = true) public function delete(User $user, $flush = true)
{ {
$user->setDeleted(true);
$user->setEmail(null);
$user->setLogin(sprintf('(#deleted_%s', $user->getLogin()));
$this->cleanProperties($user); $this->cleanProperties($user);
$this->cleanRights($user); $this->cleanRights($user);
@@ -137,7 +134,7 @@ class UserManager
private function cleanFtpExports(User $user) private function cleanFtpExports(User $user)
{ {
$elements = $this->objectManager->getRepository('Phraseanet:FtpExport') $elements = $this->objectManager->getRepository('Phraseanet:FtpExport')
->findBy(['usrId' => $user->getId()]); ->findBy(['user' => $user]);
foreach ($elements as $element) { foreach ($elements as $element) {
$this->objectManager->remove($element); $this->objectManager->remove($element);
@@ -152,13 +149,43 @@ class UserManager
private function cleanOrders(User $user) private function cleanOrders(User $user)
{ {
$orders = $this->objectManager->getRepository('Phraseanet:Order') $orders = $this->objectManager->getRepository('Phraseanet:Order')
->findBy(['usrId' => $user->getId()]); ->findBy(['user' => $user]);
foreach ($orders as $order) { foreach ($orders as $order) {
$this->objectManager->remove($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. * Removes all user's properties.
* *
@@ -180,6 +207,8 @@ class UserManager
$this->cleanFtpCredentials($user); $this->cleanFtpCredentials($user);
$this->cleanOrders($user); $this->cleanOrders($user);
$this->cleanFtpExports($user); $this->cleanFtpExports($user);
$this->cleanAuthProvider($user);
$this->cleanUserSessions($user);
} }
/** /**

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Model\Manipulator;
use Alchemy\Phrasea\Authentication\ACLProvider; use Alchemy\Phrasea\Authentication\ACLProvider;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Exception\LogicException; use Alchemy\Phrasea\Exception\LogicException;
use Alchemy\Phrasea\Model\Entities\User;
class ACLManipulator implements ManipulatorInterface class ACLManipulator implements ManipulatorInterface
{ {
@@ -39,7 +40,7 @@ class ACLManipulator implements ManipulatorInterface
/** /**
* Resets rights for users. * Resets rights for users.
* *
* @param User_Adapter $user * @param User[] $users
* *
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
@@ -53,9 +54,9 @@ class ACLManipulator implements ManipulatorInterface
/** /**
* Resets rights for a user. * 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); $acl = $this->ACLProvider->get($user);
$databoxes = $this->appbox->get_databoxes(); $databoxes = $this->appbox->get_databoxes();

View File

@@ -74,6 +74,21 @@ class UserManipulator implements ManipulatorInterface
return $user; 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. * Creates a template user and returns it.
* *
@@ -184,13 +199,17 @@ class UserManipulator implements ManipulatorInterface
* @param string $name * @param string $name
* @param string $value * @param string $value
*/ */
public function addUserSetting(User $user, $name, $value) public function setUserSetting(User $user, $name, $value)
{ {
$userSetting = new UserSetting(); if ($user->getSettings()->containsKey($name)) {
$userSetting->setUsrId($user->getId()); $user->getSettings()->get($name)->setValue($value);
$userSetting->setName($name); } else {
$userSetting->setValue($value); $userSetting = new UserSetting();
$user->addSetting($userSetting); $userSetting->setUser($user);
$userSetting->setName($name);
$userSetting->setValue($value);
$user->addSetting($userSetting);
}
$this->manager->update($user); $this->manager->update($user);
} }
@@ -202,13 +221,17 @@ class UserManipulator implements ManipulatorInterface
* @param string $name * @param string $name
* @param string $value * @param string $value
*/ */
public function addNotificationSetting(User $user, $name, $value) public function setNotificationSetting(User $user, $name, $value)
{ {
$notifSetting = new UserNotificationSetting(); if ($user->getNotificationSettings()->containsKey($name)) {
$notifSetting->setName($name); $user->getNotificationSettings()->get($name)->setValue((Boolean) $value);
$notifSetting->setValue($value); } else {
$notifSetting->setUsrId($user->getId()); $userSetting = new UserNotificationSetting();
$user->addNotificationSettings($notifSetting); $userSetting->setUser($user);
$userSetting->setName($name);
$userSetting->setValue($value);
$user->addNotificationSettings($userSetting);
}
$this->manager->update($user); $this->manager->update($user);
} }
@@ -224,7 +247,7 @@ class UserManipulator implements ManipulatorInterface
$userQuery = new UserQuery(); $userQuery = new UserQuery();
$userQuery->setUser($user); $userQuery->setUser($user);
$userQuery->setQuery($query); $userQuery->setQuery($query);
$userQuery->setUsrId($user->getId()); $userQuery->setUser($user);
$user->addQuery($userQuery); $user->addQuery($userQuery);
@@ -241,6 +264,7 @@ class UserManipulator implements ManipulatorInterface
{ {
$user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36)); $user->setNonce(base_convert(sha1(uniqid(mt_rand(), true)), 16, 36));
$user->setPassword($this->passwordEncoder->encodePassword($password, $user->getNonce())); $user->setPassword($this->passwordEncoder->encodePassword($password, $user->getNonce()));
$user->setSaltedPassword(true);
} }
/** /**

View File

@@ -0,0 +1,87 @@
<?php
/*
* This file is part of Phraseanet
*
* (c) 2005-2014 Alchemy
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Alchemy\Phrasea\Model;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Alchemy\Phrasea\Model\Entities\User;
class NativeQueryProvider
{
private $em;
public function __construct(EntityManager $em)
{
$this->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();
}
}

View File

@@ -12,6 +12,7 @@
namespace Alchemy\Phrasea\Model\Repositories; namespace Alchemy\Phrasea\Model\Repositories;
use Alchemy\Phrasea\Model\Entities\BasketElement; use Alchemy\Phrasea\Model\Entities\BasketElement;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -24,7 +25,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class BasketElementRepository extends EntityRepository class BasketElementRepository extends EntityRepository
{ {
public function findUserElement($element_id, \User_Adapter $user) public function findUserElement($element_id, User $user)
{ {
$dql = 'SELECT e $dql = 'SELECT e
FROM Phraseanet:BasketElement e FROM Phraseanet:BasketElement e
@@ -32,12 +33,12 @@ class BasketElementRepository extends EntityRepository
LEFT JOIN e.validation_datas vd LEFT JOIN e.validation_datas vd
LEFT JOIN b.validation s LEFT JOIN b.validation s
LEFT JOIN s.participants p 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'; AND e.id = :element_id';
$params = [ $params = [
'usr_id' => $user->get_id(), 'usr_id' => $user->getId(),
'same_usr_id' => $user->get_id(), 'same_usr_id' => $user->getId(),
'element_id' => $element_id 'element_id' => $element_id
]; ];
@@ -97,25 +98,25 @@ class BasketElementRepository extends EntityRepository
/** /**
* *
* @param \record_adapter $record * @param \record_adapter $record
* @param \User_Adapter $user * @param User $user
* @return \Doctrine\Common\Collections\ArrayCollection * @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 $dql = 'SELECT e
FROM Phraseanet:BasketElement e FROM Phraseanet:BasketElement e
JOIN e.basket b JOIN e.basket b
LEFT JOIN b.validation s LEFT JOIN b.validation s
LEFT JOIN s.participants p LEFT JOIN s.participants p
WHERE b.usr_id = :usr_id WHERE b.user = :usr_id
AND b.pusher_id IS NOT NULL AND b.pusher IS NOT NULL
AND e.record_id = :record_id AND e.record_id = :record_id
AND e.sbas_id = :sbas_id'; AND e.sbas_id = :sbas_id';
$params = [ $params = [
'sbas_id' => $record->get_sbas_id(), 'sbas_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id(), 'record_id' => $record->get_record_id(),
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
@@ -124,21 +125,21 @@ class BasketElementRepository extends EntityRepository
return $query->getResult(); return $query->getResult();
} }
public function findReceivedValidationElementsByRecord(\record_adapter $record, \User_Adapter $user) public function findReceivedValidationElementsByRecord(\record_adapter $record, User $user)
{ {
$dql = 'SELECT e $dql = 'SELECT e
FROM Phraseanet:BasketElement e FROM Phraseanet:BasketElement e
JOIN e.basket b JOIN e.basket b
JOIN b.validation v JOIN b.validation v
JOIN v.participants p JOIN v.participants p
WHERE p.usr_id = :usr_id WHERE p.user = :usr_id
AND e.record_id = :record_id AND e.record_id = :record_id
AND e.sbas_id = :sbas_id'; AND e.sbas_id = :sbas_id';
$params = [ $params = [
'sbas_id' => $record->get_sbas_id(), 'sbas_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id(), 'record_id' => $record->get_record_id(),
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);

View File

@@ -12,7 +12,10 @@
namespace Alchemy\Phrasea\Model\Repositories; namespace Alchemy\Phrasea\Model\Repositories;
use Alchemy\Phrasea\Model\Entities\Basket; use Alchemy\Phrasea\Model\Entities\Basket;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class BasketRepository extends EntityRepository 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 * 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 * @return \Doctrine\Common\Collections\ArrayCollection
*/ */
public function findActiveByUser(\User_Adapter $user, $sort = null) public function findActiveByUser(User $user, $sort = null)
{ {
$dql = 'SELECT b $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
LEFT JOIN b.elements e LEFT JOIN b.elements e
WHERE b.usr_id = :usr_id WHERE b.user = :usr_id
AND b.archived = false'; AND b.archived = false';
if ($sort == 'date') { if ($sort == 'date') {
@@ -42,7 +45,7 @@ class BasketRepository extends EntityRepository
} }
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
$query->setParameters(['usr_id' => $user->get_id()]); $query->setParameters(['usr_id' => $user->getId()]);
return $query->getResult(); 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 * 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 * @return \Doctrine\Common\Collections\ArrayCollection
*/ */
public function findUnreadActiveByUser(\User_Adapter $user) public function findUnreadActiveByUser(User $user)
{ {
$dql = 'SELECT b $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
@@ -62,17 +65,17 @@ class BasketRepository extends EntityRepository
LEFT JOIN s.participants p LEFT JOIN s.participants p
WHERE b.archived = false WHERE b.archived = false
AND ( AND (
(b.usr_id = :usr_id_owner AND b.is_read = false) (b.user = :usr_id_owner AND b.is_read = false)
OR (b.usr_id != :usr_id_ownertwo OR (b.user != :usr_id_ownertwo
AND p.usr_id = :usr_id_participant AND p.user = :usr_id_participant
AND p.is_aware = false) AND p.is_aware = false)
) )
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())'; AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())';
$params = [ $params = [
'usr_id_owner' => $user->get_id(), 'usr_id_owner' => $user->getId(),
'usr_id_ownertwo' => $user->get_id(), 'usr_id_ownertwo' => $user->getId(),
'usr_id_participant' => $user->get_id() 'usr_id_participant' => $user->getId()
]; ];
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
@@ -85,10 +88,10 @@ class BasketRepository extends EntityRepository
* Returns all baskets that are in validation session not expired and * Returns all baskets that are in validation session not expired and
* where a specified user is participant (not owner) * where a specified user is participant (not owner)
* *
* @param \User_Adapter $user * @param User $user
* @return \Doctrine\Common\Collections\ArrayCollection * @return \Doctrine\Common\Collections\ArrayCollection
*/ */
public function findActiveValidationByUser(\User_Adapter $user, $sort = null) public function findActiveValidationByUser(User $user, $sort = null)
{ {
$dql = 'SELECT b $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
@@ -96,7 +99,7 @@ class BasketRepository extends EntityRepository
JOIN e.validation_datas v JOIN e.validation_datas v
JOIN b.validation s JOIN b.validation s
JOIN s.participants p 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()) '; AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) ';
if ($sort == 'date') { if ($sort == 'date') {
@@ -106,23 +109,68 @@ class BasketRepository extends EntityRepository
} }
$query = $this->_em->createQuery($dql); $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(); 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 $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
JOIN b.elements e JOIN b.elements e
WHERE e.record_id = :record_id AND e.sbas_id = e.sbas_id 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 = [ $params = [
'record_id' => $record->get_record_id(), 'record_id' => $record->get_record_id(),
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
@@ -131,7 +179,7 @@ class BasketRepository extends EntityRepository
return $query->getResult(); 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 = []; $params = [];
@@ -140,9 +188,9 @@ class BasketRepository extends EntityRepository
$dql = 'SELECT b $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
JOIN b.elements e 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 = [ $params = [
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
break; break;
case self::VALIDATION_DONE: case self::VALIDATION_DONE:
@@ -151,10 +199,10 @@ class BasketRepository extends EntityRepository
JOIN b.elements e JOIN b.elements e
JOIN b.validation s JOIN b.validation s
JOIN s.participants p JOIN s.participants p
WHERE b.usr_id != ?1 AND p.usr_id = ?2'; WHERE b.user != ?1 AND p.user = ?2';
$params = [ $params = [
1 => $user->get_id() 1 => $user->getId()
, 2 => $user->get_id() , 2 => $user->getId()
]; ];
break; break;
case self::VALIDATION_SENT: case self::VALIDATION_SENT:
@@ -162,9 +210,9 @@ class BasketRepository extends EntityRepository
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
JOIN b.elements e JOIN b.elements e
JOIN b.validation v JOIN b.validation v
WHERE b.usr_id = :usr_id'; WHERE b.user = :usr_id';
$params = [ $params = [
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
break; break;
default: default:
@@ -173,10 +221,10 @@ class BasketRepository extends EntityRepository
LEFT JOIN b.elements e LEFT JOIN b.elements e
LEFT JOIN b.validation s LEFT JOIN b.validation s
LEFT JOIN s.participants p 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 = [ $params = [
'usr_id' => $user->get_id(), 'usr_id' => $user->getId(),
'validating_usr_id' => $user->get_id() 'validating_usr_id' => $user->getId()
]; ];
break; break;
case self::MYBASKETS: case self::MYBASKETS:
@@ -185,9 +233,9 @@ class BasketRepository extends EntityRepository
LEFT JOIN b.elements e LEFT JOIN b.elements e
LEFT JOIN b.validation s LEFT JOIN b.validation s
LEFT JOIN s.participants p LEFT JOIN s.participants p
WHERE (b.usr_id = :usr_id)'; WHERE (b.user = :usr_id)';
$params = [ $params = [
'usr_id' => $user->get_id() 'usr_id' => $user->getId()
]; ];
break; break;
} }
@@ -221,19 +269,19 @@ class BasketRepository extends EntityRepository
/** /**
* Return all actives validation where current user is involved and user basket * Return all actives validation where current user is involved and user basket
* *
* @param \User_Adapter $user * @param User $user
* @param type $sort * @param type $sort
* @return Array * @return Array
*/ */
public function findActiveValidationAndBasketByUser(\User_Adapter $user, $sort = null) public function findActiveValidationAndBasketByUser(User $user, $sort = null)
{ {
$dql = 'SELECT b $dql = 'SELECT b
FROM Phraseanet:Basket b FROM Phraseanet:Basket b
LEFT JOIN b.elements e LEFT JOIN b.elements e
LEFT JOIN b.validation s LEFT JOIN b.validation s
LEFT JOIN s.participants p LEFT JOIN s.participants p
WHERE (b.usr_id = :usr_id AND b.archived = false) WHERE (b.user = :usr_id AND b.archived = false)
OR (b.usr_id != :usr_id AND p.usr_id = :usr_id OR (b.user != :usr_id AND p.user = :usr_id
AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP()) AND (s.expires IS NULL OR s.expires > CURRENT_TIMESTAMP())
)'; )';
@@ -244,7 +292,7 @@ class BasketRepository extends EntityRepository
} }
$query = $this->_em->createQuery($dql); $query = $this->_em->createQuery($dql);
$query->setParameters(['usr_id' => $user->get_id()]); $query->setParameters(['usr_id' => $user->getId()]);
return $query->getResult(); return $query->getResult();
} }

View File

@@ -24,7 +24,6 @@ class FeedRepository extends EntityRepository
/** /**
* Returns all the feeds a user can access. * Returns all the feeds a user can access.
* *
* @param User_Adapter $user
* @return \Doctrine\Common\Collections\Collection * @return \Doctrine\Common\Collections\Collection
*/ */
public function getAllForUser(\ACL $userACL) public function getAllForUser(\ACL $userACL)

View File

@@ -11,6 +11,7 @@
namespace Alchemy\Phrasea\Model\Repositories; namespace Alchemy\Phrasea\Model\Repositories;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
/** /**
@@ -62,12 +63,12 @@ class FtpExportRepository extends EntityRepository
/** /**
* Returns the exports initiated by a given user. * Returns the exports initiated by a given user.
* *
* @param \User_Adapter $user * @param User $user
* *
* @return array * @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]);
} }
} }

Some files were not shown because too many files have changed in this diff Show More