/**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $dql = 'SELECT u FROM Phraseanet:User u WHERE u.nonce IS NULL';
     $q = $app['EM']->createQuery($dql);
     $q->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
     $users = $q->getResult();
     $n = 0;
     foreach ($users as $user) {
         $user->setNonce(random::generatePassword(16));
         $app['EM']->persist($user);
         $n++;
         if ($n % 100 === 0) {
             $app['EM']->flush();
         }
     }
     $app['EM']->flush();
     $sql = 'SELECT task_id, `class` FROM task2';
     $stmt = $appbox->get_connection()->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $sql = 'UPDATE task2 SET `class` = :class WHERE task_id = :task_id';
     $stmt = $appbox->get_connection()->prepare($sql);
     foreach ($rs as $row) {
         if (strpos($row['class'], 'task_period_') !== false) {
             continue;
         }
         $params = [':task_id' => $row['task_id'], ':class' => str_replace('task_', 'task_period_', $row['class'])];
         $stmt->execute($params);
     }
     $stmt->closeCursor();
     return true;
 }
 public function testGeneratePassword()
 {
     $this->assertRegExp('/[a-zA-Z]{4}/', random::generatePassword(4, random::LETTERS));
     $this->assertRegExp('/[a-zA-Z]{8}/', random::generatePassword(8, random::LETTERS));
     $this->assertRegExp('/[a-zA-Z]{16}/', random::generatePassword(16, random::LETTERS));
     $this->assertRegExp('/[a-zA-Z]{32}/', random::generatePassword(32, random::LETTERS));
     $this->assertRegExp('/[a-zA-Z]{64}/', random::generatePassword(64, random::LETTERS));
     $this->assertRegExp('/[a-zA-Z0-9]{4}/', random::generatePassword(4, random::LETTERS_AND_NUMBERS));
     $this->assertRegExp('/[a-zA-Z0-9]{8}/', random::generatePassword(8, random::LETTERS_AND_NUMBERS));
     $this->assertRegExp('/[a-zA-Z0-9]{16}/', random::generatePassword(16, random::LETTERS_AND_NUMBERS));
     $this->assertRegExp('/[a-zA-Z0-9]{32}/', random::generatePassword(32, random::LETTERS_AND_NUMBERS));
     $this->assertRegExp('/[a-zA-Z0-9]{64}/', random::generatePassword(64, random::LETTERS_AND_NUMBERS));
     $this->assertRegExp('/[0-9]{4}/', random::generatePassword(4, random::NUMBERS));
     $this->assertRegExp('/[0-9]{8}/', random::generatePassword(8, random::NUMBERS));
     $this->assertRegExp('/[0-9]{16}/', random::generatePassword(16, random::NUMBERS));
     $this->assertRegExp('/[0-9]{32}/', random::generatePassword(32, random::NUMBERS));
     $this->assertRegExp('/[0-9]{64}/', random::generatePassword(64, random::NUMBERS));
     try {
         random::generatePassword('gros caca', random::NUMBERS);
         $this->fail('An invalid argument exception should have been triggered');
     } catch (Exception_InvalidArgument $e) {
     }
     try {
         random::generatePassword('012', random::NUMBERS);
         $this->fail('An invalid argument exception should have been triggered');
     } catch (Exception_InvalidArgument $e) {
     }
     try {
         random::generatePassword('caca007', random::NUMBERS);
         $this->fail('An invalid argument exception should have been triggered');
     } catch (Exception_InvalidArgument $e) {
     }
 }
 public function testValidTokenIsValid()
 {
     $random = $this->getMockBuilder('random')->disableOriginalConstructor()->setMethods(['helloToken'])->getMock();
     $token = \random::generatePassword();
     $random->expects($this->once())->method('helloToken')->with($token)->will($this->returnValue(['usr_id' => mt_rand(), 'type' => \random::TYPE_PASSWORD]));
     $constraint = new PasswordToken($random);
     $this->assertTrue($constraint->isValid($token));
 }
 public function setUp()
 {
     parent::setUp();
     $this->account = API_OAuth2_Account::load_with_user(self::$DI['app'], self::$DI['oauth2-app-user'], self::$DI['user']);
     $expires = time() + 100;
     $this->code = random::generatePassword(8);
     $this->object = API_OAuth2_AuthCode::create(self::$DI['app'], $this->account, $this->code, $expires);
 }
 /**
  * @covers Alchemy\Phrasea\Border\Checker\Sha256::check
  */
 public function testCheckNoFile()
 {
     $mock = $this->getMock('\\Alchemy\\Phrasea\\Border\\File', ['getSha256'], [self::$DI['app'], $this->media, self::$DI['collection']]);
     $mock->expects($this->once())->method('getSha256')->will($this->returnValue(\random::generatePassword(3)));
     $response = $this->object->check(self::$DI['app']['EM'], $mock);
     $this->assertInstanceOf('\\Alchemy\\Phrasea\\Border\\Checker\\Response', $response);
     $this->assertTrue($response->isOk());
 }
 public function setUp()
 {
     parent::setUp();
     $this->account = API_OAuth2_Account::load_with_user(self::$DI['app'], self::$DI['oauth2-app-user'], self::$DI['user']);
     $expires = time() + 100;
     $this->token = random::generatePassword(8);
     $this->scope = 'scopidou';
     $this->object = API_OAuth2_RefreshToken::create(self::$DI['app'], $this->account, $expires, $this->token, $this->scope);
 }
 public function testDeleteSetMailToNullAndRemovesSessions()
 {
     if (null === ($user = self::$DI['app']['manipulator.user']->getRepository()->findByLogin('test_phpunit_sessions'))) {
         $user = self::$DI['app']['manipulator.user']->createUser('test_phpunit_sessions', \random::generatePassword());
     }
     $session = new \Alchemy\Phrasea\Model\Entities\Session();
     $session->setUser($user)->setUserAgent('');
     self::$DI['app']['EM']->persist($session);
     self::$DI['app']['EM']->flush();
     self::$DI['app']['manipulator.user']->delete($user);
     $repo = self::$DI['app']['EM']->getRepository('Phraseanet:Session');
     $this->assertCount(0, $repo->findByUser($user));
 }
 public function testIs_valid()
 {
     for ($i = 0; $i < 1000; $i++) {
         $uuid = uuid::generate_v4();
         if (!uuid::is_valid($uuid)) {
             $this->fail('Generation d\'un uuid v4 invalide');
         }
         $uuid = uuid::generate_v5($uuid, random::generatePassword(12));
         if (!uuid::is_valid($uuid)) {
             $this->fail('Generation d\'un uuid v5 invalide');
         }
         $uuid = uuid::generate_v3($uuid, random::generatePassword(12));
         if (!uuid::is_valid($uuid)) {
             $this->fail('Generation d\'un uuid v3 invalide');
         }
         unset($uuid);
     }
 }
 /**
  * @covers Alchemy\Phrasea\SearchEngine\SearchEngineLogger::log
  * @todo   Implement testLog().
  */
 public function testLog()
 {
     $databox = self::$DI['collection']->get_databox();
     $coll_ids = [self::$DI['collection']->get_coll_id()];
     $answers = 42;
     $query = \random::generatePassword();
     $object = new SearchEngineLogger(self::$DI['app']);
     $object->log($databox, $query, $answers, $coll_ids);
     $conn = $databox->get_connection();
     $sql = 'SELECT date, search, results, coll_id
             FROM log_search
             ORDER BY id DESC
             LIMIT 1';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $row = $stmt->fetch(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $this->assertEquals($query, $row['search']);
     $this->assertEquals($answers, $row['results']);
     $this->assertEquals(self::$DI['collection']->get_coll_id(), $row['coll_id']);
 }
 /**
  * @covers \caption_record::serializeYAML
  */
 public function testSerializeYAML()
 {
     foreach (self::$DI['record_1']->get_databox()->get_meta_structure() as $databox_field) {
         $n = $databox_field->is_multi() ? 3 : 1;
         for ($i = 0; $i < $n; $i++) {
             \caption_Field_Value::create(self::$DI['app'], $databox_field, self::$DI['record_1'], \random::generatePassword());
         }
     }
     $parser = new Yaml();
     $yaml = $parser->parse(self::$DI['app']['serializer.caption']->serialize($this->object, CaptionSerializer::SERIALIZE_YAML));
     foreach (self::$DI['record_1']->get_caption()->get_fields() as $field) {
         if ($field->get_databox_field()->is_multi()) {
             $tagname = $field->get_name();
             $retrieved = [];
             foreach ($yaml["record"]["description"][$tagname] as $value) {
                 $retrieved[] = (string) $value;
             }
             $values = $field->get_values();
             $this->assertEquals(count($values), count($retrieved));
             foreach ($values as $val) {
                 $this->assertTrue(in_array($val->getValue(), $retrieved));
             }
         } else {
             $tagname = $field->get_name();
             $data = $field->get_values();
             $value = array_pop($data);
             $this->assertEquals($value->getValue(), (string) $yaml["record"]["description"][$tagname]);
         }
     }
 }
 private function pathsToConf($path)
 {
     static $n = 0;
     $n++;
     return ['mount-point' => 'mp4-videos-' . $n, 'directory' => $path, 'passphrase' => \random::generatePassword(32)];
 }
 /**
  *
  * @param  Application            $app
  * @param  User                   $user
  * @param  type                   $name
  * @return API_OAuth2_Application
  */
 public static function create(Application $app, User $user = null, $name)
 {
     $sql = '
         INSERT INTO api_applications (
             application_id, creator, created_on, name, last_modified,
             nonce, client_id, client_secret, activated, grant_password
         )
         VALUES (
             null, :usr_id, NOW(), :name, NOW(), :nonce, :client_id,
             :client_secret, :activated, :grant_password
         )';
     $nonce = random::generatePassword(6);
     $client_secret = API_OAuth2_Token::generate_token();
     $client_token = API_OAuth2_Token::generate_token();
     $params = [':usr_id' => $user ? $user->getId() : null, ':name' => $name, ':client_id' => $client_token, ':client_secret' => $client_secret, ':nonce' => $nonce, ':activated' => 1, ':grant_password' => 0];
     $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
     $stmt->execute($params);
     $stmt->closeCursor();
     $application_id = $app['phraseanet.appbox']->get_connection()->lastInsertId();
     $application = new self($app, $application_id);
     if ($user) {
         API_OAuth2_Account::create($app, $user, $application);
     }
     return $application;
 }
 public function provideValidationData()
 {
     return [[\random::generatePassword(), true], [\random::generatePassword(), false]];
 }
Exemple #14
0
 /**
  *
  * @param  Application             $app
  * @param  databox                 $databox
  * @param  media_subdef            $media_subdef
  * @return media_Permalink_Adapter
  */
 public static function create(Application $app, databox $databox, media_subdef $media_subdef)
 {
     $sql = 'INSERT INTO permalinks
         (id, subdef_id, token, activated, created_on, last_modified, label)
         VALUES (null, :subdef_id, :token, :activated, NOW(), NOW(), "")';
     $params = [':subdef_id' => $media_subdef->get_subdef_id(), ':token' => random::generatePassword(8, random::LETTERS_AND_NUMBERS), ':activated' => '1'];
     $error = null;
     $stmt = $databox->get_connection()->prepare($sql);
     try {
         $stmt->execute($params);
     } catch (DBALException $e) {
         $error = $e;
     }
     $stmt->closeCursor();
     if ($error) {
         throw new RuntimeException('Permalink already exists', $e->getCode(), $e);
     }
     $permalink = self::getPermalink($app, $databox, $media_subdef);
     $permalink->set_label(strip_tags($media_subdef->get_record()->get_title(false, null, true)));
     return $permalink;
 }
Exemple #15
0
 /**
  *
  * @param  SimpleXMLElement $table
  * @return base
  */
 protected function createTable(SimpleXMLElement $table)
 {
     $field_stmt = $defaults_stmt = [];
     $create_stmt = "CREATE TABLE `" . $table['name'] . "` (";
     foreach ($table->fields->field as $field) {
         $isnull = trim($field->null) == "" ? "NOT NULL" : "NULL";
         if (trim($field->default) != "" && trim($field->default) != "CURRENT_TIMESTAMP") {
             $is_default = " default '" . $field->default . "'";
         } elseif (trim($field->default) == "CURRENT_TIMESTAMP") {
             $is_default = " default " . $field->default;
         } else {
             $is_default = '';
         }
         $character_set = '';
         if (in_array(strtolower((string) $field->type), ['text', 'longtext', 'mediumtext', 'tinytext']) || substr(strtolower((string) $field->type), 0, 7) == 'varchar' || in_array(substr(strtolower((string) $field->type), 0, 4), ['char', 'enum'])) {
             $collation = trim((string) $field->collation) != '' ? trim((string) $field->collation) : 'utf8_unicode_ci';
             $collations = array_reverse(explode('_', $collation));
             $code = array_pop($collations);
             $character_set = ' CHARACTER SET ' . $code . ' COLLATE ' . $collation;
         }
         $field_stmt[] = " `" . $field->name . "` " . $field->type . " " . $field->extra . " " . $character_set . " " . $is_default . " " . $isnull . "";
     }
     if ($table->indexes) {
         foreach ($table->indexes->index as $index) {
             switch ($index->type) {
                 case "PRIMARY":
                     $primary_fields = [];
                     foreach ($index->fields->field as $field) {
                         $primary_fields[] = "`" . $field . "`";
                     }
                     $field_stmt[] = 'PRIMARY KEY (' . implode(',', $primary_fields) . ')';
                     break;
                 case "UNIQUE":
                     $unique_fields = [];
                     foreach ($index->fields->field as $field) {
                         $unique_fields[] = "`" . $field . "`";
                     }
                     $field_stmt[] = 'UNIQUE KEY `' . $index->name . '` (' . implode(',', $unique_fields) . ')';
                     break;
                 case "INDEX":
                     $index_fields = [];
                     foreach ($index->fields->field as $field) {
                         $index_fields[] = "`" . $field . "`";
                     }
                     $field_stmt[] = 'KEY `' . $index->name . '` (' . implode(',', $index_fields) . ')';
                     break;
             }
         }
     }
     if ($table->defaults) {
         foreach ($table->defaults->default as $default) {
             $k = $v = $params = $dates_values = [];
             $nonce = random::generatePassword(16);
             foreach ($default->data as $data) {
                 $k = trim($data['key']);
                 if ($k === 'usr_password') {
                     $data = $this->app['auth.password-encoder']->encodePassword($data, $nonce);
                 }
                 if ($k === 'nonce') {
                     $data = $nonce;
                 }
                 $v = trim(str_replace(["\r\n", "\r", "\n", "\t"], '', $data));
                 if (trim(mb_strtolower($v)) == 'now()') {
                     $dates_values[$k] = 'NOW()';
                 } else {
                     $params[$k] = trim(mb_strtolower($v)) == 'null' ? null : $v;
                 }
             }
             $separator = count($params) > 0 && count($dates_values) > 0 ? ', ' : '';
             $defaults_stmt[] = ['sql' => 'INSERT INTO `' . $table['name'] . '` (' . implode(', ', array_keys($params)) . $separator . implode(', ', array_keys($dates_values)) . ')
                   VALUES (:' . implode(', :', array_keys($params)) . $separator . implode(', ', array_values($dates_values)) . ') ', 'params' => $params];
         }
     }
     $engine = mb_strtolower(trim($table->engine));
     $engine = in_array($engine, ['innodb', 'myisam']) ? $engine : 'innodb';
     $create_stmt .= implode(',', $field_stmt);
     $create_stmt .= ") ENGINE=" . $engine . " CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
     $stmt = $this->get_connection()->prepare($create_stmt);
     $stmt->execute();
     $stmt->closeCursor();
     foreach ($defaults_stmt as $def) {
         try {
             $stmt = $this->get_connection()->prepare($def['sql']);
             $stmt->execute($def['params']);
             $stmt->closeCursor();
         } catch (\Exception $e) {
             $recommends[] = ['message' => $this->app->trans('Erreur lors de la tentative ; errreur : %message%', ['%message%' => $e->getMessage()]), 'sql' => $def['sql']];
         }
     }
     return $this;
 }
Exemple #16
0
 private function doAuthentication(PhraseaApplication $app, Request $request, FormInterface $form, $redirector)
 {
     if (!is_callable($redirector)) {
         throw new InvalidArgumentException('Redirector should be callable');
     }
     $context = new Context(Context::CONTEXT_NATIVE);
     $app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));
     $form->bind($request);
     if (!$form->isValid()) {
         $app->addFlash('error', $app->trans('An unexpected error occured during authentication process, please contact an admin'));
         throw new AuthenticationException(call_user_func($redirector));
     }
     $params = [];
     if (null !== ($redirect = $request->get('redirect'))) {
         $params['redirect'] = ltrim($redirect, '/');
     }
     try {
         $usr_id = $app['auth.native']->getUsrId($request->request->get('login'), $request->request->get('password'), $request);
     } catch (RequireCaptchaException $e) {
         $app->requireCaptcha();
         $app->addFlash('warning', $app->trans('Please fill the captcha'));
         throw new AuthenticationException(call_user_func($redirector, $params));
     } catch (AccountLockedException $e) {
         $app->addFlash('warning', $app->trans('login::erreur: Vous n\'avez pas confirme votre email'));
         $app->addUnlockAccountData($e->getUsrId());
         throw new AuthenticationException(call_user_func($redirector, $params));
     }
     if (null === $usr_id) {
         $app['session']->getFlashBag()->set('error', $app->trans('login::erreur: Erreur d\'authentification'));
         throw new AuthenticationException(call_user_func($redirector, $params));
     }
     $user = $app['manipulator.user']->getRepository()->find($usr_id);
     $session = $this->postAuthProcess($app, $user);
     $response = $this->generateAuthResponse($app, $app['browser'], $request->request->get('redirect'));
     $response->headers->clearCookie('invite-usr-id');
     if ($request->cookies->has('postlog') && $request->cookies->get('postlog') == '1') {
         if (!$user->isGuest() && $request->cookies->has('invite-usr_id')) {
             if ($user->getId() != ($inviteUsrId = $request->cookies->get('invite-usr_id'))) {
                 $repo = $app['EM']->getRepository('Phraseanet:Basket');
                 $baskets = $repo->findBy(['usr_id' => $inviteUsrId]);
                 foreach ($baskets as $basket) {
                     $basket->setUser($user);
                     $app['EM']->persist($basket);
                 }
             }
         }
     }
     if ($request->request->get('remember-me') == '1') {
         $nonce = \random::generatePassword(16);
         $string = $app['browser']->getBrowser() . '_' . $app['browser']->getPlatform();
         $token = $app['auth.password-encoder']->encodePassword($string, $nonce);
         $session->setToken($token)->setNonce($nonce);
         $response->headers->setCookie(new Cookie('persistent', $token));
         $app['EM']->persist($session);
         $app['EM']->flush();
     }
     $event = new PostAuthenticate($request, $response, $user, $context);
     $app['dispatcher']->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
     return $event->getResponse();
 }
 /**
  * Generate a new valid email adress
  * @return string
  */
 private function generateEmail()
 {
     return \random::generatePassword() . '*****@*****.**';
 }
Exemple #18
0
 public function connect(Application $app)
 {
     $app['controller.prod.push'] = $this;
     $controllers = $app['controllers_factory'];
     $app['firewall']->addMandatoryAuthentication($controllers);
     $controllers->before(function (Request $request) use($app) {
         $app['firewall']->requireRight('push');
     });
     $userFormatter = $this->getUserFormatter($app);
     $listFormatter = $this->getListFormatter($app);
     $userSelection = $this->getUsersInSelectionExtractor();
     $controllers->post('/sendform/', function (Application $app) use($userSelection) {
         $push = new RecordHelper\Push($app, $app['request']);
         $repository = $app['EM']->getRepository('Phraseanet:UsrList');
         $RecommendedUsers = $userSelection($push->get_elements());
         $params = ['push' => $push, 'message' => '', 'lists' => $repository->findUserLists($app['authentication']->getUser()), 'context' => 'Push', 'RecommendedUsers' => $RecommendedUsers];
         return $app['twig']->render('prod/actions/Push.html.twig', $params);
     });
     $controllers->post('/validateform/', function (Application $app) use($userSelection) {
         $push = new RecordHelper\Push($app, $app['request']);
         $repository = $app['EM']->getRepository('Phraseanet:UsrList');
         $RecommendedUsers = $userSelection($push->get_elements());
         $params = ['push' => $push, 'message' => '', 'lists' => $repository->findUserLists($app['authentication']->getUser()), 'context' => 'Feedback', 'RecommendedUsers' => $RecommendedUsers];
         return $app['twig']->render('prod/actions/Push.html.twig', $params);
     });
     $controllers->post('/send/', function (Application $app) {
         $request = $app['request'];
         $ret = ['success' => false, 'message' => $app->trans('Unable to send the documents')];
         try {
             $pusher = new RecordHelper\Push($app, $app['request']);
             $push_name = $request->request->get('name', $app->trans('Push from %user%', ['%user%' => $app['authentication']->getUser()->getDisplayName()]));
             $push_description = $request->request->get('push_description');
             $receivers = $request->request->get('participants');
             if (!is_array($receivers) || count($receivers) === 0) {
                 throw new ControllerException($app->trans('No receivers specified'));
             }
             if (!is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) {
                 throw new ControllerException($app->trans('No elements to push'));
             }
             foreach ($receivers as $receiver) {
                 try {
                     $user_receiver = $app['manipulator.user']->getRepository()->find($receiver['usr_id']);
                 } catch (\Exception $e) {
                     throw new ControllerException($app->trans('Unknown user %user_id%', ['%user_id%' => $receiver['usr_id']]));
                 }
                 $Basket = new Basket();
                 $Basket->setName($push_name);
                 $Basket->setDescription($push_description);
                 $Basket->setUser($user_receiver);
                 $Basket->setPusher($app['authentication']->getUser());
                 $Basket->setIsRead(false);
                 $app['EM']->persist($Basket);
                 foreach ($pusher->get_elements() as $element) {
                     $BasketElement = new BasketElement();
                     $BasketElement->setRecord($element);
                     $BasketElement->setBasket($Basket);
                     $app['EM']->persist($BasketElement);
                     $Basket->addElement($BasketElement);
                     if ($receiver['HD']) {
                         $app['acl']->get($user_receiver)->grant_hd_on($BasketElement->getRecord($app), $app['authentication']->getUser(), \ACL::GRANT_ACTION_PUSH);
                     } else {
                         $app['acl']->get($user_receiver)->grant_preview_on($BasketElement->getRecord($app), $app['authentication']->getUser(), \ACL::GRANT_ACTION_PUSH);
                     }
                 }
                 $app['EM']->flush();
                 $url = $app->url('lightbox_compare', ['basket' => $Basket->getId(), 'LOG' => $app['tokens']->getUrlToken(\random::TYPE_VIEW, $user_receiver->getId(), null, $Basket->getId())]);
                 $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : '';
                 $params = ['from' => $app['authentication']->getUser()->getId(), 'from_email' => $app['authentication']->getUser()->getEmail(), 'to' => $user_receiver->getId(), 'to_email' => $user_receiver->getEmail(), 'to_name' => $user_receiver->getDisplayName(), 'url' => $url, 'accuse' => $receipt, 'message' => $request->request->get('message'), 'ssel_id' => $Basket->getId()];
                 $app['events-manager']->trigger('__PUSH_DATAS__', $params);
             }
             $app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox())->log($BasketElement->getRecord($app), \Session_Logger::EVENT_VALIDATE, $user_receiver->getId(), '');
             $app['EM']->flush();
             $message = $app->trans('%quantity_records% records have been sent to %quantity_users% users', ['%quantity_records%' => count($pusher->get_elements()), '%quantity_users%' => count($receivers)]);
             $ret = ['success' => true, 'message' => $message];
         } catch (ControllerException $e) {
             $ret['message'] = $e->getMessage() . $e->getFile() . $e->getLine();
         }
         return $app->json($ret);
     })->bind('prod_push_send');
     $controllers->post('/validate/', function (Application $app) {
         $request = $app['request'];
         $ret = ['success' => false, 'message' => $app->trans('Unable to send the documents')];
         $app['EM']->beginTransaction();
         try {
             $pusher = new RecordHelper\Push($app, $app['request']);
             $validation_name = $request->request->get('name', $app->trans('Validation from %user%', ['%user%' => $app['authentication']->getUser()->getDisplayName()]));
             $validation_description = $request->request->get('validation_description');
             $participants = $request->request->get('participants');
             if (!is_array($participants) || count($participants) === 0) {
                 throw new ControllerException($app->trans('No participants specified'));
             }
             if (!is_array($pusher->get_elements()) || count($pusher->get_elements()) === 0) {
                 throw new ControllerException($app->trans('No elements to validate'));
             }
             if ($pusher->is_basket()) {
                 $Basket = $pusher->get_original_basket();
             } else {
                 $Basket = new Basket();
                 $Basket->setName($validation_name);
                 $Basket->setDescription($validation_description);
                 $Basket->setUser($app['authentication']->getUser());
                 $Basket->setIsRead(false);
                 $app['EM']->persist($Basket);
                 foreach ($pusher->get_elements() as $element) {
                     $BasketElement = new BasketElement();
                     $BasketElement->setRecord($element);
                     $BasketElement->setBasket($Basket);
                     $app['EM']->persist($BasketElement);
                     $Basket->addElement($BasketElement);
                 }
                 $app['EM']->flush();
             }
             $app['EM']->refresh($Basket);
             if (!$Basket->getValidation()) {
                 $Validation = new ValidationSession();
                 $Validation->setInitiator($app['authentication']->getUser());
                 $Validation->setBasket($Basket);
                 $duration = (int) $request->request->get('duration');
                 if ($duration > 0) {
                     $date = new \DateTime('+' . $duration . ' day' . ($duration > 1 ? 's' : ''));
                     $Validation->setExpires($date);
                 }
                 $Basket->setValidation($Validation);
                 $app['EM']->persist($Validation);
             } else {
                 $Validation = $Basket->getValidation();
             }
             $found = false;
             foreach ($participants as $participant) {
                 if ($participant['usr_id'] === $app['authentication']->getUser()->getId()) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $participants[] = ['see_others' => 1, 'usr_id' => $app['authentication']->getUser()->getId(), 'agree' => 0, 'HD' => 0];
             }
             foreach ($participants as $key => $participant) {
                 foreach (['see_others', 'usr_id', 'agree', 'HD'] as $mandatoryparam) {
                     if (!array_key_exists($mandatoryparam, $participant)) {
                         throw new ControllerException($app->trans('Missing mandatory parameter %parameter%', ['%parameter%' => $mandatoryparam]));
                     }
                 }
                 try {
                     $participant_user = $app['manipulator.user']->getRepository()->find($participant['usr_id']);
                 } catch (\Exception $e) {
                     throw new ControllerException($app->trans('Unknown user %usr_id%', ['%usr_id%' => $participant['usr_id']]));
                 }
                 try {
                     $Participant = $Validation->getParticipant($participant_user);
                     continue;
                 } catch (NotFoundHttpException $e) {
                 }
                 $Participant = new ValidationParticipant();
                 $Participant->setUser($participant_user);
                 $Participant->setSession($Validation);
                 $Participant->setCanAgree($participant['agree']);
                 $Participant->setCanSeeOthers($participant['see_others']);
                 $app['EM']->persist($Participant);
                 foreach ($Basket->getElements() as $BasketElement) {
                     $ValidationData = new ValidationData();
                     $ValidationData->setParticipant($Participant);
                     $ValidationData->setBasketElement($BasketElement);
                     $BasketElement->addValidationData($ValidationData);
                     if ($participant['HD']) {
                         $app['acl']->get($participant_user)->grant_hd_on($BasketElement->getRecord($app), $app['authentication']->getUser(), \ACL::GRANT_ACTION_VALIDATE);
                     } else {
                         $app['acl']->get($participant_user)->grant_preview_on($BasketElement->getRecord($app), $app['authentication']->getUser(), \ACL::GRANT_ACTION_VALIDATE);
                     }
                     $app['EM']->merge($BasketElement);
                     $app['EM']->persist($ValidationData);
                     $app['phraseanet.logger']($BasketElement->getRecord($app)->get_databox())->log($BasketElement->getRecord($app), \Session_Logger::EVENT_PUSH, $participant_user->getId(), '');
                     $Participant->addData($ValidationData);
                 }
                 $Participant = $app['EM']->merge($Participant);
                 $app['EM']->flush();
                 $url = $app->url('lightbox_validation', ['basket' => $Basket->getId(), 'LOG' => $app['tokens']->getUrlToken(\random::TYPE_VALIDATE, $participant_user->getId(), null, $Basket->getId())]);
                 $receipt = $request->get('recept') ? $app['authentication']->getUser()->getEmail() : '';
                 $params = ['from' => $app['authentication']->getUser()->getId(), 'from_email' => $app['authentication']->getUser()->getEmail(), 'to' => $participant_user->getId(), 'to_email' => $participant_user->getEmail(), 'to_name' => $participant_user->getDisplayName(), 'url' => $url, 'accuse' => $receipt, 'message' => $request->request->get('message'), 'ssel_id' => $Basket->getId(), 'duration' => (int) $request->request->get('duration')];
                 $app['events-manager']->trigger('__PUSH_VALIDATION__', $params);
             }
             $Basket = $app['EM']->merge($Basket);
             $Validation = $app['EM']->merge($Validation);
             $app['EM']->flush();
             $message = $app->trans('%quantity_records% records have been sent for validation to %quantity_users% users', ['%quantity_records%' => count($pusher->get_elements()), '%quantity_users%' => count($request->request->get('participants'))]);
             $ret = ['success' => true, 'message' => $message];
             $app['EM']->commit();
         } catch (ControllerException $e) {
             $ret['message'] = $e->getMessage();
             $app['EM']->rollback();
         }
         return $app->json($ret);
     })->bind('prod_push_validate');
     $controllers->get('/user/{usr_id}/', function (Application $app, $usr_id) use($userFormatter) {
         $datas = null;
         $request = $app['request'];
         $query = new \User_Query($app);
         $query->on_bases_where_i_am($app['acl']->get($app['authentication']->getUser()), ['canpush']);
         $query->in([$usr_id]);
         $result = $query->include_phantoms()->limit(0, 1)->execute()->get_results();
         if ($result) {
             foreach ($result as $user) {
                 $datas = $userFormatter($user);
             }
         }
         return $app->json($datas);
     })->assert('usr_id', '\\d+');
     $controllers->get('/list/{list_id}/', function (Application $app, $list_id) use($listFormatter) {
         $datas = null;
         $repository = $app['EM']->getRepository('Phraseanet:UsrList');
         $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id);
         if ($list) {
             $datas = $listFormatter($list);
         }
         return $app->json($datas);
     })->bind('prod_push_lists_list')->assert('list_id', '\\d+');
     $controllers->post('/add-user/', function (Application $app, Request $request) use($userFormatter) {
         $result = ['success' => false, 'message' => '', 'user' => null];
         try {
             if (!$app['acl']->get($app['authentication']->getUser())->has_right('manageusers')) {
                 throw new ControllerException($app->trans('You are not allowed to add users'));
             }
             if (!$request->request->get('firstname')) {
                 throw new ControllerException($app->trans('First name is required'));
             }
             if (!$request->request->get('lastname')) {
                 throw new ControllerException($app->trans('Last name is required'));
             }
             if (!$request->request->get('email')) {
                 throw new ControllerException($app->trans('Email is required'));
             }
             if (!\Swift_Validate::email($request->request->get('email'))) {
                 throw new ControllerException($app->trans('Email is invalid'));
             }
         } catch (ControllerException $e) {
             $result['message'] = $e->getMessage();
             return $app->json($result);
         }
         $user = null;
         $email = $request->request->get('email');
         try {
             $user = $app['manipulator.user']->getRepository()->findByEmail($email);
             $result['message'] = $app->trans('User already exists');
             $result['success'] = true;
             $result['user'] = $userFormatter($user);
         } catch (\Exception $e) {
         }
         if (!$user instanceof User) {
             try {
                 $password = \random::generatePassword();
                 $user = $app['manipulator.user']->getRepository()->createUser($email, $password, $email);
                 $user->setFirstName($request->request->get('firstname'))->setLastName($request->request->get('lastname'));
                 if ($request->request->get('company')) {
                     $user->setCompany($request->request->get('company'));
                 }
                 if ($request->request->get('job')) {
                     $user->setCompany($request->request->get('job'));
                 }
                 if ($request->request->get('form_geonameid')) {
                     $app['manipulator.user']->setGeonameId($user, $request->request->get('form_geonameid'));
                 }
                 $result['message'] = $app->trans('User successfully created');
                 $result['success'] = true;
                 $result['user'] = $userFormatter($user);
             } catch (\Exception $e) {
                 $result['message'] = $app->trans('Error while creating user');
             }
         }
         return $app->json($result);
     })->bind('prod_push_do_add_user');
     $controllers->get('/add-user/', function (Application $app, Request $request) {
         $params = ['callback' => $request->query->get('callback')];
         return $app['twig']->render('prod/User/Add.html.twig', $params);
     })->bind('prod_push_add_user');
     $controllers->get('/search-user/', function (Application $app) use($userFormatter, $listFormatter) {
         $request = $app['request'];
         $query = new \User_Query($app);
         $query->on_bases_where_i_am($app['acl']->get($app['authentication']->getUser()), ['canpush']);
         $query->like(\User_Query::LIKE_FIRSTNAME, $request->query->get('query'))->like(\User_Query::LIKE_LASTNAME, $request->query->get('query'))->like(\User_Query::LIKE_LOGIN, $request->query->get('query'))->like_match(\User_Query::LIKE_MATCH_OR);
         $result = $query->include_phantoms()->limit(0, 50)->execute()->get_results();
         $repository = $app['EM']->getRepository('Phraseanet:UsrList');
         $lists = $repository->findUserListLike($app['authentication']->getUser(), $request->query->get('query'));
         $datas = [];
         if ($lists) {
             foreach ($lists as $list) {
                 $datas[] = $listFormatter($list);
             }
         }
         if ($result) {
             foreach ($result as $user) {
                 $datas[] = $userFormatter($user);
             }
         }
         return $app->json($datas);
     });
     $controllers->match('/edit-list/{list_id}/', function (Application $app, Request $request, $list_id) {
         $repository = $app['EM']->getRepository('Phraseanet:UsrList');
         $list = $repository->findUserListByUserAndId($app['authentication']->getUser(), $list_id);
         $query = new \User_Query($app);
         $query->on_bases_where_i_am($app['acl']->get($app['authentication']->getUser()), ['canpush']);
         if ($request->get('query')) {
             $query->like($request->get('like_field'), $request->get('query'))->like_match(\User_Query::LIKE_MATCH_OR);
         }
         if (is_array($request->get('Activity'))) {
             $query->haveActivities($request->get('Activity'));
         }
         if (is_array($request->get('Template'))) {
             $query->haveTemplate($request->get('Template'));
         }
         if (is_array($request->get('Company'))) {
             $query->inCompanies($request->get('Company'));
         }
         if (is_array($request->get('Country'))) {
             $query->inCountries($request->get('Country'));
         }
         if (is_array($request->get('Position'))) {
             $query->havePositions($request->get('Position'));
         }
         $sort = $request->get('srt', 'usr_creationdate');
         $ord = $request->get('ord', 'desc');
         $perPage = 10;
         $offset_start = Max(((int) $request->get('page') - 1) * $perPage, 0);
         $query->sort_by($sort, $ord);
         $results = $query->include_phantoms()->limit($offset_start, $perPage)->execute()->get_results();
         $params = ['query' => $query, 'results' => $results, 'list' => $list, 'sort' => $sort, 'ord' => $ord];
         if ($request->get('type') === 'fragment') {
             return new Response($app['twig']->render('prod/actions/Feedback/ResultTable.html.twig', $params));
         } else {
             return new Response($app['twig']->render('prod/actions/Feedback/list.html.twig', $params));
         }
     })->bind('prod_push_list_edit')->assert('list_id', '\\d+');
     return $controllers;
 }
 public function getUserNotAdmin()
 {
     if (null === ($user = $this->container['manipulator.user']->getRepository()->findByLogin('test_phpunit_not_admin'))) {
         $user = $this->container['manipulator.user']->createUser('test_phpunit_not_admin', \random::generatePassword(), '*****@*****.**', false);
     }
     return $user;
 }
Exemple #20
0
 public function create_template()
 {
     $name = $this->request->get('value');
     if (trim($name) === '') {
         throw new \Exception_InvalidArgument('Invalid template name');
     }
     $created_user = $this->app['manipulator.user']->getRepository()->find($name, \random::generatePassword(16));
     $created_user->setModelOf($this->app['authentication']->getUser());
     $this->usr_id = $this->app['authentication']->getUser()->getId();
     return $created_user;
 }
 public function passwordProvider()
 {
     return [[\random::generatePassword(), 'password', 'not_identical_password']];
 }