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

View File

@@ -13,20 +13,22 @@ namespace Alchemy\Phrasea\Authentication\Phrasea;
use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Authentication\Exception\AccountLockedException;
use Alchemy\Phrasea\Model\Manipulator\UserManipulator;
use Alchemy\Phrasea\Model\Entities\User;
use Symfony\Component\HttpFoundation\Request;
class NativeAuthentication implements PasswordAuthenticationInterface
{
/** @var \connection_interface */
private $conn;
/** @var UserManipulator */
private $userManipulator;
/** @var PasswordEncoder */
private $encoder;
/** @var OldPasswordEncoder */
private $oldEncoder;
public function __construct(PasswordEncoder $encoder, OldPasswordEncoder $oldEncoder, \connection_interface $conn)
public function __construct(PasswordEncoder $encoder, OldPasswordEncoder $oldEncoder, UserManipulator $userManipulator)
{
$this->conn = $conn;
$this->userManipulator = $userManipulator;
$this->encoder = $encoder;
$this->oldEncoder = $oldEncoder;
}
@@ -36,55 +38,32 @@ class NativeAuthentication implements PasswordAuthenticationInterface
*/
public function getUsrId($username, $password, Request $request)
{
if (in_array($username, ['invite', 'autoregister'])) {
if (null === $user = $this->userManipulator->getRepository()->findRealUserByLogin($username)) {
return null;
}
$sql = 'SELECT nonce, salted_password, mail_locked, usr_id, usr_login, usr_password
FROM usr
WHERE usr_login = :login
AND usr_login NOT LIKE "(#deleted_%"
AND model_of="0" AND invite="0"
LIMIT 0, 1';
$stmt = $this->conn->prepare($sql);
$stmt->execute([':login' => $username]);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!$row) {
if ($user->isSpecial()) {
return null;
}
// check locked account
if ('1' == $row['mail_locked']) {
throw new AccountLockedException('The account is locked', $row['usr_id']);
if ($user->isMailLocked()) {
throw new AccountLockedException('The account is locked', $user->getId());
}
if ('0' == $row['salted_password']) {
if (false === $user->isSaltedPassword()) {
// we need a quick update and continue
if ($this->oldEncoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) {
$row['nonce'] = \random::generatePassword(8, \random::LETTERS_AND_NUMBERS);
$row['usr_password'] = $this->encoder->encodePassword($password, $row['nonce']);
$sql = 'UPDATE usr SET usr_password = :password, nonce = :nonce
WHERE usr_id = :usr_id';
$stmt = $this->conn->prepare($sql);
$stmt->execute([
':password' => $row['usr_password'],
':nonce' => $row['nonce'],
':usr_id' => $row['usr_id'],
]);
$stmt->closeCursor();
if ($this->oldEncoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) {
$user->setSaltedPassword(true);
$this->userManipulator->setPassword($user, $user->getPassword());
}
}
if (!$this->encoder->isPasswordValid($row['usr_password'], $password, $row['nonce'])) {
if (false === $this->encoder->isPasswordValid($user->getPassword(), $password, $user->getNonce())) {
return null;
}
return $row['usr_id'];
return $user->getId();
}
/**

View File

@@ -40,16 +40,7 @@ class SuggestionFinder
$infos = $token->getIdentity();
if ($infos->has(Identity::PROPERTY_EMAIL)) {
$sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email';
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':email' => $infos->get(Identity::PROPERTY_EMAIL)]);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
if ($row) {
return $this->app['manipulator.user']->getRepository()->find($row['usr_id']);
}
return $this->app['manipulator.user']->getRepository()->findByEmail($infos->get(Identity::PROPERTY_EMAIL));
}
return null;

View File

@@ -14,6 +14,8 @@ namespace Alchemy\Phrasea\Controller\Admin;
use Alchemy\Phrasea\Helper\User as UserHelper;
use Alchemy\Phrasea\Model\Entities\FtpCredential;
use Alchemy\Phrasea\Model\Entities\User;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
@@ -353,51 +355,53 @@ class Users implements ControllerProviderInterface
})->bind('admin_users_export_csv');
$controllers->get('/demands/', function (Application $app) {
$lastMonth = time() - (3 * 4 * 7 * 24 * 60 * 60);
$sql = "DELETE FROM demand WHERE date_modif < :date";
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':date' => date('Y-m-d', $lastMonth)]);
$stmt->closeCursor();
$baslist = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin']));
$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);
$stmt->execute([':usr_id' => $app['authentication']->getUser()->getId()]);
$models = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$selectClause = $rsm->generateSelectClause([
'u' => 't1'
]);
$sql = "
SELECT demand.date_modif,demand.base_id, usr.usr_id , usr.usr_login ,usr.usr_nom,usr.usr_prenom,
usr.societe, usr.fonction, usr.usr_mail, usr.tel, usr.activite,
usr.adresse, usr.cpostal, usr.ville, usr.pays, CONCAT(usr.usr_nom,' ',usr.usr_prenom,'\n',fonction,' (',societe,')') AS info
FROM (demand INNER JOIN usr on demand.usr_id=usr.usr_id AND demand.en_cours=1 AND usr.usr_login NOT LIKE '(#deleted%' )
WHERE (base_id='" . implode("' OR base_id='", $baslist) . "') ORDER BY demand.usr_id DESC,demand.base_id ASC
";
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$query = $app['EM']->createNativeQuery("
SELECT d.date_modif AS date_demand, d.base_id AS base_demand, " . $selectClause . "
FROM (demand d INNER JOIN Users t1 ON d.usr_id=t1.id
AND d.en_cours=1
AND t1.deleted=0
)
WHERE (base_id='" . implode("' OR base_id='", $basList) . "')
ORDER BY d.usr_id DESC, d.base_id ASC
", $rsm);
$currentUsr = null;
$table = ['user' => [], 'coll' => []];
$table = ['users' => [], 'coll' => []];
foreach ($rs as $row) {
if ($row['usr_id'] != $currentUsr) {
$currentUsr = $row['usr_id'];
$row['date_modif'] = new \DateTime($row['date_modif']);
$table['user'][$row['usr_id']] = $row;
foreach ($query->getResult() as $row) {
$user = $row[0];
if ($user->getId() !== $currentUsr) {
$currentUsr = $user->getId();
$table['users'][$currentUsr] = [
'user' => $user,
'date_demand' => new \DateTime($row['date_demand']),
];
}
if (!isset($table['coll'][$row['usr_id']])) {
$table['coll'][$row['usr_id']] = [];
if (!isset($table['coll'][$user->getId()])) {
$table['coll'][$user->getId()] = [];
}
if (!in_array($row['base_id'], $table['coll'][$row['usr_id']])) {
$table['coll'][$row['usr_id']][] = $row['base_id'];
if (!in_array($row['base_demand'], $table['coll'][$user->getId()])) {
$table['coll'][$user->getId()][] = $row['base_demand'];
}
}
@@ -543,17 +547,9 @@ class Users implements ControllerProviderInterface
}
foreach ($done as $usr => $bases) {
$sql = 'SELECT usr_mail FROM usr WHERE usr_id = :usr_id';
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':usr_id' => $usr]);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$acceptColl = $denyColl = [];
if ($row) {
if (\Swift_Validate::email($row['usr_mail'])) {
if (null === $user = $app['manipulator.user']->getRepository()->find($usr)) {
if (\Swift_Validate::email($user.getEmail())) {
foreach ($bases as $bas => $isok) {
if ($isok) {
$acceptColl[] = \phrasea::bas_labels($bas, $app);
@@ -715,20 +711,23 @@ class Users implements ControllerProviderInterface
]);
}
$sql = "
SELECT usr.usr_id,usr.usr_login
FROM usr
INNER JOIN basusr
ON (basusr.usr_id=usr.usr_id)
WHERE usr.model_of = :usr_id
AND base_id in(" . implode(', ', array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))) . ")
AND usr_login not like '(#deleted_%)'
GROUP BY usr_id";
$rsm = new ResultSetMappingBuilder($app['EM']);
$stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute([':usr_id' => $app['authentication']->getUser()->getId()]);
$models = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$selectClause = $rsm->generateSelectClause([
'u' => 't1'
]);
$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', [
'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', [
'last_action' => !$app['authentication']->getUser()->is_guest() && false !== $request->cookies->has('last_act') ? $request->cookies->has('last_act') : null,
'last_action' => !$app['authentication']->getUser()->isGuest() && false !== $request->cookies->has('last_act') ? $request->cookies->has('last_act') : null,
'phrasea_home' => $this->getDefaultClientStartPage($app),
'render_topics' => $renderTopics,
'grid_properties' => $this->getGridProperty(),

View File

@@ -557,7 +557,7 @@ class Push implements ControllerProviderInterface
if ($request->request->get('job'))
$user->setCompany($request->request->get('job'));
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['success'] = true;

View File

@@ -14,6 +14,7 @@ namespace Alchemy\Phrasea\Controller\Root;
use Alchemy\Geonames\Exception\ExceptionInterface as GeonamesExceptionInterface;
use Alchemy\Phrasea\Application as PhraseaApplication;
use Alchemy\Phrasea\Exception\InvalidArgumentException;
use Alchemy\Phrasea\Model\Entities\FtpCredential;
use Alchemy\Phrasea\Notification\Receiver;
use Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate;
use Alchemy\Phrasea\Form\Login\PhraseaRenewPasswordForm;
@@ -75,13 +76,6 @@ class Account implements ControllerProviderInterface
return $controllers;
}
/**
* Reset Password
*
* @param Application $app
* @param Request $request
* @return Response
*/
public function resetPassword(Application $app, Request $request)
{
$form = $app->form(new PhraseaRenewPasswordForm());
@@ -94,7 +88,7 @@ class Account implements ControllerProviderInterface
$user = $app['authentication']->getUser();
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'));
return $app->redirectPath('account');
@@ -267,8 +261,8 @@ class Account implements ControllerProviderInterface
*/
public function accountSessionsAccess(Application $app, Request $request)
{
$dql = 'SELECT s FROM Phraseanet:Session s
WHERE s.usr_id = :usr_id
$dql = 'SELECT s FROM Alchemy\Phrasea\Model\Entities\Session s
WHERE s.user = :usr_id
ORDER BY s.created DESC';
$query = $app['EM']->createQuery($dql);
@@ -386,10 +380,16 @@ class Account implements ControllerProviderInterface
->setCompany($request->request->get("form_company"))
->setActivity($request->request->get("form_function"))
->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();
if (null === $ftpCredential) {
$ftpCredential = new FtpCredential();
}
$ftpCredential->setActive($request->request->get("form_activeFTP"));
$ftpCredential->setAddress($request->request->get("form_addressFTP"));
$ftpCredential->setLogin($request->request->get("form_loginFTP"));

View File

@@ -376,9 +376,13 @@ class Login implements ControllerProviderInterface
'job' => 'setJob',
'company' => 'setCompany',
'position' => 'setActivity',
'geonameid' => 'setGeonanameId',
'geonameid' => 'setGeonameId',
] as $property => $method) {
if (isset($data[$property])) {
if ($property === 'geonameid') {
$app['manipulator.user']->setGeonameId($user, $data[$property]);
continue;
}
call_user_func([$user, $method], $data[$property]);
}
}
@@ -490,9 +494,7 @@ class Login implements ControllerProviderInterface
$app->abort(400, 'Missing usr_id parameter.');
}
try {
$user = $app['manipulator.user']->getRepository()->find((int) $usrId);
} catch (\Exception $e) {
if (null === $user = $app['manipulator.user']->getRepository()->find((int) $usrId)) {
$app->addFlash('error', $app->trans('Invalid link.'));
return $app->redirectPath('homepage');
@@ -558,7 +560,7 @@ class Login implements ControllerProviderInterface
try {
$user = $app['manipulator.user']->getRepository()->find((int) $datas['usr_id']);
} catch (\Exception $e) {
$app->addFlash('error', $app->trans('Invalid unlock link.'));
$app->addFlash('error', _('Invalid unlock link.'));
return $app->redirectPath('homepage');
}
@@ -621,7 +623,7 @@ class Login implements ControllerProviderInterface
$datas = $app['tokens']->helloToken($token);
$user = $app['manipulator.user']->getRepository()->find($datas['usr_id']);
$user->setPassword($data['password']);
$app['manipulator.user']->setPassword($user, $data['password']);
$app['tokens']->removeToken($token);
@@ -661,7 +663,7 @@ class Login implements ControllerProviderInterface
try {
$user = $app['manipulator.user']->getRepository()->findByEmail($data['email']);
} 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 {
@@ -806,8 +808,7 @@ class Login implements ControllerProviderInterface
$context = new Context(Context::CONTEXT_GUEST);
$app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
$password = \random::generatePassword(24);
$invite_user = $app['manipulator.user']->createUser('invite', $password);
$invite_user = $app['manipulator.user']->createUser('invite', \random::generatePassword(24));
$usr_base_ids = array_keys($app['acl']->get($user)->get_granted_base());
$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');
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')) {
$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_modif_th AS bas_edit_thesaurus
FROM
(usr INNER JOIN sbasusr
ON usr.usr_id = :usr_id
AND usr.usr_id = sbasusr.usr_id
AND model_of = 0)
(Users u INNER JOIN sbasusr
ON u.id = :usr_id
AND u.id = sbasusr.usr_id
AND u.model_of = 0)
INNER JOIN
sbas ON sbas.sbas_id = sbasusr.sbas_id
HAVING bas_edit_thesaurus > 0

View File

@@ -107,7 +107,7 @@ class AuthenticationManagerServiceProvider implements ServiceProviderInterface
});
$app['auth.password-checker'] = $app->share(function (Application $app) {
return new NativeAuthentication($app['auth.password-encoder'], $app['auth.old-password-encoder'], $app['phraseanet.appbox']->get_connection());
return new NativeAuthentication($app['auth.password-encoder'], $app['auth.old-password-encoder'], $app['manipulator.user']);
});
$app['auth.native'] = $app->share(function (Application $app) {

View File

@@ -125,12 +125,12 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
sum(mask_and + mask_xor) as masks
FROM (usr u, bas b, sbas s)
FROM (Users u, bas b, sbas s)
LEFT JOIN (basusr bu)
ON (bu.base_id = b.base_id AND u.usr_id = bu.usr_id)
ON (bu.base_id = b.base_id AND u.id = bu.usr_id)
LEFT join sbasusr sbu
ON (sbu.sbas_id = b.sbas_id AND u.usr_id = sbu.usr_id)
WHERE ( (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . " )
ON (sbu.sbas_id = b.sbas_id AND u.id = sbu.usr_id)
WHERE ( (u.id = " . implode(' OR u.id = ', $this->users) . " )
AND b.sbas_id = s.sbas_id
AND (b.base_id = '" . implode("' OR b.base_id = '", $list) . "'))
GROUP BY b.base_id
@@ -192,8 +192,8 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
$this->base_id = (int) $this->request->get('base_id');
$sql = "SELECT u.usr_id, restrict_dwnld, remain_dwnld, month_dwnld_max
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ")
FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)
WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")
AND bu.base_id = :base_id";
$conn = \connection::getPDOConnection($this->app);
@@ -315,8 +315,8 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
$this->base_id = (int) $this->request->get('base_id');
$sql = "SELECT u.usr_id, time_limited, limited_from, limited_to
FROM (usr u INNER JOIN basusr bu ON u.usr_id = bu.usr_id)
WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ")
FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)
WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")
AND bu.base_id = :base_id";
$conn = \connection::getPDOConnection($this->app);
@@ -369,10 +369,10 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
$sbas_id = (int) $this->request->get('sbas_id');
$sql = "SELECT u.usr_id, time_limited, limited_from, limited_to
FROM (usr u
INNER JOIN basusr bu ON u.usr_id = bu.usr_id
FROM (Users u
INNER JOIN basusr bu ON u.id = bu.usr_id
INNER JOIN bas b ON b.base_id = bu.base_id)
WHERE (u.usr_id = " . implode(' OR u.usr_id = ', $this->users) . ")
WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")
AND b.sbas_id = :sbas_id";
$conn = \connection::getPDOConnection($this->app);
@@ -602,13 +602,14 @@ class Edit extends \Alchemy\Phrasea\Helper\Helper
->setEmail($parm['email'])
->setAddress($parm['address'])
->setZipCode($parm['zip'])
->setGeonanameId($parm['geonameid'])
->setActivity($parm['function'])
->setJob($parm['activite'])
->setCompany($parm['company'])
->setPhone($parm['telephone'])
->setFax($parm['fax']);
$this->app['manipulator.user']->setGeonameId($user, $parm['geonameid']);
$new_email = $user->getEmail();
if ($old_email != $new_email) {

View File

@@ -146,14 +146,7 @@ class Manage extends Helper
throw new \Exception_InvalidArgument('Invalid mail address');
}
$conn = $this->app['phraseanet.appbox']->get_connection();
$sql = 'SELECT usr_id FROM usr WHERE usr_mail = :email';
$stmt = $conn->prepare($sql);
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$count = count($row);
if (!is_array($row) || $count == 0) {
if (null === $createdUser = $this->app['manipulator.user']->getRepository()->findByEmail($email)) {
$sendCredentials = !!$this->request->get('send_credentials', false);
$validateMail = !!$this->request->get('validate_mail', false);
@@ -189,12 +182,9 @@ class Manage extends Helper
$this->app['notification.deliverer']->deliver($mail);
}
}
}
$this->usr_id = $createdUser->getId();
} else {
$this->usr_id = $row['usr_id'];
$createdUser = $this->app['manipulator.user']->getRepository()->find($this->usr_id);
}
return $createdUser;
}

View File

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

View File

@@ -291,6 +291,8 @@ class User
public function setLogin($login)
{
$this->login = $login;
return $this;
}
/**
@@ -307,6 +309,8 @@ class User
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
@@ -324,6 +328,8 @@ class User
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
@@ -340,6 +346,8 @@ class User
public function setNonce($nonce)
{
$this->nonce = $nonce;
return $this;
}
/**
@@ -356,6 +364,8 @@ class User
public function setSaltedPassword($saltedPassword)
{
$this->saltedPassword = (Boolean) $saltedPassword;
return $this;
}
/**
@@ -372,6 +382,8 @@ class User
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
@@ -389,6 +401,8 @@ class User
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
@@ -415,6 +429,8 @@ class User
}
$this->gender = $gender;
return $this;
}
/**
@@ -431,6 +447,8 @@ class User
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
@@ -447,6 +465,8 @@ class User
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
@@ -463,6 +483,8 @@ class User
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
@@ -479,6 +501,8 @@ class User
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
return $this;
}
/**
@@ -499,6 +523,8 @@ class User
}
$this->geonameId = $geonameId;
return $this;
}
/**
@@ -521,6 +547,8 @@ class User
}
$this->locale = $locale;
return $this;
}
/**
@@ -537,6 +565,8 @@ class User
public function setTimezone($timezone)
{
$this->timezone = $timezone;
return $this;
}
/**
@@ -553,6 +583,8 @@ class User
public function setJob($job)
{
$this->job = $job;
return $this;
}
/**
@@ -569,6 +601,8 @@ class User
public function setActivity($activity)
{
$this->activity = $activity;
return $this;
}
/**
@@ -585,6 +619,8 @@ class User
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
@@ -601,6 +637,8 @@ class User
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
@@ -617,6 +655,8 @@ class User
public function setFax($fax)
{
$this->fax = $fax;
return $this;
}
/**
@@ -633,6 +673,8 @@ class User
public function setAdmin($admin)
{
$this->admin = (Boolean) $admin;
return $this;
}
/**
@@ -649,6 +691,8 @@ class User
public function setGuest($guest)
{
$this->guest = (Boolean) $guest;
return $this;
}
/**
@@ -665,6 +709,8 @@ class User
public function setMailNotificationsActivated($mailNotifications)
{
$this->mailNotificationsActivated = (Boolean) $mailNotifications;
return $this;
}
/**
@@ -681,6 +727,8 @@ class User
public function setRequestNotificationsActivated($requestNotifications)
{
$this->requestNotificationsActivated = (Boolean) $requestNotifications;
return $this;
}
/**
@@ -697,6 +745,8 @@ class User
public function setLdapCreated($ldapCreated)
{
$this->ldapCreated = (Boolean) $ldapCreated;
return $this;
}
/**
@@ -713,6 +763,8 @@ class User
public function setModelOf(User $owner)
{
$this->modelOf = $owner;
return $this;
}
/**
@@ -729,6 +781,8 @@ class User
public function setLastModel($lastModel)
{
$this->lastModel = $lastModel;
return $this;
}
/**
@@ -745,6 +799,8 @@ class User
public function setPushList($pushList)
{
$this->pushList = $pushList;
return $this;
}
/**
@@ -761,6 +817,8 @@ class User
public function setCanChangeProfil($canChangeProfil)
{
$this->canChangeProfil = (Boolean) $canChangeProfil;
return $this;
}
/**
@@ -777,6 +835,8 @@ class User
public function setCanChangeFtpProfil($canChangeFtpProfil)
{
$this->canChangeFtpProfil = (Boolean) $canChangeFtpProfil;
return $this;
}
/**
@@ -793,6 +853,8 @@ class User
public function setLastConnection(\DateTime $lastConnection)
{
$this->lastConnection = $lastConnection;
return $this;
}
/**
@@ -809,6 +871,8 @@ class User
public function setMailLocked($mailLocked)
{
$this->mailLocked = (Boolean) $mailLocked;
return $this;
}
/**
@@ -853,6 +917,8 @@ class User
public function setCreated(\Datetime $created)
{
$this->created = $created;
return $this;
}
/**
@@ -861,6 +927,8 @@ class User
public function setUpdated(\Datetime $updated)
{
$this->updated = $updated;
return $this;
}
/**

View File

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

View File

@@ -67,4 +67,36 @@ class UserRepository extends EntityRepository
return $qb->getQuery()->getOneOrNullResult();
}
/**
* Finds a user that is not deleted, not a model and not a guest.
*
* @param $login
*
* @return null|User
*/
public function findRealUserByLogin($login)
{
$qb = $this->createQueryBuilder('u');
$qb->where($qb->expr()->eq('u.login', $qb->expr()->literal($login)))
->andWhere($qb->expr()->isNotNull('u.email'))
->andWhere($qb->expr()->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()
{
if ($this->app['authentication']->getUser()->is_guest()) {
if ($this->app['authentication']->getUser()->isGuest()) {
$this->app->abort(403, 'Guests do not have admin role');
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -62,11 +62,13 @@ class module_console_systemUpgrade extends Command
try {
$upgrader = new Setup_Upgrade($this->container, $input->getOption('force'));
$queries = $this->getService('phraseanet.appbox')->forceUpgrade($upgrader, $this->container);
} catch (\Exception_Setup_FixBadEmailAddresses $e) {
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 (0 < count($queries)) {

View File

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

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());
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 (
FtpCredential INNER JOIN usr ON (
FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id
FtpCredential INNER JOIN Users ON (
FtpCredential.active = 1 AND FtpCredential.user_id = Users.id
) INNER JOIN basusr ON (
usr.usr_id=basusr.usr_id
Users.id=basusr.usr_id
AND (basusr.base_id=
'" . implode("' OR basusr.base_id='", $lst_base_id) . "'
)
)
)
GROUP BY usr_id ";
GROUP BY Users.id ";
$params = [];
} elseif ($this->app['conf']->get(['registry', 'ftp', 'ftp-user-access'])) {
$sql = "SELECT usr.usr_id,usr_login,usr.usr_mail, FtpCredential.*
$sql = "SELECT Users.id AS usr_id ,Users.login AS usr_login ,Users.mail AS usr_mail, FtpCredential.*
FROM (
FtpCredential INNER JOIN usr ON (
FtpCredential.active = 1 AND FtpCredential.usrId = usr.usr_id
FtpCredential INNER JOIN Users ON (
FtpCredential.active = 1 AND FtpCredential.id = Users.id
) INNER JOIN basusr ON (
usr.usr_id=basusr.usr_id
AND usr.usr_id = :usr_id
Users.id=basusr.usr_id
AND Users.id = :usr_id
AND (basusr.base_id=
'" . implode("' OR basusr.base_id='", $lst_base_id) . "'
)
)
)
GROUP BY usr_id ";
GROUP BY Users.id ";
$params = [':usr_id' => $app['authentication']->getUser()->getId()];
}

View File

@@ -168,6 +168,8 @@
<legend>{{ "FTP" | trans }}</legend>
{% set ftpCredential = app["authentication"].getUser().getFtpCredential() %}
{% if ftpCredential is not none %}
<div class="control-group">
<div class="controls">
<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>
</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">
<label class="form_label control-label" for="form_addressFTP"><strong>{{ "phraseanet:: adresse" | trans }}</strong></label>
<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>
</div>
</div>
<div class="control-group">
<label class="form_label control-label" for="form_loginFTP"><strong>{{ "admin::compte-utilisateur identifiant" | trans }}</strong></label>
<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>
</div>
</div>
<div class="control-group">
<label class="form_label control-label" for="form_pwdFTP"><strong>{{ "admin::compte-utilisateur mot de passe" | trans }}</strong></label>
<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>
</div>
</div>
<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>
<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>
</div>
</div>
<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>
<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>
</div>
</div>
@@ -217,7 +220,7 @@
<div class="controls">
<label class="form_label checkbox" for="form_passifFTP">
{{ "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>
<p class="form_alert help-block"></p>
</div>
@@ -225,7 +228,7 @@
<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>
<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>
</div>
</div>

View File

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

View File

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

View File

@@ -76,7 +76,7 @@
</div>
{% 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">
p4.Dialog.get(1).Close();
parent.login({act:"dwnl",lst:"{{ lst }}",SSTTID:"{{ ssttid }}"});
@@ -145,7 +145,7 @@
{% endif %}
{{ _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">
<label for="TOU_acceptDL" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptDL" value="1" />
@@ -226,7 +226,7 @@
{% endif %}
{{ _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">
<label for="TOU_acceptMail" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptMail" value="1" />
@@ -379,7 +379,7 @@
</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">
<label for="TOU_acceptOrder" class="checkbox">
<input type="checkbox" name="TOU_accept" id="TOU_acceptOrder" value="1" />
@@ -460,7 +460,7 @@
</div>
{% 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">
<label for="TOU_acceptFTP" class="checkbox">
<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 %}
{% 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 %}

View File

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

View File

@@ -7,6 +7,7 @@ use Alchemy\Phrasea\Border\File;
use Alchemy\Phrasea\Core\PhraseaEvents;
use Alchemy\Phrasea\Authentication\Context;
use Alchemy\Phrasea\Model\Entities\Task;
use Doctrine\Common\Collections\ArrayCollection;
use Guzzle\Common\Exception\GuzzleException;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response;
@@ -893,7 +894,16 @@ abstract class ApiTestCase extends \PhraseanetWebTestCase
public function testRecordsSearchRouteWithQuery($method)
{
$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']->expects($this->once())
->method('query')
->with('koala', 0, 10)
@@ -1910,6 +1920,25 @@ abstract class ApiTestCase extends \PhraseanetWebTestCase
$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)
{
$this->assertArrayHasKey('id', $item);

View File

@@ -11,8 +11,8 @@ class RecordsRequestTest extends \PhraseanetAuthenticatedTestCase
{
$request = new Request([
'lst' => implode(';', [
self::$DI['record_3']->get_serialize_key(),
self::$DI['record_3']->get_serialize_key(),
self::$DI['record_24']->get_serialize_key(),
self::$DI['record_24']->get_serialize_key(),
self::$DI['record_2']->get_serialize_key(),
self::$DI['record_story_2']->get_serialize_key(),
self::$DI['record_no_access']->get_serialize_key(),
@@ -127,8 +127,8 @@ class RecordsRequestTest extends \PhraseanetAuthenticatedTestCase
{
$request = new Request([
'lst' => implode(';', [
self::$DI['record_3']->get_serialize_key(),
self::$DI['record_3']->get_serialize_key(),
self::$DI['record_24']->get_serialize_key(),
self::$DI['record_24']->get_serialize_key(),
self::$DI['record_2']->get_serialize_key(),
self::$DI['record_story_2']->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 Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Alchemy\Phrasea\Model\Entities\User;
class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{
@@ -123,7 +124,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
public function testPostResetMailBadEmail()
{
$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/', [
'form_password' => $password,
'form_email' => "invalid#!&&@@email.x",
@@ -143,7 +144,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
public function testPostResetMailEmailNotIdentical()
{
$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/', [
'form_password' => $password,
'form_email' => 'email1@email.com',
@@ -165,13 +166,17 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
$this->mockNotificationDeliverer('Alchemy\Phrasea\Notification\Mail\MailRequestEmailUpdate');
$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/', [
'form_password' => $password,
'form_email' => 'email1@email.com',
'form_email_confirm' => 'email1@email.com',
]);
self::$DI['client']->followRedirects();
$response = self::$DI['client']->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/', $response->headers->get('location'));
@@ -272,7 +277,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
self::$DI['client']->request('POST', '/account/', [
'demand' => $bases,
'form_gender' => 'M',
'form_gender' => User::GENDER_MR,
'form_firstname' => 'gros',
'form_lastname' => 'minet',
'form_address' => 'rue du lac',
@@ -282,7 +287,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
'form_function' => 'astronaute',
'form_company' => 'NASA',
'form_activity' => 'Space',
'form_geonameid' => '',
'form_geonameid' => '1839',
'form_addressFTP' => '',
'form_loginFTP' => '',
'form_pwdFTP' => '',
@@ -370,7 +375,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
*/
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/', [
'password' => [
@@ -407,7 +412,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{
$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/', [
'password' => [
@@ -427,7 +432,7 @@ class AccountTest extends \PhraseanetAuthenticatedWebTestCase
{
$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/', [
'password' => [

View File

@@ -275,7 +275,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'_token' => 'token',
]);
$response = self::$DI['client']->getResponse();
$this->assertFalse($response->isRedirect());
$this->assertFlashMessage($crawler, 'error', 1);
}
@@ -594,7 +593,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'password' => 'password',
'confirm' => 'password'
],
"accept-tou" => '1',
"collections" => null,
], [], 1],
[[//required extra-field missing
@@ -603,7 +601,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [
[
@@ -617,7 +614,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'passwordMismatch'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [], 1],
[[//password tooshort
@@ -626,7 +622,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'min'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [], 1],
[[//email invalid
@@ -635,7 +630,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => 'invalid.email',
"accept-tou" => '1',
"collections" => null
], [], 1],
[[//login exists
@@ -645,7 +639,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [
[
@@ -659,7 +652,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => null,
"accept-tou" => '1',
"collections" => null
], [], 1],
[[//tou declined
@@ -668,7 +660,8 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"collections" => null
"collections" => null,
"accept-tou" => '1'
], [], 1]
];
}
@@ -682,7 +675,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null,
], []],
[[
@@ -691,7 +683,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [
[
@@ -705,7 +696,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null
], [
[
@@ -763,7 +753,6 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
'confirm' => 'password'
],
"email" => $this->generateEmail(),
"accept-tou" => '1',
"collections" => null,
"login" => 'login-'.\random::generatePassword(),
"gender" => '1',
@@ -1136,7 +1125,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword();
$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);
$this->logout(self::$DI['app']);
@@ -1161,7 +1150,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword();
$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);
$this->logout(self::$DI['app']);
@@ -1208,7 +1197,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$password = \random::generatePassword();
$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']);
@@ -1516,7 +1505,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode());
$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);
@@ -1587,7 +1576,7 @@ class LoginTest extends \PhraseanetAuthenticatedWebTestCase
$this->assertSame(302, self::$DI['client']->getResponse()->getStatusCode());
$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);

View File

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

View File

@@ -18,14 +18,9 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
public function bootTestCase()
{
$binaryFinder = new ExecutableFinder();
$indexer = $binaryFinder->find('indexer');
$searchd = $binaryFinder->find('searchd');
if (!$indexer || !$searchd) {
if (null !== self::$indexerBinary = $binaryFinder->find('indexer') || null !== self::$searchdBinary = $binaryFinder->find('searchd')) {
self::$skipped = true;
return;
}
$app = self::$DI['app'];
@@ -74,6 +69,7 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
public function setUp()
{
parent::setUp();
if (self::$skipped) {
$this->markTestSkipped('SphinxSearch is not present on system');
}
@@ -90,16 +86,55 @@ class SphinxSearchEngineTest extends SearchEngineAbstractTest
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()
{
if (!self::$skipped) {
$binaryFinder = new ExecutableFinder();
$searchd = $binaryFinder->find('searchd');
self::$searchd = new Process($searchd . ' --stop -c ' . self::$config);
self::$searchd->run();
self::$searchdProcess = new Process(self::$searchdBinary . ' --stop -c ' . self::$config);
self::$searchdProcess->run();
unlink(self::$config);
}

View File

@@ -20,20 +20,29 @@ class Bridge_AccountTest extends \PhraseanetAuthenticatedTestCase
try {
$application = self::$DI['app'];
self::$DI['user'];
if (!self::$object) {
$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->closeCursor();
self::$api = Bridge_Api::create($application, 'Apitest');
self::$api = Bridge_Api::create(self::$DI['app'], 'Apitest');
self::$dist_id = 'EZ1565loPP';
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::$object = new Bridge_Account($application, self::$api, self::$id);
} catch (Exception $e) {
self::$fail($e->getMessage());
self::$object = new Bridge_Account(self::$DI['app'], self::$api, self::$id);
}
}
@@ -41,17 +50,12 @@ class Bridge_AccountTest extends \PhraseanetAuthenticatedTestCase
{
if (self::$object) {
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) {
self::$api->delete();
self::$api = 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()
{
$start = microtime(true);
$this->assertInstanceOf('Bridge_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());

View File

@@ -31,18 +31,25 @@ class Bridge_Api_AbstractTest extends \PhraseanetWebTestCase
self::$api = Bridge_Api::create($application, 'apitest');
}
try {
self::$account = Bridge_Account::load_account_from_distant_id($application, self::$api, self::$DI['user'], 'kirikoo');
} catch (Bridge_Exception_AccountNotFound $e) {
self::$account = Bridge_Account::create($application, self::$api, self::$DI['user'], 'kirikoo', 'coucou');
self::$DI['user'];
if (!self::$account) {
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()
{
if (self::$api) {
self::$api->delete();
if (self::$account instanceof Bridge_Account) {
self::$api = null;
}
if (self::$account) {
self::$account->delete();
self::$account = null;
}
self::$api = self::$account = null;
parent::tearDownAfterClass();

View File

@@ -70,7 +70,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
* @var float
*/
protected static $time_start;
public $app;
protected $start;
/**
@@ -101,18 +100,15 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
self::updateTablesSchema($application);
self::createSetOfUserTests($application);
self::setCollection($application);
self::generateRecords($application);
self::$DI['user']->setEmail('valid@phraseanet.com');
self::$updated = true;
}
}
/**
* Restores SQLite database to its initial state.
*
* @param string $path
*/
public static function initializeSqliteDB($path = '/tmp/db.sqlite')
{
if (is_file($path)) {
@@ -121,23 +117,14 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
copy(__DIR__ . '/../db-ref.sqlite', $path);
}
/**
* @{inheritdoc}
*/
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()
{
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()
{
/**
@@ -384,6 +507,7 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
$entry->setAuthorName('user');
$entry->setAuthorEmail('user@email.com');
$publisher = $feed->getPublisher($user ?: self::$DI['user']);
if ($publisher !== null) {
@@ -449,19 +573,14 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
/**
* Inserts one feed item.
*
* @param User_Adapter $user
* @param boolean $public
* @param integer $qty
* @param record_adapter $record
*
* @return FeedItem
* @return \Alchemy\Phrasea\Model\Entities\FeedItem
*/
protected function insertOneFeedItem(\User_Adapter $user = null, $public = false, $qty = 1, \record_adapter $record = null)
{
$entry = $this->insertOneFeedEntry($user, $public);
for ($i = 0; $i < $qty; $i++) {
$item = new FeedItem();
$item = new \Alchemy\Phrasea\Model\Entities\FeedItem();
$item->setEntry($entry);
if (null === $record) {
@@ -560,6 +679,28 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
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.
*
@@ -592,20 +733,20 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
*/
protected function insertFiveBasket()
{
$baskets = [];
try {
$basketFixture = new PhraseaFixture\Basket\LoadFiveBaskets();
for ($i = 0; $i < 5; $i ++) {
$basket = new Basket();
$basket->setName('test ' . $i);
$basket->setDescription('description');
$basket->setOwner(self::$DI['user']);
$basketFixture->setUser(self::$DI['user']);
self::$DI['app']['EM']->persist($basket);
$baskets[] = $basket;
$loader = new Loader();
$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->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['client'] = new Client($DI['app'], []);
return $user;
})
@@ -1032,10 +1172,9 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
/**
* 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) {
$logger = new \Monolog\Logger('tests');
$logger->pushHandler(new \Monolog\Handler\NullHandler());
self::$recordsInitialized = [];
@@ -1056,13 +1195,9 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
foreach (range(1, 24) as $i) {
self::$DI['record_' . $i] = self::$DI->share(function ($DI) use ($logger, $resolvePathfile, $i) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = $i;
$file = new File($DI['app'], $DI['app']['mediavorus']->guess($resolvePathfile($i)->getPathname()), $DI['collection']);
$record = record_adapter::createFromFile($file, $DI['app']);
$record->generate_subdefs($record->get_databox(), $DI['app']);
return $record;
@@ -1071,7 +1206,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
foreach (range(1, 2) as $i) {
self::$DI['record_story_' . $i] = self::$DI->share(function ($DI) use ($i) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'story_' . $i;
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) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = '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']);
});
self::$DI['record_no_access_by_status'] = self::$DI->share(function ($DI) {
PhraseanetPHPUnitAbstract::$recordsInitialized[] = 'no_access_by_status';
$file = new File($DI['app'], $DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), $DI['collection_no_access']);
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;
@@ -1158,12 +1270,12 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
$session = new Session();
$session->setUser(self::$DI['user']);
$session->setUserAgent('');
self::$DI['app']['EM']->persist($session);
self::$DI['app']['EM']->flush();
$app['EM']->persist($session);
$app['EM']->flush();
$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)
{
$app['session']->clear();
self::$DI['app']['authentication']->reinitUser();
$app['authentication']->reinitUser();
}
protected function assertXMLHTTPBadJsonResponse(Response $response)

View File

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

View File

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