Remove gzip encoding in Zend - zend-framework

Lots of questions here from people trying to implement gzip encoding in Zend - I need to do the opposite!
I have a controller which extends the standard Zend_Controller_Action. My downloadAction has a PDF file as it's response body. That works well, except that the downloaded file isn't correctly recognised by the client browsers.
The downloaded file is identified as a 'Zip Archive' by the browser download. When saved and double-clicked it opens correctly as a PDF. The response header shows Content-Encoding:gzip, so I figure that's likely the culprit.
The core of my action is:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($fd = fopen($pdfpath.$pdf->Filename,'r'))
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="summary.PDF"');
while(!feof($fd))
{
$buffer = fread($fd, 2048);
echo $buffer;
}
fclose($fd);
}
There is some other code before this piece, but it does nothing more exciting than populate the variables.
How would I go about disabling the Content-Encoding:gzip header for just this response, or if that's the wrong end of the stick (it would be good to use compression, but not at the expense of user experience), how do I get the client to correctly identify the downloaded file once the compression has been reversed?

I would recommend to use framework's Zend_Controller_Response_Http instead of header() function, usually I specify "default" headers with gzip compression etc. in my Bootstrap for all responses, and override them in actions for some special reasons:
public function indexAction()
{
$frontContoller = $this->getFrontController();
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$response = new Zend_Controller_Response_Http();
$response
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'attachment; filename=summary.pdf')
->setHeader('Expires', ''.gmdate('D, d M Y H:i:s', strtotime('31.08.1986')) . ' GMT', true)
->setHeader('Cache-Control', 'no-cache')
->setHeader('Pragma', 'no-cache', true);
$response->setBody(file_get_contents('/full/path/to/summary.pdf'));
$frontContoller->setResponse($response);
}

Related

Zf2 - How to create request to external API with file upload

I have a Zf2 application that communicates with another Zf2 application through RestAPI calls.
I'm able to communicate between one to another using following code and exchange parameters:
//Prepare request
$request = new Request();
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
));
$request->setUri($p_url);
$request->setMethod('POST');
$request->setPost(new Parameters($p_params));
$client = new Client();
//Send request
$client->resetParameters();
$response = $client->dispatch($request);
$data = json_decode($response->getBody(), true);
Now, I would like to do the same thing but with a multipart call: Json + files.
How can I do that?
I have tried several solutions from using setFileUpload method of client to writing headers parameters with content-type (multipart/form-data), content-disposition, ... without success.
Along my tests, I used Wireshark to check the request contents. Depending on the solution I tried, I fail in situation with "missing boundary" or HTTP error 405.
Thanks for your help.
Best
Finally, I found a solution
$this->_client->setUri($p_url);
$this->_client->setMethod('POST');
//Prepare for upload
$this->_client->setFileUpload($p_file, 'file');
//Set parameters along with file
$this->_client->setParameterPost($p_params);
//Send request
try {
$response = $this->_client->send();
} catch ( \Exception $ex ) {
}

Concrete5.7.5.2 - Where to put form file attachment headers?

I build my email headers like this:
$txt_message .= $this->txt_message;
$html_message .= $this->html_message;
$mh = Core::make('helper/mail');
$mh->to($this->email_to, $this->site_name);
$mh->from($this->email, $this->name);
$mh->replyto($this->email, $this->name);
$mh->setSubject($this->subject);
$mh->setBody($txt_message);
$mh->setBodyHtml($html_message);
#$mh->sendMail();
Some posts say an attachment can be added with
$mh->addAttachment($file);
but $file must be a file object. How can I make the uploaded file a file object?
I also found this post:http://www.adrikodde.nl/blog/2012/mail-attachments-concrete5/
But I get errors for all Zend stuff. Is Zend Mail still available in C5.7?
Where do I put headers for a file attachment? Where can I find out more about what really sends the message (is it still a Zend Mail?) and what methods are available?
Thank you.
[SOLVED]
Thanks to Nicolai, here's a working example for attaching files:
$file = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
$importer = new \Concrete\Core\File\Importer();
$file_version = $importer->import($file, $filename);
$attachment = $file_version->getFile();
$mh->addAttachment($attachment);
//Delete the file if not wanted on server
$attachment->delete();
PS. Don't forget to check the file really selected/exists/uploaded before you try to send it!
if (!empty($this->image)) {
$importer = new \Concrete\Core\File\Importer();
$image_version = $importer->import($this->image, $file_name);
if ($image_version instanceof \Concrete\Core\File\Version) {
$attachment = $image_version->getFile();
$mh->addAttachment($attachment);
}
}
#$mh->sendMail();
To add the file to your filesystem, you should take a look at this
http://concrete5.org/api/class-Concrete.Core.File.Importer.html.
On the returned object (which is a FileVersion on success), you should be able to call getFile( ) to get the actual Concrete5 File object

Downloading files with Zend Framework

I'm a newbie to Zend Framework and I have such problem. On my web page I have the demos of products to be downloaded by users. When they want to download them, they have to fill the form (name, company, e-mail, contact phone) and then click Submit to start downloading. I would like them to be redirected to the product page. Here is my showFormAction code in controller:
if ($this->_request->isPost())
{
if (!$form->isValid($this->_request->getPost()))
{
//shows messages and the form again
}
else
{
$file = $this->findYoungestFile('/demo/'.$product.'/');
$this->sendFileToClient($file);
$this->_redirect('/products/'.$product);
//sending mail
$infoMail = new InfoMail($this->_request->getPost(), 'download', $product);
$this->sendInfoMails($infoMail);
}
}
else
//show form
And here is sendFileToClient function
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
The redirection doesn't work. I suppose there is a problem with headers sent to the browser, but I don't know how to solve it. Could anyone help me, please?
Thanks & regards,
Malgorzata
By the time you're trying to redirect user to another page the HTTP-headers had already sent. In other words you cannot supply a file and do a redirect at the same time. Well, at least the way you're trying to do this.

ZEND - Issue with download file (encoding, not able to open downloaded file)

I made a download form in my project, but problem is when i download the file and im trying to open it, Zend renderer is adding to it my layout html code... I read that i have to disable renderer and layout. But the problem is tjat i have to do this in my own helper, not in controller file, cause i need to have download in that helper file.
My download function is something like this:
<?php
class Zend_View_Helper_EditArticles extends Zend_View_Helper_Abstract
{
public function EditArticles()
{
//some code here, getting data from db table
//and now the download
if (isset($_POST['downloadarticle' . $i])) {
//this is probably bad and its not working as it should
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('layout')->disableLayout();
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/articles/';
$file = $articles->GetArticleToDownload($_POST['art_id' . $i]);
$name = $file['name'];
$path = $file['path'];
$getfile = str_replace('//', '/', $targetPath) . $path . '.pdf';
$size = $file['size'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$name.pdf");
header("Content-length: $size");
header('Content-Transfer-Encoding: binary');
readfile($getfile);
break;
}
}
echo $this->view->partial('/index/index.phtml','EditArticles');
And when I download the PDF, Adobe Reader can't open it (when I download other files they can't be opened either). I opened them with notepad and before the PDF content there was a lot of HTML layout code... What am I doing wrong?
In Adobe Reader I get this message:
Adobe Reader could not open 'filename.pdf' because it is either not a supported file type or because the file has been damaged for example, it was sent as an email attachment and wasn't correctly decoded).
That code does not belong in a view helper. It belongs in the controller or maybe an action helper.
Something like this in your controller should work:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// ...
$this->getResponse()
->setHeader('Content-Description', 'File Transfer', true)
->setHeader('Content-Type', 'application/pdf', true) // change to application/pdf
->setHeader('Content-Disposition', "attachment; filename={$name}.pdf", true)
->setHeader('Content-length', $size, true)
->setHeader('Content-Transfer-Encoding', 'binary', true)
->appendBody(readfile($getfile));
The following 2 lines of code should accomplish what you need and do it in a fashion that works from anywhere in your Zend application.
Zend_Layout::getMvcInstance()->disableLayout();
Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);

Zend PDF - want to open instead of saving

am generating pdf using Zend_pdf
its saving after creating
I want to open it instead of saving.
When i access the url directly
Use render() method
// Set PDF headers
header ('Content-Type:', 'application/pdf');
header ('Content-Disposition:', 'inline;');
// Output pdf
echo $pdf->render();
I couldn't find a way to open a PDF directly, so I did this instead:
<?php
// Save PDF into file
$oPdf->save("./pdfcache/filename.pdf");
// Set headers
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename=filename.pdf');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
// Get File Contents and echo to output
echo file_get_contents("./pdfcache/filename.pdf");
// Prevent anything else from being outputted
die();
It's not perfect, but it does the job for me.