I need to send an e-mail from my custom php code using the Drupal service.
In other words, I've noticed Drupal can easily send emails so I would like to know how can I use drupal libraries to send the emails, instead of using external libraries.
You need to use drupal_mail(), and define hook_mail() in your module.
You'll then call the first one, and the e-mail information will be set by the second one.
(See the example on the documentation page for drupal_mail().)
$message = array(
'to' => 'example#mailinator.com',
'subject' => t('Example subject'),
'body' => t('Example body'),
'headers' => array('From' => 'example#mailinator.com'),
);
drupal_mail_send($message);
Caveats:
Because drupal_mail() isn't called, other modules will not be able to hook_mail_alter() your output, which can cause unexpected results.
drupal_mail_send() is ignorant about which language to send the message in, so this needs to be figured out beforehand.
You'll have to manually specify any other e-mail headers that are required ('Content-Type', etc.). These are normally taken care of for you by drupal_mail().
In the case where your module sends several different types of emails, and you want those email templates to be editable (for example, user module's various registration notification/password reset/etc. e-mails), using hook_mail() is still the best way to go.
This is what reported in a comment in the documentation for drupal_mail(). If the caveats are not important in your case, then you can use the reported snippet.
I would recommend to use mimemail. It's a contrib module that will allow you to send HTML mails (+ attachments) or plaintext-only messages with ease. Here is an excerpt from the readme file:
the mimemail() function:
$sender - a user object or email address
$recipient - a user object or email address
$subject - subject line
$body - body text in html format
$plaintext - boolean, whether to send messages in plaintext-only (default false)
This module creates a user preference for receiving plaintext-only messages. This preference will be honored by all calls to mimemail()
Link: http://drupal.org/project/mimemail
I hope this will help you!
Related
I've worked through the twilio tutorials regarding sending and receiving SMS with WordPress. I integrated them into a test install I have and then merged them into one. (The receive one is pretty short, although it's not a full "receive" more than a blind response).
Then I came across themebound's twilio-core and so I had a look at that and quickly I got a fatal error because they both use the twilio helper library. For testing, I just deactivated the first one and activated the second, which leads me into my first question:
Both of these use the same library, and have both used require_once. Each loaded it into their own plugin folder. The original name of the library is twilio-php-master, one renames it twilio the other twilio-php. Not that it matters at all, since they're in separate locations. The fatal error is as a result of the inner workings having the same function names.
How can I test for the existence of the other plugins helper library and use that in place of the one that I have installed?
What about the order of how WordPress loads the plugins? It's likely if mine loads first... Well, I can't even get that far because it crashes just trying to have both activated.
--- we're now leading into the next question ---
As a result, I'm probably going to go with the twilio-core version because it seems more featured and is available on github, even if the author isn't overly active (there's a pull request that's months old and no discussion about it).
I want to extend the functionality of one of the sending plugins (either one) with respect to the receipt of the message from twilio. At the moment, both examples use classes for the sending and the receive that I'm using is not. As such I have just added it to the end of the main plugin file (the one with the plugin metadata). (a quick note, this is not the cause of the above fatal error, this happened before I started merging the send and receive).
Because the receive is involved with the REST API and not initiated by a user action on the system (ie someone in the admin area accessing the class through the admin panel), I'm not sure if it's appropriate that a) I put it there, and b) use the send function inside the class when further processing the receipt. I have an end goal of analysing the incoming message and forwarding it back out through twilio or other application or even just recording it in wordpress itself.
Should I keep the receive functionality/plugin separate from the sending one?
And this leads on to the hardest question for me:
How would I extend either plugin to make the send function available to my receive plugin? (this is where part of my confusion comes from) -->> Because both plugins only operate in the admin area, and the REST API isn't an actual user operating in the front-end, how can I call those functions in the admin area? Will is "just be available"? Do I have to replicate them on the public side? and then if so, is it necessary to have it in the admin area as well?
edit: With respect to one of the comments below, I have tested and twl_send_sms is available once the helper is loaded. What I will do is determine a way to see if the helper is loaded (a function exists test will probably suffice) and if so, require or not require my version as appropriate.
From the receive message I am now able to craft a separate forward of a new message. But how can I pass the callback function the parameters of the initial inbound message? eg, how do I populate $sms_in with the POST data?
function register_receive_message_route() {
register_rest_route( 'sms/v1', '/receiver_sms', array(
'methods' => 'POST',
'callback' => 'trigger_receive_sms',
) );
}
function trigger_receive_sms($sms_in = '') {
/* we have three things to do:
* 1: send the reply to twilio,
* 2: craft a reply,
* 3: save the data message to the database
*/
echo header('content-type: text/xml');
echo ('<?xml version="1.0" encoding="UTF-8"?>');
echo ('<Response>');
echo (' <Message>Thanks, someone will be in contact shortly.</Message>');
echo ('</Response>');
$args = array(
'number_to' => '+xxxxxxxxxxx',
'message' => "Test Worked!\n$sms_in",
);
twl_send_sms( $args );
Twilio developer evangelist here.
It sounds to me as though your send functionality (whatever you can get out of twilio-core) is separate to your receive functionality. So I would likely split those up as two plugins and follow the instructions from the post you mentioned on how to write something that receives and responds to SMS messages. That way, twilio-core can use the Twilio library it bundles and your receive plugin won't need to use a library (it just needs to respond with TwiML, which is just XML).
I'm not sure I understand the last part of question 4 though, you can't really interact yourself with the receive endpoint of the plugin because all it will do is return XML to you. That's for Twilio to interact with.
Edit
In answer to your updated question, when your callback is triggered by a POST request it is passed a WP_REST_Request object. This object contains the POST body and the parameters can be accessed by array access.
function trigger_receive_sms($request) {
echo $request['Body'];
}
In good news, if you just plan to send two messages then you can do so entirely with TwiML. You just need to use two <Message>s:
echo ('<?xml version="1.0" encoding="UTF-8"?>');
echo ('<Response>');
echo (' <Message>Thanks, someone will be in contact shortly.</Message>');
echo (' <Message to="YOUR_OTHER_NUMBER">It worked!</Message>');
echo ('</Response>');
This way you don't need to worry about that other library.
Suppose you want to build a webpage with Facebook PHP SDK, where you want to allow the user to select the information Facebook will return to the server. I've came with the following code to allow an user to either choose from allowing Facebook to send only the basic profile or else to also send the pages managed by this user.
session_start();
// Load the Facebook PHP SDK
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
define('APP_ID', 'xxxxxxxxxxx');
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxx');
$fbProfile = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
$fbPages = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
$helperProfile = $fbProfile->getRedirectLoginHelper();
$redirectUrlProfile = 'http://www.example.com/link1.php';
$loginUrlProfile = $helperProfile->getLoginUrl($redirectUrlProfile);
echo 'Get profile with Facebook!<br>';
$helperPages = $fbPages->getRedirectLoginHelper();
$permissions = ['pages_show_list']; // Optional permissions
$redirectUrlPages = "http://www.example.com/link2.php";
$loginUrlPages = $helperPages->getLoginUrl($redirectUrlPages, $permissions);
echo 'Get pages with Facebook!';
If I use the above code (commenting the non-relevant parts) with only one facebook object to either retrieve the profile or the pages managed by user (but not both), everything works fine. But if I use both objects concurrently to give a choice to the user, I get a FacebookSDKException. I guess this is due to CRSF cookies.
Is there any way to circunvent this problem?
I guess this is due to CRSF cookies.
Correct. Calling the getLoginUrl method creates a new random state value and writes it into the session, overwriting any previously stored one.
So if you call the method twice (or more times), login will only work if you call the login dialog via the last login URL created, because only that contains a state value that matches the one stored in the session.
If you want to keep using two different redirect URIs, then you need to implement an additional step to create the correct login URL, and only that one.
So you have two links in your page, both pointing to a script on your server, and passing what permissions to ask for via a GET parameter (whether you want to pass permission names directly, or just a flag like ?loginmode=1/?loginmode=2, is up to you.)
In that script, you decide which redirect URI and scope value to call the getLoginUrl method with - once. And then your script just redirects to that login URL.
(But keep in mind that the step that exchanges the code for an access token also requires the redirect URI parameter to be passed, again - and again with the exact same value that was used in the login dialog call.)
So doing it the way #luschn suggested in comments, using the JS SDK for login purposes, is probably much easier. FB.login can be called with different scopes from different points in your client-side JS code without any such problems.
First of all, I'm not a security expert and new to form validation, password storing and wp plugin development. Any wp plugin tutorial I've been looking at never had a chapter about API passwords. Googling for wordpress password issues didn't return any satisfying results. So that's why I'm asking here.
I want to create a custom Wordpress Plugin which works with a Soap API of another page. To use the Soap API a login is needed. So the Wordpress built in functions add_option(), update_option() and get_option() are all working with plain text.
But I know that in the wp_config file authentication keys can be saved. But how to use them in an option page form to encrypt the password? And would it be possible just to store them in the database, decrypt it and use it in the backend but not showing it on the options page if the user visits that page again. So that the password field just has some black spots in it (not the same amount of the chars of the pass) and the password option only is updated if something is written into that field.
Normally the code is like this:
register_setting( 'my_plugins_option', 'my_options', 'my_validation_function' );
$options = array(
'user' = > 'name',
'password' = > 'pass',
//... other options
)
update_option( 'my_plugins_option', $options );
But how could I make this more secure? I've seen many plugin examples but nothing was about storing passwords. I'm looking for something like this:
function my_validation_function($input){
if($input['password']=='•••••'){
//use the default value of the database if nothing was changed
$old_options=get_option('my_plugins_option');
$input['password']=some_decrypting_function($old_options['password']);
}
else{
//use the password sent from the form
$password=esc_sql(some_encrypting_function($input['password']));
}
// ... validate the other inputs
update_option( 'my_plugins_soap_api_pass', $password );
}
P.S.: This code is not tested yet of course because I don't know how to work with passwords in wordpress plugins and so I wanted to ask for the best practices first.
The other question is: If the modified version of the code from above would work and the password is saved once and never loaded into the Dashboard frontend again (just showing this: '•••••' once typed in) would it be save to work with the get_option() function, decrypt the password and use it in the backend?
Here are a couple recommendations. They aren't specific to WP, but can apply.
1) Save an encrypted password in the options table (use whatever encrypting function you want, just don't write your own)
2) In the options page, simply do NOT output the password. Leave that field blank, and don't require it to be entered if there is already a password stored in the database.
3) Only decrypt the password retrieved from the options table just prior to actually needing it in code.
I currently have a registration form for people to signup and pick a date for an "appointment". They get sent an e-mail right after filling it up with the details. I need another e-mail to be sent a day before their chosen date to remind them, but that can't be fulfilled by plugins I currently have.
Does anyone know of any Wordpress plug-in that allows the sending of an e-mail message (with a template and user specific data) based on a specified date?
Any piece of information or advice would be highly appreciated. Thanks!
How I would approach this would be with Wordpresses event scheduling. When a user submits the form to schedule their appointment, set a new action for the reminder email:
// Set this when you send the confirmation email
// Set the $unix_timestamp to be whenever you want the reminder to be sent.
// Args can be an array of the data you will need. Such as the users email/appt date
$args = array(
'email' => 'email#email.com'
);
wp_schedule_single_event($unix_timestamp, 'set_reminder', $args);
Now we have to catch that, and create a function to actually create and send the email (assuming you use a similar process):
add_action('set_reminder','do_reminder');
function do_reminder($args) {
// $email = $args['email'], etc.
// send reminder email.
}
I recommend Wysija Newsletters. You http://wordpress.org/extend/plugins/wysija-newsletters/. You can use template and user specific data in your email with this plugin.
If you are comfortable with writing your own code(I guess you are more or less ok with that), you can use the WordPress Schedule API(okay, maybe that's not the official name, but it works). Basically it's kind of a cron-job, but for WordPress. It has one downside though - it will only trigger on time, if WordPress is rendered(in other words accessed, so that it's code will execute). That can be easily fixed by adding a simple cron-job to your hosting account, that will simply access your home page every X hours.
You can find useful information on the API here.
Basically what you should have inside of your scheduled function is to get the records of people that should be sent reminder emails(you should probably store additional information about whether a reminder email has been sent or not) and send them the emails. I don't know what is the way you're storing the information from the registration form, but if you are using a Custom Post Type, then things should be pretty easy for you.
I want to collect all the information that we could when someone is visiting a webpage: e.g.:
clients screen resolution: <script type='text/javascript'>document.write(screen.width+'x'+screen.height); </script>
referer: <?php print ($_SERVER['HTTP_REFERER']); ?>
client ip: <?php print ($_SERVER['REMOTE_ADDR']); ?>
user agent: <?php print ($_SERVER['HTTP_USER_AGENT']); ?>
what else is there?
Those are the basic pieces of information. Anything beyond that could be viewed as SpyWare-like and privacy advocates will [justifiably] frown upon it.
The best way to obtain more information from your users is to ask them, make the fields optional, and inform your user of exactly what you will be using the information for. Will you be mailing them a newsletter?
If you plan to eMail them, then you MUST use the "confirmed opt-in" approach -- get their consent (by having them respond to an eMail, keyed with a special-secret-unique number, confirming that they are granting permission for you to send them that newsletter or whatever notifications you plan to send to them) first.
As long as you're up-front about how you plan to use the information, and give the users options to decide how you can use it (these options should all be "you do NOT have permission" by default), you're likely to get more users who are willing to trust you and provide you with better quality information. For those who don't wish to reveal any personal information about themselves, don't waste your time trying to get it because many of them take steps to prevent that and hide anyway (and that is their right).
Get all the information of client's machine with this small PHP:
<?php
foreach($_SERVER as $key => $value){
echo '$_SERVER["'.$key.'"] = '.$value."<br />";
}
?>
The list that is available to PHP is found here.
If you need more details than that, you might want to consider using Browserhawk.
For what end?
Remember that client IP is close to meaningless now. All users coming from the same proxy or same NAT point would have the same client IP. Years go, all of AOL traffic came from just a few proxies, though now actual AOL users may be outnumbered by the proxies :).
If you want to uniquely identify a user, its easy to create a cookie in apache (mod_usertrack) or whatever framework you use. If the person blocks cookies, please respect that and don't try tricks to track them anyway. Or take the lesson of Google, make it so useful, people will choose the utility over cookie worries.
Remember that Javascript runs on the client. Your document.write() will show the info on their webpage, not do anything for your server. You'd want to use Javascript to put this info in a cookie, or store with a form submission if you have any forms.
I like to use something like this:
$log = array(
'ip' => $_SERVER['REMOTE_ADDR'],
're' => $_SERVER['HTTP_REFERER'],
'ag' => $_SERVER['HTTP_USER_AGENT'],
'ts' => date("Y-m-d h:i:s",time())
);
echo json_encode($log);
You can save that string in a file, the JSON is pretty small and is just one line.
phpinfo(32);
Prints a table with the whole extractable information. You can simply copy and paste the variables directly into your php code.
e.g:
_SERVER["GEOIP_COUNTRY_CODE"] AT
would be in php code:
echo $_SERVER["GEOIP_COUNTRY_CODE"];
get all the outputs of $_SERVER variables:
<?php
$test_HTTP_proxy_headers = array('GATEWAY_INTERFACE','SERVER_ADDR','SERVER_NAME','SERVER_SOFTWARE','SERVER_PROTOCOL','REQUEST_METHOD','REQUEST_TIME','REQUEST_TIME_FLOAT','QUERY_STRING','DOCUMENT_ROOT','HTTP_ACCEPT','HTTP_ACCEPT_CHARSET','HTTP_ACCEPT_ENCODING','HTTP_ACCEPT_LANGUAGE','HTTP_CONNECTION','HTTP_HOST','HTTP_REFERER','HTTP_USER_AGENT','HTTPS','REMOTE_ADDR','REMOTE_HOST','REMOTE_PORT','REMOTE_USER','REDIRECT_REMOTE_USER','SCRIPT_FILENAME','SERVER_ADMIN','SERVER_PORT','SERVER_SIGNATURE','PATH_TRANSLATED','SCRIPT_NAME','REQYEST_URI','PHP_AUTH_DIGEST','PHP_AUTH_USER','PHP_AUTH_PW','AUTH_TYPE','PATH_INFO','ORIG_PATH_INFO','GEOIP_COUNTRY_CODE');
foreach($test_HTTP_proxy_headers as $header){
echo $header . ": " . $_SERVER[$header] . "<br/>";
}
?>