Remove User_Adapter Inteface References

This commit is contained in:
Nicolas Le Goff
2013-11-19 12:27:51 +01:00
parent bd2f777ab9
commit 53ae0ccc24
44 changed files with 795 additions and 549 deletions

View File

@@ -72,6 +72,7 @@ use Alchemy\Phrasea\Controller\Utils\ConnectionTest;
use Alchemy\Phrasea\Controller\Utils\PathFileTest; use Alchemy\Phrasea\Controller\Utils\PathFileTest;
use Alchemy\Phrasea\Controller\User\Notifications; use Alchemy\Phrasea\Controller\User\Notifications;
use Alchemy\Phrasea\Controller\User\Preferences; use Alchemy\Phrasea\Controller\User\Preferences;
use Alchemy\Phrasea\Core\CLIProvider\DoctrineMigrationServiceProvider;
use Alchemy\Phrasea\Core\PhraseaExceptionHandler; use Alchemy\Phrasea\Core\PhraseaExceptionHandler;
use Alchemy\Phrasea\Core\Event\Subscriber\LogoutSubscriber; use Alchemy\Phrasea\Core\Event\Subscriber\LogoutSubscriber;
use Alchemy\Phrasea\Core\Event\Subscriber\PhraseaLocaleSubscriber; use Alchemy\Phrasea\Core\Event\Subscriber\PhraseaLocaleSubscriber;
@@ -129,6 +130,7 @@ use Neutron\Silex\Provider\FilesystemServiceProvider;
use Neutron\ReCaptcha\ReCaptchaServiceProvider; use Neutron\ReCaptcha\ReCaptchaServiceProvider;
use PHPExiftool\PHPExiftoolServiceProvider; use PHPExiftool\PHPExiftoolServiceProvider;
use Silex\Application as SilexApplication; use Silex\Application as SilexApplication;
use Silex\Provider\DoctrineServiceProvider;
use Silex\Application\UrlGeneratorTrait; use Silex\Application\UrlGeneratorTrait;
use Silex\Application\TranslationTrait; use Silex\Application\TranslationTrait;
use Silex\Provider\FormServiceProvider; use Silex\Provider\FormServiceProvider;
@@ -209,6 +211,7 @@ class Application extends SilexApplication
$this->register(new BasketMiddlewareProvider()); $this->register(new BasketMiddlewareProvider());
$this->register(new ACLServiceProvider()); $this->register(new ACLServiceProvider());
$this->register(new DoctrineMigrationServiceProvider());
$this->register(new AuthenticationManagerServiceProvider()); $this->register(new AuthenticationManagerServiceProvider());
$this->register(new BorderManagerServiceProvider()); $this->register(new BorderManagerServiceProvider());
$this->register(new BrowserServiceProvider()); $this->register(new BrowserServiceProvider());

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,32 @@ 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())) {
$user->setSaltedPassword(true);
$row['nonce'] = \random::generatePassword(8, \random::LETTERS_AND_NUMBERS); $this->userManipulator->setPassword($user, $user->getPassword());
$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

@@ -40,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 $this->app['manipulator.user']->getRepository()->find($row['usr_id']);
}
} }
return null; return null;

View File

@@ -14,6 +14,8 @@ 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 Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
@@ -353,51 +355,53 @@ 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'; $rsm = new ResultSetMappingBuilder($app['EM']);
$rsm->addScalarResult('date_demand', 'date_demand');
$rsm->addScalarResult('base_demand', 'base_demand');
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $selectClause = $rsm->generateSelectClause([
$stmt->execute([':usr_id' => $app['authentication']->getUser()->getId()]); 'u' => 't1'
$models = $stmt->fetchAll(\PDO::FETCH_ASSOC); ]);
$stmt->closeCursor();
$sql = " $query = $app['EM']->createNativeQuery("
SELECT demand.date_modif,demand.base_id, usr.usr_id , usr.usr_login ,usr.usr_nom,usr.usr_prenom, SELECT d.date_modif AS date_demand, d.base_id AS base_demand, " . $selectClause . "
usr.societe, usr.fonction, usr.usr_mail, usr.tel, usr.activite, FROM (demand d INNER JOIN Users t1 ON d.usr_id=t1.id
usr.adresse, usr.cpostal, usr.ville, usr.pays, CONCAT(usr.usr_nom,' ',usr.usr_prenom,'\n',fonction,' (',societe,')') AS info AND d.en_cours=1
FROM (demand INNER JOIN usr on demand.usr_id=usr.usr_id AND demand.en_cours=1 AND usr.usr_login NOT LIKE '(#deleted%' ) AND t1.deleted=0
WHERE (base_id='" . implode("' OR base_id='", $baslist) . "') ORDER BY demand.usr_id DESC,demand.base_id ASC )
"; WHERE (base_id='" . implode("' OR base_id='", $basList) . "')
ORDER BY d.usr_id DESC, d.base_id ASC
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); ", $rsm);
$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 ($query->getResult() 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' => new \DateTime($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'];
} }
} }
@@ -543,17 +547,9 @@ class Users implements ControllerProviderInterface
} }
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);
@@ -715,20 +711,23 @@ class Users implements ControllerProviderInterface
]); ]);
} }
$sql = " $rsm = new ResultSetMappingBuilder($app['EM']);
SELECT usr.usr_id,usr.usr_login
FROM usr
INNER JOIN basusr
ON (basusr.usr_id=usr.usr_id)
WHERE usr.model_of = :usr_id
AND base_id in(" . implode(', ', array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))) . ")
AND usr_login not like '(#deleted_%)'
GROUP BY usr_id";
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $selectClause = $rsm->generateSelectClause([
$stmt->execute([':usr_id' => $app['authentication']->getUser()->getId()]); 'u' => 't1'
$models = $stmt->fetchAll(\PDO::FETCH_ASSOC); ]);
$stmt->closeCursor();
$query = $app['EM']->createNativeQuery("
SELECT " . $selectClause . "
FROM Users t1
INNER JOIN basusr b ON (b.usr_id=t1.id)
WHERE t1.model_of = :user_id
AND b.base_id IN (" . implode(', ', array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))) . ")
AND t1.deleted='0'
GROUP BY t1.id"
);
$query->setParameter(':user_id', $app['authentication']->getUser()->getId());
$models = $query->getResult();
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,

View File

@@ -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(),

View File

@@ -557,7 +557,7 @@ class Push implements ControllerProviderInterface
if ($request->request->get('job')) if ($request->request->get('job'))
$user->setCompany($request->request->get('job')); $user->setCompany($request->request->get('job'));
if ($request->request->get('form_geonameid')) if ($request->request->get('form_geonameid'))
$user->setGeonanameId($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;

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());
@@ -94,7 +88,7 @@ class Account implements ControllerProviderInterface
$user = $app['authentication']->getUser(); $user = $app['authentication']->getUser();
if ($app['auth.password-encoder']->isPasswordValid($user->getPassword(), $data['oldPassword'], $user->getNonce())) { if ($app['auth.password-encoder']->isPasswordValid($user->getPassword(), $data['oldPassword'], $user->getNonce())) {
$user->setPassword($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');
@@ -267,8 +261,8 @@ 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 Alchemy\Phrasea\Model\Entities\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);
@@ -386,10 +380,16 @@ class Account implements ControllerProviderInterface
->setCompany($request->request->get("form_company")) ->setCompany($request->request->get("form_company"))
->setActivity($request->request->get("form_function")) ->setActivity($request->request->get("form_function"))
->setGeonanameId($request->request->get("form_geonameid")) ->setGeonanameId($request->request->get("form_geonameid"))
->set_mail_notifications((bool) $request->request->get("mail_notifications")); ->set_mail_notifications((Boolean) $request->request->get("mail_notifications"));
$app['manipulator.user']->setGeonameId($app['authentication']->getUser(), $request->request->get("form_geonameid"));
$ftpCredential = $app['authentication']->getUser()->getFtpCredential(); $ftpCredential = $app['authentication']->getUser()->getFtpCredential();
if (null === $ftpCredential) {
$ftpCredential = new FtpCredential();
}
$ftpCredential->setActive($request->request->get("form_activeFTP")); $ftpCredential->setActive($request->request->get("form_activeFTP"));
$ftpCredential->setAddress($request->request->get("form_addressFTP")); $ftpCredential->setAddress($request->request->get("form_addressFTP"));
$ftpCredential->setLogin($request->request->get("form_loginFTP")); $ftpCredential->setLogin($request->request->get("form_loginFTP"));

View File

@@ -376,9 +376,13 @@ class Login implements ControllerProviderInterface
'job' => 'setJob', 'job' => 'setJob',
'company' => 'setCompany', 'company' => 'setCompany',
'position' => 'setActivity', 'position' => 'setActivity',
'geonameid' => 'setGeonanameId', 'geonameid' => 'setGeonameId',
] as $property => $method) { ] as $property => $method) {
if (isset($data[$property])) { if (isset($data[$property])) {
if ($property === 'geonameid') {
$app['manipulator.user']->setGeonameId($user, $data[$property]);
continue;
}
call_user_func([$user, $method], $data[$property]); call_user_func([$user, $method], $data[$property]);
} }
} }
@@ -490,9 +494,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 = $app['manipulator.user']->getRepository()->find((int) $usrId);
} 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');
@@ -558,7 +560,7 @@ class Login implements ControllerProviderInterface
try { try {
$user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id']); $user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id']);
} catch (\Exception $e) { } catch (\Exception $e) {
$app->addFlash('error', $app->trans('Invalid unlock link.')); $app->addFlash('error', _('Invalid unlock link.'));
return $app->redirectPath('homepage'); return $app->redirectPath('homepage');
} }
@@ -621,7 +623,7 @@ class Login implements ControllerProviderInterface
$datas = $app['tokens']->helloToken($token); $datas = $app['tokens']->helloToken($token);
$user = $app['manipulator.user']->getRepository()->find($datas['usr_id']); $user = $app['manipulator.user']->getRepository()->find($datas['usr_id']);
$user->setPassword($data['password']); $app['manipulator.user']->setPassword($user, $data['password']);
$app['tokens']->removeToken($token); $app['tokens']->removeToken($token);
@@ -661,7 +663,7 @@ class Login implements ControllerProviderInterface
try { try {
$user = $app['manipulator.user']->getRepository()->findByEmail($data['email']); $user = $app['manipulator.user']->getRepository()->findByEmail($data['email']);
} catch (\Exception $e) { } catch (\Exception $e) {
throw new FormProcessingException($app->trans('phraseanet::erreur: Le compte n\'a pas ete trouve')); throw new FormProcessingException(_('phraseanet::erreur: Le compte n\'a pas ete trouve'));
} }
try { try {
@@ -806,8 +808,7 @@ 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); $invite_user = $app['manipulator.user']->createUser('invite', \random::generatePassword(24));
$invite_user = $app['manipulator.user']->createUser('invite', $password);
$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);
@@ -1051,7 +1052,7 @@ 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->getId() != $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');

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 = 0)
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

View File

@@ -107,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

@@ -125,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
@@ -192,8 +192,8 @@ 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.usr_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);
@@ -315,8 +315,8 @@ 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.usr_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);
@@ -369,10 +369,10 @@ 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.usr_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);
@@ -602,13 +602,14 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
->setEmail($parm['email']) ->setEmail($parm['email'])
->setAddress($parm['address']) ->setAddress($parm['address'])
->setZipCode($parm['zip']) ->setZipCode($parm['zip'])
->setGeonanameId($parm['geonameid'])
->setActivity($parm['function']) ->setActivity($parm['function'])
->setJob($parm['activite']) ->setJob($parm['activite'])
->setCompany($parm['company']) ->setCompany($parm['company'])
->setPhone($parm['telephone']) ->setPhone($parm['telephone'])
->setFax($parm['fax']); ->setFax($parm['fax']);
$this->app['manipulator.user']->setGeonameId($user, $parm['geonameid']);
$new_email = $user->getEmail(); $new_email = $user->getEmail();
if ($old_email != $new_email) { if ($old_email != $new_email) {

View File

@@ -146,14 +146,7 @@ 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);
@@ -189,12 +182,9 @@ class Manage extends Helper
$this->app['notification.deliverer']->deliver($mail); $this->app['notification.deliverer']->deliver($mail);
} }
} }
}
$this->usr_id = $createdUser->getId(); $this->usr_id = $createdUser->getId();
} else {
$this->usr_id = $row['usr_id'];
$createdUser = $this->app['manipulator.user']->getRepository()->find($this->usr_id);
}
return $createdUser; return $createdUser;
} }

View File

@@ -399,7 +399,7 @@ class Feed implements FeedInterface
public function getPublisher(User $user) public function getPublisher(User $user)
{ {
foreach ($this->getPublishers() as $publisher) { foreach ($this->getPublishers() as $publisher) {
if ($publisher->gteUser()->getId() == $user->getId()) { if ($publisher->getUser()->getId() == $user->getId()) {
return $publisher; return $publisher;
} }
} }

View File

@@ -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;
} }
/** /**
@@ -415,6 +429,8 @@ class User
} }
$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,6 +763,8 @@ class User
public function setModelOf(User $owner) public function setModelOf(User $owner)
{ {
$this->modelOf = $owner; $this->modelOf = $owner;
return $this;
} }
/** /**
@@ -729,6 +781,8 @@ class User
public function setLastModel($lastModel) public function setLastModel($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;
} }
/** /**

View File

@@ -136,8 +136,8 @@ class UserManager
*/ */
private function cleanFtpExports(User $user) private function cleanFtpExports(User $user)
{ {
$elements = $this->objectManager->getRepository('Phraseanet:FtpExport') $elements = $this->objectManager->getRepository('Alchemy\Phrasea\Model\Entities\FtpExport')
->findBy(['usrId' => $user->getId()]); ->findBy(['user' => $user->getId()]);
foreach ($elements as $element) { foreach ($elements as $element) {
$this->objectManager->remove($element); $this->objectManager->remove($element);
@@ -151,8 +151,8 @@ class UserManager
*/ */
private function cleanOrders(User $user) private function cleanOrders(User $user)
{ {
$orders = $this->objectManager->getRepository('Phraseanet:Order') $orders = $this->objectManager->getRepository('Alchemy\Phrasea\Model\Entities\Order')
->findBy(['usrId' => $user->getId()]); ->findBy(['user' => $user->getId()]);
foreach ($orders as $order) { foreach ($orders as $order) {
$this->objectManager->remove($order); $this->objectManager->remove($order);

View File

@@ -67,4 +67,36 @@ class UserRepository extends EntityRepository
return $qb->getQuery()->getOneOrNullResult(); return $qb->getQuery()->getOneOrNullResult();
} }
/**
* Finds a user that is not deleted, not a model and not a guest.
*
* @param $login
*
* @return null|User
*/
public function findRealUserByLogin($login)
{
$qb = $this->createQueryBuilder('u');
$qb->where($qb->expr()->eq('u.login', $qb->expr()->literal($login)))
->andWhere($qb->expr()->isNotNull('u.email'))
->andWhere($qb->expr()->eq('u.modelOf', $qb->expr()->literal('0')))
->andWhere($qb->expr()->eq('u.guest', $qb->expr()->literal('0')))
->andWhere($qb->expr()->eq('u.deleted', $qb->expr()->literal(false)));
return $qb->getQuery()->getOneOrNullResult();
}
/**
* Finds model of given user.
*
* @param User $user
*
* @return array
*/
public function findModelOf(User $user)
{
return $this->findBy(['modelOf' => $user->getId()]);
}
} }

View File

@@ -104,7 +104,7 @@ class Firewall
public function requireNotGuest() public function requireNotGuest()
{ {
if ($this->app['authentication']->getUser()->is_guest()) { if ($this->app['authentication']->getUser()->isGuest()) {
$this->app->abort(403, 'Guests do not have admin role'); $this->app->abort(403, 'Guests do not have admin role');
} }

View File

@@ -101,12 +101,12 @@ class ACL implements cache_cacheableInterface
/** /**
* Constructor * Constructor
* *
* @param User_Interface $user * @param User $user
* @param Application $app * @param Application $app
* *
* @return \ACL * @return \ACL
*/ */
public function __construct(User_Interface $user, Application $app) public function __construct(User $user, Application $app)
{ {
$this->user = $user; $this->user = $user;
$this->app = $app; $this->app = $app;
@@ -263,11 +263,11 @@ class ACL implements cache_cacheableInterface
/** /**
* Apply a template on user * Apply a template on user
* *
* @param User_Interface $template_user * @param User $template_user
* @param array $base_ids * @param array $base_ids
* @return ACL * @return ACL
*/ */
public function apply_model(User_Interface $template_user, Array $base_ids) public function apply_model(User $template_user, Array $base_ids)
{ {
if (count($base_ids) == 0) { if (count($base_ids) == 0) {
return $this; return $this;
@@ -397,7 +397,7 @@ class ACL implements cache_cacheableInterface
return $this; return $this;
} }
private function apply_template_time_limits(User_Interface $template_user, Array $base_ids) private function apply_template_time_limits(User $template_user, Array $base_ids)
{ {
foreach ($base_ids as $base_id) { foreach ($base_ids as $base_id) {
$limited = $this->app['acl']->get($template_user)->get_limits($base_id); $limited = $this->app['acl']->get($template_user)->get_limits($base_id);
@@ -752,25 +752,12 @@ class ACL implements cache_cacheableInterface
public function is_admin() public function is_admin()
{ {
$this->load_is_admin(); return $this->user->isAdmin();
return $this->is_admin;
} }
public function set_admin($boolean) public function set_admin($boolean)
{ {
$sql = 'UPDATE usr SET create_db = :create_db WHERE usr_id = :usr_id'; $this->app['manipulator.user']->promote($this->user);
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([
':create_db' => $boolean ? '1' : '0',
':usr_id' => $this->user->getId()
]);
$stmt->closeCursor();
$this->delete_data_from_cache(self::CACHE_IS_ADMIN);
$this->is_admin = null;
return $this; return $this;
} }
@@ -825,34 +812,6 @@ class ACL implements cache_cacheableInterface
return $this; return $this;
} }
protected function load_is_admin()
{
if (null !== $this->is_admin) {
return $this;
}
try {
$this->is_admin = $this->get_data_from_cache(self::CACHE_IS_ADMIN);
return $this;
} catch (Exception $e) {
}
$sql = 'SELECT create_db
FROM usr WHERE usr_id = :usr_id';
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':usr_id' => $this->user->getId()]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
unset($stmt);
$this->is_admin = !!$row['create_db'];
$this->set_data_to_cache($this->is_admin, self::CACHE_IS_ADMIN);
return $this;
}
/** /**
* Loads rights of specified user for all sbas * Loads rights of specified user for all sbas
* *

View File

@@ -153,22 +153,22 @@ class User_Query implements User_QueryInterface
const ORD_ASC = 'asc'; const ORD_ASC = 'asc';
const ORD_DESC = 'desc'; const ORD_DESC = 'desc';
const SORT_FIRSTNAME = 'usr_prenom'; const SORT_FIRSTNAME = 'first_name';
const SORT_LASTNAME = 'usr_nom'; const SORT_LASTNAME = 'last_name';
const SORT_COMPANY = 'societe'; const SORT_COMPANY = 'company';
const SORT_LOGIN = 'usr_login'; const SORT_LOGIN = 'login';
const SORT_EMAIL = 'usr_mail'; const SORT_EMAIL = 'email';
const SORT_ID = 'usr_id'; const SORT_ID = 'id';
const SORT_CREATIONDATE = 'usr_creationdate'; const SORT_CREATIONDATE = 'created';
const SORT_COUNTRY = 'pays'; const SORT_COUNTRY = 'country';
const SORT_LASTMODEL = 'lastModel'; const SORT_LASTMODEL = 'last_model';
const LIKE_FIRSTNAME = 'usr_prenom'; const LIKE_FIRSTNAME = 'first_name';
const LIKE_LASTNAME = 'usr_nom'; const LIKE_LASTNAME = 'last_name';
const LIKE_NAME = 'name'; const LIKE_NAME = 'name';
const LIKE_COMPANY = 'societe'; const LIKE_COMPANY = 'company';
const LIKE_LOGIN = 'usr_login'; const LIKE_LOGIN = 'login';
const LIKE_EMAIL = 'usr_mail'; const LIKE_EMAIL = 'email';
const LIKE_COUNTRY = 'pays'; const LIKE_COUNTRY = 'country';
const LIKE_MATCH_AND = 'AND'; const LIKE_MATCH_AND = 'AND';
const LIKE_MATCH_OR = 'OR'; const LIKE_MATCH_OR = 'OR';
@@ -209,23 +209,23 @@ class User_Query implements User_QueryInterface
$this->sql_params = []; $this->sql_params = [];
$sql = ' $sql = '
FROM usr LEFT JOIN basusr ON (usr.usr_id = basusr.usr_id) FROM Users LEFT JOIN basusr ON (Users.id = basusr.usr_id)
LEFT JOIN sbasusr ON (usr.usr_id = sbasusr.usr_id) LEFT JOIN sbasusr ON (Users.id = sbasusr.usr_id)
WHERE 1 '; WHERE 1 ';
if (! $this->include_special_users) { if (! $this->include_special_users) {
$sql .= ' AND usr_login != "autoregister" $sql .= ' AND Users.login != "autoregister"
AND usr_login != "invite" '; AND Users.login != "invite" ';
} }
$sql .= ' AND usr_login NOT LIKE "(#deleted_%" '; $sql .= ' AND Users.deleted="0" ';
if (! $this->include_invite) { if (! $this->include_invite) {
$sql .= ' AND usr.invite=0 '; $sql .= ' AND Users.guest="0" ';
} }
if ($this->email_not_null) { if ($this->email_not_null) {
$sql .= ' AND usr.usr_mail IS NOT NULL '; $sql .= ' AND Users.email IS NOT NULL ';
} }
if ($this->only_templates === true) { if ($this->only_templates === true) {
@@ -300,7 +300,7 @@ class User_Query implements User_QueryInterface
} }
if ($this->in_ids) { if ($this->in_ids) {
$sql .= 'AND (usr.usr_id = ' . implode(' OR usr.usr_id = ', $this->in_ids) . ')'; $sql .= 'AND (Users.id = ' . implode(' OR Users.id = ', $this->in_ids) . ')';
} }
if ($this->have_rights) { if ($this->have_rights) {
@@ -316,7 +316,7 @@ class User_Query implements User_QueryInterface
} }
if ($this->last_model) { if ($this->last_model) {
$sql .= ' AND usr.lastModel = ' . $this->app['phraseanet.appbox']->get_connection()->quote($this->last_model) . ' '; $sql .= ' AND Users.lastModel = ' . $this->app['phraseanet.appbox']->get_connection()->quote($this->last_model) . ' ';
} }
$sql_like = []; $sql_like = [];
@@ -330,8 +330,8 @@ class User_Query implements User_QueryInterface
continue; continue;
$qrys[] = sprintf( $qrys[] = sprintf(
' (usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci ' (Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci
OR usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci) ' OR Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci) '
, self::LIKE_FIRSTNAME , self::LIKE_FIRSTNAME
, str_replace(['"', '%'], ['\"', '\%'], $like_val) , str_replace(['"', '%'], ['\"', '\%'], $like_val)
, self::LIKE_LASTNAME , self::LIKE_LASTNAME
@@ -350,7 +350,7 @@ class User_Query implements User_QueryInterface
case self::LIKE_LOGIN: case self::LIKE_LOGIN:
case self::LIKE_COUNTRY: case self::LIKE_COUNTRY:
$sql_like[] = sprintf( $sql_like[] = sprintf(
' usr.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci ' ' Users.`%s` LIKE "%s%%" COLLATE utf8_unicode_ci '
, $like_field , $like_field
, str_replace(['"', '%'], ['\"', '\%'], $like_value) , str_replace(['"', '%'], ['\"', '\%'], $like_value)
); );
@@ -490,7 +490,7 @@ class User_Query implements User_QueryInterface
public function execute() public function execute()
{ {
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.usr_id ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.id ' . $this->generate_sql_constraints();
if ('' !== $sorter = $this->generate_sort_constraint()) { if ('' !== $sorter = $this->generate_sort_constraint()) {
$sql .= ' ORDER BY ' . $sorter; $sql .= ' ORDER BY ' . $sorter;
@@ -532,7 +532,7 @@ class User_Query implements User_QueryInterface
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql_count = 'SELECT COUNT(DISTINCT usr.usr_id) as total ' $sql_count = 'SELECT COUNT(DISTINCT Users.id) as total '
. $this->generate_sql_constraints(); . $this->generate_sql_constraints();
$stmt = $conn->prepare($sql_count); $stmt = $conn->prepare($sql_count);
@@ -865,9 +865,9 @@ class User_Query implements User_QueryInterface
{ {
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.activite ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.activity ' . $this->generate_sql_constraints();
$sql .= ' ORDER BY usr.activite'; $sql .= ' ORDER BY Users.activity';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute($this->sql_params); $stmt->execute($this->sql_params);
@@ -877,7 +877,7 @@ class User_Query implements User_QueryInterface
$activities = []; $activities = [];
foreach ($rs as $row) { foreach ($rs as $row) {
if (trim($row['activite']) === '') if (trim($row['activity']) === '')
continue; continue;
$activities[] = $row['activite']; $activities[] = $row['activite'];
@@ -890,9 +890,9 @@ class User_Query implements User_QueryInterface
{ {
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.fonction ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.job ' . $this->generate_sql_constraints();
$sql .= ' ORDER BY usr.fonction'; $sql .= ' ORDER BY Users.job';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute($this->sql_params); $stmt->execute($this->sql_params);
@@ -902,10 +902,10 @@ class User_Query implements User_QueryInterface
$fonction = []; $fonction = [];
foreach ($rs as $row) { foreach ($rs as $row) {
if (trim($row['fonction']) === '') if (trim($row['job']) === '')
continue; continue;
$fonction[] = $row['fonction']; $fonction[] = $row['job'];
} }
return $fonction; return $fonction;
@@ -917,9 +917,9 @@ class User_Query implements User_QueryInterface
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.pays ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.country ' . $this->generate_sql_constraints();
$sql .= ' ORDER BY usr.pays'; $sql .= ' ORDER BY Users.country';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute($this->sql_params); $stmt->execute($this->sql_params);
@@ -931,11 +931,11 @@ class User_Query implements User_QueryInterface
$ctry = \getCountries($this->app['locale']); $ctry = \getCountries($this->app['locale']);
foreach ($rs as $row) { foreach ($rs as $row) {
if (trim($row['pays']) === '') if (trim($row['country']) === '')
continue; continue;
if (isset($ctry[$row['pays']])) if (isset($ctry[$row['country']]))
$pays[$row['pays']] = $ctry[$row['pays']]; $pays[$row['country']] = $ctry[$row['country']];
} }
return $pays; return $pays;
@@ -945,9 +945,9 @@ class User_Query implements User_QueryInterface
{ {
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.societe ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.company ' . $this->generate_sql_constraints();
$sql .= ' ORDER BY usr.societe'; $sql .= ' ORDER BY Users.company';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute($this->sql_params); $stmt->execute($this->sql_params);
@@ -957,10 +957,10 @@ class User_Query implements User_QueryInterface
$societe = []; $societe = [];
foreach ($rs as $row) { foreach ($rs as $row) {
if (trim($row['societe']) === '') if (trim($row['company']) === '')
continue; continue;
$societe[] = $row['societe']; $societe[] = $row['company'];
} }
return $societe; return $societe;
@@ -970,9 +970,9 @@ class User_Query implements User_QueryInterface
{ {
$conn = $this->app['phraseanet.appbox']->get_connection(); $conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT DISTINCT usr.lastModel ' . $this->generate_sql_constraints(); $sql = 'SELECT DISTINCT Users.last_model ' . $this->generate_sql_constraints();
$sql .= ' ORDER BY usr.lastModel'; $sql .= ' ORDER BY Users.last_model';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute($this->sql_params); $stmt->execute($this->sql_params);
@@ -982,10 +982,10 @@ class User_Query implements User_QueryInterface
$lastModel = []; $lastModel = [];
foreach ($rs as $row) { foreach ($rs as $row) {
if (trim($row['lastModel']) === '') if (trim($row['last_model']) === '')
continue; continue;
$lastModel[] = $row['lastModel']; $lastModel[] = $row['last_model'];
} }
return $lastModel; return $lastModel;
@@ -1005,13 +1005,13 @@ class User_Query implements User_QueryInterface
case self::SORT_COMPANY: case self::SORT_COMPANY:
case self::SORT_LOGIN: case self::SORT_LOGIN:
case self::SORT_EMAIL: case self::SORT_EMAIL:
$sorter[$k] = ' usr.`' . $sort . '` COLLATE utf8_unicode_ci '; $sorter[$k] = ' Users.`' . $sort . '` COLLATE utf8_unicode_ci ';
break; break;
case self::SORT_ID: case self::SORT_ID:
case self::SORT_CREATIONDATE: case self::SORT_CREATIONDATE:
case self::SORT_COUNTRY: case self::SORT_COUNTRY:
case self::SORT_LASTMODEL: case self::SORT_LASTMODEL:
$sorter[$k] = ' usr.`' . $sort . '` '; $sorter[$k] = ' Users.`' . $sort . '` ';
break; break;
default: default:
break; break;

View File

@@ -10,6 +10,7 @@
*/ */
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Model\Entities\User;
class appbox_register class appbox_register
{ {
@@ -36,11 +37,11 @@ class appbox_register
/** /**
* Add a registration request for a user on a collection * Add a registration request for a user on a collection
* *
* @param User_Interface $user * @param User $user
* @param collection $collection * @param collection $collection
* @return appbox_register * @return appbox_register
*/ */
public function add_request(User_Interface $user, collection $collection) public function add_request(User $user, collection $collection)
{ {
$sql = "INSERT INTO demand (date_modif, usr_id, base_id, en_cours, refuser) $sql = "INSERT INTO demand (date_modif, usr_id, base_id, en_cours, refuser)
VALUES (now(), :usr_id , :base_id, 1, 0)"; VALUES (now(), :usr_id , :base_id, 1, 0)";
@@ -56,11 +57,11 @@ class appbox_register
* user is waiting for approbation * user is waiting for approbation
* *
* @param Application $app * @param Application $app
* @param User_Interface $user * @param User $user
* *
* @return array * @return array
*/ */
public function get_collection_awaiting_for_user(Application $app, User_Interface $user) public function get_collection_awaiting_for_user(Application $app, User $user)
{ {
$sql = 'SELECT base_id FROM demand WHERE usr_id = :usr_id AND en_cours="1" '; $sql = 'SELECT base_id FROM demand WHERE usr_id = :usr_id AND en_cours="1" ';
$stmt = $this->appbox->get_connection()->prepare($sql); $stmt = $this->appbox->get_connection()->prepare($sql);

View File

@@ -834,11 +834,14 @@ abstract class base implements cache_cacheableInterface
$version = $app['doctrine-migration.configuration']->getVersion($doctrineVersion); $version = $app['doctrine-migration.configuration']->getVersion($doctrineVersion);
$version->getMigration()->setEntityManager($app['EM']); $version->getMigration()->setEntityManager($app['EM']);
if (false === $version->isMigrated()) { if (false === $version->isMigrated()) {
echo "Before executing Patch ".$patch->get_release()." \n";
echo "Executing migration ".$version->getversion()." \n";
$version->execute('up'); $version->execute('up');
} }
} }
if (false === $patch->apply($this, $app)) { if (false === $patch->apply($this, $app)) {
echo "Executing Patch ".$patch->get_release()." \n";
$success = false; $success = false;
} }

View File

@@ -11,6 +11,7 @@
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\Exception\InvalidArgumentException; use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
@@ -967,10 +968,10 @@ class databox extends base
/** /**
* *
* @param User_Interface $user * @param User $user
* @return databox * @return databox
*/ */
public function registerAdmin(User_Interface $user) public function registerAdmin(User $user)
{ {
$conn = connection::getPDOConnection($this->app); $conn = connection::getPDOConnection($this->app);

View File

@@ -21,18 +21,20 @@ function giveMeBases(Application $app, $usr = null)
if ($usr != null) { if ($usr != null) {
$sqlU = 'SELECT sbas.dbname, time_limited, UNIX_TIMESTAMP( limited_from ) AS limited_from, $sqlU = '
SELECT sbas.dbname, time_limited, UNIX_TIMESTAMP( limited_from ) AS limited_from,
UNIX_TIMESTAMP( limited_to ) AS limited_to, bas.server_coll_id, UNIX_TIMESTAMP( limited_to ) AS limited_to, bas.server_coll_id,
usr.usr_id, basusr.actif, demand.en_cours, demand.refuser u.id, basusr.actif, demand.en_cours, demand.refuser
FROM (usr, bas, sbas) FROM (Users u, bas, sbas)
LEFT JOIN basusr LEFT JOIN basusr ON ( u.id = basusr.usr_id
ON ( usr.usr_id = basusr.usr_id
AND bas.base_id = basusr.base_id ) AND bas.base_id = basusr.base_id )
LEFT JOIN demand LEFT JOIN demand ON ( demand.usr_id = u.id
ON ( demand.usr_id = usr.usr_id
AND bas.base_id = demand.base_id ) AND bas.base_id = demand.base_id )
WHERE bas.active >0 AND bas.sbas_id = sbas.sbas_id WHERE bas.active >0
AND usr.usr_id = :usr_id AND model_of = 0'; AND bas.sbas_id = sbas.sbas_id
AND u.id = :usr_id
AND u.model_of = 0
';
$stmt = $conn->prepare($sqlU); $stmt = $conn->prepare($sqlU);
$stmt->execute([':usr_id' => $usr]); $stmt->execute([':usr_id' => $usr]);

View File

@@ -53,26 +53,33 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract
$mailColl = []; $mailColl = [];
$sql = 'SELECT u.usr_id, b.base_id FROM usr u, basusr b $rsm = new ResultSetMappingBuilder($this->app['EM']);
WHERE u.usr_id = b.usr_id $rsm->addScalarResult('base_id', 'base_id');
AND b.base_id $selectClause = $rsm->generateSelectClause([
IN (' . implode(', ', array_keys($base_ids)) . ') 'u' => 't1'
AND model_of="0" ]);
$query = $this->app['EM']->createNativeQuery('
SELECT b.base_id, '.$selectClause.' FROM Users u, basusr b
WHERE u.id = b.usr_id
AND b.base_id IN (' . implode(', ', array_keys($base_ids)) . ')
AND u.model_of="0"
AND b.actif="1" AND b.actif="1"
AND b.canadmin="1" AND b.canadmin="1"
AND u.usr_login NOT LIKE "(#deleted%"'; AND u.deleted="0"'
);
try { try {
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); $rs = $query->getResult();
$stmt->execute();
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
foreach ($rs as $row) { foreach ($rs as $row) {
if ( ! isset($mailColl[$row['usr_id']])) $user = $row[0];
$mailColl[$row['usr_id']] = [];
$mailColl[$row['usr_id']][] = $row['base_id']; if (!isset($mailColl[$user->getId()])) {
$mailColl[$user->getId()] = [];
}
$mailColl[$user->getId()][] = $row['base_id'];
} }
} catch (Exception $e) { } catch (Exception $e) {

View File

@@ -10,6 +10,7 @@
*/ */
use Alchemy\Phrasea\Notification\Receiver; use Alchemy\Phrasea\Notification\Receiver;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Alchemy\Phrasea\Notification\Mail\MailInfoUserRegistered; use Alchemy\Phrasea\Notification\Mail\MailInfoUserRegistered;
class eventsmanager_notify_register extends eventsmanager_notifyAbstract class eventsmanager_notify_register extends eventsmanager_notifyAbstract
@@ -52,27 +53,33 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract
$mailColl = []; $mailColl = [];
try { $rsm = new ResultSetMappingBuilder($this->app['EM']);
$sql = 'SELECT u.usr_id, b.base_id $rsm->addScalarResult('base_id', 'base_id');
FROM usr u, basusr b $selectClause = $rsm->generateSelectClause([
WHERE u.usr_id = b.usr_id 'u' => 't1'
AND b.base_id ]);
IN (' . implode(', ', array_keys($base_ids)) . ')
AND model_of="0"
AND b.canadmin="1"
AND b.actif="1"
AND u.usr_login NOT LIKE "(#deleted%"';
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); $query = $this->app['EM']->createNativeQuery('
$stmt->execute(); SELECT b.base_id, '.$selectClause.' FROM Users u, basusr b
$rs = $stmt->fetchAll(PDO::FETCH_ASSOC); WHERE u.id = b.usr_id
$stmt->closeCursor(); AND b.base_id IN (' . implode(', ', array_keys($base_ids)) . ')
AND u.model_of="0"
AND b.actif="1"
AND b.canadmin="1"
AND u.deleted="0"'
);
try {
$rs = $query->getResult();
foreach ($rs as $row) { foreach ($rs as $row) {
if ( ! isset($mailColl[$row['usr_id']])) $user = $row[0];
$mailColl[$row['usr_id']] = [];
$mailColl[$row['usr_id']][] = $row['base_id']; if (!isset($mailColl[$user->getId()])) {
$mailColl[$user->getId()] = [];
}
$mailColl[$user->getId()][] = $row['base_id'];
} }
} catch (Exception $e) { } catch (Exception $e) {

View File

@@ -62,11 +62,13 @@ class module_console_systemUpgrade extends Command
try { try {
$upgrader = new Setup_Upgrade($this->container, $input->getOption('force')); $upgrader = new Setup_Upgrade($this->container, $input->getOption('force'));
$queries = $this->getService('phraseanet.appbox')->forceUpgrade($upgrader, $this->container);
} catch (\Exception_Setup_FixBadEmailAddresses $e) { } catch (\Exception_Setup_FixBadEmailAddresses $e) {
return $output->writeln(sprintf('<error>You have to fix your database before upgrade with the system:mailCheck command </error>')); return $output->writeln(sprintf('<error>You have to fix your database before upgrade with the system:mailCheck command </error>'));
} catch (\Exception $e) {
echo $e->getTraceAsString() . "\n";
} }
$queries = $this->getService('phraseanet.appbox')->forceUpgrade($upgrader, $this->container);
if ($input->getOption('dump') || $input->getOption('stderr')) { if ($input->getOption('dump') || $input->getOption('stderr')) {
if (0 < count($queries)) { if (0 < count($queries)) {

View File

@@ -434,22 +434,23 @@ class module_report_nav extends module_report
$sql = " $sql = "
SELECT SELECT
usr_login as identifiant, login as identifiant,
usr_nom as nom, last_name as nom,
usr_mail as mail, email as mail,
adresse, tel address AS adresse,
FROM usr phone AS tel
FROM Users
WHERE $on = :value " . (('' !== $filter_id_apbox) ? "AND (" . $filter_id_apbox . ")" : ''); WHERE $on = :value " . (('' !== $filter_id_apbox) ? "AND (" . $filter_id_apbox . ")" : '');
} else { } else {
$sql = ' $sql = '
SELECT SELECT
usr_login AS identifiant, login AS identifiant,
usr_nom AS nom, last_name AS nom,
usr_mail AS mail, email AS mail,
adresse, address AS adresse,
tel phone AS tel
FROM usr FROM Users
WHERE (usr_id = :value)'; WHERE (id = :value)';
} }
$params2 = [':value' => $val]; $params2 = [':value' => $val];

View File

@@ -230,33 +230,33 @@ class set_export extends set_abstract
$lst_base_id = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base()); $lst_base_id = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base());
if ($hasadminright) { if ($hasadminright) {
$sql = "SELECT usr.usr_id,usr_login,usr.usr_mail, FtpCredential.* $sql = "SELECT Users.id AS usr_id ,Users.login AS usr_login ,Users.mail AS usr_mail, FtpCredential.*
FROM ( FROM (
FtpCredential INNER JOIN usr ON ( FtpCredential INNER JOIN Users ON (
FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id FtpCredential.active = 1 AND FtpCredential.user_id = Users.id
) INNER JOIN basusr ON ( ) INNER JOIN basusr ON (
usr.usr_id=basusr.usr_id Users.id=basusr.usr_id
AND (basusr.base_id= AND (basusr.base_id=
'" . implode("' OR basusr.base_id='", $lst_base_id) . "' '" . implode("' OR basusr.base_id='", $lst_base_id) . "'
) )
) )
) )
GROUP BY usr_id "; GROUP BY Users.id ";
$params = []; $params = [];
} elseif ($this->app['conf']->get(['registry', 'ftp', 'ftp-user-access'])) { } elseif ($this->app['conf']->get(['registry', 'ftp', 'ftp-user-access'])) {
$sql = "SELECT usr.usr_id,usr_login,usr.usr_mail, FtpCredential.* $sql = "SELECT Users.id AS usr_id ,Users.login AS usr_login ,Users.mail AS usr_mail, FtpCredential.*
FROM ( FROM (
FtpCredential INNER JOIN usr ON ( FtpCredential INNER JOIN Users ON (
FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id FtpCredential.active = 1 AND FtpCredential.id = Users.id
) INNER JOIN basusr ON ( ) INNER JOIN basusr ON (
usr.usr_id=basusr.usr_id Users.id=basusr.usr_id
AND usr.usr_id = :usr_id AND Users.id = :usr_id
AND (basusr.base_id= AND (basusr.base_id=
'" . implode("' OR basusr.base_id='", $lst_base_id) . "' '" . implode("' OR basusr.base_id='", $lst_base_id) . "'
) )
) )
) )
GROUP BY usr_id "; GROUP BY Users.id ";
$params = [':usr_id' => $app['authentication']->getUser()->getId()]; $params = [':usr_id' => $app['authentication']->getUser()->getId()];
} }

View File

@@ -168,6 +168,8 @@
<legend>{{ "FTP" | trans }}</legend> <legend>{{ "FTP" | trans }}</legend>
{% set ftpCredential = app["authentication"].getUser().getFtpCredential() %} {% set ftpCredential = app["authentication"].getUser().getFtpCredential() %}
{% if ftpCredential is not none %}
<div class="control-group"> <div class="control-group">
<div class="controls"> <div class="controls">
<label class="form_label checkbox" for="form_activeFTP">{{ "admin::compte-utilisateur:ftp: Activer le compte FTP" | trans }} <label class="form_label checkbox" for="form_activeFTP">{{ "admin::compte-utilisateur:ftp: Activer le compte FTP" | trans }}
@@ -176,40 +178,41 @@
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
{% endif %}
<div id="ftpinfos" style="display:{% if ftpCredential.isActive() %}block{% else %}none{% endif %}"> <div id="ftpinfos" style="display:{% if ftpCredential is none or ftpCredential.isActive() %}block{% else %}none{% endif %}">
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_addressFTP"><strong>{{ "phraseanet:: adresse" | trans }}</strong></label> <label class="form_label control-label" for="form_addressFTP"><strong>{{ "phraseanet:: adresse" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_addressFTP" id="form_addressFTP" value="{{ ftpCredential.getAddress() }}" /> <input class="input_element input-xlarge" type="text" name="form_addressFTP" id="form_addressFTP" value="{{ ftpCredential is not none ? ftpCredential.getAddress() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_loginFTP"><strong>{{ "admin::compte-utilisateur identifiant" | trans }}</strong></label> <label class="form_label control-label" for="form_loginFTP"><strong>{{ "admin::compte-utilisateur identifiant" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_loginFTP" id="form_loginFTP" value="{{ ftpCredential.getLogin() }}" /> <input class="input_element input-xlarge" type="text" name="form_loginFTP" id="form_loginFTP" value="{{ ftpCredential is not none ? ftpCredential.getLogin() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_pwdFTP"><strong>{{ "admin::compte-utilisateur mot de passe" | trans }}</strong></label> <label class="form_label control-label" for="form_pwdFTP"><strong>{{ "admin::compte-utilisateur mot de passe" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_pwdFTP" id="form_pwdFTP" value="{{ ftpCredential.getPassword() }}" /> <input class="input_element input-xlarge" type="text" name="form_pwdFTP" id="form_pwdFTP" value="{{ ftpCredential is not none ? ftpCredential.getPassword() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_destFTP"><strong>{{ "admin::compte-utilisateur:ftp: repertoire de destination ftp" | trans }}</strong></label> <label class="form_label control-label" for="form_destFTP"><strong>{{ "admin::compte-utilisateur:ftp: repertoire de destination ftp" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_destFTP" id="form_destFTP" value="{{ ftpCredential.getReceptionFolder() }}" /> <input class="input_element input-xlarge" type="text" name="form_destFTP" id="form_destFTP" value="{{ ftpCredential is not none ? ftpCredential.getReceptionFolder() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_prefixFTPfolder"><strong>{{ "admin::compte-utilisateur:ftp: prefixe des noms de dossier ftp" | trans }}</strong></label> <label class="form_label control-label" for="form_prefixFTPfolder"><strong>{{ "admin::compte-utilisateur:ftp: prefixe des noms de dossier ftp" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_prefixFTPfolder" id="form_prefixFTPfolder" value="{{ ftpCredential.getRepositoryPrefixName() }}" /> <input class="input_element input-xlarge" type="text" name="form_prefixFTPfolder" id="form_prefixFTPfolder" value="{{ ftpCredential is not none ? ftpCredential.getRepositoryPrefixName() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>
@@ -217,7 +220,7 @@
<div class="controls"> <div class="controls">
<label class="form_label checkbox" for="form_passifFTP"> <label class="form_label checkbox" for="form_passifFTP">
{{ "admin::compte-utilisateur:ftp: Utiliser le mode passif" | trans }} {{ "admin::compte-utilisateur:ftp: Utiliser le mode passif" | trans }}
<input class="input_element input-xlarge" type="checkbox" name="form_passifFTP" id="form_passifFTP" {% if ftpCredential.isPassive() %}checked{% endif %} /> <input class="input_element input-xlarge" type="checkbox" name="form_passifFTP" id="form_passifFTP" {% if ftpCredential is not none and ftpCredential.isPassive() %}checked{% endif %} />
</label> </label>
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
@@ -225,7 +228,7 @@
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_retryFTP"><strong>{{ "admin::compte-utilisateur:ftp: Nombre d\'essais max" | trans }}</strong></label> <label class="form_label control-label" for="form_retryFTP"><strong>{{ "admin::compte-utilisateur:ftp: Nombre d\'essais max" | trans }}</strong></label>
<div class="controls"> <div class="controls">
<input class="input_element input-xlarge" type="text" name="form_retryFTP" id="form_retryFTP" value="{{ ftpCredential.getMaxRetry() }}" /> <input class="input_element input-xlarge" type="text" name="form_retryFTP" id="form_retryFTP" value="{{ ftpCredential is not none ? ftpCredential.getMaxRetry() : '' }}" />
<p class="form_alert help-block"></p> <p class="form_alert help-block"></p>
</div> </div>
</div> </div>

View File

@@ -202,37 +202,38 @@
<div class="registration-wrapper PNB" style="top:160px;bottom: 50px;overflow: auto"> <div class="registration-wrapper PNB" style="top:160px;bottom: 50px;overflow: auto">
<div id="tab_demandes"> <div id="tab_demandes">
{% set tableColls = table['coll'] %} {% set tableColls = table['coll'] %}
{% for row in table['user'] %} {% for row in table['users'] %}
{% set user = row['user'] %}
<div class="well well-small"> <div class="well well-small">
<table class="table" style="table-layout: fixed;"> <table class="table" style="table-layout: fixed;">
<tr> <tr>
<span> <span>
{{ app['date-formatter'].getPrettyString(row["date_modif"]) }} {{ app['date-formatter'].getPrettyString(row["date_demand"]) }}
</span> </span>
</tr> </tr>
<tr> <tr>
<td> <td>
{% set colls = tableColls[row['usr_id']] %} {% set colls = tableColls[user.getId()] %}
<dl class="dl-horizontal"> <dl class="dl-horizontal">
<dt>{{ 'admin::compte-utilisateur identifiant' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur identifiant' | trans }}</dt>
<dd>{{ row['usr_login'] }}</dd> <dd>{{ user.getLogin() }}</dd>
<dt>{{ 'admin::compte-utilisateur nom' | trans }} / {{ 'admin::compte-utilisateur prenom' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur nom' | trans }} / {{ 'admin::compte-utilisateur prenom' | trans }}</dt>
<dd>{{ row['usr_nom'] }} {{ row['usr_prenom'] }}</dd> <dd>{{ user.getLastName() }} {{ user.getFirstName() }}</dd>
<dt>{{ 'admin::compte-utilisateur email' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur email' | trans }}</dt>
<dd>{{ row['usr_mail'] }}</dd> <dd>{{ user.getEmail() }}</dd>
<dt>{{ 'admin::compte-utilisateur societe' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur societe' | trans }}</dt>
<dd>{{ row['societe'] }}</dd> <dd>{{ user.getCompany() }}</dd>
<dt>{{ 'admin::compte-utilisateur poste' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur poste' | trans }}</dt>
<dd>{{ row['fonction'] }}</dd> <dd>{{ user.getJob() }}</dd>
<dt>{{ 'admin::compte-utilisateur activite' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur activite' | trans }}</dt>
<dd>{{ row['activite'] }}</dd> <dd>{{ user.getActivity() }}</dd>
<dt>{{ 'admin::compte-utilisateur telephone' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur telephone' | trans }}</dt>
<dd>{{ row['tel'] }}</dd> <dd>{{ user.getPhone() }}</dd>
<dt>{{ 'admin::compte-utilisateur adresse' | trans }}</dt> <dt>{{ 'admin::compte-utilisateur adresse' | trans }}</dt>
<dd>{{ row['adresse'] }}</dd> <dd>{{ user.getAddress() }}</dd>
<dd>{{ row['cpostal'] }}</dd> <dd>{{ user.getZipCode() }}</dd>
<dd>{{ row['ville'] }}</dd> <dd>{{ user.getCity() }}</dd>
<dd>{{ row['pays'] }}</dd> <dd>{{ user.getCountry() }}</dd>
</dl> </dl>
</td> </td>
<td> <td>
@@ -259,10 +260,10 @@
</td> </td>
<td> <td>
<div>{{ 'admin:: appliquer le modele' | trans }}</div> <div>{{ 'admin:: appliquer le modele' | trans }}</div>
<select name="template[]" id="model_{{ row['usr_id'] }}" onchange="modelChecker('{{ row['usr_id'] }}')"> <select name="template[]" id="{{ 'model_' ~ user.getId() }}" onchange="modelChecker('{{ user.getId() }}')">
<option value="">{{ 'None' | trans }}</option> <option value="">{{ 'None' | trans }}</option>
{% for model in models %} {% for model in models %}
<option value="{{ row['usr_id'] }}_{{ model['usr_id'] }}">{{ model['usr_login'] }}</option> <option value="{{ user.getId() ~ '_' ~ model.getId() }}">{{ model.getLogin() }}</option>
{% endfor %} {% endfor %}
</select> </select>
</td> </td>

View File

@@ -34,7 +34,7 @@
<textarea class="hidden" name="sr_columns">{{ columns_serialized }}</textarea> <textarea class="hidden" name="sr_columns">{{ columns_serialized }}</textarea>
<select name="modelToApply"> <select name="modelToApply">
{% for model in models %} {% for model in models %}
<option value='{{ model['usr_id'] }}'>{{ model['usr_login'] }}</option> <option value='{{ model.getId() }}'>{{ model.getLogin() }}</option>
{% endfor %} {% endfor %}
</select> </select>
<div class="form-actions"> <div class="form-actions">

View File

@@ -76,7 +76,7 @@
</div> </div>
{% endmacro %} {% endmacro %}
{% if app['conf'].get(['registry', 'actions', 'auth-required-for-export']) and app['authentication'].getUser().is_guest() %} {% if app['conf'].get(['registry', 'actions', 'auth-required-for-export']) and app['authentication'].getUser().isGuest() %}
<script type="text/javascript"> <script type="text/javascript">
p4.Dialog.get(1).Close(); p4.Dialog.get(1).Close();
parent.login({act:"dwnl",lst:"{{ lst }}",SSTTID:"{{ ssttid }}"}); parent.login({act:"dwnl",lst:"{{ lst }}",SSTTID:"{{ ssttid }}"});
@@ -145,7 +145,7 @@
{% endif %} {% endif %}
{{ _self.choose_title('download', choose_export_title, default_export_title) }} {{ _self.choose_title('download', choose_export_title, default_export_title) }}
{% if app['conf'].get(['registry', 'actions', 'tou-validation-required-for-export']) == true %} {% if app['phraseanet.registry'].get('GV_requireTOUValidationForExport') == true %}
<div class="well-small"> <div class="well-small">
<label for="TOU_acceptDL" class="checkbox"> <label for="TOU_acceptDL" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptDL" value="1" /> <input type="checkbox" name="TOU_accept" id="TOU_acceptDL" value="1" />
@@ -226,7 +226,7 @@
{% endif %} {% endif %}
{{ _self.choose_title('sendmail', choose_export_title, default_export_title) }} {{ _self.choose_title('sendmail', choose_export_title, default_export_title) }}
{% if app['conf'].get(['registry', 'actions', 'tou-validation-required-for-export']) == true %} {% if app['phraseanet.registry'].get('GV_requireTOUValidationForExport') == true %}
<div class="well-small"> <div class="well-small">
<label for="TOU_acceptMail" class="checkbox"> <label for="TOU_acceptMail" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptMail" value="1" /> <input type="checkbox" name="TOU_accept" id="TOU_acceptMail" value="1" />
@@ -379,7 +379,7 @@
</div> </div>
</div> </div>
{% if app['conf'].get(['registry', 'actions', 'tou-validation-required-for-export']) == true %} {% if app['phraseanet.registry'].get('GV_requireTOUValidationForExport') == true %}
<div class="well-small"> <div class="well-small">
<label for="TOU_acceptOrder" class="checkbox"> <label for="TOU_acceptOrder" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptOrder" value="1" /> <input type="checkbox" name="TOU_accept" id="TOU_acceptOrder" value="1" />
@@ -460,7 +460,7 @@
</div> </div>
{% endif %} {% endif %}
{% if app['conf'].get(['registry', 'actions', 'tou-validation-required-for-export']) == true %} {% if app['phraseanet.registry'].get('GV_requireTOUValidationForExport') == true %}
<div class="well-small"> <div class="well-small">
<label for="TOU_acceptFTP" class="checkbox"> <label for="TOU_acceptFTP" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptFTP" value="1" /> <input type="checkbox" name="TOU_accept" id="TOU_acceptFTP" value="1" />
@@ -636,7 +636,7 @@
} }
}); });
{% set max_download = app['conf'].get(['registry', 'actions', 'download-max-size'], 120) %} {% set max_download = app['phraseanet.registry'].get('GV_download_max', 120) %}
{% set alert_too_big_one %} {% set alert_too_big_one %}
{% trans with {'%max_download%' : max_download} %}You can not directly download more than %max_download% Mo ; time to package all documents is too long{% endtrans %} {% trans with {'%max_download%' : max_download} %}You can not directly download more than %max_download% Mo ; time to package all documents is too long{% endtrans %}
{% endset %} {% endset %}

View File

@@ -138,7 +138,7 @@
{% endif %} {% endif %}
<li> <li>
{% if app['authentication'].isAuthenticated() %} {% if app['authentication'].isAuthenticated() %}
{% if app['authentication'].getUser().is_guest %} {% if app['authentication'].getUser().isGuest %}
<span> <span>
{{ 'Guest' | trans }} {{ 'Guest' | trans }}
</span> </span>

View File

@@ -7,6 +7,7 @@ use Alchemy\Phrasea\Border\File;
use Alchemy\Phrasea\Core\PhraseaEvents; use Alchemy\Phrasea\Core\PhraseaEvents;
use Alchemy\Phrasea\Authentication\Context; use Alchemy\Phrasea\Authentication\Context;
use Alchemy\Phrasea\Model\Entities\Task; use Alchemy\Phrasea\Model\Entities\Task;
use Doctrine\Common\Collections\ArrayCollection;
use Guzzle\Common\Exception\GuzzleException; use Guzzle\Common\Exception\GuzzleException;
use Symfony\Component\HttpKernel\Client; use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -893,7 +894,16 @@ abstract class ApiTestCase extends \PhraseanetWebTestCase
public function testRecordsSearchRouteWithQuery($method) public function testRecordsSearchRouteWithQuery($method)
{ {
$this->setToken(self::$token); $this->setToken(self::$token);
$searchEngine = $this->getMockBuilder('Alchemy\Phrasea\SearchEngine\SearchEngineResult')
->disableOriginalConstructor()
->getMock();
$searchEngine->expects($this->any())
->method('getSuggestions')
->will($this->returnValue(new ArrayCollection()));
self::$DI['app']['phraseanet.SE'] = $this->getMock('Alchemy\Phrasea\SearchEngine\SearchEngineInterface'); self::$DI['app']['phraseanet.SE'] = $this->getMock('Alchemy\Phrasea\SearchEngine\SearchEngineInterface');
self::$DI['app']['phraseanet.SE']->expects($this->once()) self::$DI['app']['phraseanet.SE']->expects($this->once())
->method('query') ->method('query')
->with('koala', 0, 10) ->with('koala', 0, 10)
@@ -1910,6 +1920,25 @@ abstract class ApiTestCase extends \PhraseanetWebTestCase
$this->assertEquals($quarantineItemId, $content['response']['quarantine_item']['id']); $this->assertEquals($quarantineItemId, $content['response']['quarantine_item']['id']);
} }
protected function getQuarantineItem()
{
$lazaretSession = new \Alchemy\Phrasea\Model\Entities\LazaretSession();
self::$DI['app']['EM']->persist($lazaretSession);
$quarantineItem = null;
$callback = function ($element, $visa, $code) use (&$quarantineItem) {
$quarantineItem = $element;
};
$tmpname = tempnam(sys_get_temp_dir(), 'test_quarantine');
copy(__DIR__ . '/../../../../files/iphone_pic.jpg', $tmpname);
$file = File::buildFromPathfile($tmpname, self::$DI['collection'], self::$DI['app']);
self::$DI['app']['border-manager']->process($lazaretSession, $file, $callback, Manager::FORCE_LAZARET);
return $quarantineItem;
}
protected function evaluateGoodQuarantineItem($item) protected function evaluateGoodQuarantineItem($item)
{ {
$this->assertArrayHasKey('id', $item); $this->assertArrayHasKey('id', $item);

View File

@@ -11,8 +11,8 @@ class RecordsRequestTest extends \PhraseanetAuthenticatedTestCase
{ {
$request = new Request([ $request = new Request([
'lst' => implode(';', [ 'lst' => implode(';', [
self::$DI['record_3']->get_serialize_key(), self::$DI['record_24']->get_serialize_key(),
self::$DI['record_3']->get_serialize_key(), self::$DI['record_24']->get_serialize_key(),
self::$DI['record_2']->get_serialize_key(), self::$DI['record_2']->get_serialize_key(),
self::$DI['record_story_2']->get_serialize_key(), self::$DI['record_story_2']->get_serialize_key(),
self::$DI['record_no_access']->get_serialize_key(), self::$DI['record_no_access']->get_serialize_key(),
@@ -127,8 +127,8 @@ class RecordsRequestTest extends \PhraseanetAuthenticatedTestCase
{ {
$request = new Request([ $request = new Request([
'lst' => implode(';', [ 'lst' => implode(';', [
self::$DI['record_3']->get_serialize_key(), self::$DI['record_24']->get_serialize_key(),
self::$DI['record_3']->get_serialize_key(), self::$DI['record_24']->get_serialize_key(),
self::$DI['record_2']->get_serialize_key(), self::$DI['record_2']->get_serialize_key(),
self::$DI['record_story_2']->get_serialize_key(), self::$DI['record_story_2']->get_serialize_key(),
self::$DI['record_no_access']->get_serialize_key(), self::$DI['record_no_access']->get_serialize_key(),

View File

@@ -4,6 +4,7 @@ namespace Alchemy\Tests\Phrasea\Controller\Root;
use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Application;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Alchemy\Phrasea\Model\Entities\User;
class AccountTest extends \PhraseanetAuthenticatedWebTestCase class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{ {
@@ -123,7 +124,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
public function testPostResetMailBadEmail() public function testPostResetMailBadEmail()
{ {
$password = \random::generatePassword(); $password = \random::generatePassword();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
self::$DI['client']->request('POST', '/account/reset-email/', [ self::$DI['client']->request('POST', '/account/reset-email/', [
'form_password' => $password, 'form_password' => $password,
'form_email' => "invalid#!&&@@email.x", 'form_email' => "invalid#!&&@@email.x",
@@ -143,7 +144,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
public function testPostResetMailEmailNotIdentical() public function testPostResetMailEmailNotIdentical()
{ {
$password = \random::generatePassword(); $password = \random::generatePassword();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
self::$DI['client']->request('POST', '/account/reset-email/', [ self::$DI['client']->request('POST', '/account/reset-email/', [
'form_password' => $password, 'form_password' => $password,
'form_email' => 'email1@email.com', 'form_email' => 'email1@email.com',
@@ -165,13 +166,17 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
$this->mockNotificationDeliverer('Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate'); $this->mockNotificationDeliverer('Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate');
$password = \random::generatePassword(); $password = \random::generatePassword();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(
self::$DI['app']['authentication']->getUser(),
$password
);
self::$DI['client']->request('POST', '/account/reset-email/', [ self::$DI['client']->request('POST', '/account/reset-email/', [
'form_password' => $password, 'form_password' => $password,
'form_email' => 'email1@email.com', 'form_email' => 'email1@email.com',
'form_email_confirm' => 'email1@email.com', 'form_email_confirm' => 'email1@email.com',
]); ]);
self::$DI['client']->followRedirects();
$response = self::$DI['client']->getResponse(); $response = self::$DI['client']->getResponse();
$this->assertTrue($response->isRedirect()); $this->assertTrue($response->isRedirect());
$this->assertEquals('/account/', $response->headers->get('location')); $this->assertEquals('/account/', $response->headers->get('location'));
@@ -272,7 +277,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
self::$DI['client']->request('POST', '/account/', [ self::$DI['client']->request('POST', '/account/', [
'demand' => $bases, 'demand' => $bases,
'form_gender' => 'M', 'form_gender' => User::GENDER_MR,
'form_firstname' => 'gros', 'form_firstname' => 'gros',
'form_lastname' => 'minet', 'form_lastname' => 'minet',
'form_address' => 'rue du lac', 'form_address' => 'rue du lac',
@@ -282,7 +287,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
'form_function' => 'astronaute', 'form_function' => 'astronaute',
'form_company' => 'NASA', 'form_company' => 'NASA',
'form_activity' => 'Space', 'form_activity' => 'Space',
'form_geonameid' => '', 'form_geonameid' => '1839',
'form_addressFTP' => '', 'form_addressFTP' => '',
'form_loginFTP' => '', 'form_loginFTP' => '',
'form_pwdFTP' => '', 'form_pwdFTP' => '',
@@ -370,7 +375,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
*/ */
public function testPostRenewPasswordBadArguments($oldPassword, $password, $passwordConfirm) public function testPostRenewPasswordBadArguments($oldPassword, $password, $passwordConfirm)
{ {
self::$DI['app']['authentication']->getUser()->setPassword($oldPassword); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $oldPassword);
$crawler = self::$DI['client']->request('POST', '/account/reset-password/', [ $crawler = self::$DI['client']->request('POST', '/account/reset-password/', [
'password' => [ 'password' => [
@@ -407,7 +412,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{ {
$password = \random::generatePassword(); $password = \random::generatePassword();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
$crawler = self::$DI['client']->request('POST', '/account/reset-password/', [ $crawler = self::$DI['client']->request('POST', '/account/reset-password/', [
'password' => [ 'password' => [
@@ -427,7 +432,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{ {
$password = \random::generatePassword(); $password = \random::generatePassword();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
self::$DI['client']->request('POST', '/account/reset-password/', [ self::$DI['client']->request('POST', '/account/reset-password/', [
'password' => [ 'password' => [

View File

@@ -275,7 +275,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'_token' => 'token', '_token' => 'token',
]); ]);
$response = self::$DI['client']->getResponse(); $response = self::$DI['client']->getResponse();
$this->assertFalse($response->isRedirect()); $this->assertFalse($response->isRedirect());
$this->assertFlashMessage($crawler, 'error', 1); $this->assertFlashMessage($crawler, 'error', 1);
} }
@@ -594,7 +593,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'password' => 'password', 'password' => 'password',
'confirm' => 'password' 'confirm' => 'password'
], ],
"accept-tou" => '1',
"collections" => null, "collections" => null,
], [], 1], ], [], 1],
[[//required extra-field missing [[//required extra-field missing
@@ -603,7 +601,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [ ], [
[ [
@@ -617,7 +614,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'passwordMismatch' 'confirm' => 'passwordMismatch'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [], 1], ], [], 1],
[[//password tooshort [[//password tooshort
@@ -626,7 +622,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'min' 'confirm' => 'min'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [], 1], ], [], 1],
[[//email invalid [[//email invalid
@@ -635,7 +630,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => 'invalid.email', "email" => 'invalid.email',
"accept-tou" => '1',
"collections" => null "collections" => null
], [], 1], ], [], 1],
[[//login exists [[//login exists
@@ -645,7 +639,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [ ], [
[ [
@@ -659,7 +652,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => null, "email" => null,
"accept-tou" => '1',
"collections" => null "collections" => null
], [], 1], ], [], 1],
[[//tou declined [[//tou declined
@@ -668,7 +660,8 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"collections" => null "collections" => null,
"accept-tou" => '1'
], [], 1] ], [], 1]
]; ];
} }
@@ -682,7 +675,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null, "collections" => null,
], []], ], []],
[[ [[
@@ -691,7 +683,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [ ], [
[ [
@@ -705,7 +696,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null "collections" => null
], [ ], [
[ [
@@ -763,7 +753,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password' 'confirm' => 'password'
], ],
"email" => $this->generateEmail(), "email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null, "collections" => null,
"login" => 'login-'.\random::generatePassword(), "login" => 'login-'.\random::generatePassword(),
"gender" => '1', "gender" => '1',
@@ -1136,7 +1125,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword(); $password = \random::generatePassword();
$login = self::$DI['app']['authentication']->getUser()->getLogin(); $login = self::$DI['app']['authentication']->getUser()->getLogin();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
self::$DI['app']['authentication']->getUser()->setMailLocked(false); self::$DI['app']['authentication']->getUser()->setMailLocked(false);
$this->logout(self::$DI['app']); $this->logout(self::$DI['app']);
@@ -1161,7 +1150,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword(); $password = \random::generatePassword();
$login = self::$DI['app']['authentication']->getUser()->getLogin(); $login = self::$DI['app']['authentication']->getUser()->getLogin();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
self::$DI['app']['authentication']->getUser()->setMailLocked(false); self::$DI['app']['authentication']->getUser()->setMailLocked(false);
$this->logout(self::$DI['app']); $this->logout(self::$DI['app']);
@@ -1208,7 +1197,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword(); $password = \random::generatePassword();
$login = self::$DI['app']['authentication']->getUser()->getLogin(); $login = self::$DI['app']['authentication']->getUser()->getLogin();
self::$DI['app']['authentication']->getUser()->setPassword($password); self::$DI['app']['manipulator.user']->setPassword(self::$DI['app']['authentication']->getUser(), $password);
$this->logout(self::$DI['app']); $this->logout(self::$DI['app']);
@@ -1516,7 +1505,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode()); $this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode());
$ret = self::$DI['app']['EM']->getRepository('\Alchemy\Phrasea\Model\Entities\UsrAuthProvider') $ret = self::$DI['app']['EM']->getRepository('\Alchemy\Phrasea\Model\Entities\UsrAuthProvider')
->findBy(['usr_id' => self::$DI['user']->getId(), 'provider' => 'provider-test']); ->findBy(['user' => self::$DI['user']->getId(), 'provider' => 'provider-test']);
$this->assertCount(1, $ret); $this->assertCount(1, $ret);
@@ -1587,7 +1576,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode()); $this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode());
$ret = self::$DI['app']['EM']->getRepository('\Alchemy\Phrasea\Model\Entities\UsrAuthProvider') $ret = self::$DI['app']['EM']->getRepository('\Alchemy\Phrasea\Model\Entities\UsrAuthProvider')
->findBy(['usr_id' => $user->getId(), 'provider' => 'provider-test']); ->findBy(['user' => $user->getId(), 'provider' => 'provider-test']);
$this->assertCount(1, $ret); $this->assertCount(1, $ret);

View File

@@ -61,12 +61,12 @@ class NotificationsTest extends \PhraseanetAuthenticatedWebTestCase
public function testRequireAuthentication() public function testRequireAuthentication()
{ {
self::$DI['app']['authentication']->setUser($this->getMockBuilder('Alchemy\Phrasea\Model\Entities\User') self::$DI['app']['authentication']->setUser($this->getMockBuilder('Alchemy\Phrasea\Model\Entities\User')
->setMethods(['is_guest']) ->setMethods(['isGuest'])
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock()); ->getMock());
self::$DI['app']['authentication']->getUser()->expects($this->once()) self::$DI['app']['authentication']->getUser()->expects($this->once())
->method('is_guest') ->method('isGuest')
->will($this->returnValue(true)); ->will($this->returnValue(true));
self::$DI['client']->request('GET', '/user/notifications/'); self::$DI['client']->request('GET', '/user/notifications/');

View File

@@ -18,14 +18,9 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
public function bootTestCase() public function bootTestCase()
{ {
$binaryFinder = new ExecutableFinder(); $binaryFinder = new ExecutableFinder();
$indexer = $binaryFinder->find('indexer');
$searchd = $binaryFinder->find('searchd'); if (null !== self::$indexerBinary = $binaryFinder->find('indexer') || null !== self::$searchdBinary = $binaryFinder->find('searchd')) {
if (!$indexer || !$searchd) {
self::$skipped = true; self::$skipped = true;
return;
} }
$app = self::$DI['app']; $app = self::$DI['app'];
@@ -74,6 +69,7 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
if (self::$skipped) { if (self::$skipped) {
$this->markTestSkipped('SphinxSearch is not present on system'); $this->markTestSkipped('SphinxSearch is not present on system');
} }
@@ -90,16 +86,55 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
public function initialize() public function initialize()
{ {
if (!self::$searchEngine) {
self::$DI['app']['conf']->set(['main', 'search-engine', 'options'], [
'host' => '127.0.0.1',
'port' => 9312,
'rt_host' => '127.0.0.1',
'rt_port' => 9306,
]);
self::$searchEngine = SphinxSearchEngine::create(self::$DI['app'], self::$DI['app']['conf']->get(['main', 'search-engine', 'options']));
self::$config = tempnam(sys_get_temp_dir(), 'tmp_sphinx.conf');
$configuration = self::$searchEngine->getConfigurationPanel()->getConfiguration();
$configuration['date_fields'] = [];
foreach (self::$DI['app']['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($databox->get_meta_structure() as $databox_field) {
if ($databox_field->get_type() != \databox_field::TYPE_DATE) {
continue;
}
$configuration['date_fields'][] = $databox_field->get_name();
}
}
$configuration['date_fields'] = array_unique($configuration['date_fields']);
self::$searchEngine->getConfigurationPanel()->saveConfiguration($configuration);
$configFile = self::$searchEngine->getConfigurationPanel()->generateSphinxConf(self::$DI['app']['phraseanet.appbox']->get_databoxes(), $configuration);
file_put_contents(self::$config, $configFile);
$binaryFinder = new ExecutableFinder();
$process = new Process(self::$indexerBinary . ' --all -c ' . self::$config);
$process->run();
self::$searchdProcess = new Process(self::$searchdBinary . ' -c ' . self::$config);
self::$searchd->run();
self::$searchEngine = SphinxSearchEngine::create(self::$DI['app'], self::$DI['app']['configuration']['main']['search-engine']['options']);
}
} }
public static function tearDownAfterClass() public static function tearDownAfterClass()
{ {
if (!self::$skipped) { if (!self::$skipped) {
$binaryFinder = new ExecutableFinder(); self::$searchdProcess = new Process(self::$searchdBinary . ' --stop -c ' . self::$config);
$searchd = $binaryFinder->find('searchd'); self::$searchdProcess->run();
self::$searchd = new Process($searchd . ' --stop -c ' . self::$config);
self::$searchd->run();
unlink(self::$config); unlink(self::$config);
} }

View File

@@ -20,20 +20,29 @@ class Bridge_AccountTest extends \PhraseanetAuthenticatedTestCase
try { try {
$application = self::$DI['app']; $application = self::$DI['app'];
self::$DI['user'];
if (!self::$object) {
$sql = 'DELETE FROM bridge_apis WHERE name = "Apitest"'; $sql = 'DELETE FROM bridge_apis WHERE name = "Apitest"';
$stmt = $application['phraseanet.appbox']->get_connection()->prepare($sql); $stmt = self::$DI['app']['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute(); $stmt->execute();
$stmt->closeCursor(); $stmt->closeCursor();
self::$api = Bridge_Api::create($application, 'Apitest'); self::$api = Bridge_Api::create(self::$DI['app'], 'Apitest');
self::$dist_id = 'EZ1565loPP'; self::$dist_id = 'EZ1565loPP';
self::$named = 'Fête à pinpins'; self::$named = 'Fête à pinpins';
$account = Bridge_Account::create($application, self::$api, self::$DI['user'], self::$dist_id, self::$named);
$account = Bridge_Account::create(
self::$DI['app'],
self::$api,
self::$DI['user'],
self::$dist_id,
self::$named
);
self::$id = $account->get_id(); self::$id = $account->get_id();
self::$object = new Bridge_Account($application, self::$api, self::$id); self::$object = new Bridge_Account(self::$DI['app'], self::$api, self::$id);
} catch (Exception $e) {
self::$fail($e->getMessage());
} }
} }
@@ -41,17 +50,12 @@ class Bridge_AccountTest extends \PhraseanetAuthenticatedTestCase
{ {
if (self::$object) { if (self::$object) {
self::$object->delete(); self::$object->delete();
self::$object = null;
} }
try {
$application = new Application('test');
new Bridge_Account($application, self::$api, self::$id);
self::$fail();
} catch (Bridge_Exception_AccountNotFound $e) {
}
if (self::$api) { if (self::$api) {
self::$api->delete(); self::$api->delete();
self::$api = null;
} }
self::$object = self::$api = self::$dist_id = self::$named = self::$id = null; self::$object = self::$api = self::$dist_id = self::$named = self::$id = null;
@@ -67,7 +71,6 @@ class Bridge_AccountTest extends \PhraseanetAuthenticatedTestCase
public function testGet_api() public function testGet_api()
{ {
$start = microtime(true);
$this->assertInstanceOf('Bridge_Api', self::$object->get_api()); $this->assertInstanceOf('Bridge_Api', self::$object->get_api());
$this->assertEquals(self::$api, self::$object->get_api()); $this->assertEquals(self::$api, self::$object->get_api());
$this->assertEquals(self::$api->get_id(), self::$object->get_api()->get_id()); $this->assertEquals(self::$api->get_id(), self::$object->get_api()->get_id());

View File

@@ -31,18 +31,25 @@ class Bridge_Api_AbstractTest extends \PhraseanetWebTestCase
self::$api = Bridge_Api::create($application, 'apitest'); self::$api = Bridge_Api::create($application, 'apitest');
} }
try { self::$DI['user'];
self::$account = Bridge_Account::load_account_from_distant_id($application, self::$api, self::$DI['user'], 'kirikoo');
} catch (Bridge_Exception_AccountNotFound $e) { if (!self::$account) {
self::$account = Bridge_Account::create($application, self::$api, self::$DI['user'], 'kirikoo', 'coucou'); self::$account = Bridge_Account::create(self::$DI['app'], self::$api, self::$DI['user'], 'kirikoo', 'coucou');
} }
$this->auth = $this->getMock("Bridge_Api_Auth_Interface");
$this->bridgeApi = $this->getMock('Bridge_Api_Abstract', ["is_configured", "initialize_transport", "set_auth_params", "set_transport_authentication_params"], [self::$DI['app']['url_generator'], self::$DI['app']['phraseanet.registry'], $this->auth, "Mock_Bridge_Api_Abstract"]);
} }
public static function tearDownAfterClass() public static function tearDownAfterClass()
{ {
if (self::$api) {
self::$api->delete(); self::$api->delete();
if (self::$account instanceof Bridge_Account) { self::$api = null;
}
if (self::$account) {
self::$account->delete(); self::$account->delete();
self::$account = null;
} }
self::$api = self::$account = null; self::$api = self::$account = null;
parent::tearDownAfterClass(); parent::tearDownAfterClass();

View File

@@ -70,7 +70,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
* @var float * @var float
*/ */
protected static $time_start; protected static $time_start;
public $app;
protected $start; protected $start;
/** /**
@@ -101,18 +100,15 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
self::updateTablesSchema($application); self::updateTablesSchema($application);
self::createSetOfUserTests($application);
self::setCollection($application);
self::generateRecords($application);
self::$DI['user']->setEmail('valid@phraseanet.com');
self::$updated = true; self::$updated = true;
} }
} }
/**
* Restores SQLite database to its initial state.
*
* @param string $path
*/
public static function initializeSqliteDB($path = '/tmp/db.sqlite') public static function initializeSqliteDB($path = '/tmp/db.sqlite')
{ {
if (is_file($path)) { if (is_file($path)) {
@@ -121,23 +117,14 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
copy(__DIR__ . '/../db-ref.sqlite', $path); copy(__DIR__ . '/../db-ref.sqlite', $path);
} }
/**
* @{inheritdoc}
*/
public function createApplication() public function createApplication()
{ {
} }
/**
* Delete all ressources created during the test
*/
public function __destruct()
{
self::deleteResources();
if (self::$time_start) {
self::$time_start = null;
}
}
public function setUp() public function setUp()
{ {
ini_set('memory_limit', '4096M'); ini_set('memory_limit', '4096M');
@@ -227,6 +214,142 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
})); }));
} }
/**
* Sets self::$DI['app'] with a new API application.
*/
public function createAPIApplication()
{
self::deleteResources();
self::$DI['app'] = self::$DI->share(function () {
$environment = 'test';
$app = require __DIR__ . '/../../lib/Alchemy/Phrasea/Application/Api.php';
$app['debug'] = true;
$app['EM'] = $app->share($app->extend('EM', function ($em) {
$this::initializeSqliteDB();
return $em;
}));
return $app;
});
self::createSetOfUserTests(self::$DI['app']);
self::setCollection(self::$DI['app']);
self::generateRecords(self::$DI['app']);
}
/**
* Sets self::$DI['app'] with a new Phraseanet application.
*/
public function createRootApplication()
{
self::$DI['app'] = self::$DI->share(function ($DI) {
$environment = 'test';
$app = require __DIR__ . '/../../lib/Alchemy/Phrasea/Application/Root.php';
$app['form.csrf_provider'] = $app->share(function () {
return new CsrfTestProvider();
});
$app['url_generator'] = $app->share($app->extend('url_generator', function ($generator, $app) {
$host = parse_url($app['conf']->get(['main', 'servername']), PHP_URL_HOST);
$generator->setContext(new RequestContext('', 'GET', $host));
return $generator;
}));
$app['debug'] = true;
$app['EM'] = $app->share($app->extend('EM', function ($em) {
$this::initializeSqliteDB();
return $em;
}));
$app['browser'] = $app->share($app->extend('browser', function ($browser) {
$browser->setUserAgent(PhraseanetPHPUnitAbstract::USER_AGENT_FIREFOX8MAC);
return $browser;
}));
$app['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$app['notification.deliverer']->expects($this->any())
->method('deliver')
->will($this->returnCallback(function () {
$this->fail('Notification deliverer must be mocked');
}));
return $app;
});
self::createSetOfUserTests(self::$DI['app']);
self::setCollection(self::$DI['app']);
self::generateRecords(self::$DI['app']);
}
/**
* Sets self::$DI['app'] with a new CLI application.
*/
public function createCLIApplication()
{
self::$DI['cli'] = self::$DI->share(function ($DI) {
$app = new CLI('cli test', null, 'test');
$app['form.csrf_provider'] = $app->share(function () {
return new CsrfTestProvider();
});
$app['url_generator'] = $app->share($app->extend('url_generator', function ($generator, $app) {
$host = parse_url($app['conf']->get(['main', 'servername']), PHP_URL_HOST);
$generator->setContext(new RequestContext('', 'GET', $host));
return $generator;
}));
$app['debug'] = true;
$app['EM'] = $app->share($app->extend('EM', function ($em) {
$this::initializeSqliteDb();
return $em;
}));
$app['browser'] = $app->share($app->extend('browser', function ($browser) {
$browser->setUserAgent(PhraseanetPHPUnitAbstract::USER_AGENT_FIREFOX8MAC);
return $browser;
}));
$app['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$app['notification.deliverer']->expects($this->any())
->method('deliver')
->will($this->returnCallback(function () {
$this->fail('Notification deliverer must be mocked');
}));
return $app;
});
}
/**
* Sets self::$DI['client'] with a new browser client.
*/
public function createNewClient()
{
self::$DI['client'] = self::$DI->share(function ($DI) {
return new Client($DI['app'], []);
});
}
public function tearDown() public function tearDown()
{ {
/** /**
@@ -384,6 +507,7 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
$entry->setAuthorName('user'); $entry->setAuthorName('user');
$entry->setAuthorEmail('user@email.com'); $entry->setAuthorEmail('user@email.com');
$publisher = $feed->getPublisher($user ?: self::$DI['user']); $publisher = $feed->getPublisher($user ?: self::$DI['user']);
if ($publisher !== null) { if ($publisher !== null) {
@@ -449,19 +573,14 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
/** /**
* Inserts one feed item. * Inserts one feed item.
* *
* @param User_Adapter $user * @return \Alchemy\Phrasea\Model\Entities\FeedItem
* @param boolean $public
* @param integer $qty
* @param record_adapter $record
*
* @return FeedItem
*/ */
protected function insertOneFeedItem(\User_Adapter $user = null, $public = false, $qty = 1, \record_adapter $record = null) protected function insertOneFeedItem(\User_Adapter $user = null, $public = false, $qty = 1, \record_adapter $record = null)
{ {
$entry = $this->insertOneFeedEntry($user, $public); $entry = $this->insertOneFeedEntry($user, $public);
for ($i = 0; $i < $qty; $i++) { for ($i = 0; $i < $qty; $i++) {
$item = new FeedItem(); $item = new \Alchemy\Phrasea\Model\Entities\FeedItem();
$item->setEntry($entry); $item->setEntry($entry);
if (null === $record) { if (null === $record) {
@@ -560,6 +679,28 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
return $list; return $list;
} }
/**
* Inserts one user list.
*
* @param User_Adapter $user
*
* @return UsrListOwner
*/
protected function insertOneUsrList(\User_Adapter $user = null)
{
$owner = $this->insertOneUsrListOwner($user);
$list = new UsrList();
$list->setName('new list');
$list->addOwner($owner);
$owner->setList($list);
self::$DI['app']['EM']->persist($list);
self::$DI['app']['EM']->flush();
return $list;
}
/** /**
* Insert one user list entry. * Insert one user list entry.
* *
@@ -592,20 +733,20 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
*/ */
protected function insertFiveBasket() protected function insertFiveBasket()
{ {
$baskets = []; try {
$basketFixture = new PhraseaFixture\Basket\LoadFiveBaskets();
for ($i = 0; $i < 5; $i ++) { $basketFixture->setUser(self::$DI['user']);
$basket = new Basket();
$basket->setName('test ' . $i);
$basket->setDescription('description');
$basket->setOwner(self::$DI['user']);
self::$DI['app']['EM']->persist($basket); $loader = new Loader();
$baskets[] = $basket; $loader->addFixture($basketFixture);
$this->insertFixtureInDatabase($loader);
return $basketFixture->baskets;
} catch (\Exception $e) {
$this->fail('Fail load five Basket : ' . $e->getMessage());
} }
self::$DI['app']['EM']->flush();
return $baskets;
} }
/** /**
@@ -996,7 +1137,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
$DI['user'] = $DI->share( $DI['user'] = $DI->share(
$DI->extend('user', function ($user, $DI) use ($collection_no_acces) { $DI->extend('user', function ($user, $DI) use ($collection_no_acces) {
$DI['app']['acl']->get($user)->revoke_access_from_bases([$collection_no_acces->get_base_id()]); $DI['app']['acl']->get($user)->revoke_access_from_bases([$collection_no_acces->get_base_id()]);
$DI['client'] = new Client($DI['app'], []);
return $user; return $user;
}) })
@@ -1032,10 +1172,9 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
/** /**
* Generates a set of records for the current tests suites. * Generates a set of records for the current tests suites.
*/ */
private static function generateRecords(Application $app) protected static function generateRecords(Application $app)
{ {
if (self::$recordsInitialized === false) { if (self::$recordsInitialized === false) {
$logger = new \Monolog\Logger('tests'); $logger = new \Monolog\Logger('tests');
$logger->pushHandler(new \Monolog\Handler\NullHandler()); $logger->pushHandler(new \Monolog\Handler\NullHandler());
self::$recordsInitialized = []; self::$recordsInitialized = [];
@@ -1056,13 +1195,9 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
foreach (range(1, 24) as $i) { foreach (range(1, 24) as $i) {
self::$DI['record_' . $i] = self::$DI->share(function ($DI) use ($logger, $resolvePathfile, $i) { self::$DI['record_' . $i] = self::$DI->share(function ($DI) use ($logger, $resolvePathfile, $i) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = $i; PhraseanetPHPUnitAbstract::$recordsInitialized[] = $i;
$file = new File($DI['app'], $DI['app']['mediavorus']->guess($resolvePathfile($i)->getPathname()), $DI['collection']); $file = new File($DI['app'], $DI['app']['mediavorus']->guess($resolvePathfile($i)->getPathname()), $DI['collection']);
$record = record_adapter::createFromFile($file, $DI['app']); $record = record_adapter::createFromFile($file, $DI['app']);
$record->generate_subdefs($record->get_databox(), $DI['app']); $record->generate_subdefs($record->get_databox(), $DI['app']);
return $record; return $record;
@@ -1071,7 +1206,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
foreach (range(1, 2) as $i) { foreach (range(1, 2) as $i) {
self::$DI['record_story_' . $i] = self::$DI->share(function ($DI) use ($i) { self::$DI['record_story_' . $i] = self::$DI->share(function ($DI) use ($i) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'story_' . $i; PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'story_' . $i;
return record_adapter::createStory($DI['app'], $DI['collection']); return record_adapter::createStory($DI['app'], $DI['collection']);
@@ -1079,40 +1213,18 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
} }
self::$DI['record_no_access'] = self::$DI->share(function ($DI) { self::$DI['record_no_access'] = self::$DI->share(function ($DI) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'no_access'; PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'no_access';
$file = new File($DI['app'], $DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), $DI['collection_no_access']); $file = new File($DI['app'], $DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), $DI['collection_no_access']);
return \record_adapter::createFromFile($file, $DI['app']); return \record_adapter::createFromFile($file, $DI['app']);
}); });
self::$DI['record_no_access_by_status'] = self::$DI->share(function ($DI) { self::$DI['record_no_access_by_status'] = self::$DI->share(function ($DI) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'no_access_by_status'; PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'no_access_by_status';
$file = new File($DI['app'], $DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), $DI['collection_no_access']); $file = new File($DI['app'], $DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), $DI['collection_no_access']);
return \record_adapter::createFromFile($file, $DI['app']); return \record_adapter::createFromFile($file, $DI['app']);
}); });
self::$DI['user'] = self::$DI->share(
self::$DI->extend('user', function ($user, $DI) use ($app) {
PhraseanetPHPUnitAbstract::giveRightsToUser($app, $user);
$app['acl']->get($user)->set_admin(true);
return $user;
})
);
self::$DI['user_notAdmin'] = self::$DI->share(
self::$DI->extend('user_notAdmin', function ($user, $DI) use ($app) {
PhraseanetPHPUnitAbstract::giveRightsToUser($app, $user);
$app['acl']->get($user)->set_admin(false);
return $user;
})
);
} }
return; return;
@@ -1158,12 +1270,12 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
$session = new Session(); $session = new Session();
$session->setUser(self::$DI['user']); $session->setUser(self::$DI['user']);
$session->setUserAgent(''); $session->setUserAgent('');
self::$DI['app']['EM']->persist($session); $app['EM']->persist($session);
self::$DI['app']['EM']->flush(); $app['EM']->flush();
$app['session']->set('session_id', $session->getId()); $app['session']->set('session_id', $session->getId());
self::$DI['app']['authentication']->reinitUser(); $app['authentication']->reinitUser();
} }
/** /**
@@ -1174,7 +1286,7 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
protected function logout(Application $app) protected function logout(Application $app)
{ {
$app['session']->clear(); $app['session']->clear();
self::$DI['app']['authentication']->reinitUser(); $app['authentication']->reinitUser();
} }
protected function assertXMLHTTPBadJsonResponse(Response $response) protected function assertXMLHTTPBadJsonResponse(Response $response)

View File

@@ -18,24 +18,33 @@ class collectionTest extends \PhraseanetAuthenticatedTestCase
{ {
$application = self::$DI['app']; $application = self::$DI['app'];
$found = false; self::$DI['user'];
foreach ($application['phraseanet.appbox']->get_databoxes() as $databox) {
$found = true; if (!self::$object) {
break; if (0 === count(self::$DI['app']['phraseanet.appbox']->get_databoxes())) {
$this->fail('No databox found for collection test');
} }
if ( ! $found) $databox = array_shift(self::$DI['app']['phraseanet.appbox']->get_databoxes());
self::fail('No databox found for collection test');
self::$object = collection::create(self::$DI['app'], $databox, $application['phraseanet.appbox'], 'test_collection', self::$DI['user']); self::$object = collection::create(
self::$DI['app'],
$databox,
self::$DI['app']['phraseanet.appbox'],
'test_collection',
self::$DI['user']
);
if ( ! self::$object instanceof collection) self::$objectDisable = collection::create(
self::fail('Unable to create collection'); self::$DI['app'],
$databox,
self::$DI['app']['phraseanet.appbox'],
'test_collection',
self::$DI['user']
);
self::$objectDisable = collection::create(self::$DI['app'], $databox, $application['phraseanet.appbox'], 'test_collection', self::$DI['user']);
self::$objectDisable->disable(self::$DI['app']['phraseanet.appbox']); self::$objectDisable->disable(self::$DI['app']['phraseanet.appbox']);
if ( ! self::$objectDisable instanceof collection) }
self::fail('Unable to create disable collection');
} }
public static function tearDownAfterClass() public static function tearDownAfterClass()

View File

@@ -27,21 +27,27 @@ class media_subdefTest extends \PhraseanetTestCase
self::$DI['app']['subdef.generator']->generateSubdefs(self::$recordonbleu); self::$DI['app']['subdef.generator']->generateSubdefs(self::$recordonbleu);
foreach (self::$recordonbleu->get_subdefs() as $subdef) { foreach (self::$recordonbleu->get_subdefs() as $subdef) {
if ($subdef->get_name() === 'document') {
if ($subdef->get_name() == 'document') {
continue; continue;
} }
if (! self::$objectPresent) { if (!self::$objectPresent) {
self::$objectPresent = $subdef; self::$objectPresent = $subdef;
continue; continue;
} }
if (! self::$objectNotPresent) { if (!self::$objectNotPresent) {
self::$objectNotPresent = $subdef; self::$objectNotPresent = $subdef;
continue; continue;
} }
} }
$story = \record_adapter::createStory(self::$DI['app'], self::$DI['collection']);
self::$objectNotPresent->remove_file();
self::$storyPresent = $story->get_subdef('thumbnail');
}
}
self::$objectNotPresent->remove_file(); self::$objectNotPresent->remove_file();
} }