/** * @param Request $request * @return DecryptFileResponse */ public function prepare(Request $request) { parent::prepare($request); $this->headers->set('Content-Length', $this->fileSize); $this->headers->set('Content-Type', 'application/octet-stream'); return $this; }
/** * Handle a request for a file * * @param Request $request HTTP request * @return Response */ public function getResponse($request) { $response = new Response(); $response->prepare($request); $path = implode('/', $request->getUrlSegments()); if (!preg_match('~download-file/g(\\d+)$~', $path, $m)) { return $response->setStatusCode(400)->setContent('Malformatted request URL'); } $this->application->start(); $guid = (int) $m[1]; $file = get_entity($guid); if (!$file instanceof ElggFile) { return $response->setStatusCode(404)->setContent("File with guid {$guid} does not exist"); } $filenameonfilestore = $file->getFilenameOnFilestore(); if (!is_readable($filenameonfilestore)) { return $response->setStatusCode(404)->setContent('File not found'); } $last_updated = filemtime($filenameonfilestore); $etag = '"' . $last_updated . '"'; $response->setPublic()->setEtag($etag); if ($response->isNotModified($request)) { return $response; } $response = new BinaryFileResponse($filenameonfilestore, 200, array(), false, 'attachment'); $response->prepare($request); $expires = strtotime('+1 year'); $expires_dt = (new DateTime())->setTimestamp($expires); $response->setExpires($expires_dt); $response->setEtag($etag); return $response; }
public function invoiceAction(Convention $convention, Request $request) { $registrations = $convention->getRegistrations(); $zip = new ZipArchive(); $title = $convention->getSlug(); $filename = tempnam('/tmp/', 'ritsiGA-' . $title . '-'); unlink($filename); if ($zip->open($filename, ZIPARCHIVE::CREATE) !== true) { throw new \Exception("cannot open <{$filename}>\n"); } if (false === $zip->addEmptyDir($title)) { throw new \Exception("cannot add empty dir {$title}\n"); } $route_dir = $this->container->getParameter('kernel.root_dir'); foreach ($registrations as $registration) { $single_file = $route_dir . '/../private/documents/invoices/' . $registration->getId() . '.pdf'; if (false === file_exists($single_file)) { continue; } $name = $registration->getId(); if (false === $zip->addFile($single_file, implode('/', array($title, $name . '.pdf')))) { throw new \Exception("cannot add file\n"); } } if (false === $zip->close()) { throw new \Exception("cannot close <{$filename}>\n"); } $response = new BinaryFileResponse($filename); $response->trustXSendfileTypeHeader(); $response->prepare($request); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $convention->getSlug() . '-facturas.zip', iconv('UTF-8', 'ASCII//TRANSLIT', $convention->getSlug() . '-facturas.zip')); return $response; }
/** * @Route("/video", name="video") * * Serving video allowing to handle Range and If-Range headers from the request. */ public function videoServing(Request $request) { $file = $this->getParameter('assetic.write_to') . $this->container->get('templating.helper.assets')->getUrl('video/CreateSafe.mp4'); $response = new BinaryFileResponse($file); BinaryFileResponse::trustXSendfileTypeHeader(); $response->prepare($request); return $response; }
public function downloadAction(Application $app, Request $request, $fileId) { $repo = $app->getFileRepository(); $file = $repo->getById($fileId); $response = new BinaryFileResponse($file->getPath()); $response->prepare(Request::createFromGlobals()); $response->send(); }
/** * Handle a request for a file * * @param Request $request HTTP request * @return Response */ public function getResponse($request) { $response = new Response(); $response->prepare($request); $path = implode('/', $request->getUrlSegments()); if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) { return $response->setStatusCode(400)->setContent('Malformatted request URL'); } list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m; if ($expires && $expires < time()) { return $response->setStatusCode(403)->setContent('URL has expired'); } $etag = '"' . $last_updated . '"'; $response->setPublic()->setEtag($etag); if ($response->isNotModified($request)) { return $response; } // @todo: change to minimal boot without plugins $this->application->bootCore(); $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie); if ((bool) $use_cookie) { $hmac_data['cookie'] = _elgg_services()->session->getId(); } ksort($hmac_data); $hmac = elgg_build_hmac($hmac_data); if (!$hmac->matchesToken($mac)) { return $response->setStatusCode(403)->setContent('HMAC mistmatch'); } $dataroot = _elgg_services()->config->getDataPath(); $filenameonfilestore = "{$dataroot}{$path_from_dataroot}"; if (!is_readable($filenameonfilestore)) { return $response->setStatusCode(404)->setContent('File not found'); } $actual_last_updated = filemtime($filenameonfilestore); if ($actual_last_updated != $last_updated) { return $response->setStatusCode(403)->setContent('URL has expired'); } $public = $use_cookie ? false : true; $content_disposition = $disposition == 'i' ? 'inline' : 'attachment'; $response = new BinaryFileResponse($filenameonfilestore, 200, array(), $public, $content_disposition); $response->prepare($request); if (empty($expires)) { $expires = strtotime('+1 year'); } $expires_dt = (new DateTime())->setTimestamp($expires); $response->setExpires($expires_dt); $response->setEtag($etag); return $response; }
public function crearReciboCajaMenorAction(Request $peticion) { $formulario = $this->createForm(new ReciboCajaMenorType()); $formulario->handleRequest($peticion); if ($formulario->isValid()) { $kernel = $this->get('kernel'); //Se carga la plantilla $path = $kernel->locateResource('@FacturaBundle/Template/caja_menor_template.docx'); $plantilla = new TemplateProcessor($path); $datos = $formulario->getData(); //Se carga el archivo el valor del consecutivo $path = $kernel->locateResource('@FacturaBundle/Resources/config/consecutivos.yml'); $consecutivo = null; $value = null; try { $value = Yaml::parse(file_get_contents($path)); $consecutivo = $value['consecutivo_caja_menor']; } catch (ParseException $e) { printf("Problemas con el string: %s", $e->getMessage()); } //Se aumenta el valor del consecutivo almacenado $value['consecutivo_caja_menor'] += 1; $yaml = Yaml::dump($value); file_put_contents($path, $yaml); // Se setea el consecutivo $plantilla->setValue('consecutivo', $consecutivo); //Se setean los datos que estaban en el formulario foreach ($datos as $clave => $dato) { if ($clave != 'fecha') { $plantilla->setValue($clave, $dato); } else { $plantilla->setValue($clave, $dato->format('d/m/Y')); } } //Se almacena la suma en letras $conversor = $this->get('numeroLetras'); $numeroEnLetras = $conversor->numtoletras($datos['valor']); $plantilla->setValue('valor_letras', $numeroEnLetras); $plantilla->saveAs('descargas/temp.docx'); //Se manda a guardar al cliente $file = 'descargas/temp.docx'; $response = new BinaryFileResponse($file); $response->prepare($peticion); $response->send(); } return $this->render('FacturaBundle:Default:creacionReciboCajaMenor.html.twig', array('formulario' => $formulario->createView())); }
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { foreach ($this->matchers as $match) { $route = $request->getPathInfo(); $from = $match[0]; if (preg_match("#^" . $from . "#", $route)) { $redirect = $this->basedir . str_replace($from, $match[1], $route); $response = new BinaryFileResponse($redirect); if (isset($match[2])) { $response->headers->set('Content-Type', $match[2]); } $response->prepare($request); return $response; } } return $this->app->handle($request, $type, $catch); }
protected function serveFile($filename, $displayName, Request $request, $asAttachment = false) { $lastModified = new \DateTime(); $lastModified->setTimestamp(filemtime($filename)); $ifModifiedSince = $request->headers->has('If-Modified-Since') ? new \DateTime($request->headers->get('If-Modified-Since')) : false; $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $filename); $response = new BinaryFileResponse($filename); $response->setMaxAge(10); $response->headers->addCacheControlDirective('must-revalidate'); $response->headers->set('Content-Type', $mimeType); $response->setLastModified($lastModified); $response->setContentDisposition($asAttachment ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE, $displayName, mb_convert_encoding($displayName, "ASCII", "UTF-8")); $response->prepare($request); if ($ifModifiedSince && $ifModifiedSince <= $lastModified) { $response->setStatusCode(304); } return $response; }
/** * {@inheritdoc} */ public function prepare(Request $request) { parent::prepare($request); if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) == $this->getEtag()) { $this->setStatusCode(304); $this->maxlen = 0; } else { if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $lastModified = $this->getLastModified(); $lastModified instanceof \DateTime && ($lastModified = $lastModified->getTimeStamp()); if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) { $this->setStatusCode(304); $this->maxlen = 0; } } else { switch (substr($_SERVER['SERVER_SOFTWARE'], 0, (int) strpos($_SERVER['SERVER_SOFTWARE'], '/'))) { case 'nginx': $this->headers->set('X-Accel-Redirect', env('APP_PATH') . '/' . relative_path($this->file->getPathname(), APPPATH)); $this->headers->set('X-Accel-Buffering', 'yes'); //$this->headers->set('X-Accel-Limit-Rate', '102400'); //速度限制 Byte/s //$this->headers('Accept-Ranges', 'none');//单线程 限制多线程 $this->maxlen = 0; break; case 'Apache': if (function_exists('apache_get_modules') && in_array('mod_xsendfile', apache_get_modules())) { $this->headers->set('X-Sendfile', $this->file->getPathname()); $this->maxlen = 0; } break; case 'squid': $this->headers->set('X-Accelerator-Vary', $this->file->getPathname()); $this->maxlen = 0; break; case 'lighttpd': $this->headers->set('X-LIGHTTPD-send-file', $this->file->getPathname()); $this->maxlen = 0; break; } } } return $this; }
/** * Download file. * * @param Request $request * @param Response $response * * @return BinaryFileResponse */ public function index(Request $request, Response $response) { $key = $request->query->get('key', 'gp'); $download = $request->query->get('download', '1'); if ($download == '1') { $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT; } else { $disposition = ResponseHeaderBag::DISPOSITION_INLINE; } $metaFile = new \Molengo\MetaFile($response); $info = $metaFile->getInfo($key); $dataFile = $metaFile->getDataFileName($key); $fileName = $info['filename']; $headers = ['Pragma' => 'public', 'Content-Description' => 'File Transfer', 'Content-Transfer-Encoding' => 'binary', 'Expires' => '0', 'Cache-Control' => 'must-revalidate, post-check = 0, pre-check = 0']; $fileResponse = new BinaryFileResponse($dataFile, 200, $headers); $fileResponse->deleteFileAfterSend(false); $fileResponse->setContentDisposition($disposition, $fileName); $fileResponse->prepare($this->request); $fileResponse->sendContent(); // Delete meta file after download $metaFile->delete($key); return $fileResponse; }
/** * Prepare the file response. * * @param \Symfony\Component\HttpFoundation\BinaryFileResponse $response * @return \Symfony\Component\HttpFoundation\BinaryFileResponse */ public function prepareFileResponse(BinaryFileResponse $response) { return $response->prepare(Request::createFromGlobals()); }
/** * Handle a request for a file * * @param Request $request HTTP request * @return Response */ public function getResponse(Request $request) { $response = new Response(); $response->prepare($request); $path = implode('/', $request->getUrlSegments()); if (!preg_match('~serve-file/e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) { return $response->setStatusCode(400)->setContent('Malformatted request URL'); } list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m; if ($expires && $expires < time()) { return $response->setStatusCode(403)->setContent('URL has expired'); } $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie); if ((bool) $use_cookie) { $hmac_data['cookie'] = $this->getCookieValue($request); } ksort($hmac_data); $hmac = $this->crypto->getHmac($hmac_data); if (!$hmac->matchesToken($mac)) { return $response->setStatusCode(403)->setContent('HMAC mistmatch'); } $dataroot = $this->config->getDataPath(); $filenameonfilestore = "{$dataroot}{$path_from_dataroot}"; if (!is_readable($filenameonfilestore)) { return $response->setStatusCode(404)->setContent('File not found'); } $actual_last_updated = filemtime($filenameonfilestore); if ($actual_last_updated != $last_updated) { return $response->setStatusCode(403)->setContent('URL has expired'); } $if_none_match = $request->headers->get('if_none_match'); if (!empty($if_none_match)) { // strip mod_deflate suffixes $request->headers->set('if_none_match', str_replace('-gzip', '', $if_none_match)); } $etag = '"' . $actual_last_updated . '"'; $response->setPublic()->setEtag($etag); if ($response->isNotModified($request)) { return $response; } $public = $use_cookie ? false : true; $content_disposition = $disposition == 'i' ? 'inline' : 'attachment'; $headers = ['Content-Type' => (new MimeTypeDetector())->getType($filenameonfilestore)]; $response = new BinaryFileResponse($filenameonfilestore, 200, $headers, $public, $content_disposition); $sendfile_type = $this->config->getVolatile('X-Sendfile-Type'); if ($sendfile_type) { $request->headers->set('X-Sendfile-Type', $sendfile_type); $mapping = (string) $this->config->getVolatile('X-Accel-Mapping'); $request->headers->set('X-Accel-Mapping', $mapping); $response->trustXSendfileTypeHeader(); } $response->prepare($request); if (empty($expires)) { $expires = strtotime('+1 year'); } $expires_dt = (new DateTime())->setTimestamp($expires); $response->setExpires($expires_dt); $response->setEtag($etag); return $response; }
/** * Handle request to /serve-icon handler * * @param bool $allow_removing_headers Alter PHP's global headers to allow caching * @return BinaryFileResponse */ public function handleServeIconRequest($allow_removing_headers = true) { $response = new Response(); $response->setExpires($this->getCurrentTime('-1 day')); $response->prepare($this->request); if ($allow_removing_headers) { // clear cache-boosting headers set by PHP session header_remove('Cache-Control'); header_remove('Pragma'); header_remove('Expires'); } $path = implode('/', $this->request->getUrlSegments()); if (!preg_match('~serve-icon/(\\d+)/(.*+)$~', $path, $m)) { return $response->setStatusCode(400)->setContent('Malformatted request URL'); } list(, $guid, $size) = $m; $entity = $this->entities->get($guid); if (!$entity instanceof \ElggEntity) { return $response->setStatusCode(404)->setContent('Item does not exist'); } $thumbnail = $entity->getIcon($size); if (!$thumbnail->exists()) { return $response->setStatusCode(404)->setContent('Icon does not exist'); } $if_none_match = $this->request->headers->get('if_none_match'); if (!empty($if_none_match)) { // strip mod_deflate suffixes $this->request->headers->set('if_none_match', str_replace('-gzip', '', $if_none_match)); } $filenameonfilestore = $thumbnail->getFilenameOnFilestore(); $last_updated = filemtime($filenameonfilestore); $etag = '"' . $last_updated . '"'; $response->setPrivate()->setEtag($etag)->setExpires($this->getCurrentTime('+1 day'))->setMaxAge(86400); if ($response->isNotModified($this->request)) { return $response; } $headers = ['Content-Type' => (new MimeTypeDetector())->getType($filenameonfilestore)]; $response = new BinaryFileResponse($filenameonfilestore, 200, $headers, false, 'inline'); $response->prepare($this->request); $response->setPrivate()->setEtag($etag)->setExpires($this->getCurrentTime('+1 day'))->setMaxAge(86400); return $response; }
public function downloadAction(Request $request) { $requestedFileName = $request->attributes->get('path'); $headers = array(); $disposition = ResponseHeaderBag::DISPOSITION_INLINE; $file = $this->getFile(); $mimeType = $file->getMimeType(); $fileName = $file->getFileName(); //TODO: is case sensitive comparison OK? if ($fileName !== $requestedFileName) { throw new ResourceNotFoundException("Requested file name does not match file name on the server"); } if (!$file->isPublic() && $request->get('inline')) { $size = $request->get('size'); $sizeDir = FileStorage::RESERVED_DIR_SIZE; $fileDir = dirname($this->getFileStorage()->getFilesystemPath($file)); $path = $fileDir . DIRECTORY_SEPARATOR . $sizeDir . DIRECTORY_SEPARATOR . $size . DIRECTORY_SEPARATOR . $file->getFileName(); } else { $path = $this->getFileStorage()->getFilesystemPath($file); } if (!empty($mimeType)) { $headers['Content-Type'] = $mimeType; } if (!$request->get('inline')) { $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT; } $response = new BinaryFileResponse($path, 200, $headers, false, $disposition); $response->prepare($request); return $response; }
/** * @param Request $request * @param int $type * @param bool $catch * * @return CubexResponse|BinaryFileResponse|Response * @throws \Exception */ public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { //If the favicon has not been picked up within the public folder //return the cubex favicon if ($request->getRequestUri() === '/favicon.ico') { $favIconPaths = []; $favIconPaths[] = Path::build($this->getProjectRoot(), 'favicon.ico'); $favIconPaths[] = Path::build($this->getProjectRoot(), 'assets', 'favicon.ico'); $favIconPaths[] = Path::build(dirname(__DIR__), 'favicon.ico'); $favPath = null; foreach ($favIconPaths as $favPath) { if (file_exists($favPath)) { break; } } $favicon = new BinaryFileResponse($favPath); $favicon->prepare($request); return $favicon; } try { //Ensure all constants have been configured if ($this->getDocRoot() === null) { throw new \RuntimeException("Cubex has been constructed without a document root provided" . ", you must call createConstants before calling handle."); } //Ensure we are working with a Cubex Request for added functionality if (!$request instanceof CubexRequest) { throw new \InvalidArgumentException('You must use a \\Cubex\\Http\\Request'); } $this->instance('request', $request); //Boot Cubex $this->boot(); //Retrieve the $kernel = $this->makeWithCubex('\\Cubex\\Kernel\\CubexKernel'); if ($kernel instanceof CubexKernel) { $response = $kernel->handle($request, $type, $catch); if (!$response instanceof Response) { throw CubexException::debugException("A valid response was not generated by the default kernel", 500, $response); } return $response; } throw new \RuntimeException("No Cubex Kernel has been configured"); } catch (\Exception $e) { if ($catch) { return $this->exceptionResponse($e); } else { throw $e; } } }
public function testDeleteFileAfterSend() { $request = Request::create('/'); $path = __DIR__ . '/File/Fixtures/to_delete'; touch($path); $realPath = realpath($path); $this->assertFileExists($realPath); $response = new BinaryFileResponse($realPath); $response->deleteFileAfterSend(true); $response->prepare($request); $response->sendContent(); $this->assertFileNotExists($path); }
public function prepare(Request $request) { parent::prepare($request); $this->headers->set('content-length', $this->headers->get('content-length') + strlen($this->prepend) + strlen($this->append)); return $this; }