Additional mailer service to use the spool and send instant emails in Symfony2 - strange headers - symfony

by default I use spool mailing solution for sending newsletter in my web page. But I also need to send email immediately. So I have used this solution
If I send newsletter with Spool everything is fine. But when I use
$mailer = $this->get('instant_mailer');
I receive email with some text prepend at the beginning:
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: text/html; charset=UTF-8 Date: Fri, 07 Sep 2012 16:19:06 GMT
How to remove this?

I bet that you're trying to send a Response object.
new Response();
it goes to __toString ()
public function __toString()
{
$this->prepare();
return
sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
$this->headers."\r\n".
$this->getContent();
}
It is because:
$this->render('template.html.twig');
returns Response to avoid that use:
$response = $this->render('template.html.twig');
$text = $response->getContent();
Regards,
Max

Use
$content = $this->renderView('template.html.twig');
instead of
$content = $this->render('template.html.twig');
render returns a response

Other posible solution to the problem is to use templating service instead of $this->render():
<?php
$body = $this->get('templating')->render('template.html.twig');

Related

ArangoDB can't send request with curl

I can't unserstand what I am doing wrong, but when I am sending next request with curl, I am getting error:
echo {"id":1,"question":"aaa"},{"id":2,"question":"bbb?"} | curl -X POST --data-binary #- --dump - http://localhost:8529/_db/otest/_api/document/?collection=sitetestanswers
HTTP/1.1 100 (Continue)
HTTP/1.1 400 Bad Request
Server: ArangoDB
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
Content-Length: 100
{"error":true,"errorMessage":"failed to parse json object: expecting EOF","code":400,"errorNum":600}
Any ideas? I tied wrap it's to [...]. Nothing do not help.
With [...] validator mark this as valid
Same with D. Here is my code:
void sendQuestionsToArangoDB(Json questions)
{
string collectionUrl = "http://localhost:8529/_db/otest/_api/document/?collection=sitetestanswers";
auto rq = Request();
rq.verbosity = 2;
string s = `{"id":"1","question":"foo?"},{"id":2}`;
auto rs = rq.post(collectionUrl, s, "application/json");
writeln("SENDED");
}
--
POST /_db/otest/_api/document/?collection=sitetestanswers HTTP/1.1
Content-Length: 37
Connection: Close
Host: localhost:8529
Content-Type: application/json
HTTP/1.1 400 Bad Request
Server: ArangoDB
Connection: Close
Content-Type: application/json; charset=utf-8
Content-Length: 100
100 bytes of body received
For D I use this lib: https://github.com/ikod/dlang-requests
Same issue with vibed.
ArangoDB do not understand JSON if it's come ass array like [...]. It should be passed as key-value. So if you need pass array it should have key mykey : [].
Here is working code:
import std.stdio;
import requests.http;
void main(string[] args)
{
string collectionUrl = "http://localhost:8529/_db/otest/_api/document?collection=sitetestanswers";
auto rq = Request();
rq.verbosity = 2;
string s = `{"some_data":[{"id":1, "question":"aaa"},{"id":2, "question":"bbb"}]}`;
auto rs = rq.post(collectionUrl, s, "application/json");
writeln("SENDED");
}
otest - DB name
sitetestanswers - collection name (should be created in DB)
echo '[{"id":1,"question":"aaa"},{"id":2,"question":"bbb?"}]'
should do the trick. You need to put ticks around the JSON. The array brackets are necessary otherwise this is not valid JSON.
You are trying to send multiple documents. The data in the original question separates the documents by comma ({"id":1,"question":"aaa"},{"id":2,"question":"bbb?"}) which is invalid JSON. Thus the failed to parse json object answer from ArangoDB.
Putting the documents into angular brackets ([ ... ]) as some of the commentors suggested will make the request payload valid JSON again.
However, you're sending the data to a server endpoint that handles a single document. The API for POST /_api/document/?collection=... currently accepts a single document at a time. It does not work with multiple documents in a single request. It expects a JSON object, and whenever it is sent something different it will respond with an error code.
If you're looking for batch inserts, please try the API POST /_api/import, described in the manual here: https://docs.arangodb.com/HttpBulkImports/ImportingSelfContained.html
This will work with multiple documents in a single request. ArangoDB 3.0 will also allow sending multiple documents to the POST /_api/document?collection=... API, but this version is not yet released. A technical preview will be available soon however.

Content-Type: multipart/alternative in Wordpress with wp_mail()

Is it is possible to send emails with the wp_mail() function having its Content-Type: multipart/alternative ?
I need to send emails that can be shown as HTML or Plain Text depending on what medium interprets the email.
Any suggestions are welcome!
It's right there in the wp_mail() documentation (under Usage):
The default content type is 'text/plain' which does not allow using HTML. You can set the content type of the email either by using the 'wp_mail_content_type' filter (see example below), or by including a header like "Content-type: text/html". Be careful to reset 'wp_mail_content_type' back to 'text/plain' after you send your message, though, because failing to do so could lead to unexpected problems with e-mails from WP or plugins/themes.
(emphasis mine)
The 2nd example on the page shows you how to do it (the example uses text/html but you should be able to use your multipart/alternative instead.
It's totally possible when you have access to the phpmailer instance.
if ($is_html)
add_action('phpmailer_init', 'fix_mimeheader');
// more code.
wp_mail( $to, $subject, $html_message, $headers, $attachments );
// ...
function fix_mimeheader( $phpmailer ) {
// Generate $text_message here.
// ...
$phpmailer->AltBody = $text_message;
}
The message sent to wp_mail should be your html code. You also shouldn't include any content type headers. I currently use from, cc and reply-to in the plugin i've made.
If the email is being sent as HTML, I run the action which sets the AltBody property on the phpmailer object directly. This then causes the proper flags to convert the email to a multipart/alternative email.
You can use the wp_mail_content_type filter, which was now been documented in the Codex.
The wp_mail documentation about resetting the content type back to 'text/plain' is kind of misleading, IMO. Since this is a filter, you don't really "reset" it. What you need to consider in your filter is some conditional logic to determine when you need to use multipart vs. plain text or html:
add_filter( 'wp_mail_content_type', 'my_mail_content_type' );
function my_mail_content_type( $content_type ) {
if( $some_condition ) {
return 'multipart/mixed';
} else {
return 'text/plain';
}
}

using swift mailer of symfony 2, got an email but getting unnecessary response in email

getting this response by email "HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: text/html; charset=UTF-8 Date: Tue, 13 Nov 2012 04:56:14 GMT".
here is my code:
public function sendEmail($subject, $template, $templateParams)
{
$userEmail = $this->session->get('email');
$name = $this->session->get('name');
$adminEmail = $this->container;
$templateParams['username'] = $name;
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($adminEmail)
->setTo($userEmail)
->setBody($this->templating->render('SocialDonSocialBundle:Email:'.$template,$templateParams), 'text/html');
$this->mailer->send($message);
Also note that this method is belongs to a service namely "Email". I have created a service "Email " which responsible to send emails. Does anybody know what might be the issue??
You need to use renderView() instead of render(), because render() always display the header.
In newer versions of Symfony2 like version 2.5.*
The solution is to use renderResponse and do a getContent() on it :
$content = $this->container->get('templating')->renderResponse(
'YOUR_TEMPLATE.twig',
templateParams)
)->getContent();
or with the same values like in the question :
$this->templating->renderResponse('SocialDonSocialBundle:Email:'.$template,$templateParams)->getContent();

Reading WordPress header.php/footer.php to a text string

I am attempting to read the results of the executed header.php/footer.php files as a string of html. Here's the scenario:
There are pages in the site that are developed in a .net environment but they want to share common headers/footers across the entire domain. They wish to have WordPress be the repository for this code and any time there is an update have a PHP cURL call to a .net web service and feed it the new HTML for the header/footers.
I tried calling get_header() but that does not return a string (as I anticipated) so then I tried this test solution in functions.php:
function write_header() {
$header_content = file_get_contents(get_bloginfo('wpurl').'/index.php' );
$fp = fopen('c:\header.txt', 'a+');
fwrite($fp, $header_content);//just testing the output, this will be a cURL call eventually.
fclose($fp);
}
add_action( 'wp_update_nav_menu', 'write_header' );
It seems to be a very heavy handed method of getting the HTML since I'll have to do a lot of string manipulation to parse out the pieces I want. Is there a simpler way of doing this that I'm missing?
If get_header() outputs the header for you, try just wrapping it with an ob_start() and ob_get_contents() to extract the header to a string. You can then discard the output with ob_end_clean(). See the PHP output buffering documentation.
ob_start();
get_header();
$header_as_string = ob_get_contents();
ob_end_clean();
There's a couple ways you can approach this problem (both are a bit of kludge, but what isnt...). The first would be to create a template in your theme's directory that will include only the header and footer calls -- the body of the template can contain a delimiter string like an html comment, e.g. <!-- SPLIT HERE -->.
Request the page through CURL into an output buffer, capturing the resulting response, which you can split into it's component parts using the above delimiter. That will give you your header and footer, complete with the fully rendered tags in the header for css,js, etc. It's not pretty, but it does the job.
The second approach would be an adaptation of the first, which, rather than you doing the splitting, have your .net team take care of it on their end if possible.
UPDATE
Okay, so there's actually a third option, which I completely forgot about, and that's to use one of WP's features: wp_remote_get() http://codex.wordpress.org/Function_API/wp_remote_get
Retrieves a URL using the HTTP GET method, returning results in an array. Results include HTTP headers and content.
This is what you should get back (excerpted from the API docs):
Array
(
[headers] => Array
(
[date] => Thu, 30 Sep 2010 15:16:36 GMT
[server] => Apache
[x-powered-by] => PHP/5.3.3
[x-server] => 10.90.6.243
[expires] => Thu, 30 Sep 2010 03:16:36 GMT
[cache-control] => Array
(
[0] => no-store, no-cache, must-revalidate
[1] => post-check=0, pre-check=0
)
[vary] => Accept-Encoding
[content-length] => 1641
[connection] => close
[content-type] => application/php
)
[body] => <html>This is a website!</html>
[response] => Array
(
[code] => 200
[message] => OK
)
[cookies] => Array
(
)
)
All you'd have to do is pass the URL to a page that's using the template I mentioned above, then handle response from wp_remote_get(); extract the html content form [body] and do your string splitting. Pretty much what you want.
Further reading: wp_remote_retrieve_body() http://codex.wordpress.org/Function_API/wp_remote_retrieve_body

Why this json Symfony output outputs the headers

This is my first day to have fun with Symfony and drupal 8, so please excuse me if my question is very obvious.
With drupal 7:
drupal_json_output(array('products' => array_values($products)));
exit;
the json output is clean:
{"products":["item_1","item_2",....]}
With drupal 8:
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
print new JsonResponse(array('products' => array_values($products)));
exit;
It outputs with the headers:
HTTP/1.0 200 OK
Cache-Control: no-cache
Content-Type: application/json
Date: Wed, 18 Jul 2012 07:53:26 GMT
{"products":["item_1","item_2",....]}
How do you get rid of those headers?
I am stuck to read the reference here.
Any hint is very much appreciated.
You can get only the "content" of a response by calling $response->getContent().
In your case you could do
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
$response = new JsonResponse(array('products' => array_values($products)));
print $response->getContent();
exit;
However, be aware that this would be a bad practice because you would lose the response headers in the process, and wouldn't tell for example, what the content-type of you response is (in this case: "application/json") etc ...
I do not know how to do this properly with drupal, any tips is appreciated.

Resources