Example #1
0
 /**
  * {@inheritDoc}
  *
  * @return Stream|Response
  */
 public function indexAction()
 {
     $response = $this->getResponse();
     $params = $this->params()->fromRoute();
     if ($params['path'] === '') {
         $response->setStatusCode(404);
         return $response;
     }
     $info = pathinfo($params['path']);
     if ($info['dirname'] === '.') {
         $info['dirname'] = '';
     }
     /* @var $folder \CmsFile\Mapping\FolderInterface */
     $folder = $this->getFolderService()->getMapper()->findOneByPath('/' . trim($info['dirname'], '/'));
     if (!$folder) {
         $response->setStatusCode(404);
         return $response;
     }
     $file = $folder->getFile($info['basename']);
     if (!$file) {
         $response->setStatusCode(404);
         return $response;
     }
     $response = new Stream();
     $response->setStream(fopen($file, 'r'));
     $response->setStatusCode(200);
     $headers = new Headers();
     $headers->addHeaderLine('Content-Type', $file->getType())->addHeaderLine('Content-Disposition', 'attachment; filename="' . $file->getTitle() . '"')->addHeaderLine('Content-Length', filesize($file));
     $response->setHeaders($headers);
     return $response;
 }
Example #2
0
 /**
  *
  * @return \Zend\View\Model\ViewModel
  */
 public function execute()
 {
     $optionsRenderer = $this->getOptionsRenderer();
     $delimiter = ',';
     if (isset($optionsRenderer['delimiter'])) {
         $delimiter = $optionsRenderer['delimiter'];
     }
     $enclosure = '"';
     if (isset($optionsRenderer['enclosure'])) {
         $enclosure = $optionsRenderer['enclosure'];
     }
     $options = $this->getOptions();
     $optionsExport = $options['settings']['export'];
     $path = $optionsExport['path'];
     $saveFilename = date('Y-m-d_H-i-s') . $this->getCacheId() . '.csv';
     $fp = fopen($path . '/' . $saveFilename, 'w');
     // Force UTF-8 for CSV rendering in EXCEL.
     fprintf($fp, chr(0xef) . chr(0xbb) . chr(0xbf));
     /*
      * Save the file
      */
     // header
     if (isset($optionsRenderer['header']) && true === $optionsRenderer['header']) {
         $header = [];
         foreach ($this->getColumnsToExport() as $col) {
             $header[] = $this->getTranslator()->translate($col->getLabel());
         }
         fputcsv($fp, $header, $delimiter, $enclosure);
     }
     // data
     foreach ($this->getData() as $row) {
         $csvRow = [];
         foreach ($this->getColumnsToExport() as $col) {
             $value = $row[$col->getUniqueId()];
             if ($col->getType() instanceof Type\PhpArray || $col->getType() instanceof Type\Image) {
                 $value = implode(',', $value);
             }
             $csvRow[] = $value;
         }
         fputcsv($fp, $csvRow, $delimiter, $enclosure);
     }
     fclose($fp);
     /*
      * Return the file
      */
     $response = new ResponseStream();
     $response->setStream(fopen($path . '/' . $saveFilename, 'r'));
     $headers = new Headers();
     $headers->addHeaders(['Content-Type' => ['application/force-download', 'application/octet-stream', 'application/download', 'text/csv; charset=utf-8'], 'Content-Length' => filesize($path . '/' . $saveFilename), 'Content-Disposition' => 'attachment;filename=' . $this->getFilename() . '.csv', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT']);
     $response->setHeaders($headers);
     return $response;
 }
 /**
  * @return Stream
  * mapAction fornisce uno stream dell'immagine
  * creata dal PngRender e cambia ogni volta che
  * la mappa si aggiorna.
  */
 public function mapAction()
 {
     $session = $this->getSession();
     /** @var Wator $wator */
     $wator = $session->wator;
     $wator->updateWorld();
     $render = new PngRenderX4($wator);
     $filePng = $render->getPngFile($wator);
     $response = new Stream();
     $response->getHeaders()->addHeaders(array('Content-type' => 'image/jpg'));
     $response->setStream(fopen('/tmp/map.png', 'r'));
     return $response;
 }
Example #4
0
 public function tfaRenderQrCodeAction()
 {
     $filePath = tempnam('data/tmp/', '2fa-qr-');
     $renderer = new \BaconQrCode\Renderer\Image\Png();
     $renderer->setForegroundColor(new \BaconQrCode\Renderer\Color\Rgb(170, 45, 76));
     $renderer->setHeight(256);
     $renderer->setWidth(256);
     $writer = new \BaconQrCode\Writer($renderer);
     $writer->writeFile('123456', $filePath);
     $response = new Stream();
     $response->setCleanup(true);
     $response->setStream(fopen($filePath, 'rb'));
     $response->setStreamName($filePath);
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Length', filesize($filePath));
     $headers->addHeaderLine('Content-Type', 'image/png');
     return $response;
 }
Example #5
0
 public function testMultilineHeader()
 {
     $values = $this->readResponse('response_multiline_header');
     $response = Stream::fromStream($values['data'], $values['stream']);
     // Make sure we got the corrent no. of headers
     $this->assertEquals(6, count($response->getHeaders()), 'Header count is expected to be 6');
     // Check header integrity
     $this->assertEquals('timeout=15,max=100', $response->getHeaders()->get('keep-alive')->getFieldValue());
     $this->assertEquals('text/html;charset=iso-8859-1', $response->getHeaders()->get('content-type')->getFieldValue());
 }
 /**
  * Fetch a generated package.
  *
  * @param string $fileId
  * @param string $format
  * @param \Zend\Http\Response $response
  * @return \Zend\Http\Response
  */
 private function fetch($fileId, $format, $response)
 {
     if (!$fileId || !$format) {
         $response->setStatusCode(404);
         return $response;
     }
     $package = $this->getPackageFile($fileId, $format);
     if (!file_exists($package)) {
         $response->setStatusCode(404);
         return $response;
     }
     $stream = fopen($package, 'r');
     if (false === $stream) {
         $response->setStatusCode(500);
         return $response;
     }
     // Mark the package for deletion when the request spins down.
     $this->sentPackage = $package;
     // Create a streamable response.
     $response = new Stream();
     $response->setStream($stream);
     $response->getHeaders()->addHeaderLine('Content-Type', 'application/octet-stream')->addHeaderLine('Content-Disposition', sprintf('attachment; filename="apigility_%s.%s"', date('Y-m-d_H-i-s'), $format))->addHeaderLine('Content-Length', filesize($package));
     return $response;
 }
Example #7
0
 public function downloadErrorsAction()
 {
     $date = $this->params('date');
     $path = sprintf('data/logs/php_log.%s.xml', $date);
     $response = new Stream();
     $response->setStream(fopen($path, 'r'));
     $response->setCleanup(false);
     $response->setStatusCode(200);
     $headers = $response->getHeaders();
     $headers->addHeaderLine(sprintf('Content-Disposition: attachment; filename="log-%s.csv"', $date));
     $headers->addHeaderLine('Content-Type: text/csv');
     return $response;
 }
Example #8
0
 /**
  * Get file stream response
  * 
  * 
  * @access public
  * @param string $file
  * @return Stream
  */
 public function getFileResponse($file)
 {
     $response = new Response();
     if (!empty($file) && file_exists($file)) {
         $response = new Stream();
         $response->setStream(fopen($file, 'r'));
         $response->setStatusCode(200);
         $response->setStreamName(basename($file));
         $headers = new Headers();
         $headers->addHeaders(array('Content-Disposition' => 'attachment; filename="' . basename($file) . '"', 'Content-Type' => 'application/octet-stream', 'Content-Length' => filesize($file), 'Expires' => '@0', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'public'));
         $response->setHeaders($headers);
     }
     return $response;
 }
Example #9
0
 public function stream($file, $type)
 {
     switch ($type) {
         case "css":
             $mimeType = 'text/css';
             break;
         case 'js':
             $mimeType = 'text/javascript';
             break;
         default:
             $mimeType = mime_content_type($file);
     }
     $response = new Stream();
     $response->setStream(fopen($file, 'r'));
     $response->setStatusCode(200);
     $response->setStreamName(basename($file));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Type' => $mimeType, 'Content-Length' => filesize($file)));
     $response->setHeaders($headers);
     return $response;
 }
Example #10
0
 public function renderQrCodeAction()
 {
     /** @var AccountInterface $account */
     $account = $this->zourceAccount();
     $oneTimePassword = new TOTP($account->getContact()->getFullName(), $this->tfaService->getSecret());
     $oneTimePassword->setIssuer('Zource');
     $oneTimePassword->setIssuerIncludedAsParameter(true);
     $oneTimePassword->setParameter('image', $this->url()->fromRoute('settings/security/tfa-image', [], ['force_canonical' => true]));
     $filePath = tempnam('data/tmp/', '2fa-qr-');
     $renderer = new Png();
     $renderer->setHeight(256);
     $renderer->setWidth(256);
     $writer = new Writer($renderer);
     $writer->writeFile($oneTimePassword->getProvisioningUri(true), $filePath);
     $response = new Stream();
     $response->setCleanup(true);
     $response->setStream(fopen($filePath, 'rb'));
     $response->setStreamName($filePath);
     $headers = $response->getHeaders();
     $headers->addHeaderLine('Content-Length', filesize($filePath));
     $headers->addHeaderLine('Content-Type', 'image/png');
     return $response;
 }
Example #11
0
 public function downloadFile($filePath, $filename = FALSE)
 {
     $name = $filename ?: basename($filePath);
     $response = new Stream();
     $response->setStream(fopen($filePath, 'r'));
     $response->setStatusCode(200);
     $response->setStreamName(basename($filePath));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Disposition' => "attachment; filename='{$name}'", 'Content-Type' => 'application/octet-stream', 'Content-Length' => filesize($filePath), 'Expires' => '@0', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'public'));
     $response->setHeaders($headers);
     return $response;
 }
 /**
  * @param $file
  * @return Stream
  */
 function forceDownloadAction($file)
 {
     //        $file = '/path/to/my/file.txt';
     $file = $_SERVER['DOCUMENT_ROOT'] . '/' . $file;
     $response = new Stream();
     $response->setStream(fopen($file, 'r'));
     $response->setStatusCode(200);
     $response->setStreamName(basename($file));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Disposition' => 'attachment; filename="' . basename($file) . '"', 'Content-Type' => 'application/octet-stream', 'Content-Length' => filesize($file)));
     $response->setHeaders($headers);
     return $response;
 }
Example #13
0
 public function downloadFileAction()
 {
     $fileName = urldecode($this->params()->fromRoute("fileName", null));
     echo ROOT_PATH . '/' . $fileName;
     var_dump(file_exists(ROOT_PATH . '/' . $fileName));
     if (!$fileName || !file_exists(ROOT_PATH . '/' . $fileName)) {
         return $this->notFoundAction();
     } else {
         $pathInfo = pathinfo($fileName);
         switch ($pathInfo['extension']) {
             case "pdf":
                 $type = "application/pdf";
                 break;
             case "xls":
                 $type = "application/vnd.ms-excel";
                 break;
             case "zip":
                 $type = "application/zip";
                 break;
             case "ppt":
                 $type = "application/vnd.ms-powerpoint";
                 break;
             default:
                 $type = "text/plain";
         }
         $response = new Stream();
         $response->setStream(fopen($fileName, 'r'));
         $response->setStatusCode(200);
         $headers = new \Zend\Http\Headers();
         $headers->addHeaderLine('Content-Type', $type)->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')->addHeaderLine('Content-Length', filesize($fileName));
         $response->setHeaders($headers);
         return $response;
     }
 }
 public function pdfAction()
 {
     $number = (int) $this->params()->fromRoute('id', 0);
     $file = 'data/invoice/invoice-' . sprintf('%06d', $number) . '.pdf';
     $response = new Stream();
     $response->setStream(fopen($file, 'r'));
     $response->setStreamName(basename($file));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Disposition' => 'attachment; filename="' . basename($file) . '"', 'Content-Type' => 'application/pdf', 'Content-Length' => filesize($file)));
     $response->setHeaders($headers);
     return $response;
 }
Example #15
0
 public function viewFileAttachmentAction()
 {
     $file_no = (int) $this->params()->fromRoute('id', 0);
     if (!$file_no) {
         return $this->redirect()->toRoute('app', array('controller' => 'failed', 'action' => 'forbidden'));
     }
     $currentUser = $this->auth()->get('user_no');
     $dbAdapter = $this->getDb();
     $sql = "SELECT \n                      t_decision_file.file_no, \n                      t_decision_file.decision_no, \n                      t_decision_file.file_name, \n                      t_decision_file.content_type, \n                      OCTET_LENGTH( t_decision_file.binary_data) as file_size, \n                      t_decision_file.binary_data,\n                      t_decision.create_user\n                 FROM t_decision_file \n            LEFT JOIN t_decision \n                   ON t_decision_file.decision_no = t_decision.decision_no\n                WHERE t_decision_file.file_no = {$file_no}";
     $result = $dbAdapter->query($sql)->execute();
     $file = $result->current();
     if (!$file) {
         return $this->redirect()->toRoute('app', array('controller' => 'failed', 'action' => 'not-found'));
     }
     $continue = true;
     // you must be the create user of the request
     if ($file['create_user'] != $currentUser) {
         $continue = false;
     }
     // if you are not the create_user of the request you must be 1 of approver
     if (!$continue) {
         // check file restriction
         $result2 = $dbAdapter->query("SELECT\n                    t_decision_approval.user_no\n                    FROM t_decision_approval\n                    WHERE t_decision_approval.decision_no = {$file['decision_no']}")->execute();
         $resultSet = new ResultSet();
         $resultSet->initialize($result2);
         $resultAr = $resultSet->toArray();
         if (is_array($resultAr)) {
             foreach ($resultAr as $rec) {
                 if ((int) $rec['user_no'] === (int) $currentUser) {
                     $continue = true;
                     break;
                 }
             }
         }
     }
     // Otherwise you will not be able to access this attachment
     if (!$continue) {
         $this->flashMessenger()->addMessage("You don't have enough access level to view this document");
         return $this->redirect()->toRoute('app', array('controller' => 'failed', 'action' => 'forbidden'));
     }
     $file_name = $file["file_name"];
     $file_size = $file["file_size"];
     $file_mime_type = $file["content_type"];
     $file_content = $file["binary_data"];
     $new_filename = "temp_" . $file_name;
     $filePath = APP_UPLOAD_DIR . $new_filename;
     \file_put_contents($filePath, $file_content);
     $response = new Stream();
     $response->setStream(fopen($filePath, 'r'));
     $response->setStatusCode(200);
     $response->setStreamName(basename($filePath));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Disposition' => 'inline; filename="' . $new_filename . '"', 'Content-Type' => $file_mime_type . ';charset=UTF-8', 'Content-Length' => $file_size));
     $response->setHeaders($headers);
     /**$view = new ViewModel(array(
            'response' => $response,
            'headers' => $headers
        ));
        $view->setTemplate('/common/view-attachment.phtml');
        $view->setTerminal(true);**/
     //  return $view;
     return $response;
 }
 /**
  * Send header to download the given file
  *
  * @param int $fileID            
  * @return \Zend\Http\Response\Stream
  */
 protected function downloadFile($fileID)
 {
     $file = $this->getFileTable()->getFile($fileID);
     $this->getFileTable()->incrementDownloadCount($file);
     $fileUrl = $this->getOptions()->getDownloadFolderPath() . "/" . $file->url;
     if (!file_exists($fileUrl)) {
         throw new \Exception("File doesn't exists");
     }
     $response = new Stream();
     $response->setStream(fopen($fileUrl, 'r'));
     $response->setStatusCode(200);
     $headers = new Headers();
     $headers->addHeaderLine('Content-Type', 'application/octet-stream')->addHeaderLine('Content-Disposition', 'attachment; filename="' . $file->name . '"')->addHeaderLine('Cache-Control', 'must-revalidate')->addHeaderLine('Pragma', 'public')->addHeaderLine('Content-Length', filesize($fileUrl));
     $response->setHeaders($headers);
     return $response;
 }
Example #17
0
 /**
  * Send HTTP request
  *
  * @param  Request $request
  * @return Response
  * @throws Exception\RuntimeException
  * @throws Client\Exception\RuntimeException
  */
 public function send(Request $request = null)
 {
     if ($request !== null) {
         $this->setRequest($request);
     }
     $this->redirectCounter = 0;
     $response = null;
     $adapter = $this->getAdapter();
     // Send the first request. If redirected, continue.
     do {
         // uri
         $uri = $this->getUri();
         // query
         $query = $this->getRequest()->getQuery();
         if (!empty($query)) {
             $queryArray = $query->toArray();
             if (!empty($queryArray)) {
                 $newUri = $uri->toString();
                 $queryString = http_build_query($queryArray, null, $this->getArgSeparator());
                 if ($this->config['rfc3986strict']) {
                     $queryString = str_replace('+', '%20', $queryString);
                 }
                 if (strpos($newUri, '?') !== false) {
                     $newUri .= $this->getArgSeparator() . $queryString;
                 } else {
                     $newUri .= '?' . $queryString;
                 }
                 $uri = new Http($newUri);
             }
         }
         // If we have no ports, set the defaults
         if (!$uri->getPort()) {
             $uri->setPort($uri->getScheme() == 'https' ? 443 : 80);
         }
         // method
         $method = $this->getRequest()->getMethod();
         // this is so the correct Encoding Type is set
         $this->setMethod($method);
         // body
         $body = $this->prepareBody();
         // headers
         $headers = $this->prepareHeaders($body, $uri);
         $secure = $uri->getScheme() == 'https';
         // cookies
         $cookie = $this->prepareCookies($uri->getHost(), $uri->getPath(), $secure);
         if ($cookie->getFieldValue()) {
             $headers['Cookie'] = $cookie->getFieldValue();
         }
         // check that adapter supports streaming before using it
         if (is_resource($body) && !$adapter instanceof Client\Adapter\StreamInterface) {
             throw new Client\Exception\RuntimeException('Adapter does not support streaming');
         }
         // calling protected method to allow extending classes
         // to wrap the interaction with the adapter
         $response = $this->doRequest($uri, $method, $secure, $headers, $body);
         if (!$response) {
             throw new Exception\RuntimeException('Unable to read response, or response is empty');
         }
         if ($this->config['storeresponse']) {
             $this->lastRawResponse = $response;
         } else {
             $this->lastRawResponse = null;
         }
         if ($this->config['outputstream']) {
             $stream = $this->getStream();
             if (!is_resource($stream) && is_string($stream)) {
                 $stream = fopen($stream, 'r');
             }
             $streamMetaData = stream_get_meta_data($stream);
             if ($streamMetaData['seekable']) {
                 rewind($stream);
             }
             // cleanup the adapter
             $adapter->setOutputStream(null);
             $response = Response\Stream::fromStream($response, $stream);
             $response->setStreamName($this->streamName);
             if (!is_string($this->config['outputstream'])) {
                 // we used temp name, will need to clean up
                 $response->setCleanup(true);
             }
         } else {
             $response = $this->getResponse()->fromString($response);
         }
         // Get the cookies from response (if any)
         $setCookies = $response->getCookie();
         if (!empty($setCookies)) {
             $this->addCookie($setCookies);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && $response->getHeaders()->has('Location')) {
             // Avoid problems with buggy servers that add whitespace at the
             // end of some headers
             $location = trim($response->getHeaders()->get('Location')->getFieldValue());
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatusCode() == 303 || !$this->config['strictredirects'] && ($response->getStatusCode() == 302 || $response->getStatusCode() == 301)) {
                 $this->resetParameters(false, false);
                 $this->setMethod(Request::METHOD_GET);
             }
             // If we got a well formed absolute URI
             if (($scheme = substr($location, 0, 6)) && ($scheme == 'http:/' || $scheme == 'https:')) {
                 // setURI() clears parameters if host changed, see #4215
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 if (strpos($location, '?') !== false) {
                     list($location, $query) = explode('?', $location, 2);
                 } else {
                     $query = '';
                 }
                 $this->getUri()->setQuery($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->getUri()->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = $this->getUri()->getPath();
                     $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                     $this->getUri()->setPath($path . '/' . $location);
                 }
             }
             ++$this->redirectCounter;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter <= $this->config['maxredirects']);
     $this->response = $response;
     return $response;
 }
Example #18
0
 /**
  * Send the HTTP request and return an HTTP response object
  *
  * @param string $method
  * @return \Zend\Http\Response
  * @throws \Zend\Http\Client\Exception
  */
 public function request($method = null)
 {
     if (!$this->uri instanceof Uri\Url) {
         throw new Client\Exception('No valid URI has been passed to the client');
     }
     if ($method) {
         $this->setMethod($method);
     }
     $this->redirectCounter = 0;
     $response = null;
     // Make sure the adapter is loaded
     if ($this->adapter == null) {
         $this->setAdapter($this->config['adapter']);
     }
     // Send the first request. If redirected, continue.
     do {
         // Clone the URI and add the additional GET parameters to it
         $uri = clone $this->uri;
         if (!empty($this->paramsGet)) {
             $query = $uri->getQuery();
             if (!empty($query)) {
                 $query .= '&';
             }
             $query .= http_build_query($this->paramsGet, null, '&');
             $uri->setQuery($query);
         }
         $body = $this->_prepareBody();
         $headers = $this->_prepareHeaders();
         // check that adapter supports streaming before using it
         if (is_resource($body) && !$this->adapter instanceof Client\Adapter\Stream) {
             throw new Client\Exception('Adapter does not support streaming');
         }
         // Open the connection, send the request and read the response
         $this->adapter->connect($uri->getHost(), $uri->getPort(), $uri->getScheme() == 'https' ? true : false);
         if ($this->config['output_stream']) {
             if ($this->adapter instanceof Client\Adapter\Stream) {
                 $stream = $this->_openTempStream();
                 $this->adapter->setOutputStream($stream);
             } else {
                 throw new Client\Exception('Adapter does not support streaming');
             }
         }
         $this->last_request = $this->adapter->write($this->method, $uri, $this->config['httpversion'], $headers, $body);
         $response = $this->adapter->read();
         if (!$response) {
             throw new Client\Exception('Unable to read response, or response is empty');
         }
         if ($this->config['output_stream']) {
             rewind($stream);
             // cleanup the adapter
             $this->adapter->setOutputStream(null);
             $response = Response\Stream::fromStream($response, $stream);
             $response->setStreamName($this->_stream_name);
             if (!is_string($this->config['output_stream'])) {
                 // we used temp name, will need to clean up
                 $response->setCleanup(true);
             }
         } else {
             $response = Response::fromString($response);
         }
         if ($this->config['storeresponse']) {
             $this->last_response = $response;
         }
         // Load cookies into cookie jar
         if (isset($this->cookiejar)) {
             $this->cookiejar->addCookiesFromResponse($response, $uri);
         }
         // If we got redirected, look for the Location header
         if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
             // Check whether we send the exact same request again, or drop the parameters
             // and send a GET request
             if ($response->getStatus() == 303 || !$this->config['strictredirects'] && ($response->getStatus() == 302 || $response->getStatus() == 301)) {
                 $this->resetParameters();
                 $this->setMethod(self::GET);
             }
             // If we got a well formed absolute URI
             $url = new Uri\Url($location);
             if ($url->isValid()) {
                 $this->setHeaders('host', null);
                 $this->setUri($location);
             } else {
                 // Split into path and query and set the query
                 if (strpos($location, '?') !== false) {
                     list($location, $query) = explode('?', $location, 2);
                 } else {
                     $query = '';
                 }
                 $this->uri->setQuery($query);
                 // Else, if we got just an absolute path, set it
                 if (strpos($location, '/') === 0) {
                     $this->uri->setPath($location);
                     // Else, assume we have a relative path
                 } else {
                     // Get the current path directory, removing any trailing slashes
                     $path = $this->uri->getPath();
                     $path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
                     $this->uri->setPath($path . '/' . $location);
                 }
             }
             ++$this->redirectCounter;
         } else {
             // If we didn't get any location, stop redirecting
             break;
         }
     } while ($this->redirectCounter < $this->config['maxredirects']);
     return $response;
 }
Example #19
0
 public function execute()
 {
     $options = $this->getOptions();
     $optionsExport = $options['settings']['export'];
     $optionsRenderer = $this->getOptionsRenderer();
     $phpExcel = new PHPExcel();
     // Sheet 1
     $phpExcel->setActiveSheetIndex(0);
     $sheet = $phpExcel->getActiveSheet();
     $sheet->setTitle($this->getTranslator()->translate($optionsRenderer['sheetName']));
     if (true === $optionsRenderer['displayTitle']) {
         $sheet->setCellValue('A' . $optionsRenderer['rowTitle'], $this->getTitle());
         $sheet->getStyle('A' . $optionsRenderer['rowTitle'])->getFont()->setSize(15);
     }
     /*
      * Print settings
      */
     $this->setPrinting($phpExcel);
     /*
      * Calculate column width
      */
     $this->calculateColumnWidth($sheet, $this->getColumnsToExport());
     /*
      * Header
      */
     $xColumn = 0;
     $yRow = $optionsRenderer['startRowData'];
     foreach ($this->getColumnsToExport() as $col) {
         /* @var $column \ZfcDatagrid\Column\AbstractColumn */
         $label = $this->getTranslator()->translate($col->getLabel());
         $sheet->setCellValueByColumnAndRow($xColumn, $yRow, $label);
         $sheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($xColumn))->setWidth($col->getWidth());
         $xColumn++;
     }
     /*
      * Data
      */
     $yRow = $optionsRenderer['startRowData'] + 1;
     foreach ($this->getData() as $row) {
         $xColumn = 0;
         foreach ($this->getColumnsToExport() as $col) {
             $value = $row[$col->getUniqueId()];
             if (is_array($value)) {
                 $value = implode(PHP_EOL, $value);
             }
             /* @var $column \ZfcDatagrid\Column\AbstractColumn */
             $currentColumn = PHPExcel_Cell::stringFromColumnIndex($xColumn);
             $sheet->getCell($currentColumn . $yRow)->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
             $columnStyle = $sheet->getStyle($currentColumn . $yRow);
             $columnStyle->getAlignment()->setWrapText(true);
             /*
              * Styles
              */
             $styles = array_merge($this->getRowStyles(), $col->getStyles());
             foreach ($styles as $style) {
                 /* @var $style \ZfcDatagrid\Column\Style\AbstractStyle */
                 if ($style->isApply($row) === true) {
                     switch (get_class($style)) {
                         case 'ZfcDatagrid\\Column\\Style\\Bold':
                             $columnStyle->getFont()->setBold(true);
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\Italic':
                             $columnStyle->getFont()->setItalic(true);
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\Color':
                             $columnStyle->getFont()->getColor()->setRGB($style->getRgbHexString());
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\BackgroundColor':
                             $columnStyle->getFill()->applyFromArray(['type' => \PHPExcel_Style_Fill::FILL_SOLID, 'color' => ['rgb' => $style->getRgbHexString()]]);
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\Align':
                             switch ($style->getAlignment()) {
                                 case \ZfcDatagrid\Column\Style\Align::$RIGHT:
                                     $columnStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
                                     break;
                                 case \ZfcDatagrid\Column\Style\Align::$LEFT:
                                     $columnStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                                     break;
                                 case \ZfcDatagrid\Column\Style\Align::$CENTER:
                                     $columnStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                                     break;
                                 case \ZfcDatagrid\Column\Style\Align::$JUSTIFY:
                                     $columnStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
                                     break;
                                 default:
                                     //throw new \Exception('Not defined yet: "'.get_class($style->getAlignment()).'"');
                                     break;
                             }
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\Strikethrough':
                             $columnStyle->getFont()->setStrikethrough(true);
                             break;
                         case 'ZfcDatagrid\\Column\\Style\\Html':
                             // @todo strip the html?
                             break;
                         default:
                             throw new \Exception('Not defined yet: "' . get_class($style) . '"');
                             break;
                     }
                 }
             }
             $xColumn++;
         }
         $yRow++;
     }
     /*
      * Autofilter, freezing, ...
      */
     $highest = $sheet->getHighestRowAndColumn();
     // Letzte Zeile merken
     // Autofilter + Freeze
     $sheet->setAutoFilter('A' . $optionsRenderer['startRowData'] . ':' . $highest['column'] . $highest['row']);
     $freezeRow = $optionsRenderer['startRowData'] + 1;
     $sheet->freezePane('A' . $freezeRow);
     // repeat the data header for each page!
     $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd($optionsRenderer['startRowData'], $optionsRenderer['startRowData']);
     // highlight header line
     $style = ['font' => ['bold' => true], 'borders' => ['allborders' => ['style' => PHPExcel_Style_Border::BORDER_MEDIUM, 'color' => ['argb' => PHPExcel_Style_Color::COLOR_BLACK]]], 'fill' => ['type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => ['argb' => PHPExcel_Style_Color::COLOR_YELLOW]]];
     $range = 'A' . $optionsRenderer['startRowData'] . ':' . $highest['column'] . $optionsRenderer['startRowData'];
     $sheet->getStyle($range)->applyFromArray($style);
     // print borders
     $range = 'A' . $freezeRow . ':' . $highest['column'] . $highest['row'];
     $sheet->getStyle($range)->applyFromArray(['borders' => ['allborders' => ['style' => PHPExcel_Style_Border::BORDER_THIN]]]);
     /*
      * Save the file
      */
     $path = $optionsExport['path'];
     $saveFilename = date('Y-m-d_H-i-s') . $this->getCacheId() . '.xlsx';
     $excelWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
     $excelWriter->setPreCalculateFormulas(false);
     $excelWriter->save($path . '/' . $saveFilename);
     /*
      * Send the response stream
      */
     $response = new ResponseStream();
     $response->setStream(fopen($path . '/' . $saveFilename, 'r'));
     $headers = new Headers();
     $headers->addHeaders(['Content-Type' => ['application/force-download', 'application/octet-stream', 'application/download'], 'Content-Length' => filesize($path . '/' . $saveFilename), 'Content-Disposition' => 'attachment;filename=' . $this->getFilename() . '.xlsx', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT']);
     $response->setHeaders($headers);
     return $response;
 }
Example #20
0
 protected function saveAndSend()
 {
     $pdf = $this->getPdf();
     $options = $this->getOptions();
     $optionsExport = $options['settings']['export'];
     $path = $optionsExport['path'];
     $saveFilename = $this->getCacheId() . '.pdf';
     $pdf->Output($path . '/' . $saveFilename, 'F');
     $response = new ResponseStream();
     $response->setStream(fopen($path . '/' . $saveFilename, 'r'));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Type' => array('application/force-download', 'application/octet-stream', 'application/download'), 'Content-Length' => filesize($path . '/' . $saveFilename), 'Content-Disposition' => 'attachment;filename=' . $this->getFilename() . '.pdf', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT'));
     $response->setHeaders($headers);
     return $response;
 }
Example #21
0
 public function pdfAction()
 {
     $invoice = $this->invoiceRepository->find($this->params('invoiceId'));
     if ($invoice === null) {
         $this->getResponse()->setStatusCode(404);
         return;
     }
     $pdfPath = $this->invoiceService->generatePdf($invoice);
     $response = new StreamResponse();
     $response->setStream(fopen($pdfPath, 'r'));
     $response->getHeaders()->addHeaders(['Content-Disposition' => 'attachment; filename="invoice.pdf"', 'Content-Type' => 'application/pdf', 'Content-Length' => filesize($pdfPath)]);
     return $response;
 }
Example #22
0
 public function execute()
 {
     if ($this->getFindException()) {
         foreach ($this->getReasonsException() as $key => $reason) {
             $msg[$key] = $reason;
         }
         if ($reason !== null) {
             return $this->raiseError($reason, $key);
         }
     }
     $options = $this->getOptions();
     $optionsExport = $options['settings']['export'];
     $optionsRenderer = $this->getOptionsRenderer();
     $phpExcel = new PHPExcel();
     // Sheet 1
     $phpExcel->setActiveSheetIndex(0);
     $sheet = $phpExcel->getActiveSheet();
     $sheet->setTitle($this->getTranslator()->translate($optionsRenderer['sheetName']));
     if ($optionsRenderer['displayTitle'] === true) {
         $sheet->setCellValue('A' . $optionsRenderer['rowTitle'], $this->getTitle());
         $sheet->getStyle('A' . $optionsRenderer['rowTitle'])->getFont()->setSize(15);
     }
     $this->calculateColumnWidth($this->getColumnsToExport());
     $xColumn = 0;
     $yRow = $optionsRenderer['startRowData'];
     foreach ($this->getColumnsToExport() as $column) {
         /* @var $column \Zf2datatable\Column\AbstractColumn */
         //$label = $this->getTranslator()->translate($column->getLabel());
         $label = $column->getLabel();
         $sheet->setCellValueByColumnAndRow($xColumn, $yRow, $label);
         // $sheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($xColumn))->setCollapsed(true);
         $sheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($xColumn))->setWidth($column->getWidth());
         $xColumn++;
     }
     /*
      * Data
      */
     $yRow = $optionsRenderer['startRowData'] + 1;
     foreach ($this->getData() as $row) {
         $xColumn = 0;
         foreach ($this->getColumnsToExport() as $column) {
             /* @var $column \Zf2datatable\Column\AbstractColumn */
             $currentColumn = PHPExcel_Cell::stringFromColumnIndex($xColumn);
             $sheet->getCell($currentColumn . $yRow)->setValueExplicit($row[$column->getUniqueId()], PHPExcel_Cell_DataType::TYPE_STRING);
             $columnStyle = $sheet->getStyle($currentColumn . $yRow);
             $columnStyle->getAlignment()->setWrapText(true);
             /*
              * Styles
              */
             $styles = array_merge($this->getRowStyles(), $column->getStyles());
             foreach ($styles as $style) {
                 /* @var $style \Zf2datatable\Column\Style\AbstractStyle */
                 if ($style->isApply($row) === true) {
                     switch (get_class($style)) {
                         case 'Zf2datatable\\Column\\Style\\Bold':
                             $columnStyle->getFont()->setBold(true);
                             break;
                         case 'Zf2datatable\\Column\\Style\\Italic':
                             $columnStyle->getFont()->setItalic(true);
                             break;
                         case 'Zf2datatable\\Column\\Style\\Color':
                             $columnStyle->getFont()->getColor()->setRGB($style->getRgbHexString());
                             break;
                         case 'Zf2datatable\\Column\\Style\\BackgroundColor':
                             $columnStyle->getFill()->applyFromArray(array('type' => \PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => $style->getRgbHexString())));
                             break;
                         default:
                             throw new \Exception('Not defined yet: "' . get_class($style) . '"');
                             break;
                     }
                 }
             }
             $xColumn++;
         }
         $yRow++;
     }
     /*
      * Autofilter, freezing, ...
      */
     // Letzte Zeile merken
     $endRow = $yRow - 1;
     $endColumn = count($this->getColumnsToExport()) - 1;
     // Autofilter + Freeze
     $sheet->setAutoFilter('A' . $optionsRenderer['startRowData'] . ':' . PHPExcel_Cell::stringFromColumnIndex($endColumn) . $endRow);
     $freezeRow = $optionsRenderer['startRowData'] + 1;
     $sheet->freezePane('A' . $freezeRow);
     /*
      * Print settings
      */
     $this->setPrinting($phpExcel);
     /*
      * Save the file
      */
     $path = $optionsExport['path'];
     $saveFilename = $this->getCacheId() . '.xlsx';
     $excelWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
     $excelWriter->setPreCalculateFormulas(false);
     $excelWriter->save($path . '/' . $saveFilename);
     /*
      * Send the response stream
      */
     $response = new ResponseStream();
     $response->setStream(fopen($path . '/' . $saveFilename, 'r'));
     $headers = new Headers();
     $headers->addHeaders(array('Content-Type' => array('application/force-download', 'application/octet-stream', 'application/download'), 'Content-Length' => filesize($path . '/' . $saveFilename), 'Content-Disposition' => 'attachment;filename=' . $this->getFilename() . '.xlsx', 'Cache-Control' => 'must-revalidate', 'Pragma' => 'no-cache', 'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT'));
     $response->setHeaders($headers);
     return $response;
 }
 /**
  * @param MvcEvent $event
  */
 public function onDispatchError(MvcEvent $event)
 {
     if (Application::ERROR_ROUTER_NO_MATCH != $event->getError()) {
         // ignore other than 'no route' errors
         return;
     }
     // get URI stripped of a base URL
     $request = $event->getRequest();
     $uri = str_replace($request->getBaseUrl(), '', $request->getRequestUri());
     // try get image ID from URI
     $id = $this->manager->matchUri($uri);
     if (!$id) {
         // abort if URI does not match
         return;
     }
     // try get image from repository
     $image = $this->repository->find($id);
     if (!$image) {
         // abort if image does not exist
         return;
     }
     // store image
     $this->manager->store($image);
     // return image in response as a stream
     $headers = new Headers();
     $headers->addHeaders(['Content-Type' => $image->getType(), 'Content-Length' => $image->getLength()]);
     $response = new Stream();
     $response->setStatusCode(Response::STATUS_CODE_200);
     $response->setStream($image->getResource());
     $response->setStreamName($image->getName());
     $response->setHeaders($headers);
     $event->setResponse($response);
 }