<?php
namespace App\Controller;
use FrontendPermissionToolkitBundle\Service;
use Pimcore\Controller\FrontendController;
use Pimcore\Model\Asset;
use Pimcore\Tool\Admin;
use Pimcore\Tool\Storage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class AssetController extends DefaultController
{
/** @var TranslatorInterface */
protected $translator;
/**
* @var Service
*/
private $permissionService;
public function __construct(TranslatorInterface $translator, Service $permissionService )
{
$this->translator = $translator;
$this->permissionService = $permissionService;
parent::__construct($translator, $permissionService);
}
public function protectedAssetAction(Request $request, RouterInterface $router)
{
// IMPORTANT!
// Add your code here to check permission!
$currentUser = Admin::getCurrentUser();
if ($currentUser == null) {
$currentUser = \Pimcore\Tool\Session::getReadonly()->get("user");
}
// the following code is responsible to deliver asset & thumbnail contents
// modify it the way you need it for your use-case
$pathInfo = $request->getPathInfo();
if($pathInfo == "/faq"){
$params = $this->faqAction($request);
return $this->render("default/faq.html.twig", $params);
}
if($pathInfo == "/Emails/PublicationNewsletterEmail"){
return $this->sentPublicationNewsletterEmailAction($request);
}
$asset = Asset::getByPath($pathInfo);
if ($asset){
if(!$currentUser){
throw new AccessDeniedHttpException('Access denied.');
}
$stream = $asset->getStream();
return new StreamedResponse(function () use ($stream) {
fpassthru($stream);
}, 200, [
'Content-Type' => $asset->getMimeType(),
]);
} elseif (preg_match('@.*/(image|video)-thumb__[\d]+__.*@', $pathInfo, $matches)) {
$storage = Storage::get('thumbnail');
$storagePath = urldecode($pathInfo);
if($storage->fileExists($storagePath)){
$stream = $storage->readStream($storagePath);
return new StreamedResponse(function () use ($stream) {
fpassthru($stream);
}, 200, [
'Content-Type' => $storage->mimeType($storagePath),
]);
} else {
$pimcoreThumbnailRoute = '_pimcore_service_thumbnail';
$route = $router->getRouteCollection()->get($pimcoreThumbnailRoute);
$collection = new RouteCollection();
$collection->add($pimcoreThumbnailRoute, $route);
$matcher = new UrlMatcher($collection, $router->getContext());
try {
$parameters = $matcher->matchRequest($request);
return $this->forward('PimcoreCoreBundle:PublicServices:thumbnail', $parameters);
} catch (\Exception $e) {
// nothing to do
}
}
}
throw new AccessDeniedHttpException('Access denied.');
}
}