/** * Save uploaded image according to comur_image field configuration * * @param Request $request */ public function uploadImageAction(Request $request) { $config = json_decode($request->request->get('config'), true); $uploadUrl = $config['uploadConfig']['uploadUrl']; $uploadUrl = substr($uploadUrl, -strlen('/')) === '/' ? $uploadUrl : $uploadUrl . '/'; // We must use a streamed response because the UploadHandler echoes directly $response = new StreamedResponse(); $webDir = $config['uploadConfig']['webDir']; $webDir = substr($webDir, -strlen('/')) === '/' ? $webDir : $webDir . '/'; $filename = sha1(uniqid(mt_rand(), true)); $thumbsDir = $this->container->getParameter('comur_image.thumbs_dir'); $thumbSize = $this->container->getParameter('comur_image.media_lib_thumb_size'); $galleryDir = $this->container->getParameter('comur_image.gallery_dir'); $gThumbSize = $this->container->getParameter('comur_image.gallery_thumb_size'); $ext = $request->files->get('image_upload_file')->getClientOriginalExtension(); //('image_upload_file'); $completeName = $filename . '.' . $ext; $controller = $this; $handlerConfig = array('upload_dir' => $uploadUrl, 'param_name' => 'image_upload_file', 'file_name' => $filename, 'upload_url' => $config['uploadConfig']['webDir'], 'min_width' => $config['cropConfig']['minWidth'], 'min_height' => $config['cropConfig']['minHeight'], 'image_versions' => array('thumbnail' => array('upload_dir' => $uploadUrl . $thumbsDir . '/', 'upload_url' => $config['uploadConfig']['webDir'] . '/' . $thumbsDir . '/', 'crop' => true, 'max_width' => $thumbSize, 'max_height' => $thumbSize))); $transDomain = $this->container->getParameter('comur_image.translation_domain'); $errorMessages = array(1 => $this->get('translator')->trans('The uploaded file exceeds the upload_max_filesize directive in php.ini', array(), $transDomain), 2 => $this->get('translator')->trans('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', array(), $transDomain), 3 => $this->get('translator')->trans('The uploaded file was only partially uploaded', array(), $transDomain), 4 => $this->get('translator')->trans('No file was uploaded', array(), $transDomain), 6 => $this->get('translator')->trans('Missing a temporary folder', array(), $transDomain), 7 => $this->get('translator')->trans('Failed to write file to disk', array(), $transDomain), 8 => $this->get('translator')->trans('A PHP extension stopped the file upload', array(), $transDomain), 'post_max_size' => $this->get('translator')->trans('The uploaded file exceeds the post_max_size directive in php.ini', array(), $transDomain), 'max_file_size' => $this->get('translator')->trans('File is too big', array(), $transDomain), 'min_file_size' => $this->get('translator')->trans('File is too small', array(), $transDomain), 'accept_file_types' => $this->get('translator')->trans('Filetype not allowed', array(), $transDomain), 'max_number_of_files' => $this->get('translator')->trans('Maximum number of files exceeded', array(), $transDomain), 'max_width' => $this->get('translator')->trans('Image exceeds maximum width', array(), $transDomain), 'min_width' => $this->get('translator')->trans('Image requires a minimum width (%min%)', array('%min%' => $config['cropConfig']['minWidth']), $transDomain), 'max_height' => $this->get('translator')->trans('Image exceeds maximum height', array(), $transDomain), 'min_height' => $this->get('translator')->trans('Image requires a minimum height (%min%)', array('%min%' => $config['cropConfig']['minHeight']), $transDomain), 'abort' => $this->get('translator')->trans('File upload aborted', array(), $transDomain), 'image_resize' => $this->get('translator')->trans('Failed to resize image', array(), $transDomain)); $response->setCallback(function () use($handlerConfig, $errorMessages) { new UploadHandler($handlerConfig, true, $errorMessages); }); return $response->send(); }
/** * @Route("/exportcsvpro", name="export_pro") */ public function exportProCSVAction() { $now = new \DateTime('now'); $em = $this->getDoctrine()->getManager(); $response = new StreamedResponse(); $response->setCallback(function () use($em) { $normalizer = new ObjectNormalizer(); $count = $em->getRepository('AppBundle:Client')->getCount(); $total = intval($count[1]); $header = array('NOM', 'PRENOM', 'EMAIL', 'SEXE'); $handle = fopen('php://output', 'r+'); fputcsv($handle, $header, ";"); $row = 1; while ($total >= 0) { $clients = $em->getRepository('AppBundle:Client')->findAllClients(($row - 1) * 2, 2); foreach ($clients as $key => $obj) { $clients[$key] = $normalizer->normalize($obj); } foreach ($clients as $client) { fputcsv($handle, $client, ";"); } $total = $total - 2; $row++; } fclose($handle); }); $response->headers->set('Content-Type', 'application/force-download'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); return $response; }
/** * Genera el excel con la planilla de servicios * @param type $fechaDesde * @param type $fechaHasta * @return StreamedResponse */ public function generateExcel($fechaDesde, $fechaHasta) { $response = new StreamedResponse(); $response->setCallback(function () use($fechaDesde, $fechaHasta) { $fileType = 'Excel2007'; $fileName = 'template/informeEpidemiologico.xlsx'; //$objPHPExcel = new PHPExcel(); $objReader = PHPExcel_IOFactory::createReader($fileType); $objPHPExcel = $objReader->load($fileName); $objPHPExcel->getProperties()->setCreator("MAB")->setLastModifiedBy("MAB")->setTitle("Informe epidemiológico")->setSubject("Reporte epidemiológico")->setDescription("Informe epidemiológico")->setKeywords("reporte servicio epidemiológico")->setCategory("Reporte excel"); //Categoria // ponemos los datos generales del informe $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E3', $fechaDesde)->setCellValue('J3', $fechaHasta); $filaServicio = 3; $repository = $this->getDoctrine()->getEntityManager()->getRepository('AppBundle:Servicio'); $query = $repository->createQueryBuilder('s')->where('s.fecha >= :desde')->andwhere('s.fecha < :hasta')->setParameter('desde', $fechaDesde)->setParameter('hasta', $fechaHasta)->orderBy('s.fecha', 'ASC')->getQuery(); $servicios = $query->getResult(); foreach ($servicios as $servicio) { $this->rellenarServicio($objPHPExcel, $servicio, $filaServicio); } $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); if (ob_get_contents()) { ob_end_clean(); } $objWriter->save('php://output'); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/vnd.ms-excel'); $response->headers->set('Content-Disposition', 'attachment; filename="informeEpidemiologico.xlsx"'); return $response; }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $uri = $request->path(); $uri_arr = explode("/", $uri); if (in_array($uri, $this->noAuth)) { return $next($request); } else { if ($uri_arr[0] == "stream") { $res = $this->permissionForStream($request, $next, $uri_arr[2]); if ($res['status'] == "2") { header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $response = new StreamedResponse(); $response->setCallback(function () use($res) { $output = json_encode($res); echo "data:" . $output . "\n\n"; flush(); //sleep(1); }); $response->send(); exit; } else { return $next($request); } } else { $this->_init_($request); return $this->permissionToAccess($request, $next); } } }
public function exportAction(Request $request, Application $app) { $exportOptions = $app['exportOptions']['winners']; $exportOptionsKeys = array_keys($exportOptions['fields']); $exportOptionsValues = array_values($exportOptions['fields']); $response = new StreamedResponse(); $response->setCallback(function () use($app, $exportOptionsKeys, $exportOptionsValues) { $handle = fopen('php://output', 'w+'); fputcsv($handle, $exportOptionsKeys, ';'); $winners = $app['orm.em']->getRepository('Application\\Entity\\WinnerEntity')->findAll(); $twig = clone $app['twig']; $twig->setLoader(new \Twig_Loader_String()); foreach ($winners as $winner) { $finalExportOptionsValues = array(); foreach ($exportOptionsValues as $singleValue) { $finalExportOptionsValues[] = $twig->render($singleValue, array('winner' => $winner)); } fputcsv($handle, $finalExportOptionsValues, ';'); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="winners.csv"'); return $response; }
/** * Handles response for csv-request. * * @param ViewHandler $handler * @param View $view * @param Request $request * @param string $format * * @return Response * * @throws ObjectNotSupportedException */ public function createResponse(ViewHandler $handler, View $view, Request $request, $format) { if (!$view->getData() instanceof ListRepresentation) { throw new ObjectNotSupportedException($view); } $viewData = $view->getData(); $data = new CallbackCollection($viewData->getData(), [$this, 'prepareData']); $fileName = sprintf('%s.csv', $viewData->getRel()); $config = new ExporterConfig(); $exporter = new Exporter($config); $data->rewind(); if ($row = $data->current()) { $config->setColumnHeaders(array_keys($row)); } $config->setDelimiter($this->convertValue($request->get('delimiter', ';'), self::$delimiterMap)); $config->setNewline($this->convertValue($request->get('newLine', '\\n'), self::$newLineMap)); $config->setEnclosure($request->get('enclosure', '"')); $config->setEscape($request->get('escape', '\\')); $response = new StreamedResponse(); $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName, $fileName); $response->headers->set('Content-Type', 'text/csv'); $response->headers->set('Content-Disposition', $disposition); $response->setCallback(function () use($data, $exporter) { $exporter->export('php://output', $data); }); $response->send(); return $response; }
/** * {@inheritdoc} */ public function call(ActionEvent $event, string $format) : Response { $controller = $event->getController(); $this->checkRole($controller); $request = $event->getRequest(); $id = $request->get('id'); if (is_numeric($id)) { if (!$controller->has('knp_snappy.pdf')) { throw new \Exception('Have you registered KnpSnappyBundle?'); } $snappy = $controller->get('knp_snappy.pdf'); $showAction = $controller->get('vardius_crud.action_show'); $html = $showAction->call($event, 'html')->getContent(); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $type = $request->get('type'); if ($type === 'pdf') { if (!$controller->has('knp_snappy.pdf')) { throw new \Exception('Have you registered KnpSnappyBundle?'); } $snappy = $controller->get('knp_snappy.pdf'); $listAction = $controller->get('vardius_crud.action_list'); $html = $listAction->call($event, 'html')->getContent(); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $source = $event->getDataProvider()->getSource(); if (!$source instanceof EntityRepository) { throw new \Exception('CSV export supports only ORM db driver'); } $queryBuilder = $source->createQueryBuilder('vardius_csv_export'); $crudEvent = new CrudEvent($source, $controller, $queryBuilder); $dispatcher = $controller->get('event_dispatcher'); $queryBuilder = $dispatcher->dispatch(CrudEvents::CRUD_EXPORT, $crudEvent)->getData(); $response = new StreamedResponse(); $response->setCallback(function () use($queryBuilder, $controller) { $handle = fopen('php://output', 'w+'); $headers = $controller->getHeaders(); if (!empty($headers)) { fputcsv($handle, $headers, ';'); } $entityManager = $controller->get('doctrine.orm.entity_manager'); $results = $queryBuilder->getQuery()->iterate(); while (false !== ($row = $results->next())) { $element = $controller->getRow($row[0]); $entityManager->detach($row[0]); if (count($element)) { fputcsv($handle, $element); } } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); } } return $response; }
/** * Set the stream response content. * @param StreamedResponse $response The response object. * @return StreamedResponse */ public function setContent(StreamedResponse $response) { $stream = $this->cache->readStream($this->path); $response->setCallback(function () use($stream) { rewind($stream); fpassthru($stream); fclose($stream); }); return $response; }
/** * Create a streamed response containing a file * * @return \Symfony\Component\HttpFoundation\StreamedResponse */ protected function createStreamedResponse() { $filename = $this->createFilename(); $response = new StreamedResponse(); $attachment = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename); $response->headers->set('Content-Type', $this->getContentType()); $response->headers->set('Content-Disposition', $attachment); $response->setCallback($this->quickExportCallback()); return $response; }
/** * @see StreamingEngineInterface::stream */ public function stream($view, array $parameters = [], StreamedResponse $response = null) { $callback = function () use($view, $parameters) { $this->templating->stream($view, $parameters); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; }
/** * CSV出力の共通処理 * @param Application $app * @param Request $request * @param string $type CSV出力形式の種類 * @return StreamedResponse */ public function export(Application $app, Request $request, $type) { // タイムアウトを無効にする. set_time_limit(0); $response = new StreamedResponse(); $response->setCallback(function () use($app, $request, $type) { $app['listing_ad_csv.service.listingad.data.creator']->create($app, $request, $type); }); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename=' . $this->createFileName($type)); $response->send(); return $response; }
/** * @param string $template * @param array $arguments * @param StreamedResponse $response * @return StreamedResponse */ public function stream($template, $arguments = array(), StreamedResponse $response = null) { $this->ensureTemplatingEngineIsPresent(); $templating = $this->templatingEngine; $callback = function () use($templating, $template, $arguments) { $templating->stream($template, $arguments); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; }
protected function error($error = null, $code = 200) { $this->builder->createPartial('body', 'error')->getParamManager()->setParams(['error' => $error === null ? _i('We encountered an unexpected error.') : $error]); $this->response->setStatusCode($code); if ($this->response instanceof StreamedResponse) { $this->response->setCallback(function () { $this->builder->stream(); }); } else { $this->response->setContent($this->builder->build()); } return $this->response; }
/** * Returns the picture identified by the given id in a streamedResponse * * @route("/picture/{id}/stream", name="colibri_gallery_picture_stream", options={"expose"=true}) * @param string $id * @return StreamedResponse */ public function streamedPictureAction($id) { $mongo = $this->get('doctrine_mongodb')->getManager(); $picture = $mongo->getRepository('ColibriGalleryBundle:Picture')->find($id); /** @var \Colibri\GalleryBundle\Document\Picture $picture */ $response = new StreamedResponse(); $response->headers->add(array('Content-Type' => $picture->getMimeType())); $response->headers->add(array('Content-Disposition' => 'attachment; filename=' . $picture->getFilename())); $response->setCallback(function () use($picture) { echo $picture->getFile()->getBytes(); }); return $response; }
/** * {@inheritdoc} */ public function call(ActionEvent $event) { $controller = $event->getController(); $this->checkRole($controller); $repository = $event->getDataProvider()->getSource(); $request = $event->getRequest(); $dispatcher = $controller->get('event_dispatcher'); $snappy = $controller->get('knp_snappy.pdf'); $responseHandler = $this->getResponseHandler($controller); $crudEvent = new CrudEvent($repository, $controller); $dispatcher->dispatch(CrudEvents::CRUD_EXPORT, $crudEvent); $this->id = $request->get('id'); $options['template'] = !empty($this->options['template'] ?: (is_numeric($this->id) ? 'show' : 'list')); if (is_numeric($this->id)) { $dataProvider = $event->getDataProvider(); $html = $responseHandler->getHtml($event->getView(), $this->getTemplate(), ['data' => $dataProvider->get($this->id), 'ui' => false]); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $listView = $event->getListView(); $listDataEvent = new ListDataEvent($repository, $request); $type = $request->get('type'); if ($type === 'pdf') { $html = $responseHandler->getHtml($event->getView(), $this->getTemplate(), ['list' => $listView->render($listDataEvent), 'title' => $listView->getTitle(), 'ui' => false]); $response = new Response($snappy->getOutputFromHtml($html, ['margin-bottom' => 3, 'margin-top' => 3, 'margin-left' => 4, 'margin-right' => 14]), 200, array('Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="export.pdf"')); } else { $response = new StreamedResponse(); $listView->setPagination(false); $queryBuilder = $listView->getData($listDataEvent, true, true); $response->setCallback(function () use($queryBuilder, $controller) { $handle = fopen('php://output', 'w+'); $headers = $controller->getHeaders(); if (!empty($headers)) { fputcsv($handle, $headers, ';'); } $entityManager = $controller->get('doctrine.orm.entity_manager'); $results = $queryBuilder->getQuery()->iterate(); while (false !== ($row = $results->next())) { $element = $controller->getRow($row[0]); $entityManager->detach($row[0]); fputcsv($handle, $element); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"'); } } return $response; }
/** * Server-Sent event stream handling * */ public function syncPresentation() { Log::info('setting: ' . env('PRESENTATION_ENABLE_SYNC', 'false')); if (!env('PRESENTATION_ENABLE_SYNC', 'false')) { return; } // define the new SSE stream $response = new StreamedResponse(); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('Cache-Control', 'no-cache'); $response->headers->set("X-Accel-Buffering", "no"); $response->setCallback(function () { // get current data $newMP = $this->getNewestMainPresenter(); $newPos = $this->getNewestShowPosition(); // (nearly) endless loop to keep stream open // the client will automatically reconnect when we close the stream after a while. // this is ti avoid memory leaks and hangs on the server side! $count = 0; while (true) { // if we have a new show position, send it out if ($newPos) { echo "event: syncPresentation\n"; echo "id: " . $count++ . "\n"; echo "data: " . json_encode($newPos) . "\n\n"; ob_flush(); flush(); } // if we have a new MP, send it out if ($newMP) { echo "event: newMainPresenter\n"; echo "id: " . $count++ . "\n"; echo "data: " . json_encode($newMP) . "\n\n"; ob_flush(); flush(); } sleep(2); // get latest data (will be empty if there was no change) $newMP = $this->getNewestMainPresenter(); $newPos = $this->getNewestShowPosition(); // close the stream after some time if (++$count > 100) { break; } } }); return $response; }
public function eventSourceAction() { /*$response = new Response("id: 1\nevent: alarme\ndata: INNONDATION, APPARTEMENT, VILLA, CHEMIN DES ERABLES 17,,.AIGLE INO_101 701F1(CI_J,J01)\n\n"); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('Cache-Control', 'no-cache'); return $response;*/ $em = $this->getDoctrine()->getManager(); $reponse = new StreamedResponse(); $reponse->headers->set('Content-Type', 'text/event-stream'); $reponse->headers->set('Cache-Control', 'no-cache'); $reponse->setCallback(function () use($em) { echo "id: 1\nevent: alarme\ndata: INNONDATION, APPARTEMENT, VILLA, CHEMIN DES ERABLES 17,,.AIGLE INO_101 701F1(CI_J,J01)\n\n"; ob_flush(); flush(); }); return $reponse; }
/** * Exporting a CSV file using an entity manager * The entity manager have to provide a getCsvExport function. * * @param string $service */ public function exportCsvAction($service, $option) { $manager = $this->get($service); if (!is_callable(array($manager, 'getCsvExport'))) { throw new \Exception('The service used for CSV export have to provide an export function'); } $response = new StreamedResponse(); list($content, $filename) = empty($option) ? $manager->getCsvExport() : $manager->getCsvExport($option); $response->setCallback(function () use($content) { $handle = fopen('php://output', 'w+'); fwrite($handle, ""); // adds BOM utf8 fox Excel foreach ($content as $index => $row) { if ($index == 0) { fputcsv($handle, array_keys($row), ';'); } $csvRow = array(); foreach ($row as $attribute) { if ($attribute instanceof \Datetime) { $csvRow[] = $attribute->format('Y-m-d'); } else { if (is_object($attribute)) { if (is_callable(array($attribute, '__toString'))) { $csvRow[] = $attribute; } else { if (is_callable(array($attribute, 'getId'))) { $csvRow[] = $attribute->getId(); } else { $csvRow[] = '#error'; } } } else { $csvRow[] = $attribute; } } } fputcsv($handle, $csvRow, ';'); } fclose($handle); }); $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/force-download'); //$response->headers->set('') $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '.csv"'); return $response; }
/** * @param string $content * @param string $filename * * @return \Symfony\Component\HttpFoundation\Response */ private function fileDownload($content, $filename) { if ($content instanceof StreamInterface) { $response = new StreamedResponse(); $response->setCallback(function () use($content) { $content->rewind(); while (!$content->eof()) { echo $content->read(8192); } }); } else { $response = new Response($content); } $disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename); $response->headers->set('Content-Disposition', $disposition); return $response; }
/** * @Route("/streamed", name="responses_streamed") */ public function streamedResponseAction() { $response = new StreamedResponse(); $response->setCallback(function () { echo 'Loading'; flush(); ob_flush(); for ($i = 0; $i < 10; $i++) { usleep(200000); echo '.'; flush(); ob_flush(); } echo 'Completed!'; flush(); ob_flush(); }); return $response; }
public function execute(Request $request, WorkingFolder $workingFolder, EventDispatcher $dispatcher) { $fileName = (string) $request->query->get('fileName'); $downloadedFile = new DownloadedFile($fileName, $this->app); $downloadedFile->isValid(); $downloadedFileEvent = new DownloadFileEvent($this->app, $downloadedFile); $dispatcher->dispatch(CKFinderEvent::DOWNLOAD_FILE, $downloadedFileEvent); if ($downloadedFileEvent->isPropagationStopped()) { throw new AccessDeniedException(); } $response = new StreamedResponse(); $response->headers->set('Cache-Control', 'cache, must-revalidate'); $response->headers->set('Pragma', 'public'); $response->headers->set('Expires', '0'); if ($request->get('format') === 'text') { $response->headers->set('Content-Type', 'text/plain; charset=utf-8'); } else { $userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; $encodedName = str_replace("\"", "\\\"", $fileName); if (strpos($userAgent, 'MSIE') !== false) { $encodedName = str_replace(array("+", "%2E"), array(" ", "."), urlencode($encodedName)); } $response->headers->set('Content-Type', 'application/octet-stream; name="' . $fileName . '"'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $encodedName . '"'); } $response->headers->set('Content-Length', $downloadedFile->getSize()); $fileStream = $workingFolder->readStream($downloadedFile->getFilename()); $chunkSize = 1024 * 100; // how many bytes per chunk $response->setCallback(function () use($fileStream, $chunkSize) { if ($fileStream === false) { return false; } while (!feof($fileStream)) { echo fread($fileStream, $chunkSize); flush(); @set_time_limit(8); } return true; }); return $response; }
public function userDataAction(Request $request) { if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { throw new AccessDeniedException(); } $userType = $request->query->get('usertype'); if (!in_array($userType, array('pupils', 'mentors', 'all'))) { return null; } $status = $request->query->get('status'); if (!in_array($status, array('enabled', 'disabled', 'all'))) { return null; } // Get user data $users = $this->retrieveUserData($userType, $status); // Output in a requested format // CSV if ($request->query->get('type') === 'csv') { if ($userType === 'all') { return new HttpException(400, "Only mentors' or pupils' export can be requested, but not both."); } $response = new StreamedResponse(); $response->setCallback(function () use($userType, $users) { $this->outputCsvCallback($userType, $users); }); $filename = $userType . date('-Ymd-Hi') . '.csv'; $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"'); return $response; } else { if ($request->query->get('type') === 'email') { $formatUser = function ($user) { return $user->getFirstName() . ' ' . $user->getLastName() . ' <' . $user->getEmail() . '>'; }; $respStrs = array_map($formatUser, $users); $response = new Response(implode(",\n", $respStrs)); return $response; } } return null; }
public function recalculateAction(Player $me, $match) { $match = Match::get($match); // get a match even if it's deleted if (!$me->canEdit($match)) { throw new ForbiddenException("You are not allowed to edit that match."); } return $this->showConfirmationForm(function () use($match) { $response = new StreamedResponse(); $response->headers->set('Content-Type', 'text/plain'); $response->setCallback(function () use($match) { $this->recalculate($match); }); $response->send(); }, "Do you want to recalculate ELO history for all teams and matches after the specified match?", "ELO history recalculated", "Recalculate ELOs", function () use($match) { if ($match->isDeleted()) { return new RedirectResponse($match->getURL('list')); } return new RedirectResponse($match->getURL('show')); }, "Match/recalculate.html.twig", $noButton = true); }
/** * @param string $build * @param Request $request * @return Response */ public function manifestAction($build, Request $request) { $this->closeSession($request); try { $manifest = $this->application->getManifest($build); } catch (FileNotFoundException $e) { throw new NotFoundHttpException('Not Found', $e); } $response = new StreamedResponse(function () { echo ''; }); $response->setETag($manifest->computeETag())->setLastModified(\DateTime::createFromFormat('U', $manifest->getMTime()))->setPublic(); if ($response->isNotModified($request)) { return $response; } $response->setCallback(function () use($manifest) { echo $manifest->getContent(); }); $response->headers->set('Content-Type', 'application/json'); return $response; }
/** * Download attached files * @Route("/download/{id}/{mapping}", name="biogestion_fileupload_download") */ public function downloadAction($id, $mapping) { // var_dump($this->get('vich_uploader.metadata_reader')->getUploadableFields(\Symfony\Component\Security\Core\Util\ClassUtils::getRealClass($lr))); // var_dump($this->container->getParameter('melolab_biogestion_fileupload.mappings')); // var_dump($this->container->getParameter('vich_uploader.mappings')); die(); $mappings = $this->container->getParameter('melolab_biogestion_fileupload.mappings'); $config = $mappings[$mapping]; $entity = $this->getDoctrine()->getManager()->getRepository($config['entity'])->{$config}['repository_method']($id); if (!$entity) { throw $this->createNotFoundException($this->get('translator')->trans('file.entity_not_found')); } // Security if (true === $config['allow_anonymous_downloads']) { if (true === $this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED') and false === $this->get('security.context')->isGranted('VIEW', $entity)) { throw new AccessDeniedException(); } } else { if (false === $this->get('security.context')->isGranted('VIEW', $entity)) { throw new AccessDeniedException(); } } $mimeTypes = array('pdf' => 'application/pdf', 'txt' => 'text/plain', 'html' => 'text/html', 'exe' => 'application/octet-stream', 'zip' => 'application/zip', 'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'gif' => 'image/gif', 'png' => 'image/png', 'jpeg' => 'image/jpg', 'jpg' => 'image/jpg', 'php' => 'text/plain'); // Get filename $filename = $entity->{$config}['filename_getter'](); if (!$filename) { throw $this->createNotFoundException($this->get('translator')->trans('file.file_not_found')); } $ext = pathinfo($filename, PATHINFO_EXTENSION); $uploadFolder = $this->container->getParameter('vich_uploader.mappings')[$config['vich_mapping']]['upload_destination']; // Full path to file $path = $uploadFolder . "/" . $filename; // Prepare the http response $response = new StreamedResponse(); $response->setCallback(function () use($path) { $fp = fopen($path, 'rb'); fpassthru($fp); }); $response->headers->set('Content-Type', $mimeTypes[$ext]); return $response; }
public function logsDownloadAction(Request $request, $id) { $build = $this->findBuild($id); $redis = $this->get('app_core.redis'); $perPage = $this->container->getParameter('build_logs_load_limit'); $list = $build->getLogsList(); $gzip = (bool) $request->get('gzip', false); $tmpuri = tempnam(sys_get_temp_dir(), 'logs-download-'); if ($gzip) { $tmp = gzopen($tmpuri, 'w9'); } else { $tmp = fopen($tmpuri, 'w+'); } $offset = 0; do { $logs = $redis->lrange($list, $offset, $offset + $perPage); $logs = array_map(function ($log) { $message = json_decode($log, true)['message']; $message = preg_replace('/\\[\\d+(?:;\\d+)?m/', '', $message); return $message; }, $logs); $offset += $perPage; $string = implode('', $logs); if ($gzip) { gzwrite($tmp, $string); } else { fwrite($tmp, $string); } } while (count($logs) >= $perPage); fclose($tmp); $filename = sprintf('%s_%s_%s.%s', $build->getProject()->getSlug(), $build->getRef(), $build->getId(), $gzip ? 'log.gz' : 'log'); $response = new StreamedResponse(); $response->headers->set('Content-Disposition', 'attachment; filename=' . $filename); $response->headers->set('Content-Type', $gzip ? 'application/gzip' : 'text/plain'); $response->setCallback(function () use($tmpuri) { readfile($tmpuri); unlink($tmpuri); }); return $response; }
/** * @param Request $request * @return StreamedResponse * * @Route("/csv/do", name="cto_export_csvdo") */ public function doCSVExportAction(Request $request) { $exportDTO = new ExportFilterDTO(); $form = $this->createForm(ExportFilterDTOType::class, $exportDTO); $form->handleRequest($request); $response = new StreamedResponse(); $carJobRepository = $this->getDoctrine()->getManager()->getRepository("CTOAppBundle:CarJob"); $response->setCallback(function () use($carJobRepository, $exportDTO) { $handle = fopen('php://output', 'w+'); fputcsv($handle, ['Date', 'Day of week', 'Category', 'Description', 'Client', 'Master', 'Salary'], ';'); $result = $carJobRepository->getDataForExportToCSV($exportDTO); foreach ($result as $item) { fputcsv($handle, [$item['jdate']->format("d.m.Y"), $item['jdate']->format("l"), $item['catName'], $item['description'], $item['clientName'], $item['masterFName'] . ' ' . $item['masterLName'], $item['price']], ';'); } fclose($handle); }); $now = Carbon::now()->format("d.m.Y"); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename=' . "export_for_{$now}.csv"); return $response; }
/** * Streams a view. * * @param string $view The view name * @param array $parameters An array of parameters to pass to the view * @param StreamedResponse $response A response instance * * @return StreamedResponse A StreamedResponse instance */ public function stream($view, array $parameters = array(), StreamedResponse $response = null) { $templating = $this->container->get('templating'); $callback = function () use($templating, $view, $parameters) { $templating->stream($view, $parameters); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; }
/** * アップロード用CSV雛形ファイルダウンロード */ public function csvTemplate(Application $app, Request $request, $type) { set_time_limit(0); $response = new StreamedResponse(); if ($type == 'product') { $headers = $this->getProductCsvHeader(); $filename = 'product.csv'; } else { if ($type == 'category') { $headers = $this->getCategoryCsvHeader(); $filename = 'category.csv'; } else { throw new NotFoundHttpException(); } } $response->setCallback(function () use($app, $request, $headers) { // ヘッダ行の出力 $row = array(); foreach ($headers as $key => $value) { $row[] = mb_convert_encoding($key, $app['config']['csv_export_encoding'], 'UTF-8'); } $fp = fopen('php://output', 'w'); fputcsv($fp, $row, $app['config']['csv_export_separator']); fclose($fp); }); $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Disposition', 'attachment; filename=' . $filename); $response->send(); return $response; }
/** * Controller entry point * * @return Response|StreamedResponse * * @throws http_exception When phpBB is not installed */ public function handle() { if (!$this->install_helper->is_phpbb_installed()) { throw new http_exception(403, 'INSTALL_PHPBB_NOT_INSTALLED'); } $this->template->assign_vars(array('U_ACTION' => $this->controller_helper->route('phpbb_installer_update'))); // Set up input-output handler if ($this->request->is_ajax()) { $this->iohandler_factory->set_environment('ajax'); } else { $this->iohandler_factory->set_environment('nojs'); } // Set the appropriate input-output handler $this->installer->set_iohandler($this->iohandler_factory->get()); $this->controller_helper->handle_language_select(); // Render the intro page if ($this->request->is_ajax()) { $installer = $this->installer; $response = new StreamedResponse(); $response->setCallback(function () use($installer) { $installer->run(); }); // Try to bypass any server output buffers $response->headers->set('X-Accel-Buffering', 'no'); $response->headers->set('Content-type', 'application/json'); return $response; } else { // Set active stage $this->menu_provider->set_nav_property(array('update', 0, 'introduction'), array('selected' => true, 'completed' => false)); $this->template->assign_vars(array('SHOW_INSTALL_START_FORM' => true, 'TITLE' => $this->language->lang('UPDATE_INSTALLATION'), 'CONTENT' => $this->language->lang('UPDATE_INSTALLATION_EXPLAIN'))); /** @var \phpbb\install\helper\iohandler\iohandler_interface $iohandler */ $iohandler = $this->iohandler_factory->get(); $this->controller_helper->handle_navigation($iohandler); return $this->controller_helper->render('installer_update.html', 'UPDATE_INSTALLATION', true); } }