Example #1
0
 /**
  * @Route("/gallery/photoAlbum/{id}")
  */
 public function photoAlbumction(Request $request, $id)
 {
     $album = $this->getDoctrine()->getRepository('AppBundle:Album')->find($id);
     $userSession = $this->get('security.context')->getToken()->getUser()->getId();
     if ($album->getUser() != $userSession) {
         return new Response("<h2>No tienes acceso a este album<h2>");
     }
     // 1) build the form
     $photo = new Photo();
     $photo->setAlbum($id);
     $photo->setUser($userSession);
     $photo->setTags("");
     $form = $this->createForm(new PhotoType(), $photo);
     // 2) handle the submit (will only happen on POST)
     $form->handleRequest($request);
     if (!$form->isValid()) {
         echo $form->getErrorsAsString();
     }
     if ($form->isValid() && $form->isSubmitted()) {
         //$file = $request->files->get('image');
         $strm = fopen($photo->getFile()->getRealPath(), 'rb');
         $var = file_get_contents($photo->getFile()->getPathname());
         $photo->setImage($var);
         $em = $this->getDoctrine()->getManager();
         $em->persist($photo);
         $em->flush();
         return new RedirectResponse($this->generateUrl('app_photo_photoalbumction', array('id' => $id)));
     }
     $em = $this->getDoctrine()->getManager();
     $query = $em->createQuery('SELECT p
          FROM AppBundle:Photo p, AppBundle:Album a
         WHERE p.album = :album AND a.user = :user')->setParameters(array('album' => $id, 'user' => $userSession));
     $photos = $query->getResult();
     return $this->render('default/addPhoto.html.twig', array('form' => $form->createView(), 'datos' => $photos));
 }
Example #2
0
 public function testConstruct()
 {
     $photo = new Photo();
     $this->assertInstanceOf('\\DateTime', $photo->getDate());
     $this->assertInstanceOf('\\DateTime', $photo->getUploadDate());
     $this->assertInstanceOf('Doctrine\\Common\\Collections\\ArrayCollection', $photo->getComments());
 }
 /**
  * @Route("/photo")
  * @Method({"POST", "OPTIONS"})
  */
 public function postPhotoAction(Request $request)
 {
     $albumId = $request->request->get('albumId');
     $dateString = $request->request->get('date');
     $files = $request->files->get('photo', array());
     try {
         $date = new \DateTime($dateString);
     } catch (\Exception $e) {
         return new JsonResponse(array('message' => 'Invalid arguments', 'list' => array('date: Unable to parse string.')), 422);
     }
     // Create an array if only one photo was uploaded
     if (!is_array($files)) {
         $files = array($files);
     }
     $em = $this->getDoctrine()->getManager();
     $album = $em->getRepository('AppBundle:Album')->findOneById($albumId);
     if (null === $album) {
         $data = array('message' => 'Invalid parameters', 'list' => array('albumId: no album with such id.'));
         return new JsonResponse($data, 422);
     }
     $this->denyAccessUnlessGranted('edit', $album, 'You cannot add photos to this album.');
     foreach ($files as $file) {
         $photo = new Photo();
         $photo->setDate($date)->setUploadDate(new \DateTime())->setAuthor($this->getUser())->setFile($file);
         $album->addPhoto($photo);
     }
     $validator = $this->get('validator');
     $errors = $validator->validate($album);
     if (count($errors) > 0) {
         return new JsonResponse(Util::violationListToJson($errors), 422);
     }
     $em->persist($album);
     $em->flush();
     return new JsonResponse(array('message' => 'Photo added.'));
 }
Example #4
0
 public function testSetGallery()
 {
     $photo = new Photo();
     $gallery = new \AppBundle\Entity\Gallery();
     $photo->setGallery($gallery);
     $this->assertEquals($gallery, $photo->getGallery());
 }
 public function load(ObjectManager $manager)
 {
     $photo = new Photo();
     $photo->setTitle('First');
     $photo->setLink('1111.png');
     $manager->persist($photo);
     $manager->flush();
     $this->addReference('photo', $photo);
 }
 /**
  * @ORM\PostRemove()
  */
 public function removeFiles(Photo $photo, LifecycleEventArgs $event)
 {
     $fileNames = $photo->getTempFileNames();
     if (is_array($fileNames)) {
         foreach ($fileNames as $name) {
             $this->safeUnlink($this->uploadRootDir . $name);
         }
     }
 }
Example #7
0
 private function canDelete(Photo $photo, User $user = null)
 {
     if ($photo->getAuthor() == $user) {
         return true;
     }
     if ($photo->getAlbum()->getAuthors()->contains($user)) {
         return true;
     }
     return false;
 }
 public function testArray()
 {
     $photo = new Photo();
     $photo->setNom('wohoo');
     $serialized = $this->type->convertToDatabaseValue([$photo], $this->plateform);
     $unserialized = $this->type->convertToPHPValue($serialized, $this->plateform);
     $this->assertInstanceOf(Photo::class, $unserialized[0]);
     /** @var Photo $var */
     $var = $unserialized[0];
     $this->assertEquals('wohoo', $var->getNom());
 }
 public function photosAction($album)
 {
     /** @var \AppBundle\Entity\PhotoRepository $photoRepository */
     $photoRepository = $this->getDoctrine()->getRepository('AppBundle:Photo');
     /** @var \AppBundle\Entity\AlbumRepository $albumRepository */
     $albumRepository = $this->getDoctrine()->getRepository('AppBundle:Album');
     $album = $albumRepository->findOneBy(array('id' => $album));
     $photos = $photoRepository->findBy(array('album' => $album));
     $photo = new Photo();
     $photo->setAlbum($album);
     $form = $this->createForm(new PhotoType(), $photo);
     return $this->render('AppBundle:Admin:photos.html.twig', array('photos' => $photos, 'album' => $album, 'form' => $form->createView()));
 }
 /**
  * Adds tags to photo.
  *
  * @param Photo $photo
  * @param array $tags
  */
 public function addTagsToPhoto(Photo $photo, array $tags)
 {
     $photo->removeTags();
     $em = $this->getEntityManager();
     foreach ($tags as $name) {
         $tag = $this->findOneBy(['name' => $name]);
         if (!$tag instanceof Tag) {
             $tag = new Tag();
             $tag->setName($name);
             $em->persist($tag);
             $em->flush();
         }
         $photo->addTag($tag);
     }
 }
Example #11
0
 /**
  * Add photo
  *
  * @param \AppBundle\Entity\Photo $photo
  *
  * @return Album
  */
 public function addPhoto(Photo $photo)
 {
     $this->photos[] = $photo;
     $photo->setAlbum($this);
     return $this;
 }
 /**
  * @Route("/upload/{t}", name="_upload")
  */
 public function uploadAction(Request $request, $t = 'b')
 {
     if ($t == 'a') {
         $title = '';
         $type = 0;
         $num = (int) $request->get('num');
         $file_name = 'photoA' . $num . '.png';
     } else {
         $uploadedFile = $request->files->get('image');
         if ($uploadedFile == null || !in_array(strtolower($uploadedFile->getClientOriginalExtension()), array('png', 'jpg', 'jpeg', 'gif'))) {
             return new Response('只能上传照片喔~');
         } elseif (!$uploadedFile->isValid()) {
             return new Response($uploadedFile->getErrorMessage());
         } else {
             $file_path = preg_replace('/app$/si', 'web/uploads', $this->get('kernel')->getRootDir());
             //$file_path = $request->getBasePath().$this->path;
             $file_name = date('YmdHis') . rand(1000, 9999) . '.' . $uploadedFile->getClientOriginalExtension();
             $fs = new Filesystem();
             if (!$fs->exists($file_path)) {
                 try {
                     $fs->mkdir($file_path);
                 } catch (IOException $e) {
                     return new Response('服务器发生错误,无法创建文件夹:' . $e->getPath());
                     //$result['msg'] = '服务器发生错误,无法创建文件夹:'.$e->getPath();
                 }
             }
             $uploadedFile->move($file_path, $file_name);
             $scale = $request->get('scale');
             $pos_x = (int) $request->get('pos_x');
             $pos_y = (int) $request->get('pos_y');
             $num = $request->get('num');
             $title = trim($request->get('title'));
             $img_url = $file_path . '/' . $file_name;
             $imagine = new Imagine();
             $exif = @exif_read_data($img_url, 0, true);
             if (isset($exif['IFD0']['Orientation'])) {
                 $photo = $imagine->open($img_url);
                 if ($exif['IFD0']['Orientation'] == 6) {
                     $photo->rotate(90)->save($img_url);
                 } elseif ($exif['IFD0']['Orientation'] == 3) {
                     $photo->rotate(180)->save($img_url);
                 }
             }
             $photo = $imagine->open($img_url);
             $size = $photo->getSize();
             $width = 640;
             $height = 1039;
             $w1 = $width * $scale;
             $h1 = $w1 * $size->getHeight() / $size->getWidth();
             $imagine->open($img_url)->resize(new Box($w1, $h1))->save($img_url);
             $imagine->open($img_url)->resize(new Box($w1, $h1))->save($img_url);
             #左移裁切
             if ($pos_x < 0) {
                 $size = $imagine->open($img_url)->getSize();
                 $imagine->open($img_url)->crop(new Point(abs($pos_x), 0), new Box($size->getWidth() - abs($pos_x), $size->getHeight()))->save($img_url);
             }
             #上移裁切
             if ($pos_y < 0) {
                 $size = $imagine->open($img_url)->getSize();
                 $imagine->open($img_url)->crop(new Point(0, abs($pos_y)), new Box($size->getWidth(), $size->getHeight() - abs($pos_y)))->save($img_url);
             }
             #右移拼贴
             if ($pos_x > 0) {
                 $photo = $imagine->open($img_url);
                 $size = $photo->getSize();
                 $collage_width = $pos_x + $size->getWidth() > $width ? $pos_x + $size->getWidth() : $width;
                 $collage_height = $size->getHeight();
                 $collage = $imagine->create(new Box($collage_width, $collage_height));
                 $collage->paste($photo, new Point($pos_x, 0))->save($img_url);
             }
             #下移拼贴
             if ($pos_y > 0) {
                 $photo = $imagine->open($img_url);
                 $size = $photo->getSize();
                 $collage_width = $size->getWidth();
                 $collage_height = $pos_y + $size->getHeight() > $width ? $pos_y + $size->getHeight() : $height;
                 $collage = $imagine->create(new Box($collage_width, $collage_height));
                 $collage->paste($photo, new Point(0, $pos_y))->save($img_url);
             }
             #超出剪切
             $photo = $imagine->open($img_url);
             $size = $photo->getSize();
             $_width = $size->getWidth();
             if ($size->getWidth() > $width) {
                 $_width = $width;
                 $imagine->open($img_url)->crop(new Point(0, 0), new Box($_width, $size->getHeight()))->save($img_url);
             }
             if ($size->getHeight() > $height) {
                 $imagine->open($img_url)->crop(new Point(0, 0), new Box($_width, $height))->save($img_url);
             }
             $photo = $imagine->open($img_url);
             $collage = $imagine->create(new Box($width, $height));
             $collage->paste($photo, new Point(0, 0))->save($img_url);
             $collage = $imagine->open('bundles/app/default/images/photoB' . $num . '.png');
             $photo = $imagine->open($img_url);
             $photo->paste($collage, new Point(0, 0))->save($img_url);
             $type = 1;
             /*
             $photo = $imagine->open($img_url);
             $color = new \Imagine\Image\Color;
             $font = new \Imagine\Gd\Font('',30, $color);
             $photo->draw()->text('tesintg',$font,new Point(0,0),0);
             */
         }
     }
     $em = $this->getDoctrine()->getManager();
     $em->getConnection()->beginTransaction();
     try {
         $photo = new Entity\Photo();
         $user = $this->getUser();
         $photo->setImgUrl($file_name);
         $photo->setUser($user);
         $photo->setTitle($title);
         $photo->setType($type);
         $photo->setFavourNum(0);
         $photo->setCreateIp($request->getClientIp());
         $photo->setCreateTime(new \DateTime('now'));
         $em->persist($photo);
         $em->flush();
         $em->getConnection()->commit();
         return $this->redirect($this->generateUrl('_finish', array('id' => $photo->getId())));
     } catch (Exception $e) {
         $em->getConnection()->rollback();
         return new Response($e->getMessage());
         //$json['ret'] = 1001;
         //$json['msg']= $e->getMessage();
     }
 }
 public function testContent_UserAnonyme_PageComplete()
 {
     $pageEleveur = $this->testUtils->createUser()->toEleveur()->addAnimal()->getPageEleveur();
     $pageEleveur->setDescription('nouvelle description');
     $pageEleveur->setEspeces('chats');
     $pageEleveur->setRaces('chartreux');
     /*
      * Enregistrement d'une actualité en base pour simuler le fait que
      * la page eleveur a déjà une actualité.
      */
     /** @var EntityManager $entityManager */
     $entityManager = $this->client->getContainer()->get('doctrine.orm.entity_manager');
     $actualite1 = new Actualite($this->getName() . rand(), new \DateTime('2015/12/25'));
     $entityManager->persist($actualite1);
     $entityManager->flush($actualite1);
     $this->testUtils->clearEntities();
     /* On doit avancer le temps pour que les actualités aient des createdAt différents
        parceque les requêtes font des orderBy createdAt */
     $actu = rand();
     $pageEleveur->setActualites([$actualite1, new Actualite($actu, new \DateTime())]);
     $pageAnimal = $pageEleveur->getAnimaux()[0];
     $photo = new Photo();
     $photo->setNom('portrait');
     $pageAnimal->setPhotos([$photo]);
     /** @var PageEleveurService $pageEleveurService */
     $pageEleveurService = $this->client->getContainer()->get('zigotoo.page_eleveur');
     /** @var PageAnimalService $pageAnimalService */
     $pageAnimalService = $this->client->getContainer()->get('zigotoo.page_animal');
     $pageEleveur = $pageEleveurService->commit($this->testUtils->getUser(), $pageEleveur);
     $pageAnimalService->commit($this->testUtils->getUser(), $pageAnimal);
     $this->testUtils->logout();
     $this->testUtils->clearEntities();
     $crawler = $this->client->request('GET', '/elevage/' . $pageEleveur->getSlug());
     $this->assertEquals($pageEleveur->getNom(), $crawler->filter('h1')->text());
     $this->assertEquals($pageEleveur->getNom(), $crawler->filter('title')->text());
     $this->assertEquals('nouvelle description', $crawler->filter('#description')->text());
     $this->assertEquals('chats', trim($crawler->filter('#especes')->text()));
     $this->assertEquals('chartreux', trim($crawler->filter('#races')->text()));
     $this->assertEquals(1, $crawler->filter('#actualites h2')->count());
     $this->assertEquals(2, $crawler->filter('#actualites .actualite')->count());
     $this->assertContains($actu . '', $crawler->filter('#actualites .actualite')->first()->text());
     $this->assertContains('25/12/2015', $crawler->filter('#actualites .actualite')->nextAll()->text());
     $this->assertContains($actualite1->getContenu(), $crawler->filter('#actualites .actualite')->nextAll()->text());
     $this->assertContains($pageEleveur->getAnimaux()[0]->getNom(), $crawler->filter('#animaux .animal')->text());
     $this->assertContains($photo->getNom(), $crawler->filter('#animaux .animal img')->attr('src'));
     $this->assertContains('Disponible', $crawler->filter('#animaux .animal .statut-animal.chip-valid')->text());
 }
 public function testMappingBranchToModel()
 {
     // Mock d'une page eleveur en base de données
     $user = new User();
     $user->setId(1);
     $pageEleveurBranch = new PageEleveurBranch();
     $pageEleveurBranch->setId(1);
     $pageEleveurBranch->setOwner($user);
     $this->pageEleveurBranchRepository->method('findBySlug')->withAnyParameters()->willReturn($pageEleveurBranch);
     $pageAnimal = new PageAnimalBranch();
     $photo = new Photo();
     $photo->setNom('portrait');
     $pageAnimal->setCommit(new PageAnimalCommit(null, 'bobi', null, '', PageAnimal::DISPONIBLE, PageAnimal::MALE, [$photo]));
     $commit = new PageEleveurCommit(null, 'Tatouine', 'Plein de chartreux', 'Chats', 'Chartreux', 'Roubaix', [$pageAnimal], [new Actualite('Nouvelle portée', new \DateTime())]);
     $pageEleveurBranch->setCommit($commit);
     $this->pageEleveurCommitRepository->method('find')->with($commit->getId())->willReturn($commit);
     // requete cliente par le slug
     $pageEleveur = $this->pageEleveurService->findBySlug('');
     // l'objet PageEleveur est bien rempli
     $this->assertEquals('Tatouine', $pageEleveur->getNom());
     $this->assertEquals('Plein de chartreux', $pageEleveur->getDescription());
     $this->assertEquals('Chats', $pageEleveur->getEspeces());
     $this->assertEquals('Chartreux', $pageEleveur->getRaces());
     $this->assertEquals('Roubaix', $pageEleveur->getLieu());
     $this->assertEquals('Nouvelle portée', $pageEleveur->getActualites()[0]->getContenu());
     $this->assertEquals('portrait', $pageEleveur->getAnimaux()[0]->getPhotos()[0]->getNom());
 }
 public function testMappingBranchToModel()
 {
     $this->timeService->lockNow();
     // mock d'une page animal en bdd
     $pageAnimalBranch = new PageAnimalBranch();
     $pageAnimalBranch->setId(1);
     $this->pageAnimalBranchRepository->method('find')->with(1)->willReturn($pageAnimalBranch);
     $photo = new Photo();
     $photo->setNom('zzccd');
     $commit = new PageAnimalCommit(null, 'rudy', $this->timeService->now(), 'Un beau chien', PageAnimal::DISPONIBLE, PageAnimal::FEMELLE, [$photo]);
     $pageAnimalBranch->setCommit($commit);
     // Requete de la page animal
     $pageAnimal = $this->pageAnimalService->find(1);
     // On vérifie que la page est retournée avec les bonnes données
     $this->assertEquals('rudy', $pageAnimal->getNom());
     $this->assertEquals($this->timeService->now(), $pageAnimal->getDateNaissance());
     $this->assertEquals('Un beau chien', $pageAnimal->getDescription());
     $this->assertEquals(PageAnimal::DISPONIBLE, $pageAnimal->getStatut());
     $this->assertEquals(PageAnimal::FEMELLE, $pageAnimal->getSexe());
     $this->assertEquals('zzccd', $pageAnimal->getPhotos()[0]->getNom());
 }
 public function testCommit_success()
 {
     $pageAnimal = $this->testUtils->createUser()->toEleveur()->addAnimal()->getPageEleveur()->getAnimaux()[0];
     $pageAnimal->setNom('Bernard');
     $pageAnimal->setDateNaissance(new \DateTime('2015/01/18'));
     $pageAnimal->setDescription('Un gros toutou');
     $pageAnimal->setSexe(PageAnimal::FEMELLE);
     $pageAnimal->setStatut(PageAnimal::RESERVE);
     $photo = new Photo();
     $photo->setNom('img1.jpg');
     $pageAnimal->setPhotos([$photo]);
     // Modification du nom et de la description de la page
     $this->client->request('POST', '/animal/' . $pageAnimal->getId(), array(), array(), array(), $this->serializer->serialize($pageAnimal, 'json'));
     $this->assertEquals(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
     /** @var PageAnimalService $pageAnimalService */
     $pageAnimalService = $this->client->getContainer()->get('zigotoo.page_animal');
     $pageAnimal = $pageAnimalService->find($pageAnimal->getId());
     $this->assertEquals($this->serializer->serialize($pageAnimal, 'json'), $this->client->getResponse()->getContent());
     $this->testUtils->clearEntities();
     $crawler = $this->client->request('GET', '/animal/' . $pageAnimal->getId());
     $this->assertEquals($pageAnimal->getNom(), $crawler->filter('title')->text());
     $this->assertContains('18/01/2015', $crawler->filter('#date-naissance')->text());
     $this->assertEquals('Un gros toutou', $crawler->filter('#description')->text());
     $this->assertEquals('Réservé', trim($crawler->filter('select#statut option[selected]')->text()));
     $this->testUtils->logout();
     $this->testUtils->clearEntities();
     $crawler = $this->client->request('GET', '/animal/' . $pageAnimal->getId());
     $this->assertEquals($pageAnimal->getNom(), $crawler->filter('title')->text());
     $this->assertEquals('Femelle', trim($crawler->filter('#sexe')->text()));
     $this->assertContains('18/01/2015', $crawler->filter('#date-naissance')->text());
     $this->assertEquals('Un gros toutou', $crawler->filter('#description')->text());
     $this->assertEquals('Réservé', trim($crawler->filter('#statut')->text()));
     $this->assertEquals(1, $crawler->filter('.photo')->count());
 }
Example #17
0
 public function isAuthorized(Photo $photo, $memberId)
 {
     return $photo->getUser()->getId() == $memberId ? true : false;
 }
Example #18
0
 /**
  * Uploads all the photos when OK i pressed on the upload photo form.
  * @return Response
  * @throws \Exception
  */
 public function uploadAction()
 {
     $request = Request::createFromGlobals();
     //Get the target folder for the photo from paramters.yml
     $output_dir = $this->container->getParameter('gallery_folder') . '/';
     //Create a FileUploader
     $uploader = new FileUploader($output_dir, $this->allowed_file_types);
     //Upload the files aand get the new names created for each file
     $mappedFileNames = $uploader->upload($request);
     //Now all the files are copied to their destination folder
     //The array $mappedFileNames contains entries: $orginalFileName => fileNameWithPathOnSystemNow
     $responseText = '<html> Lastet opp følgende filer: <br>';
     $em = $this->getDoctrine()->getManager();
     foreach ($mappedFileNames as $key => $val) {
         $responseText .= $key . " to " . $val . "<br>";
         //Update the database
         //The text sent with the picture is a parameter with the same name as image + '_text'
         //http://stackoverflow.com/questions/68651/get-php-to-stop-replacing-characters-in-get-or-post-arrays
         //todo: the above SO thing is annoying.
         $commentParameterName = str_replace(".", "_", $key);
         $commentParameterName = str_replace(" ", "_", $commentParameterName);
         $text = $request->get($commentParameterName . '_text');
         $takenDate = $request->get($commentParameterName . '_taken_date_text');
         //Get taken date
         //Get the gallery id
         $gallery_id = $request->get('gallery_id');
         //Create an instance of the entity
         $photo = new Photo();
         $photo->setComment($text);
         $gallery = $this->getDoctrine()->getRepository("AppBundle:Gallery")->find($gallery_id);
         $photo->setGallery($gallery);
         $photo->setDateAdded(new \DateTime("now"));
         $photo->setDateTaken(new \DateTime($takenDate));
         $photo->setAddedByUser($this->get('security.context')->getToken()->getUser());
         $photo->setPathToFile($val);
         //Manage
         $em->persist($photo);
     }
     //Persist
     $em->flush();
     $responseText = $responseText . '</html>';
     return new Response($responseText);
 }
Example #19
0
 public function setMetadata(Photo $photo, array $metadata)
 {
     $photo->setLatitude($metadata['latitude'])->setLongitude($metadata['longitude'])->setTimestamp($metadata['timestamp'])->setDirection($metadata['direction'])->setOrientation($metadata['orientation'])->setModel($metadata['model']);
 }