Esempio n. 1
0
 public function check(EntityManager $em, File $file)
 {
     $boolean = false;
     if (method_exists($file->getMedia(), 'getWidth')) {
         $boolean = $file->getMedia()->getWidth() >= $this->width && $file->getMedia()->getHeight() >= $this->height;
     }
     return new Response($boolean, $this);
 }
Esempio n. 2
0
 public function check(EntityManager $em, File $file)
 {
     if (0 === count($this->extensions)) {
         //if empty authorize all extensions
         $boolean = true;
     } else {
         $boolean = in_array(strtolower($file->getFile()->getExtension()), $this->extensions);
     }
     return new Response($boolean, $this);
 }
Esempio n. 3
0
 public function check(EntityManager $em, File $file)
 {
     // if empty authorize all mediative
     if (0 === count($this->mediaTypes)) {
         $boolean = true;
     } else {
         $boolean = in_array($file->getMedia()->getType(), $this->mediaTypes);
     }
     return new Response($boolean, $this);
 }
Esempio n. 4
0
 /**
  * Returns true if the checker should be executed against the current file
  *
  * @param File $file A file to check
  *
  * @return Boolean
  */
 public function isApplicable(File $file)
 {
     if (null === $file->getCollection()) {
         return true;
     }
     $fileDatabox = $file->getCollection()->get_databox();
     foreach ($this->databoxes as $databox) {
         if ($databox->get_sbas_id() === $fileDatabox->get_sbas_id()) {
             return true;
         }
     }
     foreach ($this->collections as $collection) {
         if ($collection->get_base_id() === $file->getCollection()->get_base_id()) {
             return true;
         }
     }
     return false;
 }
Esempio n. 5
0
 /**
  * @covers Alchemy\Phrasea\Border\Checker\Sha256::check
  */
 public function testCheck()
 {
     $session = self::$DI['app']['EM']->find('Phraseanet:LazaretSession', 1);
     self::$DI['app']['border-manager']->process($session, File::buildFromPathfile($this->media->getFile()->getPathname(), self::$DI['collection'], self::$DI['app']), null, Manager::FORCE_RECORD);
     $mock = $this->getMock('\\Alchemy\\Phrasea\\Border\\File', ['getSha256'], [self::$DI['app'], $this->media, self::$DI['collection']]);
     $mock->expects($this->once())->method('getSha256')->will($this->returnValue('7fad283de349b903c850548cda65cf2d86d24c4e3856cdc2b97e47430494b8c8'));
     $response = $this->object->check(self::$DI['app']['EM'], $mock);
     $this->assertInstanceOf('\\Alchemy\\Phrasea\\Border\\Checker\\Response', $response);
     $this->assertFalse($response->isOk());
 }
Esempio n. 6
0
 public function check(EntityManager $em, File $file)
 {
     $boolean = false;
     if (0 === count($this->colorspaces)) {
         $boolean = true;
         //bypass color if empty array
     } elseif (method_exists($file->getMedia(), 'getColorSpace')) {
         $colorspace = null;
         switch ($file->getMedia()->getColorSpace()) {
             case \MediaVorus\Media\Image::COLORSPACE_CMYK:
                 $colorspace = self::COLORSPACE_CMYK;
                 break;
             case \MediaVorus\Media\Image::COLORSPACE_RGB:
             case \MediaVorus\Media\Image::COLORSPACE_SRGB:
                 $colorspace = self::COLORSPACE_RGB;
                 break;
             case \MediaVorus\Media\Image::COLORSPACE_GRAYSCALE:
                 $colorspace = self::COLORSPACE_GRAYSCALE;
                 break;
         }
         $boolean = $colorspace !== null && in_array(strtolower($colorspace), $this->colorspaces);
     }
     return new Response($boolean, $this);
 }
Esempio n. 7
0
 /**
  * {@inheritdoc}
  */
 public function check(EntityManager $em, File $file)
 {
     $boolean = !count(\record_adapter::get_records_by_originalname($file->getCollection()->get_databox(), $file->getOriginalName(), $this->sensitive, 0, 1));
     return new Response($boolean, $this);
 }
Esempio n. 8
0
 protected function getQuarantineItem()
 {
     $lazaretSession = new LazaretSession();
     self::$DI['app']['orm.em']->persist($lazaretSession);
     $quarantineItem = null;
     $callback = function ($element, $visa, $code) use(&$quarantineItem) {
         $quarantineItem = $element;
     };
     $tmpname = tempnam(sys_get_temp_dir(), 'test_quarantine');
     copy(__DIR__ . '/../../../../files/iphone_pic.jpg', $tmpname);
     $file = File::buildFromPathfile($tmpname, self::$DI['collection'], self::$DI['app']);
     self::$DI['app']['border-manager']->process($lazaretSession, $file, $callback, Manager::FORCE_LAZARET);
     return $quarantineItem;
 }
Esempio n. 9
0
 /**
  * Add technical Metadata attribute to a package file by reference to add it
  * to Phraseanet
  *
  * @param  File                        $file The file
  * @return \Doctrine\ORM\EntityManager
  */
 protected function addMediaAttributes(File $file)
 {
     if (method_exists($file->getMedia(), 'getWidth')) {
         $file->addAttribute(new MetadataAttr(new Metadata(new TfWidth(), new MonoValue($file->getMedia()->getWidth()))));
     }
     if (method_exists($file->getMedia(), 'getHeight')) {
         $file->addAttribute(new MetadataAttr(new Metadata(new TfHeight(), new MonoValue($file->getMedia()->getHeight()))));
     }
     if (method_exists($file->getMedia(), 'getChannels')) {
         $file->addAttribute(new MetadataAttr(new Metadata(new TfChannels(), new MonoValue($file->getMedia()->getChannels()))));
     }
     if (method_exists($file->getMedia(), 'getColorDepth')) {
         $file->addAttribute(new MetadataAttr(new Metadata(new TfBits(), new MonoValue($file->getMedia()->getColorDepth()))));
     }
     if (method_exists($file->getMedia(), 'getDuration')) {
         $file->addAttribute(new MetadataAttr(new Metadata(new TfDuration(), new MonoValue($file->getMedia()->getDuration()))));
     }
     if ($file->getFile()->getMimeType() == 'application/pdf' && null !== $this->pdfToText) {
         try {
             $text = $this->pdfToText->getText($file->getFile()->getRealPath());
             if (trim($text)) {
                 $file->addAttribute(new MetadataAttr(new Metadata(new PdfText(), new MonoValue($text))));
             }
         } catch (\XPDF\Exception\Exception $e) {
         }
     }
     $file->addAttribute(new MetadataAttr(new Metadata(new TfMimetype(), new MonoValue($file->getFile()->getMimeType()))));
     $file->addAttribute(new MetadataAttr(new Metadata(new TfSize(), new MonoValue($file->getFile()->getSize()))));
     $file->addAttribute(new MetadataAttr(new Metadata(new TfBasename(), new MonoValue(pathinfo($file->getOriginalName(), PATHINFO_BASENAME)))));
     $file->addAttribute(new MetadataAttr(new Metadata(new TfFilename(), new MonoValue(pathinfo($file->getOriginalName(), PATHINFO_FILENAME)))));
     $file->addAttribute(new MetadataAttr(new Metadata(new TfExtension(), new MonoValue(pathinfo($file->getOriginalName(), PATHINFO_EXTENSION)))));
     return $this;
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function check(EntityManager $em, File $file)
 {
     $boolean = !count($file->getCollection()->get_databox()->getRecordRepository()->findByUuid($file->getUUID()));
     return new Response($boolean, $this);
 }
 private function insertLazaretFiles(EntityManager $em, \Pimple $DI)
 {
     $session = new LazaretSession();
     $session->setUser($DI['user']);
     $em->persist($session);
     $em->flush();
     $file = File::buildFromPathfile($this->container['root.path'] . '/tests/files/cestlafete.jpg', $DI['coll'], $this->container);
     $callback = function ($element) use($DI) {
         $DI['lazaret_1'] = $element;
     };
     $this->container['border-manager']->process($session, $file, $callback, Manager::FORCE_LAZARET);
 }
Esempio n. 12
0
 /**
  * @covers Alchemy\Phrasea\Border\Manager::getVisa
  */
 public function testGetVisa()
 {
     $records = [];
     $postProcessRecord = function ($record) use(&$records) {
         $records[] = $record;
     };
     self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
     $visa = $this->object->getVisa(File::buildFromPathfile(self::$file1, self::$DI['collection'], self::$DI['app']));
     $this->assertInstanceOf('\\Alchemy\\Phrasea\\Border\\Visa', $visa);
     $this->assertTrue($visa->isValid());
     $this->object->process($this->session, File::buildFromPathfile(self::$file1, self::$DI['collection'], self::$DI['app']), $postProcessRecord);
     $visa = $this->object->getVisa(File::buildFromPathfile(self::$file1, self::$DI['collection'], self::$DI['app']));
     $this->assertInstanceOf('\\Alchemy\\Phrasea\\Border\\Visa', $visa);
     $this->assertTrue($visa->isValid());
     $this->object->registerChecker(new Sha256(self::$DI['app']));
     $visa = $this->object->getVisa(File::buildFromPathfile(self::$file1, self::$DI['collection'], self::$DI['app']));
     $this->assertInstanceOf('\\Alchemy\\Phrasea\\Border\\Visa', $visa);
     $this->assertFalse($visa->isValid());
     foreach ($records as $record) {
         if ($record instanceof \record_adapter) {
             $record->delete();
         }
     }
 }
Esempio n. 13
0
 public function addRecordAction(Request $request)
 {
     if (count($request->files->get('file')) == 0) {
         return $this->getBadRequestAction($request, 'Missing file parameter');
     }
     $file = $request->files->get('file');
     if (!$file instanceof UploadedFile) {
         return $this->getBadRequestAction($request, 'You can upload one file at time');
     }
     if (!$file->isValid()) {
         return $this->getBadRequestAction($request, 'Data corrupted, please try again');
     }
     if (!$request->get('base_id')) {
         return $this->getBadRequestAction($request, 'Missing base_id parameter');
     }
     $collection = \collection::get_from_base_id($this->app, $request->get('base_id'));
     if (!$this->getAclForUser()->has_right_on_base($request->get('base_id'), 'canaddrecord')) {
         return Result::createError($request, 403, sprintf('You do not have access to collection %s', $collection->get_label($this->app['locale'])))->createResponse();
     }
     $media = $this->app->getMediaFromUri($file->getPathname());
     $Package = new File($this->app, $media, $collection, $file->getClientOriginalName());
     if ($request->get('status')) {
         $Package->addAttribute(new Status($this->app, $request->get('status')));
     }
     $session = new LazaretSession();
     $session->setUser($this->getAuthenticatedUser());
     $entityManager = $this->app['orm.em'];
     $entityManager->persist($session);
     $entityManager->flush();
     $reasons = $output = null;
     $translator = $this->app['translator'];
     $callback = function ($element, Visa $visa) use($translator, &$reasons, &$output) {
         if (!$visa->isValid()) {
             $reasons = array_map(function (CheckerResponse $response) use($translator) {
                 return $response->getMessage($translator);
             }, $visa->getResponses());
         }
         $output = $element;
     };
     switch ($request->get('forceBehavior')) {
         case '0':
             $behavior = Manager::FORCE_RECORD;
             break;
         case '1':
             $behavior = Manager::FORCE_LAZARET;
             break;
         case null:
             $behavior = null;
             break;
         default:
             return $this->getBadRequestAction($request, sprintf('Invalid forceBehavior value `%s`', $request->get('forceBehavior')));
     }
     $nosubdef = $request->get('nosubdefs') === '' || \p4field::isyes($request->get('nosubdefs'));
     $this->getBorderManager()->process($session, $Package, $callback, $behavior, $nosubdef);
     $ret = ['entity' => null];
     if ($output instanceof \record_adapter) {
         $ret['entity'] = '0';
         $ret['url'] = '/records/' . $output->getDataboxId() . '/' . $output->getRecordId() . '/';
         $this->dispatch(PhraseaEvents::RECORD_UPLOAD, new RecordEdit($output));
     }
     if ($output instanceof LazaretFile) {
         $ret['entity'] = '1';
         $ret['url'] = '/quarantine/item/' . $output->getId() . '/';
     }
     return Result::create($request, $ret)->createResponse();
 }
Esempio n. 14
0
 /**
  * Add technical Metadata attribute to a package file by reference to add it
  * to Phraseanet
  *
  * @param File $file The file
  */
 protected function addMediaAttributes(File $file)
 {
     $metadataCollection = $this->app['phraseanet.metadata-reader']->read($file->getMedia());
     array_walk($metadataCollection, function (Metadata $metadata) use($file) {
         $file->addAttribute(new MetadataAttr($metadata));
     });
     return $this;
 }
Esempio n. 15
0
 /**
  * Creates a record
  *
  * @param  \collection     $collection  The destination collection
  * @param  string          $pathfile    The file to archive
  * @param  string|null     $captionFile The Phrasea XML caption file or null if no caption file
  * @param  integer         $grp_rid     Add the record to a story
  * @param  integer         $force       Force lazaret or record ; use \Alchemy\Phrasea\Border\Manager::FORCE_* constants
  * @return \record_adapter
  */
 public function createRecord(Application $app, \collection $collection, $pathfile, $captionFile, $grp_rid, $force, $stat0, $stat1)
 {
     $status = \databox_status::operation_or($stat0, $stat1);
     $media = $app->getMediaFromUri($pathfile);
     $databox = $collection->get_databox();
     $metadatasStructure = $databox->get_meta_structure();
     $metadatas = $this->getIndexByFieldName($metadatasStructure, $media->getMetadatas());
     $metaFields = [];
     if ($captionFile !== null && true === $app['filesystem']->exists($captionFile)) {
         $metaFields = $this->readXMLForDatabox($app, $metadatasStructure, $captionFile);
         $captionStatus = $this->parseStatusBit(@simplexml_load_file($captionFile));
         if ($captionStatus) {
             $status = \databox_status::operation_mask($status, $captionStatus);
         }
     }
     $file = new File($app, $media, $collection);
     $file->addAttribute(new BorderAttribute\Status($app, $status));
     $file->addAttribute(new BorderAttribute\Metadata(new Metadata(new PhraseaTag\TfFilepath(), new MonoValue($media->getFile()->getRealPath()))));
     $file->addAttribute(new BorderAttribute\Metadata(new Metadata(new PhraseaTag\TfDirname(), new MonoValue(dirname($media->getFile()->getRealPath())))));
     $file->addAttribute(new BorderAttribute\Metadata(new Metadata(new PhraseaTag\TfAtime(), new MonoValue($media->getFile()->getATime()))));
     $file->addAttribute(new BorderAttribute\Metadata(new Metadata(new PhraseaTag\TfMtime(), new MonoValue($media->getFile()->getMTime()))));
     $file->addAttribute(new BorderAttribute\Metadata(new Metadata(new PhraseaTag\TfCtime(), new MonoValue($media->getFile()->getCTime()))));
     foreach ($metadatas as $meta) {
         $file->addAttribute(new BorderAttribute\Metadata($meta));
     }
     foreach ($metaFields as $metaField) {
         $file->addAttribute($metaField);
     }
     if ($grp_rid) {
         $file->addAttribute(new BorderAttribute\Story(new \record_adapter($app, $databox->get_sbas_id(), $grp_rid)));
     }
     $record = null;
     $postProcess = function ($element, $visa, $code) use(&$record) {
         $record = $element;
     };
     $app['border-manager']->process($this->getLazaretSession($app), $file, $postProcess, $force);
     return $record;
 }
Esempio n. 16
0
 /**
  * Update a record with a UUID
  *
  * @param \databox $databox
  * @param array    $record
  */
 protected function updateRecordUUID(\databox $databox, array $record)
 {
     $pathfile = \p4string::addEndSlash($record['path']) . $record['file'];
     $uuid = Uuid::uuid4();
     try {
         $media = $this->app['mediavorus']->guess($pathfile);
         $collection = \collection::get_from_coll_id($this->{$app}, $databox, (int) $record['coll_id']);
         $file = new File($this->app, $media, $collection);
         $uuid = $file->getUUID(true, true);
         $sha256 = $file->getSha256();
         $this->app['monolog']->addInfo(sprintf("Upgrading record %d with uuid %s", $record['record_id'], $uuid));
     } catch (\Exception $e) {
         $this->app['monolog']->addError(sprintf("Uuid upgrade for record %s failed", $record['record_id']));
     }
     $sql = 'UPDATE record SET uuid = :uuid, sha256 = :sha256 WHERE record_id = :record_id';
     $params = [':uuid' => $uuid, 'sha256' => $sha256, ':record_id' => $record['record_id']];
     $stmt = $databox->get_connection()->prepare($sql);
     $stmt->execute($params);
     $stmt->closeCursor();
 }
Esempio n. 17
0
 /**
  * @covers Alchemy\Phrasea\Border\File::getType
  */
 public function testGetTypeNoType()
 {
     $noType = $this->getMediaMock(null);
     $file = new File(self::$DI['app'], $noType, self::$DI['collection'], 'hello');
     $this->assertNull($file->getType());
 }
Esempio n. 18
0
 /**
  *
  * @param File        $file
  * @param Application $app
  *
  * @return \record_adapter
  */
 public static function createFromFile(File $file, Application $app)
 {
     $databox = $file->getCollection()->get_databox();
     $sql = 'INSERT INTO record
           (coll_id, record_id, parent_record_id, moddate, credate
             , type, sha256, uuid, originalname, mime)
         VALUES
           (:coll_id, null, :parent_record_id, NOW(), NOW()
           , :type, :sha256, :uuid
           , :originalname, :mime)';
     $stmt = $databox->get_connection()->prepare($sql);
     $stmt->execute([':coll_id' => $file->getCollection()->get_coll_id(), ':parent_record_id' => 0, ':type' => $file->getType() ? $file->getType()->getType() : 'unknown', ':sha256' => $file->getMedia()->getHash('sha256'), ':uuid' => $file->getUUID(true), ':originalname' => $file->getOriginalName(), ':mime' => $file->getFile()->getMimeType()]);
     $record_id = $databox->get_connection()->lastInsertId();
     $record = new self($app, $databox->get_sbas_id(), $record_id);
     try {
         $log_id = $app['phraseanet.logger']($databox)->get_id();
         $sql = 'INSERT INTO log_docs (id, log_id, date, record_id, action, final, comment)
         VALUES (null, :log_id, now(),
           :record_id, "add", :coll_id,"")';
         $stmt = $databox->get_connection()->prepare($sql);
         $stmt->execute([':log_id' => $log_id, ':record_id' => $record_id, ':coll_id' => $file->getCollection()->get_coll_id()]);
         $stmt->closeCursor();
     } catch (\Exception $e) {
         unset($e);
     }
     $pathhd = databox::dispatch($app['filesystem'], trim($databox->get_sxml_structure()->path));
     $newname = $record->get_record_id() . "_document." . pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
     $app['filesystem']->copy($file->getFile()->getRealPath(), $pathhd . $newname, true);
     $media = $app['mediavorus']->guess($pathhd . $newname);
     media_subdef::create($app, $record, 'document', $media);
     $record->delete_data_from_cache(\record_adapter::CACHE_SUBDEFS);
     $record->insertTechnicalDatas($app['mediavorus']);
     $record->rebuild_subdefs();
     return $record;
 }
Esempio n. 19
0
 /**
  * Add an element to phraseanet
  *
  * @param Application $app     A Silex application
  * @param Request     $request The current request
  * @param int         $file_id A lazaret element id
  *
  * parameters   : 'bas_id'            int     (mandatory) : The id of the destination collection
  *                'keep_attributes'   boolean (optional)  : Keep all attributes attached to the lazaret element
  *                'attributes'        array   (optional)  : Attributes id's to attach to the lazaret element
  *
  * @return Response
  */
 public function addElement(Application $app, Request $request, $file_id)
 {
     $ret = ['success' => false, 'message' => '', 'result' => []];
     //Optional parameter
     $keepAttributes = !!$request->request->get('keep_attributes', false);
     $attributesToKeep = $request->request->get('attributes', []);
     //Mandatory parameter
     if (null === $request->request->get('bas_id')) {
         $ret['message'] = $app->trans('You must give a destination collection');
         return $app->json($ret);
     }
     $lazaretFile = $app['EM']->find('Phraseanet:LazaretFile', $file_id);
     /* @var $lazaretFile LazaretFile */
     if (null === $lazaretFile) {
         $ret['message'] = $app->trans('File is not present in quarantine anymore, please refresh');
         return $app->json($ret);
     }
     $lazaretFileName = $app['root.path'] . '/tmp/lazaret/' . $lazaretFile->getFilename();
     $lazaretThumbFileName = $app['root.path'] . '/tmp/lazaret/' . $lazaretFile->getThumbFilename();
     try {
         $borderFile = Border\File::buildFromPathfile($lazaretFileName, $lazaretFile->getCollection($app), $app, $lazaretFile->getOriginalName());
         $record = null;
         /* @var $record \record_adapter */
         //Post record creation
         $callBack = function ($element, $visa, $code) use(&$record) {
             $record = $element;
         };
         //Force creation record
         $app['border-manager']->process($lazaretFile->getSession(), $borderFile, $callBack, Border\Manager::FORCE_RECORD);
         $app['phraseanet.SE']->addRecord($record);
         if ($keepAttributes) {
             //add attribute
             $metaFields = new Border\MetaFieldsBag();
             $metadataBag = new Border\MetadataBag();
             foreach ($lazaretFile->getAttributes() as $attr) {
                 //Check which ones to keep
                 if (!!count($attributesToKeep)) {
                     if (!in_array($attr->getId(), $attributesToKeep)) {
                         continue;
                     }
                 }
                 try {
                     $attribute = Border\Attribute\Factory::getFileAttribute($app, $attr->getName(), $attr->getValue());
                 } catch (\InvalidArgumentException $e) {
                     continue;
                 }
                 /* @var $attribute AttributeInterface */
                 switch ($attribute->getName()) {
                     case AttributeInterface::NAME_METADATA:
                         $value = $attribute->getValue();
                         $metadataBag->set($value->getTag()->getTagname(), new \PHPExiftool\Driver\Metadata\Metadata($value->getTag(), $value->getValue()));
                         break;
                     case AttributeInterface::NAME_STORY:
                         $attribute->getValue()->appendChild($record);
                         break;
                     case AttributeInterface::NAME_STATUS:
                         $record->set_binary_status($attribute->getValue());
                         break;
                     case AttributeInterface::NAME_METAFIELD:
                         $metaFields->set($attribute->getField()->get_name(), $attribute->getValue());
                         break;
                 }
             }
             $datas = $metadataBag->toMetadataArray($record->get_databox()->get_meta_structure());
             $record->set_metadatas($datas);
             $fields = $metaFields->toMetadataArray($record->get_databox()->get_meta_structure());
             $record->set_metadatas($fields);
         }
         //Delete lazaret file
         $app['EM']->remove($lazaretFile);
         $app['EM']->flush();
         $ret['success'] = true;
     } catch (\Exception $e) {
         $ret['message'] = $app->trans('An error occured');
     }
     try {
         $app['filesystem']->remove([$lazaretFileName, $lazaretThumbFileName]);
     } catch (IOException $e) {
     }
     return $app->json($ret);
 }
Esempio n. 20
0
 /**
  * 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;
 }
Esempio n. 21
0
 public function testSearchWithRecords()
 {
     $this->authenticate(self::$DI['app']);
     $record = \record_adapter::createFromFile(BorderFile::buildFromPathfile(__DIR__ . '/../../../files/cestlafete.jpg', self::$DI['collection'], self::$DI['app']), self::$DI['app']);
     $request = new Request(['search_type' => 0], [], [], [], [], ['HTTP_Accept' => 'application/json']);
     $result = $this->object->search($request);
     $this->assertEquals(200, $result->get_http_code());
     $this->assertEquals('application/json', $result->get_content_type());
     $this->assertTrue(is_array(json_decode($result->format(), true)));
     $data = json_decode($result->format(), true);
     $this->assertArrayHasKey('records', $data['response']['results']);
     $this->assertArrayHasKey('stories', $data['response']['results']);
     $found = false;
     foreach ($data['response']['results']['records'] as $retRecord) {
         if ($retRecord['record_id'] == $record->get_record_id() && $retRecord['databox_id'] == $record->get_sbas_id()) {
             $found = true;
             break;
         }
     }
     if (!$found) {
         $this->fail('unable to find the record back');
     }
 }
Esempio n. 22
0
 public function add_record(Application $app, Request $request)
 {
     if (count($request->files->get('file')) == 0) {
         return $this->getBadRequest($app, $request, 'Missing file parameter');
     }
     if (!$request->files->get('file') instanceof UploadedFile) {
         return $this->getBadRequest($app, $request, 'You can upload one file at time');
     }
     $file = $request->files->get('file');
     /* @var $file UploadedFile */
     if (!$file->isValid()) {
         return $this->getBadRequest($app, $request, 'Datas corrupted, please try again');
     }
     if (!$request->get('base_id')) {
         return $this->getBadRequest($app, $request, 'Missing base_id parameter');
     }
     $collection = \collection::get_from_base_id($app, $request->get('base_id'));
     if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_base($request->get('base_id'), 'canaddrecord')) {
         return Result::createError($request, 403, sprintf('You do not have access to collection %s', $collection->get_label($app['locale'])))->createResponse();
     }
     $media = $app['mediavorus']->guess($file->getPathname());
     $Package = new File($app, $media, $collection, $file->getClientOriginalName());
     if ($request->get('status')) {
         $Package->addAttribute(new Status($app, $request->get('status')));
     }
     $session = new LazaretSession();
     $session->setUser($app['authentication']->getUser());
     $app['EM']->persist($session);
     $app['EM']->flush();
     $reasons = $output = null;
     $callback = function ($element, $visa, $code) use($app, &$reasons, &$output) {
         if (!$visa->isValid()) {
             $reasons = array_map(function ($response) use($app) {
                 return $response->getMessage($app['translator']);
             }, $visa->getResponses());
         }
         $output = $element;
     };
     switch ($request->get('forceBehavior')) {
         case '0':
             $behavior = BorderManager::FORCE_RECORD;
             break;
         case '1':
             $behavior = BorderManager::FORCE_LAZARET;
             break;
         case null:
             $behavior = null;
             break;
         default:
             return $this->getBadRequest($app, $request, sprintf('Invalid forceBehavior value `%s`', $request->get('forceBehavior')));
     }
     $app['border-manager']->process($session, $Package, $callback, $behavior);
     $ret = ['entity' => null];
     if ($output instanceof \record_adapter) {
         $ret['entity'] = '0';
         $ret['url'] = '/records/' . $output->get_sbas_id() . '/' . $output->get_record_id() . '/';
         $app['phraseanet.SE']->addRecord($output);
     }
     if ($output instanceof LazaretFile) {
         $ret['entity'] = '1';
         $ret['url'] = '/quarantine/item/' . $output->getId() . '/';
     }
     return Result::create($request, $ret)->createResponse();
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  */
 public function check(EntityManager $em, File $file)
 {
     $boolean = !count(\record_adapter::get_record_by_uuid($this->app, $file->getCollection()->get_databox(), $file->getUUID()));
     return new Response($boolean, $this);
 }
Esempio n. 24
0
 /**
  * Add an element to phraseanet
  *
  * @param Request     $request The current request
  * @param int         $file_id A lazaret element id
  *
  * parameters   : 'bas_id'            int     (mandatory) : The id of the destination collection
  *                'keep_attributes'   boolean (optional)  : Keep all attributes attached to the lazaret element
  *                'attributes'        array   (optional)  : Attributes id's to attach to the lazaret element
  *
  * @return Response
  */
 public function addElement(Request $request, $file_id)
 {
     $ret = ['success' => false, 'message' => '', 'result' => []];
     //Optional parameter
     $keepAttributes = !!$request->request->get('keep_attributes', false);
     $attributesToKeep = $request->request->get('attributes', []);
     //Mandatory parameter
     if (null === $request->request->get('bas_id')) {
         $ret['message'] = $this->app->trans('You must give a destination collection');
         return $this->app->json($ret);
     }
     /* @var LazaretFile $lazaretFile */
     $lazaretFile = $this->getLazaretFileRepository()->find($file_id);
     if (null === $lazaretFile) {
         $ret['message'] = $this->app->trans('File is not present in quarantine anymore, please refresh');
         return $this->app->json($ret);
     }
     $path = $this->app['tmp.lazaret.path'];
     $lazaretFileName = $path . '/' . $lazaretFile->getFilename();
     $lazaretThumbFileName = $path . '/' . $lazaretFile->getThumbFilename();
     try {
         $borderFile = Border\File::buildFromPathfile($lazaretFileName, $lazaretFile->getCollection($this->app), $this->app, $lazaretFile->getOriginalName());
         //Post record creation
         /** @var \record_adapter $record */
         $record = null;
         $callBack = function ($element) use(&$record) {
             $record = $element;
         };
         //Force creation record
         $this->getBorderManager()->process($lazaretFile->getSession(), $borderFile, $callBack, Border\Manager::FORCE_RECORD);
         if ($keepAttributes) {
             //add attribute
             $metaFields = new Border\MetaFieldsBag();
             $metadataBag = new Border\MetadataBag();
             foreach ($lazaretFile->getAttributes() as $attr) {
                 //Check which ones to keep
                 if (!!count($attributesToKeep)) {
                     if (!in_array($attr->getId(), $attributesToKeep)) {
                         continue;
                     }
                 }
                 try {
                     $attribute = Border\Attribute\Factory::getFileAttribute($this->app, $attr->getName(), $attr->getValue());
                 } catch (\InvalidArgumentException $e) {
                     continue;
                 }
                 switch ($attribute->getName()) {
                     case AttributeInterface::NAME_METADATA:
                         /** @var Metadata $value */
                         $value = $attribute->getValue();
                         $metadataBag->set($value->getTag()->getTagname(), new Metadata($value->getTag(), $value->getValue()));
                         break;
                     case AttributeInterface::NAME_STORY:
                         /** @var \record_adapter $value */
                         $value = $attribute->getValue();
                         $value->appendChild($record);
                         break;
                     case AttributeInterface::NAME_STATUS:
                         $record->set_binary_status($attribute->getValue());
                         break;
                     case AttributeInterface::NAME_METAFIELD:
                         /** @var Border\Attribute\MetaField $attribute */
                         $metaFields->set($attribute->getField()->get_name(), $attribute->getValue());
                         break;
                 }
             }
             $data = $metadataBag->toMetadataArray($record->get_databox()->get_meta_structure());
             $record->set_metadatas($data);
             $fields = $metaFields->toMetadataArray($record->get_databox()->get_meta_structure());
             $record->set_metadatas($fields);
         }
         //Delete lazaret file
         $manager = $this->getEntityManager();
         $manager->remove($lazaretFile);
         $manager->flush();
         $ret['success'] = true;
     } catch (\Exception $e) {
         $ret['message'] = $this->app->trans('An error occured');
     }
     try {
         $this->getFilesystem()->remove([$lazaretFileName, $lazaretThumbFileName]);
     } catch (IOException $e) {
     }
     return $this->app->json($ret);
 }