/** * @param UserInterface $user * @param string $filter * @param array $runtimeConfig * * @return null|string */ public function getUserAvartar(UserInterface $user = null, $filter = '70x70', array $runtimeConfig = array()) { if (!$user) { return; } if ($avatar = $user->getProfilePicture()) { if (preg_match('/\\/\\//', $avatar)) { return $avatar; } if (empty($runtimeConfig)) { $runtimeConfig = array('thumbnail' => array("size" => explode('x', $filter), "mode" => 'inset')); } /** * We must to define `sizing` filter first! * eg. * * liip_imagine: * filter_sets: * sizing: * data_loader: cmf_media_doctrine_phpcr * filters: * thumbnail: { size: [200, 200], mode: inset } */ return $this->cacheManager->getBrowserPath($avatar, 'sizing', $runtimeConfig); } return; }
/** * Gets the browser path for the image and filter to apply. * * @param string $path * @param string $filter * @param array $runtimeConfig * * @return \Twig_Markup */ public function filter($path, $filter, array $runtimeConfig = array()) { return new \Twig_Markup( $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig), 'utf8' ); }
public function reverseConvert($object) { if (is_string($object)) { return $this->cacheManager->getBrowserPath($object, 'user_photo_review'); } return $this->defaultAvatar; }
/** * @param Request $request * @param string $filename * * @throws NotFoundHttpException If media is not found * * @return Response */ public function showAction(Request $request, $filename) { if (!$this->filesystem->has($filename)) { throw new NotFoundHttpException(sprintf('Media "%s" not found', $filename)); } $response = new Response($content = $this->filesystem->read($filename)); $mime = $this->filesystem->mimeType($filename); if (($filter = $request->query->get('filter')) && null !== $mime && 0 === strpos($mime, 'image')) { try { $cachePath = $this->cacheManager->resolve($request, $filename, $filter); if ($cachePath instanceof Response) { $response = $cachePath; } else { $image = $this->imagine->load($content); $response = $this->filterManager->get($request, $filter, $image, $filename); $response = $this->cacheManager->store($response, $cachePath, $filter); } } catch (\RuntimeException $e) { if (0 === strpos($e->getMessage(), 'Filter not defined')) { throw new HttpException(404, sprintf('The filter "%s" cannot be found', $filter), $e); } throw $e; } } if ($mime) { $response->headers->set('Content-Type', $mime); } return $response; }
/** * @param ObjectEvent $event */ public function onPostSerialize(ObjectEvent $event) { // getSubscribedEvents doesn't seem to support parent classes if (!$event->getObject() instanceof MediaInterface) { return; } $provider = $this->pool->getProvider($event->getObject()->getProvider()); if ($provider->getName() == 'image') { $reference = $provider->getThumb($event->getObject()); $groups = $event->getContext()->attributes->get('groups'); if (!$groups instanceof None && in_array('detail', $groups->get())) { $filters = array_keys($this->filterConfig->all()); } else { $filters = ['medialibrary']; } $variants = []; foreach ($filters as $filter) { if ($event->getObject()->getContentType() == 'image/svg+xml') { $variants[$filter] = $provider->getUrl($event->getObject()); } else { $variants[$filter] = $this->cacheManager->getBrowserPath($reference, $filter); } } $event->getVisitor()->addData('images', $variants); } $event->getVisitor()->addData('original', $provider->getUrl($event->getObject())); }
/** * delete the given file * * @param string $file */ public function deleteFile($file) { if (!$this->filesystem->has($file)) { return; } $this->filesystem->delete($file); $this->cacheManager->remove($file); }
/** * @param File $file * * @return string|null */ private function getThumbnail(File $file) { $ext = $this->getExtension($file); if (!in_array($ext, self::IMAGE_EXTENSIONS)) { return; } return $this->cache_manager->getBrowserPath($file->getName(), $this->filter_name); }
public function filter($file, $filter, array $runtimeConfig = []) { if (is_object($file)) { return new \Twig_Markup($this->fileService->getFilteredPath($file, $filter), 'utf8'); } else { return new \Twig_Markup($this->cacheManager->getBrowserPath($file, $filter, $runtimeConfig), 'utf8'); } }
/** * {@inheritdoc} */ public function getImageUrl($fileType, $filter) { $fileKey = sprintf('%s_default_image', $fileType); if (!$this->cacheManager->isStored($fileKey, $filter)) { $binary = $this->getImageBinary($fileType); $this->cacheManager->store($this->filterManager->applyFilter($binary, $filter), $fileKey, $filter); } return $this->cacheManager->resolve($fileKey, $filter); }
/** * {@inheritdoc} */ public function convertItem($user) { $result = parent::convertItem($user); $result['avatar'] = null; $imagePath = $this->getPropertyValue('imagePath', $user); if ($imagePath) { $result['avatar'] = $this->cacheManager->getBrowserPath($imagePath, self::IMAGINE_AVATAR_FILTER); } return $result; }
/** * Gets the browser path for the image and filter to apply. * * @param string $path * @param string $filter * @param array $runtimeConfig * * @return \Twig_Markup */ public function filter($path, $filter, array $runtimeConfig = array()) { if ($path instanceof ImageInterface) { $path = $path->getPath(); } if (empty($path)) { return $this->imageHolderPath . '/' . $this->getFilterDimension($filter); } return new \Twig_Markup($this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig), 'utf8'); }
/** * @param ImagePreview $imagePreviewData * @return string */ private function resize(ImagePreview $imagePreviewData) { $filter = 'preview'; if (!$this->cacheManager->isStored($imagePreviewData->getTargetName(), $filter)) { $binary = $this->dataManager->find($filter, $imagePreviewData->getSourceUri()); $filteredBinary = $this->filterManager->applyFilter($binary, $filter, ['filters' => ['thumbnail' => ['size' => [$imagePreviewData->getWidth(), $imagePreviewData->getHeight()]]]]); $this->cacheManager->store($filteredBinary, $imagePreviewData->getTargetName(), $filter); } return $this->assetsResolver->uriToPath($this->targetBasePath . $imagePreviewData->getTargetName()); }
/** * Finds first available image for listing purposes * * @param Content $content * * @return string */ public function getCoverImage(Content $content) { $key = $content->getCoverImageCacheKey(); if (!($image = $this->cache->fetch($key))) { $image = $content->getCoverImage(); if ($image) { $image = $this->imageCacheManager->getBrowserPath($image, 'medialibrary'); } $this->cache->save($key, $image, 86400); } return $image; }
/** * Serialize a single file. * * @param AbstractFile $File * * @return array */ public function serialize(AbstractFile $file) { $fileFile = $file->getFile(); $data = ['id' => $file->getId(), 'name' => $file->getFileName(), 'path' => $this->vich->asset($file, 'file'), 'size' => $this->formatSize(is_null($fileFile) ? $file->getFileSize() : $fileFile->getSize()), 'mime' => is_null($fileFile) ? $file->getMimeType() : $fileFile->getMimeType()]; if ($file->isImage()) { $fileName = $this->vich->asset($file, 'file'); $data['thumb'] = $this->imagine->getBrowserPath($fileName, 'tgmedia_thumbnail'); } else { $data['type'] = $file->getExtension(); } return $data; }
/** * @param ObjectEvent $event */ public function onPostSerialize(ObjectEvent $event) { $object = $event->getObject(); // getSubscribedEvents doesn't seem to support parent classes if (!$object instanceof Content) { return; } if (false !== ($coverImage = $this->getCoverImage($object))) { $coverImage = $this->cacheManager->getBrowserPath($coverImage, 'medialibrary'); $event->getVisitor()->addData('coverImage', $coverImage); } $event->getVisitor()->addData('path', $this->router->generate('_content', ['slug' => $object->getSlug()])); }
/** * This action applies a given filter to a given image, optionally saves the image and outputs it to the browser at the same time. * * @param Request $request * @param string $path * @param string $filter * * @return Response */ public function filterAction(Request $request, $path, $filter) { $targetPath = $this->cacheManager->resolve($request, $path, $filter); if ($targetPath instanceof Response) { return $targetPath; } $image = $this->dataManager->find($filter, $path); $response = $this->filterManager->get($request, $filter, $image, $path); if ($targetPath) { $response = $this->cacheManager->store($response, $targetPath, $filter); } return $response; }
/** * @param string $path * @param string $filter * @param Image $image * * @return string */ public function getFormattedImage($path, $filter, Image $image = null) { if (!$this->cacheManager->isStored($path, $filter)) { $config = $this->filterManager->getFilterConfiguration()->get($filter); if (isset($config['filters']['focused_crop'])) { $config['filters']['focused_crop']['object'] = $image; } $binary = $this->dataManager->find($filter, $path); $binary = $this->filterManager->applyFilter($binary, $filter, $config); $this->cacheManager->store($binary, $path, $filter); } return $this->cacheManager->resolve($path, $filter); }
/** * @param string $imageData * @param string $filter * @throws \Exception * @return bool|string */ public function handle($imageData, $filter) { try { $binary = $this->createBinary($imageData); $pictureName = time() . '.' . $binary->getFormat(); $this->imagineCache->store($this->filterManager->applyFilter($binary, $filter), $pictureName, $filter); $this->imagineCache->resolve($pictureName, $filter); return $this->getUploadDir() . $filter . '/' . $pictureName; } catch (\Exception $e) { $this->error = $e->getMessage(); } return false; }
function it_renders_a_product_with_an_image($templating, ProductInterface $blender, AttributeGroupInterface $media, AttributeInterface $mainImage, ProductValueInterface $productValue, FileInfoInterface $fileInfo, CacheManager $cacheManager) { $blender->getAttributes()->willReturn([$mainImage]); $blender->getValue("main_image", "en_US", "ecommerce")->willReturn($productValue); $productValue->getMedia()->willReturn($fileInfo); $fileInfo->getKey()->willReturn('fookey'); $cacheManager->isStored('fookey', 'thumbnail')->willReturn(true); $mainImage->getGroup()->willReturn($media); $media->getLabel()->willReturn('Media'); $mainImage->getCode()->willReturn('main_image'); $mainImage->getAttributeType()->willReturn('pim_catalog_image'); $templating->render(self::TEMPLATE_NAME, ['product' => $blender, 'locale' => 'en_US', 'scope' => 'ecommerce', 'groupedAttributes' => ['Media' => ['main_image' => $mainImage]], 'imageAttributes' => ['main_image' => $mainImage], 'uploadDir' => '/tmp/' . DIRECTORY_SEPARATOR, 'customFont' => null])->shouldBeCalled(); $this->render($blender, 'pdf', ['locale' => 'en_US', 'scope' => 'ecommerce']); }
/** * @param ActivityInterface $object * @return null|array */ public function reverseConvert($object) { if ($object instanceof ActivityInterface) { // Retrieve user for activity $user = $object->getUser(); if ($user instanceof UserInterface) { $photo = $this->defaultAvatar; if (is_string($user->getPhoto())) { $photo = $this->cacheManager->getBrowserPath($user->getPhoto(), 'user_photo_review'); } return ['id' => $user->getId(), 'firstName' => $user->getFirstName(), 'middleName' => $user->getMiddleName(), 'lastName' => $user->getLastName(), 'photo' => $photo]; } } return null; }
/** * This action applies a given filter to a given image, optionally saves the image and outputs it to the browser at the same time. * * @param Request $request * @param string $hash * @param string $path * @param string $filter * * @throws \RuntimeException * @throws BadRequestHttpException * * @return RedirectResponse */ public function filterRuntimeAction(Request $request, $hash, $path, $filter) { try { $filters = $request->query->get('filters', array()); if (!is_array($filters)) { throw new NotFoundHttpException(sprintf('Filters must be an array. Value was "%s"', $filters)); } if (true !== $this->signer->check($hash, $path, $filters)) { throw new BadRequestHttpException(sprintf('Signed url does not pass the sign check for path "%s" and filter "%s" and runtime config %s', $path, $filter, json_encode($filters))); } try { $binary = $this->dataManager->find($filter, $path); } catch (NotLoadableException $e) { if ($defaultImageUrl = $this->dataManager->getDefaultImageUrl($filter)) { return new RedirectResponse($defaultImageUrl); } throw new NotFoundHttpException(sprintf('Source image could not be found for path "%s" and filter "%s"', $path, $filter), $e); } $rcPath = $this->cacheManager->getRuntimePath($path, $filters); $this->cacheManager->store($this->filterManager->applyFilter($binary, $filter, array('filters' => $filters)), $rcPath, $filter); return new RedirectResponse($this->cacheManager->resolve($rcPath, $filter), 301); } catch (NonExistingFilterException $e) { $message = sprintf('Could not locate filter "%s" for path "%s". Message was "%s"', $filter, $hash . '/' . $path, $e->getMessage()); if (null !== $this->logger) { $this->logger->debug($message); } throw new NotFoundHttpException($message, $e); } catch (RuntimeException $e) { throw new \RuntimeException(sprintf('Unable to create image for path "%s" and filter "%s". Message was "%s"', $hash . '/' . $path, $filter, $e->getMessage()), 0, $e); } }
/** * Check if this could mean an image document was modified (check resource, * file and image). * * @param LifecycleEventArgs $args */ private function invalidateCache(LifecycleEventArgs $args) { $object = $args->getObject(); // If we hear about the Resource which is nested in a File, we get the // parent. instanceof can handle the case where Resource is not a known // class - the condition will just be false in that case. if ($object instanceof Resource) { $object = $object->getParent(); } if (!$object instanceof ImageInterface) { return; } if (null === $this->request) { // do not fail on CLI return; } foreach ($this->filters as $filter) { $path = $this->manager->resolve($this->mediaManager->getUrlSafePath($object), $filter); if ($path instanceof RedirectResponse) { $path = $path->getTargetUrl(); } // TODO: this might not be needed https://github.com/liip/LiipImagineBundle/issues/162 if (false !== strpos($path, $filter)) { $path = substr($path, strpos($path, $filter) + strlen($filter)); } $this->manager->remove($path, $filter); } }
/** * {@inheritDoc} */ public function getBrowserPath($path, $filter, $absolute = false) { $objectPath = $this->getObjectPath($path, $filter); if ($this->objectExists($objectPath)) { return $this->getObjectUrl($objectPath); } return $this->cacheManager->generateUrl($path, $filter, $absolute); }
/** * @param string $operationId * @return string * @throws \Exception */ public function execute($operationId) { /** @var NewsItem $newsItem */ $newsItem = $this->em->getRepository('CampaignChainOperationLinkedInBundle:NewsItem')->findOneByOperation($operationId); if (!$newsItem) { throw new \Exception('No news item found for an operation with ID: ' . $operationId); } //have images? $images = $this->em->getRepository('CampaignChainHookImageBundle:Image')->getImagesForOperation($newsItem->getOperation()); // if the message does not contain a url, we need to skip the content block if (is_null($newsItem->getLinkUrl())) { // LinkedIn accepts an image link only if we also provided a submitted URL. if ($images) { throw new \Exception('To include an image, you must also provide a URL in the text message.'); return self::STATUS_WARNING; } $content = ['comment' => $newsItem->getMessage(), 'visibility' => ['code' => 'anyone']]; } else { /* * process urls and add tracking * important: both the urls in the message and submitted url field must be identical */ $newsItem->setLinkUrl($this->ctaService->processCTAs($newsItem->getLinkUrl(), $newsItem->getOperation())->getContent()); $newsItem->setMessage($this->ctaService->processCTAs($newsItem->getMessage(), $newsItem->getOperation())->getContent()); $content = ['comment' => $newsItem->getMessage(), 'content' => ['title' => $newsItem->getLinkTitle(), 'description' => $newsItem->getLinkDescription(), 'submitted-url' => $newsItem->getLinkUrl()], 'visibility' => ['code' => 'anyone']]; if ($images) { //Linkedin can handle only 1 image $content['content']['submitted-image-url'] = $this->cacheManager->getBrowserPath($images[0]->getPath(), "campaignchain_linkedin_news_item"); } } $activity = $newsItem->getOperation()->getActivity(); $locationModuleIdentifier = $activity->getLocation()->getLocationModule()->getIdentifier(); $isCompanyPageShare = 'campaignchain-linkedin-page' == $locationModuleIdentifier; $connection = $this->client->getConnectionByActivity($activity); if ($isCompanyPageShare) { $response = $connection->shareOnCompanyPage($activity, $content); } else { $response = $connection->shareOnUserPage($content); } $newsItem->setUrl($response['updateUrl']); $newsItem->setUpdateKey($response['updateKey']); // Set Operation to closed. $newsItem->getOperation()->setStatus(Action::STATUS_CLOSED); $location = $newsItem->getOperation()->getLocations()[0]; $location->setIdentifier($response['updateKey']); $location->setUrl($response['updateUrl']); $location->setName($newsItem->getOperation()->getName()); $location->setStatus(Medium::STATUS_ACTIVE); // Schedule data collection for report $this->reportShareNewsItem->schedule($newsItem->getOperation()); $this->em->flush(); $this->message = 'The message "' . $newsItem->getMessage() . '" with the ID "' . $newsItem->getUpdateKey() . '" has been posted on LinkedIn. See it on LinkedIn: <a href="' . $newsItem->getUrl() . '">' . $newsItem->getUrl() . '</a>'; return self::STATUS_OK; }
/** * {@inheritdoc} */ public function getBrowserPath($path, $filter, array $runtimeConfig = array(), $resolver = null) { $info = pathinfo($path); $url = parent::getBrowserPath($path, $filter, $runtimeConfig, $resolver); $newPath = parse_url($url, PHP_URL_PATH); $newInfo = pathinfo($newPath); if ($info['extension'] != $newInfo['extension']) { $query = parse_url($url, PHP_URL_QUERY); $url .= ($query ? '&' : '?') . 'originalExtension=' . $info['extension']; } return $url; }
/** * {@inheritdoc} */ public function getUrls() { if (is_null($this->urls) || $this->refresh === true) { $this->urls = []; $this->refresh = false; foreach ($this->options['images'] as $image) { $filterName = $this->mappingService->getImagineFilterName($this->className, $this->fieldName, $this->layout, $image); $this->urls[] = $this->cacheManager->getBrowserPath($this->sources[$image['index']], $filterName); } } return $this->urls; }
/** * Generate media thumbnails cache used by the PDF document * * @param ProductInterface $product * @param AttributeInterface[] $imageAttributes * @param string $locale * @param string $scope */ protected function generateThumbnailsCache(ProductInterface $product, array $imageAttributes, $locale, $scope) { foreach ($imageAttributes as $attribute) { $media = $product->getValue($attribute->getCode(), $locale, $scope)->getMedia(); if (null !== $media && null !== $media->getKey()) { $path = $media->getKey(); $filter = 'thumbnail'; if (!$this->cacheManager->isStored($path, $filter)) { $binary = $this->dataManager->find($filter, $path); $this->cacheManager->store($this->filterManager->applyFilter($binary, $filter), $path, $filter); } } } }
public function testFilterActionLive() { $router = $this->getMockRouter(); $router->expects($this->any())->method('generate')->with('_imagine_thumbnail', array('path' => 'cats.jpeg'), false)->will($this->returnValue('/media/cache/thumbnail/cats.jpeg')); $dataLoader = new FileSystemLoader($this->imagine, array(), $this->dataDir); $dataManager = new DataManager($this->configuration, 'filesystem'); $dataManager->addLoader('filesystem', $dataLoader); $filterLoader = new ThumbnailFilterLoader(); $filterManager = new FilterManager($this->configuration); $filterManager->addLoader('thumbnail', $filterLoader); $webPathResolver = new WebPathResolver($this->filesystem); $cacheManager = new CacheManager($this->configuration, $router, $this->webRoot, 'web_path'); $cacheManager->addResolver('web_path', $webPathResolver); $controller = new ImagineController($dataManager, $filterManager, $cacheManager); $request = Request::create('/media/cache/thumbnail/cats.jpeg'); $response = $controller->filterAction($request, 'cats.jpeg', 'thumbnail'); $targetPath = realpath($this->webRoot) . '/media/cache/thumbnail/cats.jpeg'; $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response); $this->assertEquals(201, $response->getStatusCode()); $this->assertTrue(file_exists($targetPath)); $this->assertNotEmpty(file_get_contents($targetPath)); return $controller; }
/** * This action applies a given filter to a given image, optionally saves the image and outputs it to the browser at the same time. * * @param Request $request * @param string $hash * @param string $path * @param string $filter * * @throws \RuntimeException * @throws BadRequestHttpException * * @return RedirectResponse */ public function filterRuntimeAction(Request $request, $hash, $path, $filter) { try { $filters = $request->query->get('filters', array()); if (true !== $this->signer->check($hash, $path, $filters)) { throw new BadRequestHttpException(sprintf('Signed url does not pass the sign check for path "%s" and filter "%s" and runtime config %s', $path, $filter, json_encode($filters))); } try { $binary = $this->dataManager->find($filter, $path); } catch (NotLoadableException $e) { throw new NotFoundHttpException(sprintf('Source image could not be found for path "%s" and filter "%s"', $path, $filter), $e); } $cachePrefix = 'rc/' . $hash; $this->cacheManager->store($this->filterManager->applyFilter($binary, $filter, array('filters' => $filters)), $cachePrefix . '/' . $path, $filter); return new RedirectResponse($this->cacheManager->resolve($cachePrefix . '/' . $path, $filter), 301); } catch (RuntimeException $e) { throw new \RuntimeException(sprintf('Unable to create image for path "%s" and filter "%s". Message was "%s"', $hash . '/' . $path, $filter, $e->getMessage()), 0, $e); } }
/** * {@inheritdoc} */ public function getImage($path, $filter, array $config = []) { return $this->manager->getBrowserPath($path, $filter, $config); }