Exemple #1
0
 /**
  * Prepare a set of documents for download
  *
  * @param Application $app
  * @param Request     $request
  * @param Token       $token
  *
  * @return Response
  */
 public function prepareDownload(Application $app, Request $request, Token $token)
 {
     if (false === ($list = @unserialize($token->getData()))) {
         $app->abort(500, 'Invalid datas');
     }
     if (!is_array($list)) {
         $app->abort(500, 'Invalid datas');
     }
     foreach (['export_name', 'files'] as $key) {
         if (!isset($list[$key])) {
             $app->abort(500, 'Invalid datas');
         }
     }
     $records = [];
     foreach ($list['files'] as $file) {
         if (!is_array($file) || !isset($file['base_id']) || !isset($file['record_id'])) {
             continue;
         }
         $sbasId = \phrasea::sbasFromBas($app, $file['base_id']);
         try {
             $record = new \record_adapter($app, $sbasId, $file['record_id']);
         } catch (\Exception $e) {
             continue;
         }
         $records[sprintf('%s_%s', $sbasId, $file['record_id'])] = $record;
     }
     return new Response($app['twig']->render('/prod/actions/Download/prepare.html.twig', ['module_name' => $app->trans('Export'), 'module' => $app->trans('Export'), 'list' => $list, 'records' => $records, 'token' => $token, 'anonymous' => $request->query->get('anonymous', false), 'type' => $request->query->get('type', \Session_Logger::EVENT_EXPORTDOWNLOAD)]));
 }
 /**
  *  Share a record
  *
  * @param  integer     $base_id
  * @param  integer     $record_id
  * @return Response
  */
 public function shareRecord($base_id, $record_id)
 {
     $record = new \record_adapter($this->app, \phrasea::sbasFromBas($this->app, $base_id), $record_id);
     if (!$this->getAclForUser()->has_access_to_subdef($record, 'preview')) {
         $this->app->abort(403);
     }
     return $this->renderResponse('prod/Share/record.html.twig', ['record' => $record]);
 }
Exemple #3
0
 /**
  *  Share a record
  *
  * @param  Application $app
  * @param  Request     $request
  * @param  integer     $base_id
  * @param  integer     $record_id
  * @return Response
  */
 public function shareRecord(Application $app, Request $request, $base_id, $record_id)
 {
     $record = new \record_adapter($app, \phrasea::sbasFromBas($app, $base_id), $record_id);
     if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_subdef($record, 'preview')) {
         $app->abort(403);
     }
     return new Response($app['twig']->render('prod/Share/record.html.twig', ['record' => $record]));
 }
Exemple #4
0
 public function connect(Application $app)
 {
     $controllers = $this->createAuthenticatedCollection($app);
     $firewall = $this->getFirewall($app);
     $controllers->before(function () use($firewall) {
         $firewall->requireNotGuest();
     });
     $controllers->get('/record/{base_id}/{record_id}/', 'controller.prod.share:shareRecord')->before(function (Request $request) use($app, $firewall) {
         $firewall->requireRightOnSbas(\phrasea::sbasFromBas($app, $request->attributes->get('base_id')), 'bas_chupub');
     })->bind('share_record');
     return $controllers;
 }
 /**
  * Prepare a set of documents for download
  *
  * @param Application $app
  * @param Request     $request
  * @param String      $token
  *
  * @return Response
  */
 public function prepareDownload(Application $app, Request $request, $token)
 {
     $datas = $app['tokens']->helloToken($token);
     if (false === ($list = @unserialize((string) $datas['datas']))) {
         $app->abort(500, 'Invalid datas');
     }
     $records = [];
     foreach ($list['files'] as $file) {
         if (!is_array($file) || !isset($file['base_id']) || !isset($file['record_id'])) {
             continue;
         }
         $sbasId = \phrasea::sbasFromBas($app, $file['base_id']);
         try {
             $record = new \record_adapter($app, $sbasId, $file['record_id']);
         } catch (\Exception $e) {
             continue;
         }
         $records[sprintf('%s_%s', $sbasId, $file['record_id'])] = $record;
     }
     return new Response($app['twig']->render('/prod/actions/Download/prepare.html.twig', ['module_name' => $app->trans('Export'), 'module' => $app->trans('Export'), 'list' => $list, 'records' => $records, 'token' => $token, 'anonymous' => $request->query->get('anonymous', false)]));
 }
Exemple #6
0
 /**
  *
  * @param  Application $app
  * @param  int         $base_id
  * @return collection
  */
 public static function get_from_base_id(Application $app, $base_id)
 {
     $coll_id = phrasea::collFromBas($app, $base_id);
     $sbas_id = phrasea::sbasFromBas($app, $base_id);
     if (!$sbas_id || !$coll_id) {
         throw new Exception_Databox_CollectionNotFound(sprintf("Collection with base_id %s could not be found", $base_id));
     }
     $databox = $app['phraseanet.appbox']->get_databox($sbas_id);
     return self::get_from_coll_id($app, $databox, $coll_id);
 }
Exemple #7
0
 /**
  * Return basic information about a record
  *
  * @param integer $bid base id
  * @param integer $rid record id
  * @param array   $tab config for the html table
  *
  * @return array
  */
 public function buildTabUserWhat($bid, $rid, $tab = false)
 {
     $this->initialize();
     $sbas_id = phrasea::sbasFromBas($this->app, $bid);
     try {
         $record = new record_adapter($this->app, $sbas_id, $rid);
     } catch (\Exception_Record_AdapterNotFound $e) {
         return $this->report;
     }
     $this->setDisplay($tab);
     $this->champ = ['photo', 'record_id', 'date', 'type', 'titre', 'taille'];
     $document = $record->get_subdef('document');
     $this->title = $this->app->trans('report:: Information sur l\'enregistrement numero %number%', ['%number%' => (int) $rid]);
     $x = $record->get_thumbnail();
     $this->result[] = ['photo' => "<img style='width:" . $x->get_width() . "px;height:" . $x->get_height() . "px;'\n                        src='" . $x->get_url() . "'>", 'record_id' => $record->get_record_id(), 'date' => $this->app['date-formatter']->getPrettyString($document->get_creation_date()), 'type' => $document->get_mime(), 'titre' => $record->get_title(), 'taille' => $document->get_size()];
     $this->setDisplayNav();
     $this->setReport();
     return $this->report;
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function query($query, $offset, $perPage, SearchEngineOptions $options = null)
 {
     if (null === $options) {
         $options = new SearchEngineOptions();
     }
     $this->initialize();
     $this->checkSession();
     $this->clearAllCache(new \DateTime('-1 hour'));
     assert(is_int($offset));
     assert($offset >= 0);
     assert(is_int($perPage));
     if (trim($query) === '') {
         $query = "all";
     }
     if ($options->getRecordType()) {
         $query .= ' AND recordtype=' . $options->getRecordType();
     }
     $sql = 'SELECT query, query_time, duration, total FROM cache WHERE session_id = :ses_id';
     $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
     $stmt->execute([':ses_id' => $this->app['session']->get('phrasea_session_id')]);
     $row = $stmt->fetch(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $date_obj = new \DateTime('-10 min');
     $date_quest = new \DateTime($row['query_time']);
     if ($query != $row['query']) {
         $this->resetCacheNextQuery = true;
     }
     if ($date_obj > $date_quest) {
         $this->resetCacheNextQuery = true;
     }
     if ($this->resetCacheNextQuery === true) {
         phrasea_clear_cache($this->app['session']->get('phrasea_session_id'));
         $this->addQuery($query, $options);
         $this->executeQuery($query, $options);
         $sql = 'SELECT query, query_time, duration, total FROM cache WHERE session_id = :ses_id';
         $stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
         $stmt->execute([':ses_id' => $this->app['session']->get('phrasea_session_id')]);
         $row = $stmt->fetch(\PDO::FETCH_ASSOC);
         $stmt->closeCursor();
     } else {
         /**
          * @todo clean this in DB
          */
         $this->total_available = $this->total_results = $this->app['session']->get('phrasea_engine_n_results');
     }
     $res = phrasea_fetch_results($this->app['session']->get('phrasea_session_id'), $offset + 1, $perPage, false);
     $rs = [];
     $error = $this->app->trans('Unable to execute query');
     if (isset($res['results']) && is_array($res['results'])) {
         $rs = $res['results'];
         $error = '';
     }
     $resultNumber = $offset;
     $records = new ArrayCollection();
     foreach ($rs as $data) {
         try {
             $records->add(new \record_adapter($this->app, \phrasea::sbasFromBas($this->app, $data['base_id']), $data['record_id'], $resultNumber));
         } catch (\Exception $e) {
         }
         $resultNumber++;
     }
     $propositions = $this->getPropositions();
     $suggestions = $this->getSuggestions($query);
     return new SearchEngineResult($records, $query, $row['duration'], $offset, $row['total'], $row['total'], $error, '', $suggestions, $propositions, '');
 }
 private function getFlagsRules(\appbox $appbox, \ACL $acl, array $collections)
 {
     $rules = [];
     foreach ($collections as $collectionId) {
         $databoxId = \phrasea::sbasFromBas($this->app, $collectionId);
         $databox = $appbox->get_databox($databoxId);
         $mask_xor = $acl->get_mask_xor($collectionId);
         $mask_and = $acl->get_mask_and($collectionId);
         foreach ($databox->getStatusStructure()->getBits() as $bit) {
             $rules[$databoxId][$collectionId][$bit] = $this->computeAccess($mask_xor, $mask_and, $bit);
         }
     }
     return $rules;
 }
Exemple #10
0
 public function apply_rights()
 {
     $ACL = $this->app->getAclForUser($this->app->getAuthenticatedUser());
     $base_ids = array_keys($ACL->get_granted_base(['canadmin']));
     $update = $create = $delete = $create_sbas = $update_sbas = [];
     foreach ($base_ids as $base_id) {
         $rights = ['access', 'actif', 'canputinalbum', 'nowatermark', 'candwnldpreview', 'candwnldhd', 'cancmd', 'canaddrecord', 'canmodifrecord', 'chgstatus', 'candeleterecord', 'imgtools', 'canadmin', 'canreport', 'canpush', 'manage', 'modify_struct'];
         foreach ($rights as $k => $right) {
             if ($right == 'access' && !$ACL->has_access_to_base($base_id) || $right != 'access' && !$ACL->has_right_on_base($base_id, $right)) {
                 unset($rights[$k]);
                 continue;
             }
             $rights[$k] = $right . '_' . $base_id;
         }
         $parm = $this->unserializedRequestData($this->app['request'], $rights, 'values');
         foreach ($parm as $p => $v) {
             if (trim($v) == '') {
                 continue;
             }
             $serial = explode('_', $p);
             $base_id = array_pop($serial);
             $p = implode('_', $serial);
             if ($p == 'access') {
                 if ($v === '1') {
                     $create_sbas[\phrasea::sbasFromBas($this->app, $base_id)] = \phrasea::sbasFromBas($this->app, $base_id);
                     $create[] = $base_id;
                 } else {
                     $delete[] = $base_id;
                 }
             } else {
                 $create_sbas[\phrasea::sbasFromBas($this->app, $base_id)] = \phrasea::sbasFromBas($this->app, $base_id);
                 $update[$base_id][$p] = $v;
             }
         }
     }
     $sbas_ids = $ACL->get_granted_sbas();
     foreach ($sbas_ids as $databox) {
         $rights = ['bas_modif_th', 'bas_manage', 'bas_modify_struct', 'bas_chupub'];
         foreach ($rights as $k => $right) {
             if (!$ACL->has_right_on_sbas($databox->get_sbas_id(), $right)) {
                 unset($rights[$k]);
                 continue;
             }
             $rights[$k] = $right . '_' . $databox->get_sbas_id();
         }
         $parm = $this->unserializedRequestData($this->app['request'], $rights, 'values');
         foreach ($parm as $p => $v) {
             if (trim($v) == '') {
                 continue;
             }
             $serial = explode('_', $p);
             $sbas_id = array_pop($serial);
             $p = implode('_', $serial);
             $update_sbas[$sbas_id][$p] = $v;
         }
     }
     foreach ($this->users as $usr_id) {
         try {
             $this->app->getApplicationBox()->get_connection()->beginTransaction();
             $user = $this->app['repo.users']->find($usr_id);
             $this->app->getAclForUser($user)->revoke_access_from_bases($delete)->give_access_to_base($create)->give_access_to_sbas($create_sbas);
             foreach ($update as $base_id => $rights) {
                 $this->app->getAclForUser($user)->update_rights_to_base($base_id, $rights);
             }
             foreach ($update_sbas as $sbas_id => $rights) {
                 $this->app->getAclForUser($user)->update_rights_to_sbas($sbas_id, $rights);
             }
             $this->app->getApplicationBox()->get_connection()->commit();
             $this->app->getAclForUser($user)->revoke_unused_sbas_rights();
             unset($user);
         } catch (\Exception $e) {
             $this->app->getApplicationBox()->get_connection()->rollBack();
         }
     }
     return $this;
 }
Exemple #11
0
 /**
  * @param int $base_id
  * @return collection
  */
 public function get_collection($base_id)
 {
     $sbas_id = phrasea::sbasFromBas($this->app, $base_id);
     if ($sbas_id === false) {
         throw new \RuntimeException('Collection not found.');
     }
     $collections = $this->get_databox($sbas_id)->get_collections();
     foreach ($collections as $collection) {
         if ($collection->get_base_id() == $base_id) {
             return $collection;
         }
     }
     // This should not happen, but I'd rather be safe than sorry.
     throw new \RuntimeException('Collection not found.');
 }
Exemple #12
0
 private function send_mails(Application $app, FtpExport $export)
 {
     $transferts = [];
     $transfert_status = $this->translator->trans('task::ftp:Tous les documents ont ete transferes avec succes');
     foreach ($export->getElements() as $element) {
         if (!$element->isError() && $element->isDone()) {
             $transferts[] = '<li>' . $this->translator->trans('task::ftp:Record %recordid% - %filename% de la base (%databoxname% - %collectionname%) - %subdefname%', ['%recordid%' => $element->getRecordId(), '%filename%' => $element->getFilename(), '%databoxname%' => \phrasea::sbas_labels(\phrasea::sbasFromBas($app, $element->getBaseId()), $app), '%collectionname%' => \phrasea::bas_labels($element->getBaseId(), $app), $element->getSubdef(), '%subdefname%' => $element->getSubdef()]) . ' : ' . $this->translator->trans('Transfert OK') . '</li>';
         } else {
             $transferts[] = '<li>' . $this->translator->trans('task::ftp:Record %recordid% - %filename% de la base (%databoxname% - %collectionname%) - %subdefname%', ['%recordid%' => $element->getRecordId(), '%filename%' => $element->getFilename(), '%databoxname%' => \phrasea::sbas_labels(\phrasea::sbasFromBas($app, $element->getBaseId()), $app), '%collectionname%' => \phrasea::bas_labels($element->getBaseId(), $app), $element->getSubdef(), '%subdefname%' => $element->getSubdef()]) . ' : ' . $this->translator->trans('Transfert Annule') . '</li>';
             $transfert_status = $this->translator->trans('task::ftp:Certains documents n\'ont pas pu etre tranferes');
         }
     }
     if ($export->getCrash() >= $export->getNbretry()) {
         $connection_status = $this->translator->trans('Des difficultes ont ete rencontres a la connection au serveur distant');
     } else {
         $connection_status = $this->translator->trans('La connection vers le serveur distant est OK');
     }
     $text_mail_sender = $export->getTextMailSender();
     $text_mail_receiver = $export->getTextMailReceiver();
     $sendermail = $export->getSendermail();
     $ftp_server = $export->getAddr();
     $message = "\n\n----------------------------------------\n\n";
     $message = $connection_status . "\n";
     $message .= $transfert_status . "\n";
     $message .= $this->translator->trans("task::ftp:Details des fichiers") . "\n\n";
     $message .= implode("\n", $transferts);
     $sender_message = $text_mail_sender . $message;
     $receiver_message = $text_mail_receiver . $message;
     try {
         $receiver = new Receiver(null, $sendermail);
         $mail = MailSuccessFTPSender::create($app, $receiver, null, $sender_message);
         $mail->setServer($ftp_server);
         $app['notification.deliverer']->deliver($mail);
     } catch (InvalidArgumentException $e) {
     }
     try {
         $receiver = new Receiver(null, $export->getMail());
         $mail = MailSuccessFTPReceiver::create($app, $receiver, null, $receiver_message);
         $mail->setServer($ftp_server);
         $app['notification.deliverer']->deliver($mail);
     } catch (\Exception $e) {
         $this->log('debug', sprintf('Unable to deliver success message : %s', $e->getMessage()));
     }
 }
Exemple #13
0
 /**
  * Send an order
  *
  * @param  Application                   $app
  * @param  Request                       $request
  * @param  integer                       $order_id
  * @return RedirectResponse|JsonResponse
  */
 public function sendOrder(Application $app, Request $request, $order_id)
 {
     $success = false;
     if (null === ($order = $app['EM']->getRepository('Phraseanet:Order')->find($order_id))) {
         throw new NotFoundHttpException('Order not found');
     }
     $basket = $order->getBasket();
     if (null === $basket) {
         $basket = new Basket();
         $basket->setName($app->trans('Commande du %date%', ['%date%' => $order->getCreatedOn()->format('Y-m-d')]));
         $basket->setUser($order->getUser());
         $basket->setPusher($app['authentication']->getUser());
         $app['EM']->persist($basket);
         $app['EM']->flush();
     }
     $n = 0;
     $elements = $request->request->get('elements', []);
     foreach ($order->getElements() as $orderElement) {
         if (in_array($orderElement->getId(), $elements)) {
             $sbas_id = \phrasea::sbasFromBas($app, $orderElement->getBaseId());
             $record = new \record_adapter($app, $sbas_id, $orderElement->getRecordId());
             $basketElement = new BasketElement();
             $basketElement->setRecord($record);
             $basketElement->setBasket($basket);
             $orderElement->setOrderMaster($app['authentication']->getUser());
             $orderElement->setDeny(false);
             $orderElement->getOrder()->setBasket($basket);
             $basket->addElement($basketElement);
             $n++;
             $app['acl']->get($basket->getUser())->grant_hd_on($record, $app['authentication']->getUser(), 'order');
         }
     }
     try {
         if ($n > 0) {
             $order->setTodo($order->getTodo() - $n);
             $app['events-manager']->trigger('__ORDER_DELIVER__', ['ssel_id' => $order->getBasket()->getId(), 'from' => $app['authentication']->getUser()->getId(), 'to' => $order->getUser()->getId(), 'n' => $n]);
         }
         $success = true;
         $app['EM']->persist($basket);
         $app['EM']->persist($orderElement);
         $app['EM']->persist($order);
         $app['EM']->flush();
     } catch (\Exception $e) {
     }
     if ('json' === $app['request']->getRequestFormat()) {
         return $app->json(['success' => $success, 'msg' => $success ? $app->trans('Order has been sent') : $app->trans('An error occured while sending, please retry  or contact an admin if problem persists'), 'order_id' => $order_id]);
     }
     return $app->redirectPath('prod_orders', ['success' => (int) $success, 'action' => 'send']);
 }
Exemple #14
0
 /**
  * Display suggested values
  *
  * @param Application $app     The silex application
  * @param Request     $request The current request
  * @param integer     $bas_id  The collection base_id
  */
 public function getSuggestedValues(Application $app, Request $request, $bas_id)
 {
     $databox = $app['phraseanet.appbox']->get_databox(\phrasea::sbasFromBas($app, $bas_id));
     $collection = \collection::get_from_base_id($app, $bas_id);
     $structFields = $suggestedValues = $basePrefs = [];
     foreach ($databox->get_meta_structure() as $meta) {
         if ($meta->is_readonly()) {
             continue;
         }
         $structFields[$meta->get_name()] = $meta;
     }
     if ($sxe = simplexml_load_string($collection->get_prefs())) {
         $z = $sxe->xpath('/baseprefs/sugestedValues');
         if ($z && is_array($z)) {
             $f = 0;
             foreach ($z[0] as $ki => $vi) {
                 if ($vi && isset($structFields[$ki])) {
                     foreach ($vi->value as $oneValue) {
                         $suggestedValues[] = ['key' => $ki, 'value' => $f, 'name' => (string) $oneValue];
                         $f++;
                     }
                 }
             }
         }
         $z = $sxe->xpath('/baseprefs');
         if ($z && is_array($z)) {
             foreach ($z[0] as $ki => $vi) {
                 $pref = ['status' => null, 'xml' => null];
                 if ($ki == 'status') {
                     $pref['status'] = $vi;
                 } elseif ($ki != 'sugestedValues') {
                     $pref['xml'] = $vi->asXML();
                 }
                 $basePrefs[] = $pref;
             }
         }
     }
     return $app['twig']->render('admin/collection/suggested_value.html.twig', ['collection' => $collection, 'databox' => $databox, 'suggestedValues' => $suggestedValues, 'structFields' => $structFields, 'basePrefs' => $basePrefs]);
 }
 /**
  * Send an order
  *
  * @param  Request $request
  * @param  integer $order_id
  * @return RedirectResponse|JsonResponse
  */
 public function sendOrder(Request $request, $order_id)
 {
     $success = false;
     /** @var Order $order */
     if (null === ($order = $this->getOrderRepository()->find($order_id))) {
         throw new NotFoundHttpException('Order not found');
     }
     $manager = $this->getEntityManager();
     $basket = $order->getBasket();
     if (null === $basket) {
         $basket = new Basket();
         $basket->setName($this->app->trans('Commande du %date%', ['%date%' => $order->getCreatedOn()->format('Y-m-d')]));
         $basket->setUser($order->getUser());
         $basket->setPusher($this->getAuthenticatedUser());
         $manager->persist($basket);
         $manager->flush();
     }
     $n = 0;
     $elements = $request->request->get('elements', []);
     foreach ($order->getElements() as $orderElement) {
         if (in_array($orderElement->getId(), $elements)) {
             $sbas_id = \phrasea::sbasFromBas($this->app, $orderElement->getBaseId());
             $record = new \record_adapter($this->app, $sbas_id, $orderElement->getRecordId());
             $basketElement = new BasketElement();
             $basketElement->setRecord($record);
             $basketElement->setBasket($basket);
             $orderElement->setOrderMaster($this->getAuthenticatedUser());
             $orderElement->setDeny(false);
             $orderElement->getOrder()->setBasket($basket);
             $basket->addElement($basketElement);
             $n++;
             $this->getAclForUser($basket->getUser())->grant_hd_on($record, $this->getAuthenticatedUser(), 'order');
         }
     }
     try {
         if ($n > 0) {
             $order->setTodo($order->getTodo() - $n);
             $this->dispatch(PhraseaEvents::ORDER_DELIVER, new OrderDeliveryEvent($order, $this->getAuthenticatedUser(), $n));
         }
         $success = true;
         // There was a basketElement persist here. Seems useless as all entities are managed.
         $manager->persist($basket);
         $manager->persist($order);
         $manager->flush();
     } catch (\Exception $e) {
     }
     if ('json' === $request->getRequestFormat()) {
         return $this->app->json(['success' => $success, 'msg' => $success ? $this->app->trans('Order has been sent') : $this->app->trans('An error occured while sending, please retry  or contact an admin if problem persists'), 'order_id' => $order_id]);
     }
     return $this->app->redirectPath('prod_orders', ['success' => (int) $success, 'action' => 'send']);
 }
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     try {
         $sql = 'ALTER TABLE `ssel` ADD `migrated` INT NOT NULL DEFAULT "0"';
         $stmt = $appbox->get_connection()->prepare($sql);
         $stmt->execute();
         $stmt->closeCursor();
     } catch (\Exception $e) {
     }
     $sql = 'SELECT ssel_id, usr_id, name, descript, pub_date, updater, pub_restrict, homelink
             FROM ssel
             WHERE (public = "1" OR homelink="1")
               AND migrated = 0';
     $stmt = $appbox->get_connection()->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $date_ref = new DateTime();
     $n = 0;
     $app['orm.em']->getEventManager()->removeEventSubscriber(new TimestampableListener());
     foreach ($rs as $row) {
         if (null === ($user = $this->loadUser($app['orm.em'], $row['usr_id']))) {
             continue;
         }
         $feed = $this->get_feed($app, $appbox, $user, $row['pub_restrict'], $row['homelink']);
         if (!$feed instanceof Feed) {
             continue;
         }
         $publishers = $feed->getPublishers();
         $entry = new FeedEntry();
         $entry->setAuthorEmail((string) $user->getEmail());
         $entry->setAuthorName((string) $user->getDisplayName());
         $entry->setFeed($feed);
         $entry->setPublisher($publishers->first());
         $entry->setTitle($row['name']);
         $entry->setSubtitle($row['descript']);
         $feed->addEntry($entry);
         $date_create = new DateTime($row['pub_date']);
         if ($date_create < $date_ref) {
             $date_ref = $date_create;
         }
         $entry->setCreatedOn($date_create);
         if ($row['updater'] != '0000-00-00 00:00:00') {
             $date_update = new DateTime($row['updater']);
             $entry->setUpdatedOn($date_update);
         }
         $sql = 'SELECT sselcont_id, ssel_id, base_id, record_id
                 FROM sselcont
                 WHERE ssel_id = :ssel_id
                 ORDER BY ord ASC';
         $stmt = $appbox->get_connection()->prepare($sql);
         $stmt->execute([':ssel_id' => $row['ssel_id']]);
         $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
         $stmt->closeCursor();
         foreach ($rs as $row) {
             try {
                 $record = new record_adapter($app, phrasea::sbasFromBas($app, $row['base_id']), $row['record_id']);
                 $item = new FeedItem();
                 $item->setEntry($entry);
                 $entry->addItem($item);
                 $item->setRecordId($record->get_record_id());
                 $item->setSbasId($record->get_sbas_id());
                 $app['orm.em']->persist($item);
             } catch (NotFoundHttpException $e) {
             }
         }
         $app['orm.em']->persist($entry);
         $sql = 'UPDATE ssel SET deleted = "1", migrated="1"
                 WHERE ssel_id = :ssel_id';
         $stmt = $appbox->get_connection()->prepare($sql);
         $stmt->execute([':ssel_id' => $row['ssel_id']]);
         $stmt->closeCursor();
         $app['orm.em']->persist($feed);
         $n++;
         if ($n % 1000 == 0) {
             $app['orm.em']->flush();
             $app['orm.em']->clear();
         }
     }
     $this->set_feed_dates($date_ref);
     $app['orm.em']->flush();
     $app['orm.em']->clear();
     $app['orm.em']->getEventManager()->removeEventSubscriber(new TimestampableListener());
     return true;
 }
Exemple #17
0
 /**
  * @todo a revoir le cas anonymous
  *
  * @param Application $app
  * @param Array       $list
  * @param String      $type
  * @param boolean     $anonymous
  * @param string      $comment
  *
  * @return Void
  */
 public static function log_download(Application $app, array $list, $type, $anonymous = false, $comment = '')
 {
     $tmplog = [];
     $files = $list['files'];
     $event_names = ['mail-export' => Session_Logger::EVENT_EXPORTMAIL, 'download' => Session_Logger::EVENT_EXPORTDOWNLOAD];
     $event_name = isset($event_names[$type]) ? $event_names[$type] : Session_Logger::EVENT_EXPORTDOWNLOAD;
     foreach ($files as $record) {
         foreach ($record["subdefs"] as $o => $obj) {
             $sbas_id = phrasea::sbasFromBas($app, $record['base_id']);
             $record_object = new record_adapter($app, $sbas_id, $record['record_id']);
             $app['phraseanet.logger']($record_object->get_databox())->log($record_object, $event_name, $o, $comment);
             if ($o != "caption") {
                 $log["rid"] = $record_object->get_record_id();
                 $log["subdef"] = $o;
                 $log["poids"] = $obj["size"];
                 $log["shortXml"] = $app['serializer.caption']->serialize($record_object->get_caption(), CaptionSerializer::SERIALIZE_XML);
                 $tmplog[$record_object->get_base_id()][] = $log;
                 if (!$anonymous && $o == 'document') {
                     $app['acl']->get($app['authentication']->getUser())->remove_remaining($record_object->get_base_id());
                 }
             }
             unset($record_object);
         }
     }
     $list_base = array_unique(array_keys($tmplog));
     if (!$anonymous) {
         $sql = "UPDATE basusr\n            SET remain_dwnld = :remain_dl\n            WHERE base_id = :base_id AND usr_id = :usr_id";
         $stmt = $app['phraseanet.appbox']->get_connection()->prepare($sql);
         foreach ($list_base as $base_id) {
             if ($app['acl']->get($app['authentication']->getUser())->is_restricted_download($base_id)) {
                 $params = [':remain_dl' => $app['acl']->get($app['authentication']->getUser())->remaining_download($base_id), ':base_id' => $base_id, ':usr_id' => $app['acl']->get($app['authentication']->getUser())->getId()];
                 $stmt->execute($params);
             }
         }
         $stmt->closeCursor();
     }
     return;
 }
Exemple #18
0
 /**
  *
  * @return record_exportElement
  */
 protected function get_actions()
 {
     $this->downloadable = $downloadable = [];
     $this->orderable = $orderable = [];
     $sd = $this->get_subdefs();
     $sbas_id = phrasea::sbasFromBas($this->app, $this->base_id);
     $subdefgroups = $this->app['phraseanet.appbox']->get_databox($sbas_id)->get_subdef_structure();
     $subdefs = [];
     foreach ($subdefgroups as $subdef_type => $subdefs_obj) {
         if ($subdef_type == $this->get_type()) {
             $subdefs = $subdefs_obj;
             break;
         }
     }
     $go_dl = ['document' => false, 'preview' => false, 'thumbnail' => true];
     if ($this->app['acl']->get($this->app['authentication']->getUser())->has_right_on_base($this->get_base_id(), 'candwnldhd')) {
         $go_dl['document'] = true;
     }
     if ($this->app['acl']->get($this->app['authentication']->getUser())->has_right_on_base($this->get_base_id(), 'candwnldpreview')) {
         $go_dl['preview'] = true;
     }
     if ($this->app['acl']->get($this->app['authentication']->getUser())->has_hd_grant($this)) {
         $go_dl['document'] = true;
         $go_dl['preview'] = true;
     }
     if ($this->app['acl']->get($this->app['authentication']->getUser())->has_preview_grant($this)) {
         $go_dl['preview'] = true;
     }
     $query = $this->app['phraseanet.user-query'];
     $masters = $query->on_base_ids([$this->base_id])->who_have_right(['order_master'])->execute()->get_results();
     $go_cmd = count($masters) > 0 && $this->app['acl']->get($this->app['authentication']->getUser())->has_right_on_base($this->base_id, 'cancmd');
     $orderable['document'] = false;
     $downloadable['document'] = false;
     if (isset($sd['document']) && is_file($sd['document']->get_pathfile())) {
         if ($go_dl['document'] === true) {
             if ($this->app['acl']->get($this->app['authentication']->getUser())->is_restricted_download($this->base_id)) {
                 $this->remain_hd--;
                 if ($this->remain_hd >= 0) {
                     $localizedLabel = $this->app->trans('document original');
                     $downloadable['document'] = ['class' => 'document', 'label' => $localizedLabel];
                 }
             } else {
                 $localizedLabel = $this->app->trans('document original');
                 $downloadable['document'] = ['class' => 'document', 'label' => $localizedLabel];
             }
         }
         if ($go_cmd === true) {
             $orderable['document'] = true;
         }
         $this->add_count('document', $sd['document']->get_size());
     }
     foreach ($subdefs as $subdef) {
         $name = $subdef->get_name();
         $class = $subdef->get_class();
         $subdef_label = $name;
         foreach ($subdef->get_labels() as $lang => $label) {
             if (trim($label) == '') {
                 continue;
             }
             if ($lang == $this->app['locale']) {
                 $subdef_label = $label;
                 break;
             }
             $subdef_label = $label;
         }
         $downloadable[$name] = false;
         $downloadable_settings = $subdef->is_downloadable();
         if (!$downloadable_settings || $go_dl[$class] === false) {
             continue;
         }
         if ($go_dl[$class]) {
             if (isset($sd[$name]) && $sd[$name]->is_physically_present()) {
                 if ($class == 'document') {
                     if ($this->app['acl']->get($this->app['authentication']->getUser())->is_restricted_download($this->base_id)) {
                         $this->remain_hd--;
                         if ($this->remain_hd >= 0) {
                             $downloadable[$name] = ['class' => $class, 'label' => $subdef_label];
                         }
                     } else {
                         $downloadable[$name] = ['class' => $class, 'label' => $subdef_label];
                     }
                 } else {
                     $downloadable[$name] = ['class' => $class, 'label' => $subdef_label];
                 }
                 $this->add_count($name, $sd[$name]->get_size());
             }
         }
     }
     $xml = $this->app['serializer.caption']->serialize($this->get_caption(), CaptionSerializer::SERIALIZE_XML);
     if ($xml) {
         $localizedLabel = $this->app->trans('caption XML');
         $downloadable['caption'] = ['class' => 'caption', 'label' => $localizedLabel];
         $this->add_count('caption', strlen($xml));
         $localizedLabel = $this->app->trans('caption YAML');
         $downloadable['caption-yaml'] = ['class' => 'caption', 'label' => $localizedLabel];
         $this->add_count('caption-yaml', strlen(strip_tags($xml)));
     }
     $this->downloadable = $downloadable;
     $this->orderable = $orderable;
     return $this;
 }
 /**
  * Edit a record share state
  * @param Request $request
  * @param $base_id
  * @param $record_id
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function editRecordSharing(Request $request, $base_id, $record_id)
 {
     $record = new \record_adapter($this->app, \phrasea::sbasFromBas($this->app, $base_id), $record_id);
     $subdefName = (string) $request->request->get('name');
     $state = $request->request->get('state') == 'true' ? true : false;
     $acl = $this->getAclForUser();
     if (!$acl->has_right('bas_chupub') || !$acl->has_right_on_base($record->getBaseId(), 'canmodifrecord') || !$acl->has_right_on_base($record->getBaseId(), 'imgtools') || 'document' == $subdefName && !$acl->has_right_on_base($record->getBaseId(), 'candwnldhd') || 'document' != $subdefName && !$acl->has_access_to_subdef($record, $subdefName)) {
         $this->app->abort(403);
     }
     $subdef = $record->get_subdef($subdefName);
     if (null === ($permalink = $subdef->get_permalink())) {
         return $this->app->json(['success' => false, 'state' => false], 400);
     }
     try {
         $permalink->set_is_activated($state);
         $return = ['success' => true, 'state' => $permalink->get_is_activated()];
     } catch (\Exception $e) {
         $return = ['success' => false, 'state' => $permalink->get_is_activated()];
     }
     return $this->app->json($return);
 }
Exemple #20
0
 /**
  * {@inheritdoc}
  */
 protected function doJob(JobData $data)
 {
     $app = $data->getApplication();
     $task = $data->getTask();
     $settings = simplexml_load_string($task->getSettings());
     $baseId = (string) $settings->base_id;
     $sbasId = \phrasea::sbasFromBas($app, $baseId);
     if (!$sbasId) {
         throw new RuntimeException('Invalid collection base_id.');
     }
     $databox = $app->findDataboxById($sbasId);
     $TColls = [];
     $collection = null;
     foreach ($databox->get_collections() as $coll) {
         $TColls['c' . $coll->get_coll_id()] = $coll->get_coll_id();
         if ($baseId == $coll->get_base_id()) {
             $collection = $coll;
         }
     }
     $server_coll_id = $collection->get_coll_id();
     // mask(s) of accepted files
     $tmask = [];
     $tmaskgrp = [];
     $cold = min(max((int) $settings->cold, self::MINCOLD), self::MAXCOLD);
     $stat0 = $stat1 = "0";
     if (false !== ($sxBasePrefs = simplexml_load_string($collection->get_prefs()))) {
         if ($sxBasePrefs->status) {
             $stat0 = (string) $sxBasePrefs->status;
         }
     }
     if ($settings->status) {
         $stat1 = (string) $settings->status;
     }
     if (!$stat0) {
         $stat0 = '0';
     }
     if (!$stat1) {
         $stat1 = '0';
     }
     // check the data-repository exists
     $pathhd = (string) $settings->path;
     if ($pathhd) {
         $app['filesystem']->mkdir($pathhd, 0750);
     }
     // load masks
     if ($settings->files && $settings->files->file) {
         foreach ($settings->files->file as $ft) {
             $tmask[] = ["mask" => (string) $ft["mask"], "caption" => (string) $ft["caption"], "accept" => (string) $ft["accept"]];
         }
     }
     if ($settings->files && $settings->files->grouping) {
         foreach ($settings->files->grouping as $ft) {
             $tmaskgrp[] = ["mask" => (string) $ft["mask"], "caption" => (string) $ft["caption"], "representation" => (string) $ft["representation"], "accept" => (string) $ft["accept"]];
         }
     }
     if (count($tmask) == 0) {
         // no mask defined : accept all kind of files
         $tmask[] = ["mask" => ".*", "caption" => "", "accept" => ""];
     }
     while ($this->isStarted()) {
         $path_in = (string) $settings->hotfolder;
         if (!@is_dir($path_in)) {
             throw new RuntimeException(sprintf('Error : missing hotfolder \'%s\', stopping.', $path_in));
         }
         // copy settings to task, so it's easier to get later
         $moveArchived = \p4field::isyes($settings->move_archived);
         $moveError = \p4field::isyes($settings->move_error);
         clearstatcache();
         if (false === $app['filesystem']->exists($path_in . "/.phrasea.xml")) {
             throw new RuntimeException(sprintf('NO .phrasea.xml AT ROOT \'%s\' !', $path_in));
         }
         $path_archived = $path_error = null;
         if ($moveArchived) {
             $path_archived = $path_in . '_archived';
             $app['filesystem']->mkdir($path_archived, 0755);
         }
         if ($moveError) {
             $path_error = $path_in . '_error';
             $app['filesystem']->mkdir($path_error, 0755);
         }
         $dom = new \DOMDocument();
         $dom->formatOutput = true;
         $root = $dom->appendChild($dom->createElement('root'));
         $nnew = $this->listFilesPhase1($app, $dom, $root, $path_in, $server_coll_id, 0, $TColls);
         if ($app['debug']) {
             $this->log('debug', "=========== listFilesPhase1 ========== (returned " . $nnew . ")\n" . $dom->saveXML());
         }
         if (!$this->isStarted()) {
             return;
         }
         // wait for files to be cold
         $this->pause($cold);
         if (!$this->isStarted()) {
             return;
         }
         $this->listFilesPhase2($app, $dom, $root, $path_in, 0);
         if ($app['debug']) {
             $this->log('debug', "=========== listFilesPhase2 ========== : \n" . $dom->saveXML());
         }
         if (!$this->isStarted()) {
             return;
         }
         $this->makePairs($dom, $root, $path_in, $path_archived, $path_error, false, 0, $tmask, $tmaskgrp);
         if ($app['debug']) {
             $this->log('debug', "=========== makePairs ========== : \n" . $dom->saveXML());
         }
         $r = $this->removeBadGroups($app, $dom, $root, $path_in, $path_archived, $path_error, 0, $moveError);
         if ($app['debug']) {
             $this->log('debug', "=========== removeBadGroups ========== (returned " . ((bool) $r ? 'true' : 'false') . ") : \n" . $dom->saveXML());
         }
         $this->archive($app, $databox, $dom, $root, $path_in, $path_archived, $path_error, 0, $moveError, $moveArchived, $stat0, $stat1);
         if ($app['debug']) {
             $this->log('debug', "=========== archive ========== : \n" . $dom->saveXML());
         }
         if (!$this->isStarted()) {
             return;
         }
         $this->bubbleResults($dom, $root, $path_in, 0, \p4field::isyes($settings->copy_spe));
         if ($app['debug']) {
             $this->log('debug', "=========== bubbleResults ========== : \n" . $dom->saveXML());
         }
         $moved = $this->moveFiles($app, $dom, $root, $path_in, $path_archived, $path_error, 0, $moveArchived, $moveError);
         if ($app['debug']) {
             $this->log('debug', "=========== moveFiles ========== (returned " . ($moved ? 'true' : 'false') . ") : \n" . $dom->saveXML());
         }
     }
 }
Exemple #21
0
 /**
  *
  * @return array
  */
 public function get_distinct_sbas_ids()
 {
     $ret = [];
     foreach ($this->elements as $record) {
         $sbas_id = phrasea::sbasFromBas($this->app, $record->get_base_id());
         $ret[$sbas_id] = $sbas_id;
     }
     return $ret;
 }
Exemple #22
0
 /**
  * Apply a template on user
  *
  * @param  User  $template_user
  * @param  array $base_ids
  * @return ACL
  */
 public function apply_model(User $template_user, array $base_ids)
 {
     if (count($base_ids) == 0) {
         return $this;
     }
     $sbas_ids = [];
     foreach ($base_ids as $base_id) {
         $sbas_ids[] = phrasea::sbasFromBas($this->app, $base_id);
     }
     $sbas_ids = array_unique($sbas_ids);
     $sbas_rights = ['bas_manage', 'bas_modify_struct', 'bas_modif_th', 'bas_chupub'];
     $sbas_to_acces = [];
     $rights_to_give = [];
     foreach ($this->app['acl']->get($template_user)->get_granted_sbas() as $databox) {
         $sbas_id = $databox->get_sbas_id();
         if (!in_array($sbas_id, $sbas_ids)) {
             continue;
         }
         if (!$this->has_access_to_sbas($sbas_id)) {
             $sbas_to_acces[] = $sbas_id;
         }
         foreach ($sbas_rights as $right) {
             if ($this->app['acl']->get($template_user)->has_right_on_sbas($sbas_id, $right)) {
                 $rights_to_give[$sbas_id][$right] = '1';
             }
         }
     }
     $this->give_access_to_sbas($sbas_to_acces);
     foreach ($rights_to_give as $sbas_id => $rights) {
         $this->update_rights_to_sbas($sbas_id, $rights);
     }
     $bas_rights = ['canputinalbum', 'candwnldhd', 'candwnldpreview', 'cancmd', 'canadmin', 'actif', 'canreport', 'canpush', 'canaddrecord', 'canmodifrecord', 'candeleterecord', 'chgstatus', 'imgtools', 'manage', 'modify_struct', 'nowatermark', 'order_master'];
     $bas_to_acces = $masks_to_give = $rights_to_give = [];
     /**
      * map masks (and+xor) of template to masks to apply to user on base
      * (and_and, and_or, xor_and, xor_or)
      */
     $sbmap = ['00' => ['aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'], '01' => ['aa' => '1', 'ao' => '0', 'xa' => '1', 'xo' => '0'], '10' => ['aa' => '1', 'ao' => '1', 'xa' => '0', 'xo' => '0'], '11' => ['aa' => '1', 'ao' => '1', 'xa' => '1', 'xo' => '1']];
     foreach ($this->app['acl']->get($template_user)->get_granted_base() as $collection) {
         $base_id = $collection->get_base_id();
         if (!in_array($base_id, $base_ids)) {
             continue;
         }
         if (!$this->has_access_to_base($base_id)) {
             $bas_to_acces[] = $base_id;
         }
         foreach ($bas_rights as $right) {
             if ($this->app['acl']->get($template_user)->has_right_on_base($base_id, $right)) {
                 $rights_to_give[$base_id][$right] = '1';
             }
         }
         $mask_and = $this->app['acl']->get($template_user)->get_mask_and($base_id);
         $mask_xor = $this->app['acl']->get($template_user)->get_mask_xor($base_id);
         /**
          * apply sb is substractive
          */
         $mand = substr(str_repeat('0', 32) . decbin($mask_and), -32);
         $mxor = substr(str_repeat('0', 32) . decbin($mask_xor), -32);
         $m = ['aa' => '', 'ao' => '', 'xa' => '', 'xo' => ''];
         for ($i = 0; $i < 32; $i++) {
             $ax = $mand[$i] . $mxor[$i];
             foreach ($m as $k => $v) {
                 $m[$k] .= $sbmap[$ax][$k];
             }
         }
         $masks_to_give[$base_id] = ['aa' => $m['aa'], 'ao' => $m['ao'], 'xa' => $m['xa'], 'xo' => $m['xo']];
     }
     $this->give_access_to_base($bas_to_acces);
     foreach ($masks_to_give as $base_id => $mask) {
         $this->set_masks_on_base($base_id, $mask['aa'], $mask['ao'], $mask['xa'], $mask['xo']);
     }
     foreach ($rights_to_give as $base_id => $rights) {
         $this->update_rights_to_base($base_id, $rights);
     }
     $this->apply_template_time_limits($template_user, $base_ids);
     $this->user->setLastAppliedTemplate($template_user);
     return $this;
 }
Exemple #23
0
 /**
  * Returns the matching sbasId
  *
  * @param  Application $app
  * @return int
  */
 public function getSbasId(Application $app)
 {
     return \phrasea::sbasFromBas($app, $this->getBaseId());
 }