Using the new 'data' option for CakeEmail attachments with CakePHP 2.4.x - email-attachments

The CakeEmail help page states that the data option has been added as of 2.4, so you no long have to have a physical file to add an attachment to an email.
I've got the following code:
$Email->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($this->request->data['email-to'])
->subject($this->request->data['email-subject'])
->attachments(array('attachement1.pdf', array('data' => $pdf)))
->send($this->request->data['email-message']);
But whenever I run that I get an Internal Error saying File Not Found: "".

I had a look at the source code (which I'm beginning to learn is often more useful than reading the documentation!): https://github.com/cakephp/cakephp/blob/master/lib/Cake/Network/Email/CakeEmail.php
Changing my code to:
$Email = new CakeEmail('default');
$Email->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($this->request->data['email-to'])
->subject($this->request->data['email-subject'])
->attachments(array('attachement1.pdf' => array('data' => $pdf, 'mimetype' => 'application/pdf')))
->send($this->request->data['email-message']);
Notice on the attachments line, the array is assigned to the filename variable, rather than passed in as a parameter!
For completeness, if anyone else is reading this and is wondering how I am generating my PDF with CakePDF:
// Create PDF for attachment
$CakePdf = new CakePdf();
$CakePdf->template('claim', 'default');
//get the pdf string returned
$pdf = $CakePdf->output();

Related

File Upload in Userfrosting

We need to have the user upload an image as a part of sign up process.
Had tried accessing $_FILES['filename'] in the controller, which turns out to be undefined under slim.
Had seen about Slim's way of file uploading in a couple of articles, which are reported to be working, but I hit the wall.
The twig part works fine with Bootstrap File Input library
For the server part using File Upload library for Slim
Controller code (modifications to AccountController) looks like this
...
$storage = new \Upload\Storage\FileSystem('c:/xampp/htdocs/userfrosting/public/images/');
$file = new \Upload\File('imagefile', $storage);
$new_filename = 'test.jpg';
$file->setName($new_filename);
$file->addValidations(array(
// Ensure file is of type "image/jpg"
new \Upload\Validation\Mimetype('image/jpg'),
// Ensure file is no larger than 500K (use "B", "K", M", or "G")
new \Upload\Validation\Size('500K')
));
// Access data about the file that has been uploaded
$uploadfiledata = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
error_log('$uploadfiledata' . print_r($uploadfiledata, true));
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}
...
This returns the following error,
Type: InvalidArgumentException
Message: Cannot find uploaded file identified by key: imagefile
File: C:\xampp\htdocs\userfrosting\userfrosting\vendor\codeguy\upload\src\Upload\File.php
Line: 139
The relevant twig chunk is
<input id="imagefile" type="file" name="imagefile" class="file" data-show-upload="false">
Has anyone been able to get file upload working as a part of any Userfrosting code?
Appreciate any help / pointers.
Thanks!
My guess is that you're using ufFormSubmit to submit your registration form, and it is not grabbing the file input. So, you will probably need to add some extra code on the client side to explicitly submit the file input along with the rest of the form. See this example using Dropzone and UF: https://gist.github.com/frostbitten/c1dce70023321158a2fd#file-upload-twig
By the way, you can use your browser to see what data is actually being sent in your POST request. For example, in Firefox you can use the Network Monitor.

CakePHP 2.1.0: Capture E-mail Output

I'm building a CakePHP website that sends an e-mail like this:
$email = new CakeEmail('default');
$email->template('test');
$email->emailFormat('html');
$email->to(array('john_doe#example.com' => 'John Doe'));
$email->subject('Test E-mail');
$email->helpers(array('Html', 'Text'));
$email->viewVars(
array(
...
)
);
if ($email->send()) {
$this->Session->setFlash('The e-mail was sent!', 'default', array('class' => 'alert alert-success'));
}
else {
$this->Session->setFlash('An unexpected error occurred while sending the e-mail.', 'default', array('class' => 'alert alert-error'));
}
I'd like to be able to capture the HTML rendered by the e-mail in a variable in addition to actually sending the e-mail. This way, I can record in the database the exact content of the e-mail's body. Is this doable?
Per line 50 of the MailTransport class, it appears the actual send() function returns the message and the header. So instead of:
if($email->send()) {
Try:
$mySend = $email->send();
if($mySend) {
//...
Then, $mySend should be an array:
array('headers' => $headers, 'message' => $message);
Thats what I do in my EmailLib:
https://github.com/dereuromark/tools/blob/2.0/Lib/EmailLib.php
it logs email attempts and captures the email output into a log file (email_trace.log) in /tmp/logs/ - if you are in debug mode it will only log (no emails sent - this has been proven quite useful for local delopment).
you can write a similar wrapper for your case.
but if you want to write it back into the DB Dave's approach seems to fit better.

Upload and encrypt a file using Zend_File_Transfer_Adapter_Http

In Zend Framework documentation titled "Filters for Zend_File_Transfer", it said file can be encrypted and saved as a different name using the filename option.
This filter supports one additional option which can be used to save the encrypted file with another filename. Set the filename option to change the filename where the encrypted file will be stored. If you suppress this option, the encrypted file will overwrite the original file.
How do I specify the filename option? I tried:
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addFilter('Encrypt', array('adapter' => 'mcrypt', 'key' => 'mykey'), 'file.txt');
and
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addFilter('Encrypt', array('adapter' => 'mcrypt', 'key' => 'mykey', 'filename' => 'file.txt'));
both don't seem to work.
I took a look into Zend/File/Transfer/Adapter/Http.php and it does not seem that filename is a valid option for this adapter.
Maybe this is a Bug in the Documentation.
Instead you could use the Rename-Filter to change the filename.
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addFilter('Rename', array('target' => APPLICATION_PATH . '/../data/file.txt'));
$upload->addFilter('Decrypt', array('adapter' => 'mcrypt', 'key' => 'mykey'));
$upload->receive();

Custom error message for input validators (using the array syntax)

ZF 1.11.2
I've tried most of the syntaxes. They didn't click.
$validators = array('product_name' => array('alnum'));
//...
$input = new Zend_Filter_Input($filters, $validators, $_POST);
How in the world do you set a custom error message for alnum with the syntax above? Using 'messages' => array('Not alnum!!')? Yeah, well... How? I must've tried 100 nested arrays.
Use the built in translator.
For example, configure the translator in your config file to use a simple array
; Translations
resources.translate.data = APPLICATION_PATH "/lang"
resources.translate.adapter = "Array"
resources.translate.options.scan = "directory"
resources.translate.options.disableNotices = "1"
This tells the Translate application resource plugin that you want to
keep your translations under APPLICATION_PATH/lang
use the Array adapter (simplest)
scan the translation directory for languages / locales
ignore errors about unknown translations (ie user preferes en_AU but you don't have a specific translation file for that language)
Now, create folders for any languages you want to support. At a minimum, you'll want application/lang/en. For example
application
lang
en
en_AU
en_US
In each language folder, create a translate.php file. This file will contain (and return) an array of key / value pairs for each translation. You can find the keys for each validator message in the validator class. Here's an example for the Alnum validator
<?php
// application/lang/en/translate.php
return array(
Zend_Validate_Alnum::NOT_ALNUM => 'Not alnum!!',
Zend_Validate_Alnum::INVALID => 'Not valid!!'
);
For all Zend validators, you can also use the %value% placeholder in your message, eg
Zend_Validate_Alnum::NOT_ALNUM => "'%value%' is not alpha-numeric"
If you are simply trying to change the validation messages for a form element, I have always done it like this (inside a class that extends Zend_Form):
$this->addElement('text', 'myTextField', array(
'label' => 'The Label',
'description' => 'The description for the field...',
'filters' => array(
'StringTrim',
// etc
),
'validators' => array(
array('NotEmpty', true, array(
'messages' => 'This field is required',
)),
array('AnotherValidator', true, array(
'messages' => 'Bad value',
)),
// etc
),
));
Are you saying that this didn't work? Or are you using your validator in a more general context, in which case #Phil Brown's (awesome!) answer will do the job.
Disabling the translator on the element will disable the translation of all the validator messages. It is not possible to use a translator on the form or element and overwrite just one validator message. When the element is validated the translator is injected to every validator. The validator will use the translator if it is set. Thereby the custom error message won't be used.
Zend_Validate_Abstract::_createMessage()
// $message is your custom error message
$message = $this->_messageTemplates[$messageKey];
if (null !== ($translator = $this->getTranslator())) {
// your custom error message gets overwritten because the messageKey can be translated
if ($translator->isTranslated($messageKey)) {
$message = $translator->translate($messageKey);
} else {
$message = $translator->translate($message);
}
}
I think it is only possible to use a custom error message by disable the translator on the element.
$element->setDisableTranslator(true)
Use setMessage and disable translator if you have one.
$alnum = new Zend_Validate_Alnum();
$alnum->setDisableTranslator(true);
$alnum->setMessage(
'Not alnum!!',
Zend_Validate_Alnum::NOT_ALNUM
);
$validators = array('product_name' => array($alnum));
If you use your validator on a form element, you have to disable the translator on the element.

Image Upload with Zend_Service_Nirvanix

I can't seem to upload an image using Zend_Service_Nirvanix. Is it even possible?
I have a feeling that my problem has something to do with not being able to figure out how to set the UploadHost on the Transfer Service.
Any help is greatly appreciated! My deadline is July 16th!
Here is my code:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$options = array('sizeBytes' => filesize($source));
$storageNode = $NSImfs->getStorageNode($options);
$NSTransfer = $nirvanix->getService('Transfer');
$options = array('uploadToken' => $storageNode->getStorageNode->UploadToken,
'path' => $original,
'fileData' => file_get_contents($source));
$result = $NSTransfer->uploadFile($options);
Here is the error I keep getting:
Zend_Service_Nirvanix_Exception: XML
could not be parsed from response:
Server Error in '/' Application. The
resource cannot be found. Description:
HTTP 404. The resource you are looking
for (or one of its dependencies) could
have been removed, had its name
changed, or is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/ws/Transfer/UploadFile.ashx
in
/Applications/MAMP/bin/php5/lib/php/Zend/Service/Nirvanix/Response.php
on line 119
You're getting a 404?
Have you checked for an updated version of that library?
Try going into the libray and changing UploadFile.ashx to UploadFile.aspx. I don't think ashx is not a standard extension.
Maybe that will fix it.
There's a commercial upload tool from Aurigma that has support for file and image upload to Nirvanix. Here's the link (see Uploading to Nirvanix section there) to the help topic to check.
To do a local upload (rather than a web upload via the browser) you just have to call the putContents method passing the files data.
Example:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$response = $NSImfs->putContents($destination_file_and_path,
file_get_contents($source_file));
if($response->ResponseCode != 0)
{
echo 'Fail!';
}
You would only call GetStorageNode if you want to generate a token to pass a browser the upload token.