Symfony2 styled emails best practices - symfony

What are the best practices to send emails from html & css? I have much mails in my projects & need the solution, that can allow me not to write all below code again & again:
$msg = \Swift_Message::newInstance()
->setSubject('Test')
->setFrom('noreply#example.com')
->setTo('user#example.com')
->setBody($this->renderView('MyBundle:Default:email1.text.twig'));
$this->get('mailer')->send($msg);

Maybe my answer can help. There is a special bundle Symfony2-MailerBundle that render email body from template and allows to set up sending parameters in config file & you won't have to pass them every time you want to build & send email.

Set that code as a function in a service. Functions are for that.
To create a service see the link below.
How to inject $_SERVER variable into a Service
Note: don't forget to inject the mail service as an argument!
arguments: ["#mailer"]
After you set your service;
public function sendMail($data)
{
$msg = \Swift_Message::newInstance()
->setSubject($data['subject'])
->setFrom($data['from'])
->setTo($data['to'])
->setBody($this->renderView($data['view']));
$this->mailer->send($msg);
}
And you can call your service like;
// this code below is just for setting the data
$data = [
'subject' => 'Hello World!',
'from' => 'from#address.com',
'to' => 'to#address.com',
'template' => 'blabla.html.twig'
];
// this code below is the actual code that will save you
$mailer = $this->get('my_mailer_service');
$mailer->sendMail($data);

Related

Get current user inside register_rest_route method

How to retrive wp_get_current_user() inside a register_rest_route callback (Wordpress site)?
I'm just trying to do a simple hello wp_get_current_user()->user_login on a php test page:
add_action('rest_api_init', 'helloTest');
function helloTest() {
register_rest_route('hello', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
));
}
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
But wp_get_current_user() is null and wp_get_current_user->ID is 0;
I dont want to authenticate the user again. I just want to retrieve his username. If he is not logged in, just show empty an empty string.
If I have to authenticate again, how to add a "nonce" to it? On internet I just have examples using javascript, but not directly on PHP methods.
Issues in your code
First off, you should understand properly how to add custom WP REST API endpoints:
An endpoint's namespace (the first parameter passed to register_rest_route()) should be in this format: your-plugin/v<version>. E.g. hello/v1 or hello-world/v1 and not just hello or hello-world.
$someVariable (the first parameter passed to your endpoint callback function) is not just any variable — it's an instance of the WP_REST_Request class — and shouldn't be echo-ed like what you did here:
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
And normally, the $someVariable is better be changed to $request (i.e. rename it to "request").
And you should return a valid WP REST API response. For example, to return just the username:
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
And know your own API endpoint URL..
(based on your original namespace)
/wp-json/hello/hello/1 <- correct
/wp-json/hello/?John <- incorrect
because in your code, the parameter is a number and not string: (?P<id>\d+)
I hope those help you, and once again, do read the handbook for a more detailed guide.
The Corrected Code
add_action( 'rest_api_init', 'helloTest' );
function helloTest() {
register_rest_route( 'hello/v1', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
) );
}
function showHello( $request ) {
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
}
Now about getting the user (from the API endpoint — showHello())
If I have to authenticate again, how to add a "nonce" to it?
Just because the user is logged-in/authenticated to the (WordPress) site, it doesn't mean the user is automatically logged-in to the WP REST API. So yes, you'd need to either provide a nonce along with your API request, or use one of the authentication plugins mentioned right here.
Now in most cases, GET (i.e. read-only) requests to the API do not need any authentication, but if you'd like to retrieve the data of the currently logged-in user on your site, then one way is via the _wpnonce data parameter (either POST data or in the query for GET requests).
Example for a GET request:
http://example.com/wp-json/wp/v2/posts?_wpnonce=<nonce>
So based on your comment and the corrected code (above):
Theres no "code" that make the request. Its is just an anchor that
calls my route: Hello
You can add the nonce as part of the URL query string like so: (the namespace is hello/v1 and the <id> is 1)
// Make request to /wp-json/hello/v1/hello/<id>
$nonce = wp_create_nonce( 'wp_rest' );
echo 'Hello';
So try that out along with the corrected code and let me know how it goes. :)
And once again, be sure to read the REST API authentication handbook.

Symfony2, Swiftmailer, Mandrill get response

We've build an email system using Swiftmailer and Mandrill. It works really great but now we would like to integrate the webhooks to trigger alerts on bounces / failures / ...
At this moment we add a custom header with an unique id to each email sent and find our way back when the webhook triggers.
It works well but mandrill already uses an _id that we could use so that we do not add 'another' unique ID on top of that.
Mandrill responds with something like:
[
{
"email": "recipient.email#example.com",
"status": "sent",
"reject_reason": "hard-bounce",
"_id": "abc123abc123abc123abc123abc123"
}
]
Is there any way in Swiftmailer to get this response back into Symfony ?
(So that we can read and store that _id for later use)
I know we could use the Mandrill php SDK but preferably we would like to keep on using Swiftmailer.
EDIT
We are using SMTP Transport with a basic Swiftmailer instance as explained here
<?php
include_once "swift_required.php";
$subject = 'Hello from Mandrill, PHP!';
$from = array('you#yourdomain.com' =>'Your Name');
$to = array(
'recipient1#example.com' => 'Recipient1 Name',
'recipient2#example2.com' => 'Recipient2 Name'
);
$text = "Mandrill speaks plaintext";
$html = "<em>Mandrill speaks <strong>HTML</strong></em>";
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
$transport->setUsername('MANDRILL_USERNAME');
$transport->setPassword('MANDRILL_PASSWORD');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($recipients = $swift->send($message, $failures))
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
I don't think Mandrill supports passing this reply via SMTP, you'll have to use API for that.
For example, in accord/mandrill-swiftmailer there is a method that returns response from Mandrill: https://github.com/AccordGroup/MandrillSwiftMailer/blob/master/SwiftMailer/MandrillTransport.php#L215
You can get Mandrill's response using following code:
$transport = new MandrillTransport($dispatcher);
$transport->setApiKey('ABCDEFG12345');
$transport->setAsync(true); # Optional
$response = $transport->getMandrillMessage($message);
// $response now contains array with Mandrill's response.
You can integrate it with Symfonu using accord/mandrill-swiftmailer-bundle and after that you can do:
$response = $mailer->getTransport()->getMandrillMessage($message);

HTTP client Cakephp 3 ignores json body

I'm currently writing a RESTful API in Cakephp 3 whereby I need to test a POST operation through http://host.com/api/pictures. The code for the test:
<?php
namespace App\Test\TestCase\Controller;
use App\Controller\Api\UsersController;
use Cake\TestSuite\IntegrationTestCase;
use Cake\Network\Http\Client;
use Cake\Network\Http\FormData;
class ApiPicturesControllerTest extends IntegrationTestCase{
public $fixtures = [
'app.users',
'app.comments',
'app.albums',
'app.users_albums'
];
public function testAdd(){
// $data = new FormData();
$accessToken ='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$http = new Client([
'headers' => ['Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json']
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$result = $http->post('http://vecto.app/api/pictures/add.json', $data, ['type'=>'json']);
// $this->assertResponseOk();
// debug($result);
}
}
When I try to debug the result I get a 'cannot add or update child row' while I'm sure the responding id does exists
(the fixtures does have the id's too). Additionally, the log indicates that it only tries to insert the create/update rows. Therefore, I'm pretty sure the data is ignored but however I can't find a solution. I already tried different combination of headers like only application/json for Accept, application/json for Content-Type etc. I'm using the CRUD plugin for Cakephp to pass the data to an add function.
Postman output
Furthermore, I tried the Postman Chrome plugin to save the data and that actually does work. Does anyone know what I'm doing wrong in the test?
That's not how the integration test case is ment to be used. You are dispatching an external, real request, which will leave the test environment, while you should use the request dispatching tools that the integration test case supplies, that is
IntegrationTestCase::get()
IntegrationTestCase::post()
IntegrationTestCase::put()
etc...
These methods will dispatch simulated requests that do not leave the test environment, which is crucial for things to work properly, as you want to use test connections, inspect possible exceptions, have access to the used session, etc...
ie, you should do something along the lines of
$accessToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjksImV4cCI6MTQ1NzYyOTU3NH0.NnjXWEQCno3PUiwHhnUCBjiknR-NlmT42oPLA5KhuYo';
$this->configRequest([
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json'
]
]);
$data = [
"album_id" => 1,
"link" => "http://www.google.com",
"description" => "testtesttest",
"favorite" => true
];
$this->post('/api/pictures/add.json', json_encode($data));
Note that a content type of application/json will require you to send raw JSON data! If you don't actually need/want to test parsing of raw input, then you could skip that header, and pass the array as data instead.
See also
Cookbook > Testing > Controller Integration Testing
API > \Cake\TestSuite\IntegrationTestCase

Need to pull fields from an issue in Sitecore

I'm working with SiteCore and I need to pull some data out of the software via either that API or the SQL database using a PHP script. The reason I say both are possible is because even if the database changes later on, that doesn't matter to me.
Anyway...
I'm trying to pull any data fields that I can get from a particular issue. This is my SOAP code so far, and it connects to the service and such, but the return isn't what I need...
try
{
$client = new SoapClient('http://localhost:8083/sitecore/shell/webservice/service.asmx?WSDL');
$credentials = array('Password' => 'mypassword','Username' => 'sitecore\myusername');
$Current_Issue = array(
'id' => '{043B69BA-3175-4184-812F-C925CE80324E}',
//'language' => 'en',
//'version' => '1',
//'allFields' => 'true',
'databaseName' => 'web',
'credentials' => $credentials
);
$response = $client->GetItemMasters($Current_Issue);
print_r($response);
}
catch(SoapFault $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
This is my output:
stdClass Object
(
[GetItemMastersResult] => stdClass Object
(
[any] => <sitecore xmlns=""/>
)
)
ANY help is appreciated. If anybody knows an example SQL query that I can use, that would be just as useful as an alternative method.
Thanks
If you are running Sitecore 6.5 / 6.6 you may want to take a look at the Sitecore Item Web API which was released yesterday (5/11/12).
http://sdn.sitecore.net/Products/Sitecore%20Item%20Web%20API.aspx
This allows you to perform RESTful operations against Sitecore items without the need for the old web service / SOAP interface. Using this module you can receive a JSON representation of a Sitecore item or collection of items and even post back changes. You may find it easier to work with :)
If you have to use the SOAP interface, are you sure that your items are published ? Try changing the databaseName -> 'master' and see if you get any results. Other things to check are the permissions of the user credentials you are using.

Edit include/mail.inc, add my own SMTP setting there

The following function is contained in include/mail.inc of Drupal6, it uses the default SMTP settings buried in a file named "php.ini" to send mail.
function drupal_mail_send($message) {
// Allow for a custom mail backend.
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
include_once './'. variable_get('smtp_library', '');
return drupal_mail_wrapper($message);
}
else {
$mimeheaders = array();
foreach ($message['headers'] as $name => $value) {
$mimeheaders[] = $name .': '. mime_header_encode($value);
}
return mail(
$message['to'],
mime_header_encode($message['subject']),
// Note: e-mail uses CRLF for line-endings, but PHP's API requires LF.
// They will appear correctly in the actual e-mail that is sent.
str_replace("\r", '', $message['body']),
// For headers, PHP's API suggests that we use CRLF normally,
// but some MTAs incorrecly replace LF with CRLF. See #234403.
join("\n", $mimeheaders)
);
}
}
but I use shared host, therefore i can't edit php.ini, i want to edit the above function "drupal_mail_send", add the codes below into that function so that it can bypass the PHP mail() function and send email directly to my favorite SMTP server.
include('Mail.php');
$recipients = array( 'someone#example.com' ); # Can be one or more emails
$headers = array (
'From' => 'someone#example.com',
'To' => join(', ', $recipients),
'Subject' => 'Testing email from project web',
);
$body = "This was sent via php from project web!\n";
$mail_object =& Mail::factory('smtp',
array(
'host' => 'prwebmail',
'auth' => true,
'username' => 'YOUR_PROJECT_NAME',
'password' => 'PASSWORD', # As set on your project's config page
#'debug' => true, # uncomment to enable debugging
));
$mail_object->send($recipients, $headers, $body);
Could you write down the modified code for my reference?
The code in drupal_mail_send is part o the Drupal core functionality and should not be changed directly as your changes may be overwritten when you update Drupal.
Modifications of Drupal core files is often referred to by the Drupal community as "hacking core" and is largely discouraged.
Drupal already has a number of modules available which may help you. See:
http://drupal.org/project/phpmailer module:
Adds SMTP support for sending e-mails using the PHPMailer library.
Comes with detailed configuration instructions for how to use Google
Mail as mail server.
http://drupal.org/project/smtp module:
This module allows Drupal to bypass the PHP mail() function and send
email directly to an SMTP server.

Resources