PHP returning extra whitespace with return statement? - php

My code works, but for some strange reason when I return a string it adds extra space and I think a new line as well.
The code below works fine. However the length of this when fetched with Ajax is 11, the string success has a length of seven so this isn't right and it also doesn't equal to 'success' when comparing.
I've looked through a few other questions but all the solutions they offer don't seem to be working for me. No trailing spaces anywhere as far as I can see. And it's also not coming from any of the files I'm requiring.
<?php
/*
Plugin Name: Quotation Rest API
Plugin URI:
Description: A rest API for sending quotation request through to email using Sendgrid.
Version: 1.0
Author: Niels
Author URI:
*/
add_action( 'rest_api_init', function () {
register_rest_route( 'offerte', '/send',array(
'methods' => 'POST',
'callback' => 'send_mail',
) );
} );
include('MailChimp.php');
use \DrewM\MailChimp\MailChimp;
function send_mail( WP_REST_Request $request) {
$data = $request['data'];
$name = htmlspecialchars($request['name']);
$email = htmlspecialchars($request['email']);
$comment = htmlspecialchars($request['comment']);
$website = htmlspecialchars($request['url']);
$company = htmlspecialchars($request['company']);
$tel = htmlspecialchars($request['tel']);
$mailchimp = htmlspecialchars($request['mailchimp']);
$dataArray = json_decode($data, true);
ob_start();
include('mail.php');
$mailHTML = ob_get_clean();
$success = 'success';
if (!empty($mailchimp)) {
// add email to mailchimp list
$client = new MailChimp('-us14');// get from setttings
$list_id = ' ';// get from setttings
$result = $client->post("lists/$list_id/members", [
'email_address' => $email,
'status' => 'subscribed',
]);
}
$to = " #icloud.com";// get from setttings
$subject = "Offerte van " . $name;// // get from setttings (maybe...)
$message = $mailHTML;
if(wp_mail( $to, $subject, $message)){
return $success;
} else {
// return 'error';
}
}
?>

Related

Adding media to Twilio group messaging system

My group messaging app allowing people in a group (people.php) to sms each other in a closed system where all users can view and reply to the sms.
My next step would be to allow the media files which I can see on the Twilio Console to be sent to others in this group message system and possibly save a record of that media file.
This my code so far, it functions just missing the media part.
listener.php
<?php
include("../Services/Twilio.php");
include("config.php");
$client = new Services_Twilio($accountsid, $authtoken);
include("functions.php");
include("pdo.class.php");
include("people.php");
if( isset($_POST['Body']) ){
$phone = $_POST['From'];
$message = ($_POST['Body']);
$media = ($_POST['MediaUrl0']);
$name = $people[ $phone ];
if( empty($name) ) $name = $phone;
// resends sms message to group
$message = '['.$name.'] '.$message .$media;
foreach ($people as $number => $name) {
if( $number == $phone ) continue;
$sid = send_sms($number,$message,$media);
}
// reply message for succesfull sent sms
print_sms_reply("Message delivered");
// insert sms traffic into database for record purposes
$now = time();
$pdo = Db::singleton();
$sql = "INSERT INTO message_log SET `message`='{$message}', `sent_from`='{$name}'";
$pdo->exec( $sql );
}
?>
function.php
<?php
function send_sms($number,$message){
global $client,$fromNumber;
$sms = $client->account->sms_messages->create(
$fromNumber,
$number,
$message
);
return $sms->sid;
}
function print_sms_reply ($sms_reply){
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>\n<Sms>\n";
echo $sms_reply;
echo "</Sms></Response>\n";
}
?>
people.php
<?php
include("config.php");
$conn=mysqli_connect("$dbhost","$dbuser","$dbpass","$dbname")
or die (mysqli_error());
$query = "SELECT phone, name FROM grouplist";
$result = mysqli_query($conn, $query);
$people = array();
while ($row = mysqli_fetch_assoc($result)) {
$people[$row['phone']] = $row['name'];
}
?>
Twilio developer evangelist here.
Looks like you need to update your send_sms function to include the media url. Something like this should work:
<?php
function send_sms($number,$message,$media_url){
global $client,$fromNumber;
$sms = $client->account->messages->create(array(
'To' => $number,
'From' => $fromNumber,
'Body' => $message,
'MediaUrl' => $media_url
);
return $sms->sid;
}
?>
Notably, I've updated the call from $client->account->sms_messages->create because the sms_messages resource is deprecated and cannot send media messages. Using $client->account->messages->create uses the newer Messages resource and means you will be able to send media messages.
Let me know if this helps at all.

Wordpress invalidate cf7 after api call

Here's my issue, I have contact form 7 for wordpress installed and during the wpcf7_before_send_mail I make a call to an API, I need to invalidate the form if the API returns an error then I need to invalidate the request and return the error passed back from the API call.
I set a flag to false on API failure and the error message is also stored but my form is going through as success despite the failure I induce.
add_action("wpcf7_before_send_mail", "wpcf7_send_contact_builder");
function wpcf7_send_contact_builder($form) {
$submission = WPCF7_Submission::get_instance();
$wpcf7_data = $submission->get_posted_data();
... api call and set $success to true if ok and false if not ...
if (!$success) {
$form->status = 'validation_failed (statuscode:' . $xml->status->statuscode[0] . ').';
$form->valid = false;
$form->response = $xml->status->statusdesc[0];
return $forml
}
}
I've also tried using:
$form->invalidate('validation_failed (statuscode:' . $xml->status->statuscode[0] . ').', $xml->status->statusdesc[0]);
But whichever way I am unable to prevent the success email being sent and the form validates as successful. Debugging proved that the !success in the if statement is working and the code contained is added to the variable. I also tried as if form was an array ($form['valid'] = false) but this also didn't work and the form submits as successful. Any ideas of what I'm missing here? I've omitted the code for the API call itself and the determining of the correct form id, both of these work correctly, only the form I'm after is parsed and the API call is returning the expected data.
I needed the same. After going through the CF7 plugin files, I found the following solution:
//To make it working, we must need at least CF7-v5.0;
add_action( 'wpcf7_before_send_mail', 'cf7_validate_api', 15, 3 );
function cf7_validate_api($cf7, &$abort, $submission){
if ( $cf7->id() !== 789 ) //CF7 post-id from admin settings;
return;
$errMsg = '';
//$submission = WPCF7_Submission::get_instance();
$postedData = $submission->get_posted_data();
//$postedData['more-data'] = 'something';
unset($postedData['not-sending-data']);
//-----API posting------
$url = "http://my-web.com/wp-admin/admin-ajax.php?action=get-something";
$username = 'apiUserName';
$password = 'apiUserPass';
$args = [
'headers' => [
'Authorization' => "Basic ".base64_encode( $username . ':' . $password ),
'Accept' => 'application/json; charset=utf-8', // The API returns JSON
//'Content-Type' => 'application/json; charset=utf-8'
],
'body' => $postedData
];
$response = wp_remote_post( $url, $args );
//------------------
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
$errMsg = "Something went wrong:\n{$error_message}";
} else {
$response_body = wp_remote_retrieve_body( $response );
$data = json_decode( $response_body );
if( empty($data) || $data->status==0 ){ //API validation error!
$errMsg = $data->msg->title."\n".$data->msg->description;
}
}
if( $errMsg ){ //do not send mail;
//$cf7->skip_mail = true; //for older versions!
$abort = true; //==> Here, it is with 'called by reference' since CF7-v5.0 :)
$submission->set_status( 'validation_failed' );
//$submission->set_response( $cf7->message( 'validation_error' ) ); //msg from admin settings;
$submission->set_response( $cf7->filter_message($errMsg) ); //custom msg;
}
}
Hopefully, it will help someone. Happy Coding :)

Email using cron and including attachment to email from moodle

I would like to send emails only to users that have completed a specific course and add a pdf file (a certificate for completing the course) as attachment to the email, and do so at a specific time using moodle cron.
I have looked at some plugins to find out how it's done, but I'm still not sure how exactly I should do this.
I need:
1. to know how I would add an attachment to an email (and which API to use),
2. how I would use cron to send the emails to the desired group at a certain time,
3. how to retrieve users that have completed the course so that I could send emails (with attachment) to them.
Thanks in advance.
(I'm using moodle version 3.0)
This is an overview.
First create a local plugin. For example /local/yourplugin
https://docs.moodle.org/dev/Local_plugins
Then set up a message provider
https://docs.moodle.org/dev/Message_API
defined('MOODLE_INTERNAL') || die();
in local/yourplugin/db/messages.php
$messageproviders = array (
'coursecompleted' => array (
),
Then add an event observer - you will want to respond to the course_completed event
https://docs.moodle.org/dev/Event_2
in /local/yourpluginname/db/events.php
have something like
$observers = array(
array(
'eventname' => '\core\event\course_completed',
'callback' => 'local_yourplugin_observer::course_completed',
),
);
Now add the message code
Add something like this to '/local/message/classes/observer.php'
defined('MOODLE_INTERNAL') || die();
class local_yourplugin_observer {
/**
* Triggered when 'course_completed' event is triggered.
*
* #param \core\event\course_completed $event
* #return bool
*/
public static function course_completed(\core\event\course_completed $event) {
// Your code here.
$message = new \core\message\message();
$message->component = 'local_yourplugin'; // Name of your local plugin.
$message->name = 'coursecompleted'; // Name of message provider.
$message->userfrom = $USER;
$message->userto = $user;
$message->subject = 'message subject 1';
$message->fullmessage = 'message body';
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = '<p>message body</p>';
$message->smallmessage = 'small message';
$message->notification = '0';
$message->contexturl = 'http://GalaxyFarFarAway.com';
$message->contexturlname = 'Context name';
$message->replyto = "random#example.com";
$content = array('*' => array('header' => ' test ', 'footer' => ' test ')); // Extra content for specific processor
$message->set_additional_content('email', $content);
// Create a file instance.
$usercontext = context_user::instance($user->id);
$file = new stdClass;
$file->contextid = $usercontext->id;
$file->component = 'user';
$file->filearea = 'private';
$file->itemid = 0;
$file->filepath = '/';
$file->filename = '1.txt';
$file->source = 'test';
$fs = get_file_storage();
$file = $fs->create_file_from_string($file, 'file1 content');
$message->attachment = $file;
$messageid = message_send($message);
}
}

add html ouput in joomla email

i am trying to set html on the output of the email send by joomla. my file is located in the joomla core.
i know i have to add something like ->isHTML(true); but i do not know where and how.
here is the code:
class MailtoController extends JControllerLegacy
{
/**
* Show the form so that the user can send the link to someone.
*
* #return void
*
* #since 1.5
*/
public function mailto()
{
$session = JFactory::getSession();
$session->set('com_mailto.formtime', time());
$this->input->set('view', 'mailto');
$this->display();
}
public function send()
{
// Check for request forgeries
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$session = JFactory::getSession();
$timeout = $session->get('com_mailto.formtime', 0);
if ($timeout == 0 || time() - $timeout < 1)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
$SiteName = $app->get('sitename');
$link = MailtoHelper::validateHash($this->input->get('link', '', 'post'));
// Verify that this is a local link
if (!$link || !JUri::isInternal($link))
{
// Non-local url...
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
// An array of email headers we do not want to allow as input
$headers = array (
'Content-Type:',
'MIME-Version:',
'Content-Transfer-Encoding:',
'bcc:',
'cc:'
);
// An array of the input fields to scan for injected headers
$fields = array(
'mailto',
'sender',
'from',
'subject',
);
/*
* Here is the meat and potatoes of the header injection test. We
* iterate over the array of form input and check for header strings.
* If we find one, send an unauthorized header and die.
*/
foreach ($fields as $field)
{
foreach ($headers as $header)
{
if (strpos($_POST[$field], $header) !== false)
{
JError::raiseError(403, '');
}
}
}
/*
* Free up memory
*/
unset ($headers, $fields);
$email = $this->input->post->getString('mailto', '');
$sender = $this->input->post->getString('sender', '');
$from = $this->input->post->getString('from', '');
$subject_default = JText::sprintf('COM_MAILTO_SENT_BY', $sender);
$subject = $this->input->post->getString('subject', $subject_default);
// Check for a valid to address
$error = false;
if (!$email || !JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $email);
JError::raiseWarning(0, $error);
}
// Check for a valid from address
if (!$from || !JMailHelper::isEmailAddress($from))
{
$error = JText::sprintf('COM_MAILTO_EMAIL_INVALID', $from);
JError::raiseWarning(0, $error);
}
if ($error)
{
return $this->mailto();
}
// Build the message to send
$msg = JText::_('COM_MAILTO_EMAIL_MSG');
$link = $link;
//$body = sprintf($msg, $SiteName, $sender, $from, $link);
$body = "<p>Hello Test F,</p><br/><p>Thank you for registering at Deals&offers. Your account is created and activated.</p><br/>You may login to ".$SiteName." using the following username and password:</br><p>Username: ".$sender."</p><p>Password: ".$from."/p><br/><p><b>Note:</b> It is recomended to change your password after first login. ".$link."</p>";
// Clean the email data
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
// To send we need to use punycode.
$from = JStringPunycode::emailToPunycode($from);
$from = JMailHelper::cleanAddress($from);
$email = JStringPunycode::emailToPunycode($email);
// Send the email
if (JFactory::getMailer()->sendMail($from, $sender, $email, $subject, $body) !== true)
{
JError::raiseNotice(500, JText::_('COM_MAILTO_EMAIL_NOT_SENT'));
return $this->mailto();
}
JFactory::getApplication()->enqueueMessage('ok!', '');
$this->input->set('view', 'sent');
$this->display();
}
}
thank you very much
you can add before body or between subject and body . however, it must be before the submit command !!
here is an example of PhpMailler firstly, you need to call the class like this and you can use it
$this->mail= new PHPMailer();
$this->mail->IsSMTP();
$this->mailIsHTML(true);
$subject = JMailHelper::cleanSubject($subject);
$body = JMailHelper::cleanBody($body);
however if the function is static also you call the function in same class
you can call the function by sef command
self::mailIsHTML(true)

PHP Mail function not working on Web Services

I am using two different servers for dev site and live site. My webservice function to send email confirmation is working on Dev Site but it is not working in Live Site. My
email confirmation function is:
function getEmailConfirmation($UserName, $ChecklistID,$UserID,$AnswerBulkID, $TotalSubmitted){
if ( ($UserID == '') || (!isset($UserID)) ) {
return error("partial");
}
$entry = new Entry();
$entry_date_check = date('Y-m-d'); //for check if already
$count_tbl_answers = $entry->listEntry("SELECT count(*) as total_from_answers FROM tbl_answers where user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' and date(ent_date) = '".$entry_date_check."' ");
$to = "****#gmail.com";
$subject = "TDL Checklist email";
$message = "Hello there! \n User ID: ".$UserID." \n User Name: ".$UserName."\n Check List ID: ".$ChecklistID."\n Answer Bulk ID: ".$AnswerBulkID;
$from = "TLD-Email-Confirmation";
$headers = "From:" . $from;
if(($count_tbl_answers[0]['total_from_answers']) == $TotalSubmitted){
mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
} else{
$delete_bulk = $entry->query("delete FROM tbl_answerbulk WHERE user_id ='".$UserID."' and check_list_id ='".$ChecklistID."' and id ='".$AnswerBulkID."' ");
$delete_answer = $entry->query("delete FROM tbl_answers WHERE user_id='".$UserID."' and answer_bulk_id ='".$AnswerBulkID."' ");
return error("custom","","Could not submit your answer this time. Please try again later.");
}
$message = json_encode(
$result
);
$fin_data['response'] = json_encode(array('Message'=>'ok','Data'=>$message));
return $fin_data;
}
This function works perfectly on dev server, but it does not work on live server. What might be the reason?
Note:
Although mail function not working on Live site, it returns the result array which is just after the mail function.
That is:
#mail($to,$subject,$message,$headers);
$result = array(
"user_id" => $UserID,
"user_name" => $UserName,
"check_list_id" => $ChecklistID,
"answer_bulk_id" => $AnswerBulkID,
);
I also tried ini_set('smtp_port', 587); and #mail($to,$subject,$message,$headers); but does not worked.

Categories