public function apply(Application $app, Request $request) { $records = RecordsRequest::fromRequest($app, $request, false, ['candeleterecord']); $datas = ['success' => false, 'message' => '']; try { if (null === $request->request->get('base_id')) { $datas['message'] = $app->trans('Missing target collection'); return $app->json($datas); } if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($request->request->get('base_id'), 'canaddrecord')) { $datas['message'] = $app->trans("You do not have the permission to move records to %collection%", ['%collection%', \phrasea::bas_labels($request->request->get('base_id'), $app)]); return $app->json($datas); } try { $collection = \collection::get_from_base_id($app, $request->request->get('base_id')); } catch (\Exception_Databox_CollectionNotFound $e) { $datas['message'] = $app->trans('Invalid target collection'); return $app->json($datas); } foreach ($records as $record) { $record->move_to_collection($collection, $app['phraseanet.appbox']); if ($request->request->get("chg_coll_son") == "1") { foreach ($record->get_children() as $child) { if ($app['acl']->get($app['authentication']->getUser())->has_right_on_base($child->get_base_id(), 'candeleterecord')) { $child->move_to_collection($collection, $app['phraseanet.appbox']); } } } } $ret = ['success' => true, 'message' => $app->trans('Records have been successfuly moved')]; } catch (\Exception $e) { $ret = ['success' => false, 'message' => $app->trans('An error occured')]; } return $app->json($ret); }
/** * {@inheritdoc} */ protected function doJob(JobData $data) { $app = $data->getApplication(); $task = $data->getTask(); $settings = simplexml_load_string($task->getSettings()); $baseId = (string) $settings->base_id; $collection = \collection::get_from_base_id($app, $baseId); $collection->empty_collection(200); if (0 === $collection->get_record_amount()) { $this->stop(); $this->dispatcher->dispatch(JobEvents::FINISHED, new JobFinishedEvent($task)); } }
/** * {@inheritdoc} */ public function apply(base $appbox, Application $app) { $em = $app['orm.em']; $sql = "SELECT date_modif, usr_id, base_id, en_cours, refuser\n FROM demand"; $rsm = new ResultSetMapping(); $rsm->addScalarResult('base_id', 'base_id'); $rsm->addScalarResult('en_cours', 'en_cours'); $rsm->addScalarResult('refuser', 'refuser'); $rsm->addScalarResult('usr_id', 'usr_id'); $rsm->addScalarResult('date_modif', 'date_modif'); $rs = $em->createNativeQuery($sql, $rsm)->getResult(); $n = 0; foreach ($rs as $row) { try { $user = $em->createQuery('SELECT PARTIAL u.{id} FROM Phraseanet:User s WHERE u.id = :id')->setParameters(['id' => $row['usr_id']])->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true)->getSingleResult(); } catch (NoResultException $e) { $app['monolog']->addInfo(sprintf('Patch %s : Registration for user (%s) could not be turn into doctrine entity as user could not be found.', $this->get_release(), $row['usr_id'])); continue; } try { $collection = \collection::get_from_base_id($app, $row['base_id']); } catch (\Exception $e) { $app['monolog']->addInfo(sprintf('Patch %s : Registration for user (%s) could not be turn into doctrine entity as base with id (%s) could not be found.', $this->get_release(), $row['usr_id'], $row['base_id'])); continue; } $registration = new Registration(); $registration->setCollection($collection); $registration->setUser($user); $registration->setPending($row['en_cours']); $registration->setCreated(new \DateTime($row['date_modif'])); $registration->setRejected($row['refuser']); if ($n % 100 === 0) { $em->flush(); $em->clear(); } $n++; } $em->flush(); $em->clear(); }
public function postCreateFormAction(Request $request) { $collection = \collection::get_from_base_id($this->app, $request->request->get('base_id')); if (!$this->getAclForUser()->has_right_on_base($collection->get_base_id(), 'canaddrecord')) { throw new AccessDeniedHttpException('You can not create a story on this collection'); } $story = \record_adapter::createStory($this->app, $collection); $records = RecordsRequest::fromRequest($this->app, $request, true); foreach ($records as $record) { if ($story->hasChild($record)) { continue; } $story->appendChild($record); } $metadatas = []; foreach ($collection->get_databox()->get_meta_structure() as $meta) { if ($meta->get_thumbtitle()) { $value = $request->request->get('name'); } else { continue; } $metadatas[] = ['meta_struct_id' => $meta->get_id(), 'meta_id' => null, 'value' => $value]; break; } $story->set_metadatas($metadatas)->rebuild_subdefs(); $storyWZ = new StoryWZ(); $storyWZ->setUser($this->getAuthenticatedUser()); $storyWZ->setRecord($story); $manager = $this->getEntityManager(); $manager->persist($storyWZ); $manager->flush(); if ($request->getRequestFormat() == 'json') { $data = ['success' => true, 'message' => $this->app->trans('Story created'), 'WorkZone' => $storyWZ->getId(), 'story' => ['sbas_id' => $story->get_sbas_id(), 'record_id' => $story->get_record_id()]]; return $this->app->json($data); } return $this->app->redirectPath('prod_stories_story', ['sbas_id' => $storyWZ->getSbasId(), 'record_id' => $storyWZ->getRecordId()]); }
public function connect(Application $app) { $app['controller.prod.story'] = $this; $controllers = $app['controllers_factory']; $app['firewall']->addMandatoryAuthentication($controllers); $controllers->get('/create/', function (Application $app) { return $app['twig']->render('prod/Story/Create.html.twig', []); })->bind('prod_stories_create'); $controllers->post('/', function (Application $app, Request $request) { /* @var $request \Symfony\Component\HttpFoundation\Request */ $collection = \collection::get_from_base_id($app, $request->request->get('base_id')); if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($collection->get_base_id(), 'canaddrecord')) { throw new AccessDeniedHttpException('You can not create a story on this collection'); } $Story = \record_adapter::createStory($app, $collection); $records = RecordsRequest::fromRequest($app, $request, true); foreach ($records as $record) { if ($Story->hasChild($record)) { continue; } $Story->appendChild($record); } $metadatas = []; foreach ($collection->get_databox()->get_meta_structure() as $meta) { if ($meta->get_thumbtitle()) { $value = $request->request->get('name'); } else { continue; } $metadatas[] = ['meta_struct_id' => $meta->get_id(), 'meta_id' => null, 'value' => $value]; break; } $Story->set_metadatas($metadatas)->rebuild_subdefs(); $StoryWZ = new StoryWZ(); $StoryWZ->setUser($app['authentication']->getUser()); $StoryWZ->setRecord($Story); $app['EM']->persist($StoryWZ); $app['EM']->flush(); if ($request->getRequestFormat() == 'json') { $data = ['success' => true, 'message' => $app->trans('Story created'), 'WorkZone' => $StoryWZ->getId(), 'story' => ['sbas_id' => $Story->get_sbas_id(), 'record_id' => $Story->get_record_id()]]; return $app->json($data); } else { return $app->redirectPath('prod_stories_story', ['sbas_id' => $StoryWZ->getSbasId(), 'record_id' => $StoryWZ->getRecordId()]); } })->bind('prod_stories_do_create'); $controllers->get('/{sbas_id}/{record_id}/', function (Application $app, $sbas_id, $record_id) { $Story = new \record_adapter($app, $sbas_id, $record_id); $html = $app['twig']->render('prod/WorkZone/Story.html.twig', ['Story' => $Story]); return new Response($html); })->bind('prod_stories_story')->assert('sbas_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/{sbas_id}/{record_id}/addElements/', function (Application $app, Request $request, $sbas_id, $record_id) { $Story = new \record_adapter($app, $sbas_id, $record_id); if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) { throw new AccessDeniedHttpException('You can not add document to this Story'); } $n = 0; $records = RecordsRequest::fromRequest($app, $request, true); foreach ($records as $record) { if ($Story->hasChild($record)) { continue; } $Story->appendChild($record); $n++; } $data = ['success' => true, 'message' => $app->trans('%quantity% records added', ['%quantity%' => $n])]; if ($request->getRequestFormat() == 'json') { return $app->json($data); } else { return $app->redirectPath('prod_stories_story', ['sbas_id' => $sbas_id, 'record_id' => $record_id]); } })->assert('sbas_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/{sbas_id}/{record_id}/delete/{child_sbas_id}/{child_record_id}/', function (Application $app, Request $request, $sbas_id, $record_id, $child_sbas_id, $child_record_id) { $Story = new \record_adapter($app, $sbas_id, $record_id); $record = new \record_adapter($app, $child_sbas_id, $child_record_id); if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($Story->get_base_id(), 'canmodifrecord')) { throw new AccessDeniedHttpException('You can not add document to this Story'); } $Story->removeChild($record); $data = ['success' => true, 'message' => $app->trans('Record removed from story')]; if ($request->getRequestFormat() == 'json') { return $app->json($data); } else { return $app->redirectPath('prod_stories_story', ['sbas_id' => $sbas_id, 'record_id' => $record_id]); } })->bind('prod_stories_story_remove_element')->assert('sbas_id', '\\d+')->assert('record_id', '\\d+')->assert('child_sbas_id', '\\d+')->assert('child_record_id', '\\d+'); /** * Get the Basket reorder form */ $controllers->get('/{sbas_id}/{record_id}/reorder/', function (Application $app, $sbas_id, $record_id) { $story = new \record_adapter($app, $sbas_id, $record_id); if (!$story->is_grouping()) { throw new \Exception('This is not a story'); } return new Response($app['twig']->render('prod/Story/Reorder.html.twig', ['story' => $story])); })->bind('prod_stories_story_reorder')->assert('sbas_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/{sbas_id}/{record_id}/reorder/', function (Application $app, $sbas_id, $record_id) { $ret = ['success' => false, 'message' => $app->trans('An error occured')]; try { $story = new \record_adapter($app, $sbas_id, $record_id); if (!$story->is_grouping()) { throw new \Exception('This is not a story'); } if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($story->get_base_id(), 'canmodifrecord')) { throw new ControllerException($app->trans('You can not edit this story')); } $sql = 'UPDATE regroup SET ord = :ord WHERE rid_parent = :parent_id AND rid_child = :children_id'; $stmt = $story->get_databox()->get_connection()->prepare($sql); foreach ($app['request']->request->get('element') as $record_id => $ord) { $params = [':ord' => $ord, ':parent_id' => $story->get_record_id(), ':children_id' => $record_id]; $stmt->execute($params); } $stmt->closeCursor(); $ret = ['success' => true, 'message' => $app->trans('Story updated')]; } catch (ControllerException $e) { $ret = ['success' => false, 'message' => $e->getMessage()]; } catch (\Exception $e) { } return $app->json($ret); })->assert('sbas_id', '\\d+')->assert('record_id', '\\d+'); return $controllers; }
/** * Returns the collection to which the feed belongs. * * @param Application $app * * @return \collection */ public function getCollection(Application $app) { if ($this->getBaseId() !== null) { return \collection::get_from_base_id($app, $this->getBaseId()); } }
protected function print_preview($withtdm, $write_caption) { if ($withtdm === true) { $this->print_thumbnailGrid($this->pdf, $this->records, true); } foreach ($this->records as $krec => $rec) { /* @var $rec record_adapter */ $this->pdf->AddPage(); if ($withtdm === "CALCPAGES") { $rec->setNumber($this->pdf->PageNo()); } $lmargin = $this->pdf->GetX(); $himg = 0; $y = 0; $miniConv = NULL; $LEFT__TEXT = ""; $LEFT__IMG = NULL; $RIGHT_TEXT = ""; $RIGHT_IMG = NULL; $LEFT__IMG = $this->app['root.path'] . "/config/minilogos/logopdf_" . $rec->get_sbas_id() . ".jpg"; if (!is_file($LEFT__IMG)) { $databox = $rec->get_databox(); $str = $databox->get_sxml_structure(); $vn = (string) $str->pdfPrintLogo; if ($vn * 1 == 1) { $LEFT__TEXT = $databox->get_label($this->app['locale']); } } $collection = \collection::get_from_base_id($this->app, $rec->get_base_id()); $vn = ""; if (false !== ($str = simplexml_load_string($collection->get_prefs()))) { $vn = (string) $str->pdfPrintappear; } if ($vn == "" || $vn == "1") { $RIGHT_TEXT = \phrasea::bas_labels($rec->get_base_id(), $this->app); } elseif ($vn == "2") { $RIGHT_IMG = $this->app['root.path'] . "/config/minilogos/" . $rec->get_base_id(); } $xtmp = $this->pdf->GetX(); $ytmp = $this->pdf->GetY(); $this->pdf->SetFont(PhraseaPDF::FONT, '', 12); $this->pdf->SetFillColor(220, 220, 220); $y = $this->pdf->GetY(); $this->pdf->MultiCell(95, 7, $LEFT__TEXT, "LTB", "L", 1); $y2 = $this->pdf->GetY(); $h = $y2 - $y; $this->pdf->SetY($y); $this->pdf->SetX(105); $this->pdf->Cell(95, $h, $RIGHT_TEXT, "TBR", 1, "R", 1); if ($LEFT__TEXT == "" && is_file($LEFT__IMG)) { if ($size = @getimagesize($LEFT__IMG)) { $wmm = (int) $size[0] * 25.4 / 72; $hmm = (int) $size[1] * 25.4 / 72; if ($hmm > 6) { $coeff = $hmm / 6; $wmm = (int) $wmm / $coeff; $hmm = (int) $hmm / $coeff; } $this->pdf->Image($LEFT__IMG, $xtmp + 0.5, $ytmp + 0.5, $wmm, $hmm); } } if ($RIGHT_IMG != NULL && is_file($RIGHT_IMG)) { if ($size = @getimagesize($RIGHT_IMG)) { if ($size[2] == '1') { if (!isset($miniConv[$RIGHT_IMG])) { $tmp_filename = tempnam('minilogos/', 'gif4fpdf'); $img = imagecreatefromgif($RIGHT_IMG); imageinterlace($img, 0); imagepng($img, $tmp_filename); rename($tmp_filename, $tmp_filename . '.png'); $miniConv[$RIGHT_IMG] = $tmp_filename . '.png'; $RIGHT_IMG = $tmp_filename . '.png'; } else { $RIGHT_IMG = $miniConv[$RIGHT_IMG]; } $wmm = (int) $size[0] * 25.4 / 72; $hmm = (int) $size[1] * 25.4 / 72; if ($hmm > 6) { $coeff = $hmm / 6; $wmm = (int) $wmm / $coeff; $hmm = (int) $hmm / $coeff; } $tt = 0; if ($hmm < 6) { $tt = (6 - $hmm) / 2; } $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5 + $tt); } else { $wmm = (int) $size[0] * 25.4 / 72; $hmm = (int) $size[1] * 25.4 / 72; if ($hmm > 6) { $coeff = $hmm / 6; $wmm = (int) $wmm / $coeff; $hmm = (int) $hmm / $coeff; } $this->pdf->Image($RIGHT_IMG, 200 - 0.5 - $wmm, $ytmp + 0.5); } } } $y = $this->pdf->GetY() + 5; $subdef = $rec->get_subdef('preview'); if ($subdef->get_type() !== \media_subdef::TYPE_IMAGE) { $subdef = $rec->get_thumbnail(); } $f = $subdef->get_pathfile(); if (!$this->app->getAclForUser($this->app->getAuthenticatedUser())->has_right_on_base($rec->get_base_id(), "nowatermark") && $subdef->get_type() == \media_subdef::TYPE_IMAGE) { $f = \recordutils_image::watermark($this->app, $subdef); } // original height / original width x new width = new height $wimg = $himg = 150; // preview dans un carre de 150 mm // 1px = 3.77952 mm $finalWidth = round($subdef->get_width() / 3.779528, 2); $finalHeight = round($subdef->get_height() / 3.779528, 2); $aspectH = $finalWidth / $finalHeight; $aspectW = $finalHeight / $finalWidth; if ($finalWidth > 0 && $finalHeight > 0) { if ($finalWidth > $finalHeight && $finalWidth > $wimg) { $finalWidth = $wimg; $finalHeight = $wimg * $aspectW; } else { if ($finalHeight > $finalWidth && $finalHeight > $himg) { $finalHeight = $himg; $finalWidth = $himg * $aspectH; } else { if ($finalHeight == $finalWidth & $finalWidth > $wimg) { $finalHeight = $wimg; $finalWidth = $himg; } } } } $this->pdf->Image($f, (210 - $finalWidth) / 2, $y, $finalWidth, $finalHeight); if ($miniConv != NULL) { foreach ($miniConv as $oneF) { unlink($oneF); } } $this->pdf->SetXY($lmargin, $y += $finalHeight + 5); $nf = 0; if ($write_caption) { foreach ($rec->get_caption()->get_fields() as $field) { /* @var $field caption_field */ if ($nf > 0) { $this->pdf->Write(6, "\n"); } $this->pdf->SetFont(PhraseaPDF::FONT, 'B', 12); $this->pdf->Write(5, $field->get_name() . " : "); $this->pdf->SetFont(PhraseaPDF::FONT, '', 12); $t = str_replace(["<", ">", "&"], ["<", ">", "&"], strip_tags($field->get_serialized_values())); $this->pdf->Write(5, $t); $nf++; } } } return; }
public function register(Application $app) { $app['border-manager'] = $app->share(function (Application $app) { $borderManager = new Manager($app); try { $borderManager->setPdfToText($app['xpdf.pdftotext']); } catch (BinaryNotFoundException $e) { } $options = $app['conf']->get('border-manager'); $registeredCheckers = []; if ($options['enabled']) { foreach ($options['checkers'] as $checker) { if (!isset($checker['type'])) { continue; } if (isset($checker['enabled']) && $checker['enabled'] !== true) { continue; } $className = sprintf('\\Alchemy\\Phrasea\\Border\\%s', $checker['type']); if (!class_exists($className)) { $app['monolog']->error(sprintf('Border manager checker, invalid checker %s', $checker['type'])); continue; } $options = []; if (isset($checker['options']) && is_array($checker['options'])) { $options = $checker['options']; } try { $checkerObj = new $className($app, $options); if (isset($checker['databoxes'])) { $databoxes = []; foreach ($checker['databoxes'] as $sbas_id) { try { $databoxes[] = $app['phraseanet.appbox']->get_databox($sbas_id); } catch (\Exception $e) { throw new \InvalidArgumentException('Invalid databox option'); } } $checkerObj->restrictToDataboxes($databoxes); } if (isset($checker['collections'])) { $collections = []; foreach ($checker['collections'] as $base_id) { try { $collections[] = \collection::get_from_base_id($app, $base_id); } catch (\Exception $e) { throw new \InvalidArgumentException('Invalid collection option'); } } $checkerObj->restrictToCollections($collections); } $registeredCheckers[] = $checkerObj; } catch (\InvalidArgumentException $e) { $app['monolog']->error(sprintf('Border manager checker InvalidArgumentException : %s', $e->getMessage())); } catch (\LogicException $e) { $app['monolog']->error(sprintf('Border manager checker LogicException : %s', $e->getMessage())); } } $borderManager->registerCheckers($registeredCheckers); } return $borderManager; }); $app['border-manager.mime-guesser-configuration'] = $app->share(function (Application $app) { return new MimeGuesserConfiguration($app['conf']); }); }
private function doDeliverPermalink(PhraseaApplication $app, $sbas_id, $record_id, $token, $subdef) { $databox = $app['phraseanet.appbox']->get_databox((int) $sbas_id); $record = $this->retrieveRecord($app, $databox, $token, $record_id, $subdef); $watermark = $stamp = false; if ($app['authentication']->isAuthenticated()) { $watermark = !$app['acl']->get($app['authentication']->getUser())->has_right_on_base($record->get_base_id(), 'nowatermark'); if ($watermark) { $repository = $app['EM']->getRepository('Phraseanet:BasketElement'); if (count($repository->findReceivedValidationElementsByRecord($record, $app['authentication']->getUser())) > 0) { $watermark = false; } elseif (count($repository->findReceivedElementsByRecord($record, $app['authentication']->getUser())) > 0) { $watermark = false; } } $response = $this->deliverContent($app['request'], $record, $subdef, $watermark, $stamp, $app); $linkToCaption = $app->url("permalinks_caption", ['sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token]); $response->headers->set('Link', $linkToCaption); return $response; } $collection = \collection::get_from_base_id($app, $record->get_base_id()); switch ($collection->get_pub_wm()) { default: case 'none': $watermark = false; break; case 'stamp': $stamp = true; break; case 'wm': $watermark = false; break; } $response = $this->deliverContent($app['request'], $record, $subdef, $watermark, $stamp, $app); $linkToCaption = $app->url("permalinks_caption", ['sbas_id' => $sbas_id, 'record_id' => $record_id, 'token' => $token]); $response->headers->set('Link', $linkToCaption); return $response; }
/** * @param Request $request * @param int $id * @return Response */ function updateAction(Request $request, $id) { if ('' === ($title = trim($request->request->get('title', '')))) { $this->app->abort(400, "Bad request"); } $feedRepository = $this->getFeedRepository(); /** @var Feed $feed */ $feed = $feedRepository->find($id); if (!$feed->isOwner($this->getAuthenticatedUser())) { return $this->app->redirectPath('admin_feeds_feed', ['id' => $request->attributes->get('id'), 'error' => $this->app->trans('You are not the owner of this feed, you can not edit it')]); } try { $collection = \collection::get_from_base_id($this->app, $request->request->get('base_id')); } catch (\Exception $e) { $collection = null; } $feed->setTitle($title); $feed->setSubtitle($request->request->get('subtitle', '')); $feed->setCollection($collection); $feed->setIsPublic('1' === $request->request->get('public')); $manager = $this->getObjectManager(); $manager->persist($feed); $manager->flush(); return $this->app->redirectPath('admin_feeds_list'); }
/** * @covers Alchemy\Phrasea\Controller\Admin\Bas::unmount */ public function testPostUnmountCollection() { $this->setAdmin(true); $collection = $this->createOneCollection(); $this->XMLHTTPRequest('POST', '/admin/collection/' . $collection->get_base_id() . '/unmount/'); $json = $this->getJson(self::$DI['client']->getResponse()); $this->assertTrue($json->success); try { \collection::get_from_base_id(self::$DI['app'], $collection->get_base_id()); $this->fail('Collection not unmounted'); } catch (\Exception_Databox_CollectionNotFound $e) { } unset($collection); }
public function get_time() { $this->base_id = (int) $this->request->get('base_id'); $sql = "SELECT u.id, time_limited, limited_from, limited_to\n FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)\n WHERE (u.id = " . implode(' OR u.id = ', $this->users) . ")\n AND bu.base_id = :base_id"; $conn = $this->app['phraseanet.appbox']->get_connection(); $stmt = $conn->prepare($sql); $stmt->execute([':base_id' => $this->base_id]); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $time_limited = -1; $limited_from = $limited_to = false; foreach ($rs as $row) { if ($time_limited < 0) { $time_limited = $row['time_limited']; } if ($time_limited < 2 && $row['time_limited'] != $row['time_limited']) { $time_limited = 2; } if ($limited_from !== '' && trim($row['limited_from']) != '0000-00-00 00:00:00') { $limited_from = $limited_from === false ? $row['limited_from'] : ($limited_from == $row['limited_from'] ? $limited_from : ''); } if ($limited_to !== '' && trim($row['limited_to']) != '0000-00-00 00:00:00') { $limited_to = $limited_to === false ? $row['limited_to'] : ($limited_to == $row['limited_to'] ? $limited_to : ''); } } if ($limited_from) { $date_obj_from = new \DateTime($limited_from); $limited_from = $date_obj_from->format('Y-m-d'); } if ($limited_to) { $date_obj_to = new \DateTime($limited_to); $limited_to = $date_obj_to->format('Y-m-d'); } $datas = ['time_limited' => $time_limited, 'limited_from' => $limited_from, 'limited_to' => $limited_to]; $this->users_datas = $datas; return ['datas' => $this->users_datas, 'users' => $this->users, 'users_serial' => implode(';', $this->users), 'base_id' => $this->base_id, 'collection' => \collection::get_from_base_id($this->app, $this->base_id)]; }
public function setUp() { parent::setUp(); if (null !== self::$DI) { unset(self::$DI['app']['dbal.provider']); } self::$DI = new \Pimple(); ini_set('memory_limit', '4096M'); \PHPUnit_Framework_Error_Warning::$enabled = true; \PHPUnit_Framework_Error_Notice::$enabled = true; self::$DI['app'] = self::$DI->share(function ($DI) { return $this->loadApp('/lib/Alchemy/Phrasea/Application/Root.php'); }); self::$DI['cli'] = self::$DI->share(function ($DI) { return $this->loadCLI(); }); self::$DI['local-guzzle'] = self::$DI->share(function ($DI) { return new Guzzle(self::$DI['app']['conf']->get('servername')); }); self::$DI['client'] = self::$DI->share(function ($DI) { return new Client($DI['app'], []); }); self::$DI['user'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['test_phpunit']); }); self::$DI['user_1'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['user_1']); }); self::$DI['user_2'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['user_2']); }); self::$DI['user_3'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['user_3']); }); self::$DI['user_guest'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['user_guest']); }); self::$DI['user_notAdmin'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['test_phpunit_not_admin']); }); self::$DI['user_alt1'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['test_phpunit_alt1']); }); self::$DI['user_alt2'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['test_phpunit_alt2']); }); self::$DI['user_template'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.user']->getRepository()->find(self::$fixtureIds['user']['user_template']); }); self::$DI['registration_1'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.registration']->getRepository()->find(self::$fixtureIds['registrations']['registration_1']); }); self::$DI['registration_2'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.registration']->getRepository()->find(self::$fixtureIds['registrations']['registration_2']); }); self::$DI['registration_3'] = self::$DI->share(function ($DI) { return $DI['app']['manipulator.registration']->getRepository()->find(self::$fixtureIds['registrations']['registration_3']); }); self::$DI['oauth2-app-user'] = self::$DI->share(function ($DI) { return new \API_OAuth2_Application($DI['app'], self::$fixtureIds['oauth']['user']); }); self::$DI['oauth2-app-user_notAdmin'] = self::$DI->share(function ($DI) { return new \API_OAuth2_Application($DI['app'], self::$fixtureIds['oauth']['user_notAdmin']); }); self::$DI['logger'] = self::$DI->share(function () { $logger = new Logger('tests'); $logger->pushHandler(new NullHandler()); return $logger; }); self::$DI['collection'] = self::$DI->share(function ($DI) { return collection::get_from_base_id($DI['app'], self::$fixtureIds['collection']['coll']); }); self::$DI['collection_no_access'] = self::$DI->share(function ($DI) { return collection::get_from_base_id($DI['app'], self::$fixtureIds['collection']['coll_no_access']); }); self::$DI['collection_no_access_by_status'] = self::$DI->share(function ($DI) { return collection::get_from_base_id($DI['app'], self::$fixtureIds['collection']['coll_no_status']); }); if (!self::$booted) { if (!self::$DI['app']['phraseanet.configuration-tester']->isInstalled()) { echo "[0;31mPhraseanet is not set up[0;37m\n"; exit(1); } self::$fixtureIds = array_merge(self::$fixtureIds, json_decode(file_get_contents(__DIR__ . '/../fixtures.json'), true)); self::resetUsersRights(self::$DI['app'], self::$DI['user']); self::resetUsersRights(self::$DI['app'], self::$DI['user_notAdmin']); self::$booted = true; } self::$DI['lazaret_1'] = self::$DI->share(function ($DI) { return $DI['app']['EM']->find('Phraseanet:LazaretFile', self::$fixtureIds['lazaret']['lazaret_1']); }); foreach (range(1, 7) as $i) { self::$DI['record_' . $i] = self::$DI->share(function ($DI) use($i) { return new \record_adapter($DI['app'], self::$fixtureIds['databox']['records'], self::$fixtureIds['record']['record_' . $i]); }); } foreach (range(1, 3) as $i) { self::$DI['record_story_' . $i] = self::$DI->share(function ($DI) use($i) { return new \record_adapter($DI['app'], self::$fixtureIds['databox']['records'], self::$fixtureIds['record']['record_story_' . $i]); }); } self::$DI['record_no_access_resolver'] = self::$DI->protect(function () { $id = 'no_access'; if (isset(self::$fixtureIds['records'][$id])) { return self::$fixtureIds['records'][$id]; } self::$recordsInitialized[] = $id; $file = new File(self::$DI['app'], self::$DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), self::$DI['collection_no_access']); $record = record_adapter::createFromFile($file, self::$DI['app']); self::$DI['app']['subdef.generator']->generateSubdefs($record); self::$fixtureIds['records'][$id] = $record->get_record_id(); return self::$fixtureIds['records'][$id]; }); self::$DI['record_no_access_by_status_resolver'] = self::$DI->protect(function () { $id = 'no_access_by_status'; if (isset(self::$fixtureIds['records'][$id])) { return self::$fixtureIds['records'][$id]; } self::$recordsInitialized[] = $id; $file = new File(self::$DI['app'], self::$DI['app']['mediavorus']->guess(__DIR__ . '/../files/cestlafete.jpg'), self::$DI['collection_no_access_by_status']); $record = record_adapter::createFromFile($file, self::$DI['app']); self::$DI['app']['subdef.generator']->generateSubdefs($record); self::$fixtureIds['records'][$id] = $record->get_record_id(); return self::$fixtureIds['records'][$id]; }); self::$DI['record_no_access'] = self::$DI->share(function ($DI) { return new \record_adapter($DI['app'], self::$fixtureIds['databox']['records'], $DI['record_no_access_resolver']()); }); self::$DI['record_no_access_by_status'] = self::$DI->share(function ($DI) { return new \record_adapter($DI['app'], self::$fixtureIds['databox']['records'], $DI['record_no_access_by_status_resolver']()); }); if (!self::$testCaseBooted) { $this->bootTestCase(); } self::$testCaseBooted = true; }
/** * Upload processus * * @param Application $app The Silex application * @param Request $request The current request * * parameters : 'bas_id' int (mandatory) : The id of the destination collection * 'status' array (optional) : The status to set to new uploaded files * 'attributes' array (optional) : Attributes id's to attach to the uploaded files * 'forceBehavior' int (optional) : Force upload behavior * - 0 Force record * - 1 Force lazaret * * @return Response */ public function upload(Application $app, Request $request) { $datas = ['success' => false, 'code' => null, 'message' => '', 'element' => '', 'reasons' => [], 'id' => '']; if (null === $request->files->get('files')) { throw new BadRequestHttpException('Missing file parameter'); } if (count($request->files->get('files')) > 1) { throw new BadRequestHttpException('Upload is limited to 1 file per request'); } $base_id = $request->request->get('base_id'); if (!$base_id) { throw new BadRequestHttpException('Missing base_id parameter'); } if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($base_id, 'canaddrecord')) { throw new AccessDeniedHttpException('User is not allowed to add record on this collection'); } $file = current($request->files->get('files')); if (!$file->isValid()) { throw new BadRequestHttpException('Uploaded file is invalid'); } try { // Add file extension, so mediavorus can guess file type for octet-stream file $uploadedFilename = $file->getRealPath(); $renamedFilename = $file->getRealPath() . '.' . pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); $app['filesystem']->rename($uploadedFilename, $renamedFilename); $media = $app['mediavorus']->guess($renamedFilename); $collection = \collection::get_from_base_id($app, $base_id); $lazaretSession = new LazaretSession(); $lazaretSession->setUser($app['authentication']->getUser()); $app['EM']->persist($lazaretSession); $packageFile = new File($app, $media, $collection, $file->getClientOriginalName()); $postStatus = $request->request->get('status'); if (isset($postStatus[$collection->get_base_id()]) && is_array($postStatus[$collection->get_base_id()])) { $postStatus = $postStatus[$collection->get_base_id()]; $status = ''; foreach (range(0, 31) as $i) { $status .= isset($postStatus[$i]) ? $postStatus[$i] ? '1' : '0' : '0'; } $packageFile->addAttribute(new Status($app, strrev($status))); } $forceBehavior = $request->request->get('forceAction'); $reasons = []; $elementCreated = null; $callback = function ($element, $visa, $code) use($app, &$reasons, &$elementCreated) { foreach ($visa->getResponses() as $response) { if (!$response->isOk()) { $reasons[] = $response->getMessage($app['translator']); } } $elementCreated = $element; }; $code = $app['border-manager']->process($lazaretSession, $packageFile, $callback, $forceBehavior); $app['filesystem']->rename($renamedFilename, $uploadedFilename); if (!!$forceBehavior) { $reasons = []; } if ($elementCreated instanceof \record_adapter) { $id = $elementCreated->get_serialize_key(); $element = 'record'; $message = $app->trans('The record was successfully created'); $app['phraseanet.SE']->addRecord($elementCreated); // try to create thumbnail from data URI if ('' !== ($b64Image = $request->request->get('b64_image', ''))) { try { $dataUri = Parser::parse($b64Image); $fileName = $app['temporary-filesystem']->createTemporaryFile('base_64_thumb', null, "png"); file_put_contents($fileName, $dataUri->getData()); $media = $app['mediavorus']->guess($fileName); $app['subdef.substituer']->substitute($elementCreated, 'thumbnail', $media); $app['phraseanet.logger']($elementCreated->get_databox())->log($elementCreated, \Session_Logger::EVENT_SUBSTITUTE, 'thumbnail', ''); unset($media); $app['temporary-filesystem']->clean('base_64_thumb'); } catch (DataUriException $e) { } } } else { $app['dispatcher']->dispatch(PhraseaEvents::LAZARET_CREATE, new LazaretEvent($elementCreated)); $id = $elementCreated->getId(); $element = 'lazaret'; $message = $app->trans('The file was moved to the quarantine'); } $datas = ['success' => true, 'code' => $code, 'message' => $message, 'element' => $element, 'reasons' => $reasons, 'id' => $id]; } catch (\Exception $e) { $datas['message'] = $app->trans('Unable to add file to Phraseanet'); } $response = $app->json($datas); // IE 7 and 8 does not correctly handle json response in file API // lets send them an html content-type header $response->headers->set('Content-type', 'text/html'); return $response; }
public function connect(Application $app) { $app['controller.admin.users'] = $this; $controllers = $app['controllers_factory']; $app['firewall']->addMandatoryAuthentication($controllers); $controllers->before(function (Request $request) use($app) { $app['firewall']->requireAccessToModule('admin')->requireRight('manageusers'); }); $controllers->post('/rights/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers.html.twig', $rights->get_users_rights()); }); $controllers->get('/rights/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers.html.twig', $rights->get_users_rights()); }); $controllers->post('/rights/reset/', function (Application $app, Request $request) { try { $datas = ['error' => false]; $helper = new UserHelper\Edit($app, $request); $helper->resetRights(); } catch (\Exception $e) { $datas['error'] = true; $datas['message'] = $e->getMessage(); } return $app->json($datas); })->bind('admin_users_rights_reset'); $controllers->post('/delete/', function (Application $app) { $module = new UserHelper\Edit($app, $app['request']); $module->delete_users(); return $app->redirectPath('admin_users_search'); }); $controllers->post('/rights/apply/', function (Application $app) { $datas = ['error' => true]; try { $rights = new UserHelper\Edit($app, $app['request']); if (!$app['request']->request->get('reset_before_apply')) { $rights->apply_rights(); } if ($app['request']->request->get('template')) { if ($app['request']->request->get('reset_before_apply')) { $rights->resetRights(); } $rights->apply_template(); } $rights->apply_infos(); $datas = ['error' => false]; } catch (\Exception $e) { $datas['message'] = $e->getMessage(); } return $app->json($datas); })->bind('admin_users_rights_apply'); $controllers->post('/rights/quotas/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers_quotas.html.twig', $rights->get_quotas()); }); $controllers->post('/rights/quotas/apply/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); $rights->apply_quotas(); return $app->json(['message' => '', 'error' => false]); }); $controllers->post('/rights/time/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers_timelimit.html.twig', $rights->get_time()); }); $controllers->post('/rights/time/sbas/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers_timelimit_sbas.html.twig', $rights->get_time_sbas()); }); $controllers->post('/rights/time/apply/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); $rights->apply_time(); return $app->json(['message' => '', 'error' => false]); }); $controllers->post('/rights/masks/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); return $app['twig']->render('admin/editusers_masks.html.twig', $rights->get_masks()); }); $controllers->post('/rights/masks/apply/', function (Application $app) { $rights = new UserHelper\Edit($app, $app['request']); $rights->apply_masks(); return $app->json(['message' => '', 'error' => false]); }); $controllers->match('/search/', function (Application $app) { $users = new UserHelper\Manage($app, $app['request']); return $app['twig']->render('admin/users.html.twig', $users->search()); })->bind('admin_users_search'); $controllers->post('/search/export/', function () use($app) { $request = $app['request']; $users = new UserHelper\Manage($app, $app['request']); $userTable = [['ID', 'Login', 'Last Name', 'First Name', 'E-Mail', 'Created', 'Updated', 'Address', 'City', 'Zip', 'Country', 'Phone', 'Fax', 'Job', 'Company', 'Position']]; foreach ($users->export() as $user) { $userTable[] = [$user->getId(), $user->getLogin(), $user->getLastName(), $user->getFirstName(), $user->getEmail(), $user->getCreated()->format(DATE_ATOM), $user->getUpdated()->format(DATE_ATOM), $user->getAddress(), $user->getCity(), $user->getZipCode(), $user->getCountry(), $user->getPhone(), $user->getFax(), $user->getJob(), $user->getCompany(), $user->getActivity()]; } $CSVDatas = \format::arr_to_csv($userTable); $response = new Response($CSVDatas, 200, ['Content-Type' => 'text/csv']); $response->headers->set('Content-Disposition', 'attachment; filename=export.csv'); return $response; })->bind('admin_users_search_export'); $controllers->post('/apply_template/', function () use($app) { $users = new UserHelper\Edit($app, $app['request']); if ($app['request']->request->get('reset_before_apply')) { $users->resetRights(); } $users->apply_template(); return $app->redirectPath('admin_users_search'); })->bind('admin_users_apply_template'); $controllers->get('/typeahead/search/', function (Application $app) { $request = $app['request']; $user_query = new \User_Query($app); $like_value = $request->query->get('term'); $rights = $request->query->get('filter_rights') ?: []; $have_right = $request->query->get('have_right') ?: []; $have_not_right = $request->query->get('have_not_right') ?: []; $on_base = $request->query->get('on_base') ?: []; $elligible_users = $user_query->on_sbas_where_i_am($app['acl']->get($app['authentication']->getUser()), $rights)->like(\User_Query::LIKE_EMAIL, $like_value)->like(\User_Query::LIKE_FIRSTNAME, $like_value)->like(\User_Query::LIKE_LASTNAME, $like_value)->like(\User_Query::LIKE_LOGIN, $like_value)->like_match(\User_Query::LIKE_MATCH_OR)->who_have_right($have_right)->who_have_not_right($have_not_right)->on_base_ids($on_base)->execute()->get_results(); $datas = []; foreach ($elligible_users as $user) { $datas[] = ['email' => $user->getEmail() ?: '', 'login' => $user->getLogin() ?: '', 'name' => $user->getDisplayName(), 'id' => $user->getId()]; } return $app->json($datas); }); $controllers->post('/create/', function (Application $app) { $datas = ['error' => false, 'message' => '', 'data' => null]; try { $request = $app['request']; $module = new UserHelper\Manage($app, $app['request']); if ($request->request->get('template') == '1') { $user = $module->create_template(); } else { $user = $module->create_newuser(); } if (!$user instanceof User) { throw new \Exception('Unknown error'); } $datas['data'] = $user->getId(); } catch (\Exception $e) { $datas['error'] = true; if ($request->request->get('template') == '1') { $datas['message'] = $app->trans('Unable to create template, the name is already used.'); } else { $datas['message'] = $app->trans('Unable to create the user.'); } } return $app->json($datas); }); $controllers->post('/export/csv/', function (Application $app) { $request = $app['request']; $user_query = new \User_Query($app); $like_value = $request->request->get('like_value'); $like_field = $request->request->get('like_field'); $on_base = $request->request->get('base_id') ?: null; $on_sbas = $request->request->get('sbas_id') ?: null; $elligible_users = $user_query->on_bases_where_i_am($app['acl']->get($app['authentication']->getUser()), ['canadmin'])->like($like_field, $like_value)->on_base_ids($on_base)->on_sbas_ids($on_sbas); $offset = 0; $buffer = []; $buffer[] = ['ID', 'Login', $app->trans('admin::compte-utilisateur nom'), $app->trans('admin::compte-utilisateur prenom'), $app->trans('admin::compte-utilisateur email'), 'CreationDate', 'ModificationDate', $app->trans('admin::compte-utilisateur adresse'), $app->trans('admin::compte-utilisateur ville'), $app->trans('admin::compte-utilisateur code postal'), $app->trans('admin::compte-utilisateur pays'), $app->trans('admin::compte-utilisateur telephone'), $app->trans('admin::compte-utilisateur fax'), $app->trans('admin::compte-utilisateur poste'), $app->trans('admin::compte-utilisateur societe'), $app->trans('admin::compte-utilisateur activite')]; do { $elligible_users->limit($offset, 20); $offset += 20; $results = $elligible_users->execute()->get_results(); foreach ($results as $user) { $buffer[] = [$user->getId(), $user->getLogin(), $user->getLastName(), $user->getFirstName(), $user->getEmail(), $app['date-formatter']->format_mysql($user->getCreated()), $app['date-formatter']->format_mysql($user->getUpdated()), $user->getAddress(), $user->getCity(), $user->getZipCode(), $user->getCountry(), $user->getPhone(), $user->getFax(), $user->getJob(), $user->getCompany(), $user->getActivity()]; } } while (count($results) > 0); $out = \format::arr_to_csv($buffer); $response = new Response($out, 200, ['Content-type' => 'text/csv', 'Content-Disposition' => 'attachment; filename=export.csv']); $response->setCharset('UTF-8'); return $response; })->bind('admin_users_export_csv'); $controllers->get('/registrations/', function (Application $app) { $app['manipulator.registration']->deleteOldRegistrations(); $models = $app['manipulator.user']->getRepository()->findModelOf($app['authentication']->getUser()); $userRegistrations = []; foreach ($app['manipulator.registration']->getRepository()->getUserRegistrations($app['authentication']->getUser(), $app['acl']->get($app['authentication']->getUser())->get_granted_base(['canadmin'])) as $registration) { $user = $registration->getUser(); $userRegistrations[$user->getId()]['user'] = $user; $userRegistrations[$user->getId()]['registrations'][$registration->getBaseid()] = $registration; } return $app['twig']->render('admin/user/registrations.html.twig', ['user_registrations' => $userRegistrations, 'models' => $models]); })->bind('users_display_registrations'); $controllers->post('/registrations/', function (Application $app, Request $request) { $templates = $deny = $accept = $options = []; foreach ($request->request->get('template', []) as $tmp) { if ('' === trim($tmp)) { continue; } $tmp = explode('_', $tmp); if (count($tmp) == 2) { $templates[$tmp[0]] = $tmp[1]; } } foreach ($request->request->get('deny', []) as $den) { $den = explode('_', $den); if (count($den) == 2 && !isset($templates[$den[0]])) { $deny[$den[0]][$den[1]] = $den[1]; } } foreach ($request->request->get('accept', []) as $acc) { $acc = explode('_', $acc); if (count($acc) == 2 && !isset($templates[$acc[0]])) { $accept[$acc[0]][$acc[1]] = $acc[1]; $options[$acc[0]][$acc[1]] = ['HD' => false, 'WM' => false]; } } foreach ($request->request->get('accept_hd', []) as $accHD) { $accHD = explode('_', $accHD); if (count($accHD) == 2 && isset($accept[$accHD[0]]) && isset($options[$accHD[0]][$accHD[1]])) { $options[$accHD[0]][$accHD[1]]['HD'] = true; } } foreach ($request->request->get('watermark', []) as $wm) { $wm = explode('_', $wm); if (count($wm) == 2 && isset($accept[$wm[0]]) && isset($options[$wm[0]][$wm[1]])) { $options[$wm[0]][$wm[1]]['WM'] = true; } } if (count($templates) > 0 || count($deny) > 0 || count($accept) > 0) { $cacheToUpdate = $done = []; foreach ($templates as $usr => $template_id) { if (null === ($user = $app['manipulator.user']->getRepository()->find($usr))) { $app->abort(400, srpintf("User with id % in provided in 'template' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; $user_template = $app['manipulator.user']->getRepository()->find($template_id); $collections = $app['acl']->get($user_template)->get_granted_base(); $baseIds = array_keys($collections); $app['acl']->get($user)->apply_model($user_template, $baseIds); foreach ($collections as $collection) { $done[$usr][$collection->get_base_id()] = true; } $app['manipulator.registration']->deleteUserRegistrations($user, $collections); } foreach ($deny as $usr => $bases) { if (null === ($user = $app['manipulator.user']->getRepository()->find($usr))) { $app->abort(400, srpintf("User with id % in provided in 'deny' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; foreach ($app['manipulator.registration']->getRepository()->getUserRegistrations($user, array_map(function ($baseId) use($app) { return \collection::get_from_base_id($app, $baseId); }, $bases)) as $registration) { $app['manipulator.registration']->rejectRegistration($registration); $done[$usr][$registration->getBaseId()] = false; } } foreach ($accept as $usr => $bases) { if (null === ($user = $app['manipulator.user']->getRepository()->find($usr))) { $app->abort(400, srpintf("User with id % in provided in 'accept' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; foreach ($app['manipulator.registration']->getRepository()->getUserRegistrations($user, array_map(function ($baseId) use($app) { return \collection::get_from_base_id($app, $baseId); }, $bases)) as $registration) { $done[$usr][$registration->getBaseId()] = true; $app['manipulator.registration']->acceptRegistration($registration, $options[$usr][$registration->getBaseId()]['HD'], $options[$usr][$registration->getBaseId()]['WM']); } } array_walk($cacheToUpdate, function (User $user) use($app) { $app['acl']->get($user)->delete_data_from_cache(); }); unset($cacheToUpdate); foreach ($done as $usr => $bases) { $user = $app['manipulator.user']->getRepository()->find($usr); $acceptColl = $denyColl = []; foreach ($bases as $bas => $isok) { $collection = \collection::get_from_base_id($app, $bas); if ($isok) { $acceptColl[] = $collection->get_label($app['locale']); continue; } $denyColl[] = $collection->get_label($app['locale']); } if (0 !== count($acceptColl) || 0 !== count($denyColl)) { $message = ''; if (0 !== count($acceptColl)) { $message .= "\n" . $app->trans('login::register:email: Vous avez ete accepte sur les collections suivantes : ') . implode(', ', $acceptColl) . "\n"; } if (0 !== count($denyColl)) { $message .= "\n" . $app->trans('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . implode(', ', $denyColl) . "\n"; } $receiver = new Receiver(null, $user->getEmail()); $mail = MailSuccessEmailUpdate::create($app, $receiver, null, $message); $app['notification.deliverer']->deliver($mail); } } } return $app->redirectPath('users_display_registrations', ['success' => 1]); })->bind('users_submit_registrations'); $controllers->get('/import/file/', function (Application $app, Request $request) { return $app['twig']->render('admin/user/import/file.html.twig'); })->bind('users_display_import_file'); $controllers->post('/import/file/', function (Application $app, Request $request) { if (null === ($file = $request->files->get('files')) || !$file->isValid()) { return $app->redirectPath('users_display_import_file', ['error' => 'file-invalid']); } $equivalenceToMysqlField = self::getEquivalenceToMysqlField(); $loginDefined = $pwdDefined = $mailDefined = false; $loginNew = []; $out = ['ignored_row' => [], 'errors' => []]; $nbUsrToAdd = 0; $lines = \format::csv_to_arr($file->getPathname()); $roughColumns = array_shift($lines); $columnsSanitized = array_map(function ($columnName) { return trim(mb_strtolower($columnName)); }, $roughColumns); $columns = array_filter($columnsSanitized, function ($columnName) use(&$out, $equivalenceToMysqlField) { if (!isset($equivalenceToMysqlField[$columnName])) { $out['ignored_row'][] = $columnName; return false; } return true; }); foreach ($columns as $columnName) { if ($equivalenceToMysqlField[$columnName] === 'usr_login') { $loginDefined = true; } if ($equivalenceToMysqlField[$columnName] === 'usr_password') { $pwdDefined = true; } if ($equivalenceToMysqlField[$columnName] === 'usr_mail') { $mailDefined = true; } } if (!$loginDefined) { return $app->redirectPath('users_display_import_file', ['error' => 'row-login']); } if (!$pwdDefined) { return $app->redirectPath('users_display_import_file', ['error' => 'row-pwd']); } if (!$mailDefined) { return $app->redirectPath('users_display_import_file', ['error' => 'row-mail']); } foreach ($lines as $nbLine => $line) { $loginValid = false; $pwdValid = false; $mailValid = false; foreach ($columns as $nbCol => $colName) { if (!isset($equivalenceToMysqlField[$colName])) { unset($lines[$nbCol]); continue; } $sqlField = $equivalenceToMysqlField[$colName]; $value = $line[$nbCol]; if ($sqlField === 'usr_login') { $loginToAdd = $value; if ($loginToAdd === "") { $out['errors'][] = $app->trans("Login line %line% is empty", ['%line%' => $nbLine + 1]); } elseif (in_array($loginToAdd, $loginNew)) { $out['errors'][] = $app->trans("Login %login% is already defined in the file at line %line%", ['%login%' => $loginToAdd, '%line%' => $nbLine]); } else { if (null !== $app['manipulator.user']->getRepository()->findByLogin($loginToAdd)) { $out['errors'][] = $app->trans("Login %login% already exists in database", ['%login%' => $loginToAdd]); } else { $loginValid = true; } } } if ($loginValid && $sqlField === 'usr_mail') { $mailToAdd = $value; if ($mailToAdd === "") { $out['errors'][] = $app->trans("Mail line %line% is empty", ['%line%' => $nbLine + 1]); } elseif (null !== $app['manipulator.user']->getRepository()->findByEmail($mailToAdd)) { $out['errors'][] = $app->trans("Email '%email%' for login '%login%' already exists in database", ['%email%' => $mailToAdd, '%login%' => $loginToAdd]); } else { $mailValid = true; } } if ($sqlField === 'usr_password') { $passwordToVerif = $value; if ($passwordToVerif === "") { $out['errors'][] = $app->trans("Password is empty at line %line%", ['%line%' => $nbLine]); } else { $pwdValid = true; } } } if ($loginValid && $pwdValid && $mailValid) { $loginNew[] = $loginToAdd; $nbUsrToAdd++; } } if (count($out['errors']) > 0 && $nbUsrToAdd === 0) { return $app['twig']->render('admin/user/import/file.html.twig', ['errors' => $out['errors']]); } if ($nbUsrToAdd === 0) { return $app->redirectPath('users_display_import_file', ['error' => 'no-user']); } $basList = array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage'])); $models = $app['EM.native-query']->getModelForUser($app['authentication']->getUser(), $basList); return $app['twig']->render('/admin/user/import/view.html.twig', ['nb_user_to_add' => $nbUsrToAdd, 'models' => $models, 'lines_serialized' => serialize($lines), 'columns_serialized' => serialize($columns), 'errors' => $out['errors']]); })->bind('users_submit_import_file'); $controllers->post('/import/', function (Application $app, Request $request) { $nbCreation = 0; if (null === ($serializedColumns = $request->request->get('sr_columns')) || '' === $serializedColumns) { $app->abort(400); } if (null === ($serializedLines = $request->request->get('sr_lines')) || '' === $serializedLines) { $app->abort(400); } if (null === ($model = $request->request->get("modelToApply"))) { $app->abort(400); } $lines = unserialize($serializedLines); $columns = unserialize($serializedColumns); $equivalenceToMysqlField = Users::getEquivalenceToMysqlField(); foreach ($lines as $nbLine => $line) { $curUser = []; foreach ($columns as $nbCol => $colName) { if (!isset($equivalenceToMysqlField[$colName]) || !isset($line[$nbCol])) { continue; } $sqlField = $equivalenceToMysqlField[$colName]; $value = trim($line[$nbCol]); if ($sqlField === "usr_sexe") { switch ($value) { case "Mlle": case "Mlle.": case "mlle": case "Miss": case "miss": case "0": $curUser[$sqlField] = 0; break; case "Mme": case "Madame": case "Ms": case "Ms.": case "1": $curUser[$sqlField] = 1; break; case "M": case "M.": case "Mr": case "Mr.": case "Monsieur": case "Mister": case "2": $curUser[$sqlField] = 2; break; } } else { $curUser[$sqlField] = $value; } } if (isset($curUser['usr_login']) && trim($curUser['usr_login']) !== '' && isset($curUser['usr_password']) && trim($curUser['usr_password']) !== '' && isset($curUser['usr_mail']) && trim($curUser['usr_mail']) !== '') { if (null === $app['manipulator.user']->getRepository()->findByLogin($curUser['usr_login']) && false === $app['manipulator.user']->getRepository()->findByEmail($curUser['usr_mail'])) { $newUser = $app['manipulator.user']->createUser($curUser['usr_login'], $curUser['usr_password'], $curUser['usr_mail']); $ftpCredential = new FtpCredential(); $ftpCredential->setUser($newUser); if (isset($curUser['activeFTP'])) { $ftpCredential->setActive((int) $curUser['activeFTP']); } if (isset($curUser['addrFTP'])) { $ftpCredential->setAddress((string) $curUser['addrFTP']); } if (isset($curUser['passifFTP'])) { $ftpCredential->setPassive((int) $curUser['passifFTP']); } if (isset($curUser['destFTP'])) { $ftpCredential->setReceptionFolder($curUser['destFTP']); } if (isset($curUser['prefixFTPfolder'])) { $ftpCredential->setRepositoryPrefixName($curUser['prefixFTPfolder']); } if (isset($curUser['usr_prenom'])) { $newUser->setFirstName($curUser['usr_prenom']); } if (isset($curUser['usr_nom'])) { $newUser->setLastName($curUser['usr_nom']); } if (isset($curUser['adresse'])) { $newUser->setAdress($curUser['adresse']); } if (isset($curUser['cpostal'])) { $newUser->setZipCode($curUser['cpostal']); } if (isset($curUser['usr_sexe'])) { $newUser->setGender((int) $curUser['usr_sexe']); } if (isset($curUser['tel'])) { $newUser->setPhone($curUser['tel']); } if (isset($curUser['fax'])) { $newUser->setFax($curUser['fax']); } if (isset($curUser['activite'])) { $newUser->setJob($curUser['activite']); } if (isset($curUser['fonction'])) { $newUser->setPosition($curUser['fonction']); } if (isset($curUser['societe'])) { $newUser->setCompany($curUser['societe']); } $app['acl']->get($newUser)->apply_model($app['manipulator.user']->getRepository()->find($model), array_keys($app['acl']->get($app['authentication']->getUser())->get_granted_base(['manage']))); $nbCreation++; } } } return $app->redirectPath('admin_users_search', ['user-updated' => $nbCreation]); })->bind('users_submit_import'); $controllers->get('/import/example/csv/', function (Application $app) { $file = new \SplFileInfo($app['root.path'] . '/lib/Fixtures/exampleImportUsers.csv'); if (!$file->isFile()) { $app->abort(400); } $response = new Response(); $response->setStatusCode(200); $response->headers->set('Pragma', 'public'); $response->headers->set('Content-Disposition', 'attachment; filename=' . $file->getFilename()); $response->headers->set('Content-Length', $file->getSize()); $response->headers->set('Content-Type', 'text/csv'); $response->setContent(file_get_contents($file->getPathname())); return $response; })->bind('users_import_csv'); $controllers->get('/import/example/rtf/', function (Application $app) { $file = new \SplFileInfo($app['root.path'] . '/lib/Fixtures/Fields.rtf'); if (!$file->isFile()) { $app->abort(400); } $response = new Response(); $response->setStatusCode(200); $response->headers->set('Pragma', 'public'); $response->headers->set('Content-Disposition', 'attachment; filename=' . $file->getFilename()); $response->headers->set('Content-Length', $file->getSize()); $response->headers->set('Content-Type', 'text/rtf'); $response->setContent(file_get_contents($file->getPathname())); return $response; })->bind('users_import_rtf'); return $controllers; }
/** * {@inheritdoc} */ public function apply(base $appbox, Application $app) { if (false === $this->hasFeedBackup($app)) { return false; } $sql = 'DELETE FROM Feeds'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedEntries'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedPublishers'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedItems'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM FeedTokens'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $sql = 'DELETE FROM AggregateTokens'; $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); $conn = $app['phraseanet.appbox']->get_connection(); $sql = 'SELECT id, title, subtitle, public, created_on, updated_on, base_id FROM feeds_backup;'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $n = 0; $em = $app['EM']; $fpSql = 'SELECT id, usr_id, owner, created_on FROM feed_publishers WHERE feed_id = :feed_id;'; $fpStmt = $conn->prepare($fpSql); $feSql = 'SELECT id, title, description, created_on, updated_on, author_name, author_email FROM feed_entries WHERE feed_id = :feed_id AND publisher = :publisher_id;'; $feStmt = $conn->prepare($feSql); $fiSql = 'SELECT sbas_id, record_id, ord FROM feed_entry_elements WHERE entry_id = :entry_id;'; $fiStmt = $conn->prepare($fiSql); $ftSql = 'SELECT token, usr_id, aggregated FROM feed_tokens WHERE feed_id = :feed_id;'; $ftStmt = $conn->prepare($ftSql); $faSql = 'SELECT token, usr_id FROM feed_tokens WHERE aggregated = 1;'; $faStmt = $conn->prepare($faSql); foreach ($rs as $row) { $feed = new Feed(); $feed->setTitle($row['title']); $feed->setSubtitle($row['subtitle']); $feed->setIconUrl(false); $feed->setIsPublic($row['public']); $feed->setCreatedOn(new \DateTime($row['created_on'])); $feed->setUpdatedOn(new \DateTime($row['updated_on'])); $feed->setCollection($row['base_id'] ? collection::get_from_base_id($app, $row['base_id']) : null); $fpStmt->execute([':feed_id' => $row['id']]); $fpRes = $fpStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fpRes as $fpRow) { if (null === ($user = $this->loadUser($app['EM'], $fpRow['usr_id']))) { continue; } $feedPublisher = new FeedPublisher(); $feedPublisher->setFeed($feed); $feed->addPublisher($feedPublisher); $feedPublisher->setCreatedOn(new \DateTime($fpRow['created_on'])); $feedPublisher->setIsOwner((bool) $fpRow['owner']); $feedPublisher->setUser($user); $feStmt->execute([':feed_id' => $row['id'], ':publisher_id' => $fpRow['id']]); $feRes = $feStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($feRes as $feRow) { $feedEntry = new FeedEntry(); $feedEntry->setFeed($feed); $feed->addEntry($feedEntry); $feedEntry->setPublisher($feedPublisher); $feedEntry->setTitle($feRow['title']); $feedEntry->setSubtitle($feRow['description']); $feedEntry->setAuthorName($feRow['author_name']); $feedEntry->setAuthorEmail($feRow['author_email']); $feedEntry->setCreatedOn(new \DateTime($feRow['created_on'])); $feedEntry->setUpdatedOn(new \DateTime($feRow['updated_on'])); $fiStmt->execute([':entry_id' => $feRow['id']]); $fiRes = $fiStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($fiRes as $fiRow) { $feedItem = new FeedItem(); $feedItem->setEntry($feedEntry); $feedEntry->addItem($feedItem); $feedItem->setOrd($fiRow['ord']); $feedItem->setSbasId($fiRow['sbas_id']); $feedItem->setRecordId($fiRow['record_id']); $em->persist($feedItem); } $em->persist($feedEntry); } $em->persist($feedPublisher); } $ftStmt->execute([':feed_id' => $row['id']]); $ftRes = $ftStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($ftRes as $ftRow) { if (null === ($user = $this->loadUser($app['EM'], $ftRow['usr_id']))) { continue; } $token = new FeedToken(); $token->setFeed($feed); $feed->addToken($token); $token->setUser($user); $token->setValue($ftRow['token']); $em->persist($token); } $em->persist($feed); $n++; if ($n % 100 === 0) { $em->flush(); $em->clear(); } } $fiStmt->closeCursor(); $feStmt->closeCursor(); $fpStmt->closeCursor(); $ftStmt->closeCursor(); $faStmt->execute(); $faRes = $faStmt->fetchAll(\PDO::FETCH_ASSOC); foreach ($faRes as $faRow) { if (null === ($user = $this->loadUser($app['EM'], $faRow['usr_id']))) { continue; } $token = new AggregateToken(); $token->setUser($user); $token->setValue($faRow['token']); $em->persist($token); } $faStmt->closeCursor(); $em->flush(); $em->clear(); return true; }
public function testGet_granted_base() { $base_ids = []; $n = 0; foreach (self::$DI['app']['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($databox->get_collections() as $collection) { $base_ids[] = $collection->get_base_id(); $n++; } } if ($n === 0) { $this->fail('Not enough collection to test'); } self::$object->give_access_to_base($base_ids); $bases = array_keys(self::$object->get_granted_base()); $this->assertEquals(count($bases), count($base_ids)); $this->assertEquals($n, count($base_ids)); foreach ($bases as $base_id) { try { $collection = collection::get_from_base_id(self::$DI['app'], $base_id); $this->assertTrue($collection instanceof collection); $this->assertEquals($base_id, $collection->get_base_id()); unset($collection); } catch (Exception $e) { $this->fail('get granted base should returned OK collection'); } } }
public function connect(Application $app) { $app['controller.admin.publications'] = $this; $controllers = $app['controllers_factory']; $app['firewall']->addMandatoryAuthentication($controllers); $controllers->before(function (Request $request) use($app) { $app['firewall']->requireAccessToModule('admin')->requireRight('bas_chupub'); }); $controllers->get('/list/', function (PhraseaApplication $app) { $feeds = $app['EM']->getRepository('Phraseanet:Feed')->getAllForUser($app['acl']->get($app['authentication']->getUser())); return $app['twig']->render('admin/publications/list.html.twig', ['feeds' => $feeds]); })->bind('admin_feeds_list'); $controllers->post('/create/', function (PhraseaApplication $app, Request $request) { if ('' === ($title = trim($request->request->get('title', '')))) { $app->abort(400, "Bad request"); } $publisher = new FeedPublisher(); $feed = new Feed(); $publisher->setFeed($feed); $publisher->setUser($app['authentication']->getUser()); $publisher->setIsOwner(true); $feed->addPublisher($publisher); $feed->setTitle($title); $feed->setSubtitle($request->request->get('subtitle', '')); if ($request->request->get('public') == '1') { $feed->setIsPublic(true); } elseif ($request->request->get('base_id')) { $feed->setCollection(\collection::get_from_base_id($app, $request->request->get('base_id'))); } $publisher->setFeed($feed); $app['EM']->persist($feed); $app['EM']->persist($publisher); $app['EM']->flush(); return $app->redirectPath('admin_feeds_list'); })->bind('admin_feeds_create'); $controllers->get('/feed/{id}/', function (PhraseaApplication $app, Request $request, $id) { $feed = $app["EM"]->find('Phraseanet:Feed', $id); return $app['twig']->render('admin/publications/fiche.html.twig', ['feed' => $feed, 'error' => $app['request']->query->get('error')]); })->bind('admin_feeds_feed')->assert('id', '\\d+'); $controllers->post('/feed/{id}/update/', function (PhraseaApplication $app, Request $request, $id) { if ('' === ($title = trim($request->request->get('title', '')))) { $app->abort(400, "Bad request"); } $feed = $app["EM"]->find('Phraseanet:Feed', $id); try { $collection = \collection::get_from_base_id($app, $request->request->get('base_id')); } catch (\Exception $e) { $collection = null; } $feed->setTitle($title); $feed->setSubtitle($request->request->get('subtitle', '')); $feed->setCollection($collection); $feed->setIsPublic('1' === $request->request->get('public')); $app['EM']->persist($feed); $app['EM']->flush(); return $app->redirectPath('admin_feeds_list'); })->before(function (Request $request) use($app) { $feed = $app["EM"]->find('Phraseanet:Feed', $request->attributes->get('id')); if (!$feed->isOwner($app['authentication']->getUser())) { return $app->redirectPath('admin_feeds_feed', ['id' => $request->attributes->get('id'), 'error' => $app->trans('You are not the owner of this feed, you can not edit it')]); } })->bind('admin_feeds_feed_update')->assert('id', '\\d+'); $controllers->post('/feed/{id}/iconupload/', function (PhraseaApplication $app, Request $request, $id) { $datas = ['success' => false, 'message' => '']; $feed = $app["EM"]->find('Phraseanet:Feed', $id); if (null === $feed) { $app->abort(404, "Feed not found"); } $request = $app["request"]; if (!$feed->isOwner($app['authentication']->getUser())) { $app->abort(403, "Access Forbidden"); } try { if (!$request->files->get('files')) { throw new BadRequestHttpException('Missing file parameter'); } if (count($request->files->get('files')) > 1) { throw new BadRequestHttpException('Upload is limited to 1 file per request'); } $file = current($request->files->get('files')); if (!$file->isValid()) { throw new BadRequestHttpException('Uploaded file is invalid'); } $media = $app['mediavorus']->guess($file->getPathname()); if ($media->getType() !== \MediaVorus\Media\MediaInterface::TYPE_IMAGE) { throw new BadRequestHttpException('Bad filetype'); } $spec = new \MediaAlchemyst\Specification\Image(); $spec->setResizeMode(\MediaAlchemyst\Specification\Image::RESIZE_MODE_OUTBOUND); $spec->setDimensions(32, 32); $spec->setStrip(true); $spec->setQuality(72); $tmpname = tempnam(sys_get_temp_dir(), 'feed_icon') . '.png'; try { $app['media-alchemyst']->turnInto($media->getFile()->getPathname(), $tmpname, $spec); } catch (\MediaAlchemyst\Exception\ExceptionInterface $e) { throw new \Exception_InternalServerError('Error while resizing'); } unset($media); $feed->setIconUrl(true); $app['EM']->persist($feed); $app['EM']->flush(); $app['filesystem']->copy($tmpname, $app['root.path'] . '/config/feed_' . $feed->getId() . '.jpg'); $app['filesystem']->copy($tmpname, sprintf('%s/www/custom/feed_%d.jpg', $app['root.path'], $feed->getId())); $app['filesystem']->remove($tmpname); $datas['success'] = true; } catch (\Exception $e) { $datas['message'] = $app->trans('Unable to add file to Phraseanet'); } return $app->json($datas); })->bind('admin_feeds_feed_icon')->assert('id', '\\d+'); $controllers->post('/feed/{id}/addpublisher/', function (PhraseaApplication $app, $id) { $error = ''; try { $request = $app['request']; $user = $app['manipulator.user']->getRepository()->find($request->request->get('usr_id')); $feed = $app["EM"]->find('Phraseanet:Feed', $id); $publisher = new FeedPublisher(); $publisher->setUser($user); $publisher->setFeed($feed); $feed->addPublisher($publisher); $app['EM']->persist($feed); $app['EM']->persist($publisher); $app['EM']->flush(); } catch (\Exception $e) { $error = "An error occured"; } return $app->redirectPath('admin_feeds_feed', ['id' => $id, 'error' => $error]); })->bind('admin_feeds_feed_add_publisher')->assert('id', '\\d+'); $controllers->post('/feed/{id}/removepublisher/', function (PhraseaApplication $app, $id) { try { $request = $app['request']; $feed = $app["EM"]->find('Phraseanet:Feed', $id); $publisher = $app["EM"]->find('Phraseanet:FeedPublisher', $request->request->get('publisher_id')); if (null === $publisher) { $app->abort(404, "Feed Publisher not found"); } $user = $publisher->getUser(); if ($feed->isPublisher($user) && !$feed->isOwner($user)) { $feed->removePublisher($publisher); $app['EM']->remove($publisher); $app['EM']->flush(); } } catch (\Exception $e) { $error = "An error occured"; } return $app->redirectPath('admin_feeds_feed', ['id' => $id, 'error' => $error]); })->bind('admin_feeds_feed_remove_publisher')->assert('id', '\\d+'); $controllers->post('/feed/{id}/delete/', function (PhraseaApplication $app, $id) { $feed = $app["EM"]->find('Phraseanet:Feed', $id); if (null === $feed) { $app->abort(404); } if (true === $feed->getIconURL()) { unlink($app['root.path'] . '/config/feed_' . $feed->getId() . '.jpg'); unlink('custom/feed_' . $feed->getId() . '.jpg'); } $app['EM']->remove($feed); $app['EM']->flush(); return $app->redirectPath('admin_feeds_list'); })->bind('admin_feeds_feed_delete')->assert('id', '\\d+'); return $controllers; }
/** * Update account information * * @param Request $request The current request * @return Response */ public function updateAccount(Request $request) { $registrations = $request->request->get('registrations', []); if (false === is_array($registrations)) { $this->app->abort(400, '"registrations" parameter must be an array of base ids.'); } $user = $this->getAuthenticatedUser(); if (0 !== count($registrations)) { foreach ($registrations as $baseId) { $this->getRegistrationManipulator()->createRegistration($user, \collection::get_from_base_id($this->app, $baseId)); } $this->app->addFlash('success', $this->app->trans('Your registration requests have been taken into account.')); } $accountFields = ['form_gender', 'form_firstname', 'form_lastname', 'form_address', 'form_zip', 'form_phone', 'form_fax', 'form_function', 'form_company', 'form_activity', 'form_geonameid', 'form_addressFTP', 'form_loginFTP', 'form_pwdFTP', 'form_destFTP', 'form_prefixFTPfolder', 'form_retryFTP']; $service = $this->app['accounts.service']; if (0 === count(array_diff($accountFields, array_keys($request->request->all())))) { $command = new UpdateAccountCommand(); $command->setGender((int) $request->request->get("form_gender"))->setFirstName($request->request->get("form_firstname"))->setLastName($request->request->get("form_lastname"))->setAddress($request->request->get("form_address"))->setZipCode($request->request->get("form_zip"))->setPhone($request->request->get("form_phone"))->setFax($request->request->get("form_fax"))->setJob($request->request->get("form_activity"))->setCompany($request->request->get("form_company"))->setPosition($request->request->get("form_function"))->setNotifications((bool) $request->request->get("mail_notifications")); $service->updateAccount($command); $this->getUserManipulator()->setGeonameId($user, $request->request->get("form_geonameid")); $ftpCredential = $user->getFtpCredential(); if (null === $ftpCredential) { $ftpCredential = new FtpCredential(); $ftpCredential->setUser($user); } $command = new UpdateFtpCredentialsCommand(); $command->setEnabled($request->request->get("form_activeFTP")); $command->setAddress($request->request->get("form_addressFTP")); $command->setLogin($request->request->get("form_loginFTP")); $command->setPassword($request->request->get("form_pwdFTP")); $command->setPassiveMode($request->request->get("form_passifFTP")); $command->setFolder($request->request->get("form_destFTP")); $command->setFolderPrefix($request->request->get("form_prefixFTPfolder")); $command->setRetries($request->request->get("form_retryFTP")); $service->updateFtpSettings($command); $this->app->addFlash('success', $this->app->trans('login::notification: Changements enregistres')); } $requestedNotifications = (array) $request->request->get('notifications', []); $manipulator = $this->getUserManipulator(); foreach ($this->getEventManager()->list_notifications_available($user) as $notifications) { foreach ($notifications as $notification) { $manipulator->setNotificationSetting($user, $notification['id'], isset($requestedNotifications[$notification['id']])); } } return $this->app->redirectPath('account'); }
/** * {@inheritdoc} */ public function apply(base $appbox, Application $app) { $conn = $appbox->get_connection(); try { //get all old lazaret file & transform them to LazaretFile object $sql = 'SELECT * FROM lazaret'; $stmt = $conn->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(); $stmt->closeCursor(); } catch (DBALException $e) { // table not found if ($e->getCode() == '42S02') { } return; } //order matters for foreign keys constraints //truncate all altered tables $this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretAttribute'); $this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretCheck'); $this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretFile'); $this->truncateTable($app['EM'], 'Alchemy\\Phrasea\\Model\\Entities\\LazaretSession'); $i = 0; foreach ($rs as $row) { $filePath = $app['tmp.lazaret.path'] . '/' . $row['filepath']; if (null === ($user = $this->loadUser($app['EM'], $row['usr_id']))) { continue; } if (file_exists($filePath)) { $spec = new ImageSpec(); $spec->setResizeMode(ImageSpec::RESIZE_MODE_INBOUND_FIXEDRATIO); $spec->setDimensions(375, 275); $thumbPath = $app['tmp.lazaret.path'] . '/' . sprintf("thumb_%s", $row['filepath']); try { $app['media-alchemyst']->turnInto($filePath, $thumbPath, $spec); } catch (MediaAlchemystException $e) { } $media = $app['mediavorus']->guess($filePath); $collection = \collection::get_from_base_id($app, $row['base_id']); $borderFile = new \Alchemy\Phrasea\Border\File($app, $media, $collection); $lazaretSession = new LazaretSession(); $lazaretSession->setUser($user); $lazaretFile = new LazaretFile(); $lazaretFile->setBaseId($row['base_id']); if (null === $row['uuid']) { $uuid = $borderFile->getUUID(true); $lazaretFile->setUuid($uuid); } else { $lazaretFile->setUuid($row['uuid']); } if (null === $row['sha256']) { $sha256 = $media->getHash('sha256'); $lazaretFile->setSha256($sha256); } else { $lazaretFile->setSha256($row['sha256']); } $lazaretFile->setOriginalName($row['filename']); $lazaretFile->setFilename($row['filepath']); $lazaretFile->setThumbFilename(pathinfo($thumbPath), PATHINFO_BASENAME); $lazaretFile->setCreated(new \DateTime($row['created_on'])); $lazaretFile->setSession($lazaretSession); $app['EM']->persist($lazaretFile); if (0 === ++$i % 100) { $app['EM']->flush(); $app['EM']->clear(); } } } $app['EM']->flush(); $app['EM']->clear(); $stmt->closeCursor(); return true; }
/** * Apply collection reorder changes * * @param Application $app The silex application * @param Request $request The current HTTP request * @param integer $databox_id The requested databox * @return JsonResponse|RedirectResponse */ public function setReorder(Application $app, Request $request, $databox_id) { try { foreach ($request->request->get('order', []) as $data) { $collection = \collection::get_from_base_id($app, $data['id']); $collection->set_ord($data['offset']); } $success = true; } catch (\Exception $e) { $success = false; } if ('json' === $app['request']->getRequestFormat()) { return $app->json(['success' => $success, 'msg' => $success ? $app->trans('Successful update') : $app->trans('An error occured'), 'sbas_id' => $databox_id]); } return $app->redirectPath('admin_database_display_collections_order', ['databox_id' => $databox_id, 'success' => (int) $success]); }
public function get_time() { $this->base_id = (int) $this->request->get('base_id'); $sql = "SELECT u.id, time_limited, limited_from, limited_to\n FROM (Users u INNER JOIN basusr bu ON u.id = bu.usr_id)\n WHERE (u.id IN (:users)) AND bu.base_id = :base_id"; /** @var Connection $conn */ $conn = $this->app->getApplicationBox()->get_connection(); $rs = $conn->fetchAll($sql, ['base_id' => $this->base_id, 'users' => $this->users], ['base_id' => \PDO::PARAM_INT, 'users' => Connection::PARAM_INT_ARRAY]); $time_limited = -1; $limited_from = $limited_to = false; foreach ($rs as $row) { if ($time_limited < 0) { $time_limited = $row['time_limited']; } if ($time_limited < 2 && $row['time_limited'] != $row['time_limited']) { $time_limited = 2; } if ($limited_from !== '' && trim($row['limited_from']) != '0000-00-00 00:00:00') { $limited_from = $limited_from === false ? $row['limited_from'] : ($limited_from == $row['limited_from'] ? $limited_from : ''); } if ($limited_to !== '' && trim($row['limited_to']) != '0000-00-00 00:00:00') { $limited_to = $limited_to === false ? $row['limited_to'] : ($limited_to == $row['limited_to'] ? $limited_to : ''); } } if ($limited_from) { $date_obj_from = new \DateTime($limited_from); $limited_from = $date_obj_from->format('Y-m-d'); } if ($limited_to) { $date_obj_to = new \DateTime($limited_to); $limited_to = $date_obj_to->format('Y-m-d'); } $datas = ['time_limited' => $time_limited, 'limited_from' => $limited_from, 'limited_to' => $limited_to]; $this->users_datas = $datas; return ['datas' => $this->users_datas, 'users' => $this->users, 'users_serial' => implode(';', $this->users), 'base_id' => $this->base_id, 'collection' => \collection::get_from_base_id($this->app, $this->base_id)]; }
private function doDeliverPermalink(Request $request, $sbas_id, $record_id, $token, $subdef) { $databox = $this->getDatabox($sbas_id); $record = $this->retrieveRecord($databox, $token, $record_id, $subdef); $watermark = $stamp = false; if ($this->authentication->isAuthenticated()) { $watermark = !$this->acl->get($this->authentication->getUser())->has_right_on_base($record->get_base_id(), 'nowatermark'); if ($watermark) { /** @var BasketElementRepository $repository */ $repository = $this->app['repo.basket-elements']; if (count($repository->findReceivedValidationElementsByRecord($record, $this->authentication->getUser())) > 0) { $watermark = false; } elseif (count($repository->findReceivedElementsByRecord($record, $this->authentication->getUser())) > 0) { $watermark = false; } } return $this->deliverContentWithCaptionLink($request, $record, $subdef, $watermark, $stamp, $token); } $collection = \collection::get_from_base_id($this->app, $record->get_base_id()); switch ($collection->get_pub_wm()) { default: case 'none': $watermark = false; break; case 'stamp': $stamp = true; break; case 'wm': $watermark = true; break; } return $this->deliverContentWithCaptionLink($request, $record, $subdef, $watermark, $stamp, $token); }
/** * Update account informations * * @param PhraseaApplication $app A Silex application where the controller is mounted on * @param Request $request The current request * @return Response */ public function updateAccount(PhraseaApplication $app, Request $request) { $registrations = $request->request->get('registrations'); if (false === is_array($registrations)) { $app->abort(400, '"registrations" parameter must be an array of base ids.'); } if (0 !== count($registrations)) { foreach ($registrations as $baseId) { $app['manipulator.registration']->createRegistration($app['authentication']->getUser(), \collection::get_from_base_id($app, $baseId)); } $app->addFlash('success', $app->trans('Your registration requests have been taken into account.')); } $accountFields = ['form_gender', 'form_firstname', 'form_lastname', 'form_address', 'form_zip', 'form_phone', 'form_fax', 'form_function', 'form_company', 'form_activity', 'form_geonameid', 'form_addressFTP', 'form_loginFTP', 'form_pwdFTP', 'form_destFTP', 'form_prefixFTPfolder', 'form_retryFTP']; if (0 === count(array_diff($accountFields, array_keys($request->request->all())))) { $app['authentication']->getUser()->setGender($request->request->get("form_gender"))->setFirstName($request->request->get("form_firstname"))->setLastName($request->request->get("form_lastname"))->setAddress($request->request->get("form_address"))->setZipCode($request->request->get("form_zip"))->setPhone($request->request->get("form_phone"))->setFax($request->request->get("form_fax"))->setJob($request->request->get("form_activity"))->setCompany($request->request->get("form_company"))->setActivity($request->request->get("form_function"))->setMailNotificationsActivated((bool) $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->setUser($app['authentication']->getUser()); } $ftpCredential->setActive($request->request->get("form_activeFTP")); $ftpCredential->setAddress($request->request->get("form_addressFTP")); $ftpCredential->setLogin($request->request->get("form_loginFTP")); $ftpCredential->setPassword($request->request->get("form_pwdFTP")); $ftpCredential->setPassive($request->request->get("form_passifFTP")); $ftpCredential->setReceptionFolder($request->request->get("form_destFTP")); $ftpCredential->setRepositoryPrefixName($request->request->get("form_prefixFTPfolder")); $app['EM']->persist($ftpCredential); $app['EM']->persist($app['authentication']->getUser()); $app['EM']->flush(); $app->addFlash('success', $app->trans('login::notification: Changements enregistres')); } $requestedNotifications = (array) $request->request->get('notifications', []); foreach ($app['events-manager']->list_notifications_available($app['authentication']->getUser()->getId()) as $notifications) { foreach ($notifications as $notification) { $app['manipulator.user']->setNotificationSetting($app['authentication']->getUser(), $notification['id'], isset($requestedNotifications[$notification['id']])); } } return $app->redirectPath('account'); }
protected function doExecute(InputInterface $input, OutputInterface $output) { try { $collection = \collection::get_from_base_id($this->container, $input->getArgument('base_id')); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('Collection %s is invalid', $input->getArgument('base_id'))); } $file = $input->getArgument('file'); if (false === $this->container['filesystem']->exists($file)) { throw new \InvalidArgumentException(sprintf('File %s does not exists', $file)); } $media = $this->container['mediavorus']->guess($file); $dialog = $this->getHelperSet()->get('dialog'); if (!$input->getOption('yes')) { do { $continue = strtolower($dialog->ask($output, sprintf("Will add record <info>%s</info> (%s) on collection <info>%s</info>\n<question>Continue ? (y/N)</question>", $file, $media->getType(), $collection->get_label($this->container['locale'])), 'N')); } while (!in_array($continue, ['y', 'n'])); if (strtolower($continue) !== 'y') { $output->writeln('Aborted !'); return; } } $tempfile = $originalName = null; if ($input->getOption('in-place') !== '1') { $originalName = pathinfo($file, PATHINFO_BASENAME); $tempfile = $this->container['temporary-filesystem']->createTemporaryFile('add_record', null, pathinfo($file, PATHINFO_EXTENSION)); $this->container['monolog']->addInfo(sprintf('copy file from `%s` to temporary `%s`', $file, $tempfile)); $this->container['filesystem']->copy($file, $tempfile, true); $file = $tempfile; $media = $this->container['mediavorus']->guess($file); } $file = new File($this->container, $media, $collection, $originalName); $session = new LazaretSession(); $this->container['orm.em']->persist($session); $forceBehavior = null; if ($input->getOption('force')) { switch ($input->getOption('force')) { default: $this->container['temporary-filesystem']->clean('add_record'); throw new \InvalidArgumentException(sprintf('`%s` is not a valid force option', $input->getOption('force'))); break; case 'record': $forceBehavior = Manager::FORCE_RECORD; break; case 'quarantine': $forceBehavior = Manager::FORCE_LAZARET; break; } } $elementCreated = null; $callback = function ($element, $visa, $code) use(&$elementCreated) { $elementCreated = $element; }; $this->container['border-manager']->process($session, $file, $callback, $forceBehavior); if ($elementCreated instanceof \record_adapter) { $output->writeln(sprintf("Record id <info>%d</info> on collection `%s` (databox `%s`) has been created", $elementCreated->get_record_id(), $elementCreated->get_collection()->get_label($this->container['locale']), $elementCreated->get_databox()->get_label($this->container['locale']))); } elseif ($elementCreated instanceof LazaretFile) { $output->writeln(sprintf("Quarantine item id <info>%d</info> has been created", $elementCreated->getId())); } if ($tempfile) { $this->container['monolog']->addInfo(sprintf('Remove temporary file `%s`', $tempfile)); $this->container['temporary-filesystem']->clean('add_record'); } return; }
public function submitRegistrationAction(Request $request) { $templates = $this->normalizeTemplateArray($request->request->get('template', [])); $deny = $this->normalizeDenyArray($request->request->get('deny', []), $templates); $accepts = $request->request->get('accept', []); $accept = $options = []; foreach ($accepts as $acc) { $acc = explode('_', $acc); if (count($acc) == 2 && !isset($templates[$acc[0]])) { $accept[$acc[0]][$acc[1]] = $acc[1]; $options[$acc[0]][$acc[1]] = ['HD' => false, 'WM' => false]; } } foreach ($request->request->get('accept_hd', []) as $accHD) { $accHD = explode('_', $accHD); if (count($accHD) == 2 && isset($accept[$accHD[0]]) && isset($options[$accHD[0]][$accHD[1]])) { $options[$accHD[0]][$accHD[1]]['HD'] = true; } } foreach ($request->request->get('watermark', []) as $wm) { $wm = explode('_', $wm); if (count($wm) == 2 && isset($accept[$wm[0]]) && isset($options[$wm[0]][$wm[1]])) { $options[$wm[0]][$wm[1]]['WM'] = true; } } $registrationManipulator = $this->getRegistrationManipulator(); if (count($templates) > 0 || count($deny) > 0 || count($accept) > 0) { $cacheToUpdate = $done = []; /** @var UserRepository $userRepository */ $userRepository = $this->app['repo.users']; $searchedUserIds = array_unique(array_merge(array_keys($templates), array_keys($deny), array_keys($accept))); // Load all user entities needed afterwards $userRepository->findBy(['id' => $searchedUserIds]); foreach ($templates as $usr => $template_id) { /** @var User $user */ $user = $userRepository->find($usr); if (null === $user) { $this->app->abort(400, sprintf("User with id % in provided in 'template' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; /** @var User $user_template */ $user_template = $userRepository->find($template_id); $collections = $this->getAclForUser($user_template)->get_granted_base(); $baseIds = array_keys($collections); $this->getAclForUser($user)->apply_model($user_template, $baseIds); foreach ($collections as $collection) { $done[$usr][$collection->get_base_id()] = true; } $registrationManipulator->deleteUserRegistrations($user, $collections); } /** @var RegistrationRepository $registrationRepository */ $registrationRepository = $this->app['repo.registrations']; foreach ($deny as $usr => $bases) { /** @var User $user */ $user = $userRepository->find($usr); if (null === $user) { $this->app->abort(400, sprintf("User with id % in provided in 'deny' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; foreach ($registrationRepository->getUserRegistrations($user, array_map(function ($baseId) { return \collection::get_from_base_id($this->app, $baseId); }, $bases)) as $registration) { $registrationManipulator->rejectRegistration($registration); $done[$usr][$registration->getBaseId()] = false; } } foreach ($accept as $usr => $bases) { /** @var User $user */ $user = $userRepository->find($usr); if (null === $user) { $this->app->abort(400, sprintf("User with id % in provided in 'accept' request variable could not be found", $usr)); } $cacheToUpdate[$usr] = $user; foreach ($registrationRepository->getUserRegistrations($user, array_map(function ($baseId) { return \collection::get_from_base_id($this->app, $baseId); }, $bases)) as $registration) { $done[$usr][$registration->getBaseId()] = true; $registrationManipulator->acceptRegistration($registration, $options[$usr][$registration->getBaseId()]['HD'], $options[$usr][$registration->getBaseId()]['WM']); } } array_walk($cacheToUpdate, function (User $user) { $this->getAclForUser($user)->delete_data_from_cache(); }); unset($cacheToUpdate); foreach ($done as $usr => $bases) { $user = $userRepository->find($usr); $acceptColl = $denyColl = []; $hookName = WebhookEvent::USER_REGISTRATION_REJECTED; $hookType = WebhookEvent::USER_REGISTRATION_TYPE; $hookData = ['user_id' => $user->getId(), 'granted' => [], 'rejected' => []]; foreach ($bases as $bas => $isok) { $collection = \collection::get_from_base_id($this->app, $bas); $label = $collection->get_label($this->app['locale']); if ($isok) { $acceptColl[] = $label; $hookData['granted'][$bas] = $label; $hookName = WebhookEvent::USER_REGISTRATION_GRANTED; } else { $denyColl[] = $label; $hookData['rejected'][$bas] = $label; } } $this->app['manipulator.webhook-event']->create($hookName, $hookType, $hookData); if ($user->hasMailNotificationsActivated() && (0 !== count($acceptColl) || 0 !== count($denyColl))) { $message = ''; if (0 !== count($acceptColl)) { $message .= "\n" . $this->app->trans('login::register:email: Vous avez ete accepte sur les collections suivantes : ') . implode(', ', $acceptColl) . "\n"; } if (0 !== count($denyColl)) { $message .= "\n" . $this->app->trans('login::register:email: Vous avez ete refuse sur les collections suivantes : ') . implode(', ', $denyColl) . "\n"; } $receiver = new Receiver(null, $user->getEmail()); $mail = MailSuccessEmailUpdate::create($this->app, $receiver, null, $message); $this->deliver($mail); } } } return $this->app->redirectPath('users_display_registrations', ['success' => 1]); }
/** * @param Application $app * * @return \collection */ public function getCollection(Application $app) { return \collection::get_from_base_id($app, $this->baseId); }
/** * Return record collection * * @return \collection */ public function get_collection() { return \collection::get_from_base_id($this->app, $this->base_id); }
/** * Returns an array of collections on which the user is 'order master' * * @return array */ public function get_order_master_collections() { $sql = 'SELECT base_id FROM basusr WHERE order_master="1" AND usr_id= :usr_id'; $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql); $stmt->execute([':usr_id' => $this->user->getId()]); $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); $collections = []; foreach ($rs as $row) { $collections[] = \collection::get_from_base_id($this->app, $row['base_id']); } return $collections; }
public function doRegistration(PhraseaApplication $app, Request $request) { if (!$app['registration.manager']->isRegistrationEnabled()) { $app->abort(404, 'Registration is disabled'); } $form = $app->form(new PhraseaRegisterForm($app, $app['registration.optional-fields'], $app['registration.fields'])); if ('POST' === $request->getMethod()) { $requestData = $request->request->all(); // Remove geocompleter field for validation this field is added client side // with jquery geonames plugin if (isset($requestData['geonameid']) && isset($requestData['geonameid-completer'])) { unset($requestData['geonameid-completer']); } $form->bind($requestData); $data = $form->getData(); $provider = null; if ($data['provider-id']) { try { $provider = $this->findProvider($app, $data['provider-id']); } catch (NotFoundHttpException $e) { $app->addFlash('error', $app->trans('You tried to register with an unknown provider')); return $app->redirectPath('login_register'); } try { $token = $provider->getToken(); } catch (NotAuthenticatedException $e) { $app->addFlash('error', $app->trans('You tried to register with an unknown provider')); return $app->redirectPath('login_register'); } $userAuthProvider = $app['EM']->getRepository('Phraseanet:UsrAuthProvider')->findWithProviderAndId($token->getProvider()->getId(), $token->getId()); if (null !== $userAuthProvider) { $this->postAuthProcess($app, $userAuthProvider->getUser()); if (null !== ($redirect = $request->query->get('redirect'))) { $redirection = '../' . $redirect; } else { $redirection = $app->path('prod'); } return $app->redirect($redirection); } } try { if ($form->isValid()) { $captcha = $app['recaptcha']->bind($request); if ($app['conf']->get(['registry', 'webservices', 'captcha-enabled']) && !$captcha->isValid()) { throw new FormProcessingException($app->trans('Invalid captcha answer.')); } if ($app['conf']->get(['registry', 'registration', 'auto-select-collections'])) { $selected = null; } else { $selected = isset($data['collections']) ? $data['collections'] : null; } $inscriptions = $app['registration.manager']->getRegistrationSummary(); $inscOK = []; foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) { foreach ($databox->get_collections() as $collection) { if (null !== $selected && !in_array($collection->get_base_id(), $selected)) { continue; } if ($canRegister = igorw\get_in($inscriptions, [$databox->get_sbas_id(), 'config', 'collections', $collection->get_base_id(), 'can-register'])) { $inscOK[$collection->get_base_id()] = $canRegister; } } } if (!isset($data['login'])) { $data['login'] = $data['email']; } $user = $app['manipulator.user']->createUser($data['login'], $data['password'], $data['email'], false); if (isset($data['geonameid'])) { $app['manipulator.user']->setGeonameId($user, $data['geonameid']); } foreach (['gender' => 'setGender', 'firstname' => 'setFirstName', 'lastname' => 'setLastName', 'address' => 'setAddress', 'zipcode' => 'setZipCode', 'tel' => 'setPhone', 'fax' => 'setFax', 'job' => 'setJob', 'company' => 'setCompany', 'position' => 'setActivity'] as $property => $method) { if (isset($data[$property])) { call_user_func([$user, $method], $data[$property]); } } $app['EM']->persist($user); $app['EM']->flush(); if (null !== $provider) { $this->attachProviderToUser($app['EM'], $provider, $user); $app['EM']->flush(); } $registrationsOK = []; if ($app['conf']->get(['registry', 'registration', 'auto-register-enabled'])) { $template_user = $app['manipulator.user']->getRepository()->findByLogin(User::USER_AUTOREGISTER); $app['acl']->get($user)->apply_model($template_user, array_keys($inscOK)); } $autoReg = $app['acl']->get($user)->get_granted_base(); foreach ($inscOK as $baseId => $authorization) { if (false === $authorization || $app['acl']->get($user)->has_access_to_base($baseId)) { continue; } $app['manipulator.registration']->createRegistration($user, \collection::get_from_base_id($app, $baseId)); $registrationsOK[$baseId] = true; } $params = ['registrations' => $registrationsOK, 'autoregister' => $autoReg, 'usr_id' => $user->getId()]; $app['events-manager']->trigger('__REGISTER_AUTOREGISTER__', $params); $app['events-manager']->trigger('__REGISTER_APPROVAL__', $params); $user->setMailLocked(true); try { $this->sendAccountUnlockEmail($app, $user); $app->addFlash('info', $app->trans('login::notification: demande de confirmation par mail envoyee')); } catch (InvalidArgumentException $e) { // todo, log this failure $app->addFlash('error', $app->trans('Unable to send your account unlock email.')); } return $app->redirectPath('homepage'); } } catch (FormProcessingException $e) { $app->addFlash('error', $e->getMessage()); } } elseif (null !== $request->query->get('providerId')) { $provider = $this->findProvider($app, $request->query->get('providerId')); $identity = $provider->getIdentity(); $form->setData(array_filter(['email' => $identity->getEmail(), 'firstname' => $identity->getFirstname(), 'lastname' => $identity->getLastname(), 'company' => $identity->getCompany(), 'provider-id' => $provider->getId()])); } return $app['twig']->render('login/register-classic.html.twig', array_merge(self::getDefaultTemplateVariables($app), ['geonames_server_uri' => str_replace(sprintf('%s:', parse_url($app['geonames.server-uri'], PHP_URL_SCHEME)), '', $app['geonames.server-uri']), 'form' => $form->createView()])); }