Im trying to send a MailChimp campaign, from a cron job in a cpanel, in a php file.
The idea is to have a condition and if realized, send a MC campaign.
The test is if there is an unseen message in a certain mailbox with a certain subject. The test is done trough an imap connexion as you will see below.
The unseen email test is working with a cron job, no pb.
But when i add the MC connexion and campaign sending, it is stuck.
Here is the entire code i have tried to write (actually, i tried to use others pieces of code).
Please help if possible.
<?php
//needed for the MailChimp connection
require_once (‘wp-config.php’);
$SCUpdate = 0 ;
$mailbox = imap_open('{imap.server.com:993/imap/ssl}INBOX', 'email#domain.com', 'password');
$unseenMessages = imap_search($mailbox, 'UNSEEN');
if ($unseenMessages != 0) {
$MailHeaders = imap_headers( $unseenMessages );
$Subject = "Subject_Search_Name";
Foreach ($MailHeaders as $Subject) {
$SCUpdate = 1 ;
}
If ($SCUpdate = 1) {
//make the MailChimp connection
function mailchimp_api_request($endpoint,$type=‘POST’,$body = ‘’) {
$api_key = 'xxxxxxx';
$endpoint = ‘https://<dc>.api.mailchimp.com/3.0/’;
list(, $datacenter) = explode( ‘-’, $api_key );
$endpoint = str_replace( ‘<dc>’, $datacenter, $endpoint );
$url = $endpoint . $endpoint;
$request_args = array(
‘method’ => $type,
‘timeout’ => 20,
‘headers’ => array(
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘apikey ‘ . $api_key
)
);
if ( $body ) {
$request_args[‘body’] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
return $response;
}
//link campaign to template
$campaign_id = 'xxxxxxx';
function set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id = "your-list-id";
$date = date('Y-m-d',strtotime(current_time('mysql')));
$title = "campaign-title";
$subject = "campaign-subject";
$campaign_id = null;
$campaign_id = create_mailchimp_campaign( $list_id, $subject, $title );
if($campaign_id == null){
exit(2);
}
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => xxxxxxx,
)
);
$set_campaign_content = set_mail_campaign_content( $campaign_id, $template_content );
if($set_campaign_content == false){
exit(3);
}
// Schedule time
$time = time();
$schedule = mailchimp_api_request( "campaigns/$campaign_id/actions/schedule", 'POST', array('schedule_time' => $time) );
$campaign = mailchimp_api_request( "/campaigns/$campaign_id", 'GET', '' );
mail('myemail#test.com', 'Test Subject', 'Test Name');
$SCUpdate = 0 ;
}
}
if ($unseenMessages) {
imap_setflag_full( $mailbox, implode(',', $unseenMessages ), '\Seen');
imap_close( $mailbox );
}
?>
Related
I need to interact with a third party plugin to send SMS. The plugin is Bookly, which is for making appointments. I edited the Ajax.php that Bookly uses for saving the appointment. I've sent the SMS succesfully on Ajax.php. However, I want to code an external plugin to make the process controllable on admin panel.
I use a custom hook named "bookly_appointment_saved" and send an array with that. And in my new plugin I catch the hook succesfully. The SMS is always sent but the Ajax.php of Bookly doesn't send the response to the frontend. It keeps showing the page as loading.
Please see the codes below and help.
Ajax.php (Bookly) - Only related method is included.
/**
* Save cart appointments.
*/
public static function saveAppointment()
{
$userData = new Lib\UserBookingData( self::parameter( 'form_id' ) );
if ( $userData->load() ) {
$failed_cart_key = $userData->cart->getFailedKey();
if ( $failed_cart_key === null ) {
$cart_info = $userData->cart->getInfo();
$is_payment_disabled = Lib\Config::paymentStepDisabled();
$skip_payment = BookingProxy\CustomerGroups::getSkipPayment( $userData->getCustomer() );
$gateways = self::getGateways( $userData, clone $cart_info );
if ( $is_payment_disabled || isset( $gateways['local'] ) || $cart_info->getPayNow() <= 0 || $skip_payment ) {
// Handle coupon.
$coupon = $userData->getCoupon();
if ( $coupon ) {
$coupon->claim()->save();
}
// Handle payment.
$payment = null;
if ( ! $is_payment_disabled && ! $skip_payment ) {
if ( $cart_info->getTotal() <= 0 ) {
if ( $cart_info->withDiscount() ) {
$payment = new Lib\Entities\Payment();
$payment
->setType( Lib\Entities\Payment::TYPE_FREE )
->setStatus( Lib\Entities\Payment::STATUS_COMPLETED )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( 0 )
->setPaid( 0 )
->save();
}
} else {
$payment = new Lib\Entities\Payment();
$status = Lib\Entities\Payment::STATUS_PENDING;
$type = Lib\Entities\Payment::TYPE_LOCAL;
$paid = 0;
foreach ( $gateways as $gateway => $data ) {
if ( $data['pay'] == 0 ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$type = Lib\Entities\Payment::TYPE_FREE;
$cart_info->setGateway( $gateway );
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
break;
}
}
if ( $status !== Lib\Entities\Payment::STATUS_COMPLETED ) {
$gift_card = $userData->getGiftCard();
if ( $gift_card ) {
$type = Lib\Entities\Payment::TYPE_CLOUD_GIFT;
$cart_info->setGateway( $type );
if ( $gift_card->getBalance() >= $cart_info->getPayNow() ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$paid = $cart_info->getPayNow();
$gift_card->charge( $paid )->save();
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
}
}
}
$payment
->setType( $type )
->setStatus( $status )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( $cart_info->getTotal() )
->setTax( $cart_info->getTotalTax() )
->setPaid( $paid )
->save();
}
}
// Save cart.
$order = $userData->save( $payment );
if ( $payment !== null ) {
$payment->setDetailsFromOrder( $order, $cart_info )->save();
}
// Send notifications.
Lib\Notifications\Cart\Sender::send( $order );
$response = array(
'success' => true,
);
} else {
$response = array(
'success' => false,
'error' => Errors::PAY_LOCALLY_NOT_AVAILABLE,
);
}
} else {
$response = array(
'success' => false,
'failed_cart_key' => $failed_cart_key,
'error' => Errors::CART_ITEM_NOT_AVAILABLE,
);
}
//Custom hook
$user_appointed=$userData->getData();
do_action('bookly_appointment_saved',
$appointment=[
'date'=>date("d/m/Y", strtotime($user_appointed['slots'][0][2]) ),
'time'=>date("H:i", strtotime($user_appointed['slots'][0][2]) ),
'full_name'=>$user_appointed['full_name']=''?$user_appointed['first_name'].' '.$user_appointed['last_name']:$user_appointed['full_name'],
'service_name'=>$userData->cart->getItemsTitle(),
]
);
// end of hook
$userData->sessionSave();
wp_send_json( $response );
}
Errors::sendSessionError();
}
custom-sms-sender-plugin.php (My plugin)
add_action('bookly_appointment_saved','send_sms');
function send_sms($appointment){
$phone = "66666666666";
$message="New appointment - ".$appointment['full_name']." Service: ".$appointment['service_name']." Date: ".$appointment['date']." Time:".$appointment['time'];
$message = urlencode($message);
$url= "//request url with parameters";
$request = wp_remote_get($url);
if ($request['body'] !=30 || $request['body'] !=20 || $request['body'] !=40 || $request['body'] !=50 || $request['body'] != 51 || $request['body'] != 70 || $request['body'] != 85) {
write_log("SENT - SMS Code : ".explode(" ",$request['body'])[1]);
} else {
write_log("ERROR - Code : ".$request['body']);
}
}
I've solved the problem. It is caused by the "write_log" commands as the command doesn't exist. After changing the log method, it worked like a charm. Thanks for all comments.
I created a hook in function.php in wordpress that I want to run every minute, and added the function in the hook with PHP code. At the same time, I use the WP-Control plugin to try to make this hook run every minute.
But when I set up the cron job in the plug-in, I found that even if the hook is run every minute, the function still does not work properly. I am a little confused about the reason of the function running.
Here is my php code:
// add autocheck function into a hook to get WP-Control
add_action( 'autocheck_run_every_minute', 'run_autocheck_every_minute' );
function run_autocheck_every_minute() {
// add autocheck.php function in custom-auction into this method
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$args = array(
'post_type' => 'product',
'posts_per_page' => 1,
'orderby' => 'ID',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '=',
),
array(
'key' => '_auction_has_started',
'value' => '1',
'compare' => '=',
),
array(
'key' => '_auction_current_bid',
'value' => '',
'compare' => '!=',
),
array(
'key' => '_auction_current_bider',
'value' => '',
'compare' => '!=',
),
array(
'key' => '_reserved_option',
//'value' => '',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_auction_dates_to',
'value' => date( "Y-m-d H:i" ),
'compare' => '<', // '>' auction still fresh, '<' auction ended!
),
),
);
//echo "1<br>";
//print_r($args);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
//$product_id = '7771';
//$product = wc_get_product($product_id);
if ($product->get_type() !== "auction"){
return;
}
$product_id = $product->get_id();
//echo $product_id;
$user_id = get_post_meta($product_id, '_auction_current_bider', true);
$auction_id = $product_id;
$product_name = $product->get_name();
$current_bid = $product->get_curent_bid();
$reserve = get_post_meta($product_id, '_auction_reserved_price', true);
$reserved_option = get_post_meta($product_id, '_reserved_option', true);
if ((!isset($reserve)) || ($reserve == "") || (empty($reserve))){
$reserve == 0;
}
$vendor_id = get_post( $auction_id )->post_author;
//echo $vendor_id;
$vendor = new WP_User( $vendor_id );
//print_r($vendor);
$vendor_recipient = $vendor->user_email;
//$vendor_name = $vendor->first_name." ".$vendor->last_name;
$vendor_name = $vendor->display_name;
$customer = new WC_Customer( $user_id );
$customer_recipient = $customer->get_email();
//print_r($customer);
//if ((!isset($reserved_option)) || ($reserved_option == "") || (empty($reserved_option))){
if ($reserve <= $current_bid){
//touch reserved price
//echo $reserve - $current_bid;
$data = array();
$data['billing_first_name'] = $customer->get_billing_first_name();
$data['billing_last_name']= $customer->get_billing_last_name();
$data['billing_company']= $customer->get_billing_company();
$data['billing_address_1']= $customer->get_billing_address_1();
$data['billing_address_2']= $customer->get_billing_address_2();
$data['billing_city']= $customer->get_billing_city();
$data['billing_state']= $customer->get_billing_state();
$data['billing_postcode']= $customer->get_billing_postcode();
$data['billing_country']= $customer->get_billing_country();
$data['billing_email']= $customer->get_email();
$data['billing_phone']= get_user_meta( $user_id, 'billing_phone', true );
//print_r($data);
//echo $product['name'] = $product->get_name();
//print_r($product->get_tax_class());
$taxes = WC_Tax::get_rates( $product->get_tax_class());
$tota_tax_rate = 0;
foreach($taxes as $tax){
$tota_tax_rate = $tota_tax_rate + $tax['rate'];
$tax_label = $tax['label'];
}
$data['taxes'] = $taxes;
$data['product'][$product_id]['stock_status'] = $product->get_stock_status();
$data['product'][$product_id]['price'] = $product->get_curent_bid();
$data['product'][$product_id]['name'] = $product->get_name();
$data['product'][$product_id]['type'] = $product->get_type();
$data['product'][$product_id]['total_tax_rate'] = $tota_tax_rate;
$data['product'][$product_id]['taxes'] = $taxes;
$data['product'][$product_id]['sub'] = $sub = $product->get_curent_bid();
$data['product'][$product_id]['sub_tax'] = $product_tax = round($product->get_curent_bid() * ($tota_tax_rate / 100), 2);
$data['product'][$product_id]['sub_total'] = $subtotal = $product->get_curent_bid() + $product_tax;
$data['product'][$product_id]['tax_class'] = $product->get_tax_class();
//service fee:
$service_fee = get_service_fee($user_id, $product_id, $product->get_curent_bid());
$service_fee_tax = round($service_fee * ($tota_tax_rate / 100), 2);
$service_fee_total = $service_fee + $service_fee_tax;
$total = $product->get_curent_bid() + $product_tax ;
$data['service_fee'][0]['amount'] = $service_fee;
$data['service_fee'][0]['tax'] = $service_fee_tax;
$data['service_fee'][0]['total'] = $service_fee;
$data['service_fee'][0]['tax_class'] = $product->get_tax_class();
$data['service_fee'][0]['taxes'] = $taxes;
$data['total_before_tax'] = $sub + $service_fee;
$data['total_tax'] = $product_tax + $service_fee_tax;
$data['total'] = $subtotal + $service_fee_total;
$result = CreateOrder($data, $user_id, $vendor_id);
if(strpos($result, "error") == false){
$order_id = $result;
}else{
return;
}
//print_r($order_id);
$data_pdf = array();
$data_pdf['order_id'] = $order_id;
$data_pdf['tax_rate'] = $tota_tax_rate;
$data_pdf['service_fee_total'] = $service_fee_total;
$data_pdf['order_total'] = $subtotal + $service_fee_total;
$data_pdf['order_subtotal'] = $sub + $service_fee;
$data_pdf['order_GST'] = $tax_label=="GST"?$product_tax + $service_fee_tax:0;
$data_pdf['order_PST'] = $tax_label=="PST"?$product_tax + $service_fee_tax:0;
$data_pdf['customer_name'] = $customer_name = $customer->get_billing_first_name()." ".$customer->get_billing_last_name();
$data_pdf['first_name'] = $customer->get_billing_first_name();
$data_pdf['last_name'] = $customer->get_billing_last_name();
$data_pdf['date'] = date("Y-m-d");
$data_pdf['address'] = $customer->get_billing_address_1().$customer->get_billing_address_2();
$data_pdf['city'] = $customer->get_billing_city();
$data_pdf['postcode'] = $customer->get_billing_postcode();
$data_pdf['phone'] = get_user_meta( $user_id, 'billing_phone', true );
$data_pdf['username'] = get_user_meta( $user_id, 'nickname', true );
//$data_pdf['invoice_number']
$data_pdf['orders'][$order_id]['order_id'] = $order_id;
$data_pdf['orders'][$order_id]['service_fee'] = $service_fee;
$data_pdf['orders'][$order_id]['service_fee_PST'] = $tax_label=="PST"?$service_fee_tax:0;
$data_pdf['orders'][$order_id]['service_fee_GST'] = $tax_label=="GST"?$service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['product_name'] = $product->get_name();
$data_pdf['orders'][$order_id]['products'][$product_id]['qty'] = 1;
$data_pdf['orders'][$order_id]['products'][$product_id]['unit_price'] = $product->get_curent_bid();
$data_pdf['orders'][$order_id]['products'][$product_id]['echo_PST'] = $tax_label=="PST"?$product_tax + $service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['echo_GST'] = $tax_label=="GST"?$product_tax + $service_fee_tax:0;
$data_pdf['orders'][$order_id]['products'][$product_id]['description'] = $product->get_short_description();
//print_r($data_pdf);
$file = generate_new_pdf_download($data_pdf, "customer", 0, 0);
$title = "Successful Bid on Reserved ".$product_name." at $".$current_bid." for Lot".$product_id;
// print_r($title);
//$dir = plugin_dir_path();
//print_r($dir);
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/12_self_service_agree_bid_customer.html');
//print_r($content);
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
$file,
);
//echo $auction_id."--".$product_name."--".$current_bid;
//print_r($content);
$profileid = get_user_meta($user_id, 'wc_authorize_net_cim_customer_profile_id', true);
$paymentprofileid = json_decode(get_user_meta($user_id, 'wc_authorize_net_cim_customer_payment_id', true))[0];
$service_fee_total = number_format($service_fee_total, 2);
//echo gettype($service_fee_total);
$res = chargeCustomerProfile($profileid, $paymentprofileid, $service_fee_total);
//die();
if (!$res){
//pay failed
//echo "no";
update_post_meta( $order_id, '_auction_payment', "1" );
//failed payment first time sent email to buyer
$title = 'Failed Payment by Bidder';
//$dir = plugin_dir_path( __DIR__ );
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/14_self_service_1st_payment_fail_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
//failed payment first time sent email to seller
$title = 'Failed Payment by Bidder';
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/16_self_service_1st_payment_fail_vendor.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$vendor_recipient,
$title,
$content,
$headers,
);
}else{
//pay successful
//echo "yes";
update_post_meta( $order_id, '_auction_payment', "TRUE" );
$order = wc_get_order( $order_id );
if (!empty($order)) {
$order->update_status( 'wc-processing' );
}
//for customer
$title = 'Purchase Information of '.$product_name.' for Lot'.$product_id ;
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/22_self_serivce_breach_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$content = str_replace('[vendor_name]',$vendor_name, $content);
$content = str_replace('[vendor_email]',$vendor_recipient, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
//for vendor
$title = 'Sale Information of '.$product_name.' for Lot'.$product_id ;
$content = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/23_self_service_payment_success_vendor.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
$content = str_replace('[customer_name]',$customer_name, $content);
$content = str_replace('[customer_email]',$customer_recipient, $content);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$vendor_recipient,
$title,
$content,
$headers,
);
}
}else{
//no touch resered price
//echo $reserve - $current_bid;
//for customer email
$service_type = get_post_meta($auction_id, 'service_type', true);
if ($service_type == "delegation"){
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'Cc:'.ADMIN_EMAIL;
$title = " High Bidder on Reserved on ".$product_name." for Lot ".$auction_id;
$content = file_get_contents(__DIR__ .'/templates/7_angeldd_no_reserve_customer.html');
$content = str_replace('[product_id]',$auction_id, $content);
$content = str_replace('[product_name]',$product_name, $content);
$content = str_replace('[current_bid]',$current_bid, $content);
wp_mail(
$customer_recipient,
$title,
$content,
$headers,
);
}else if ($service_type == "self_service"){
$title = "High Bidder on Reserved ".$product_name." for Lot ".$auction_id;
$content_customer = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/9_self_service_no_reserve_customer.html');
$content_customer = str_replace('[product_id]',$auction_id, $content_customer);
$content_customer = str_replace('[product_name]',$product_name, $content_customer);
$content_customer = str_replace('[current_bid]',$current_bid, $content_customer);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
wp_mail(
$customer_recipient,
$title,
$content_customer,
$headers,
);
//for vendor email
//$vendor_recipient = $vendor->user_email;
$title = "Reserve Not Met on Reserved ".$product_name." for Lot ".$auction_id;
$content_vendor = file_get_contents('/home/littl462/public_html/wp-content/plugins/custom-auction/templates/10_self_service_no_reserve_vendor.html');
$content_vendor = str_replace('[product_id]',$auction_id, $content_vendor);
$content_vendor = str_replace('[product_name]',$product_name, $content_vendor);
$content_vendor = str_replace('[current_bid]',$current_bid, $content_vendor);
//$content_vendor = str_replace('[user_id]',$user_id, $content_vendor);
$data = $product_id.OPTION_SPLITE.$user_id;
$data = _encrypt($data, OPTION_KEY);
$content_vendor = str_replace('[data]',$data, $content_vendor);
$headers[] = 'Content-Type: text/html; charset=UTF-8';
//$headers[] = 'Cc:neo.itcg#gmail.com';
wp_mail(
$vendor_recipient,
$title,
$content_vendor,
$headers,
);
/* echo $data."--".$auction_id."--".$product_name."--".$user_id;
echo "<br>";
print_r($content_vendor); */
update_post_meta( $product_id, '_reserved_option', 'none' );
}
}
/* }else{
echo "1";
} */
endwhile;
wp_reset_query();
}
When I do a test email for a contact form in Live Server and press 'Send' nothing happens, no email goes through and no success message. Am I missing something in my PHP code or do I need to setup SMTP?
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
// If you intend you use SMTP, uncomment next line
require 'phpmailer/src/SMTP.php';
// Set the recipient email address here
$recipients = array();
$recipients[] = array(
'email' => 'contact#westonborst.com',
'name' => 'Weston'
);
// Set the sender email address here
$sender = array(
'email' => 'contact#westonborst.com',
'name' => 'Weston'
);
// reCaptcha Secret Key - Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = '';
// PHPMailer Initialization
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
// End of SMTP
// Form Messages
$message = array(
'success' => 'Thank you for your message. It has been sent.',
'error' => 'There was an error trying to send your message. Please try again later.',
'error_bot' => 'Bot Detected! Message could not be send. Please try again.',
'error_unexpected' => 'There was an unexpected error trying to send your message. Please try again later.',
'recaptcha_invalid' => 'Captcha not Validated! Please Try Again.',
'recaptcha_error' => 'Captcha not Submitted! Please Try Again.'
);
// Form Processor
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$prefix = !empty( $_POST['prefix'] ) ? $_POST['prefix'] : '';
$submits = $_POST;
$botpassed = false;
$message_form = !empty( $submits['message'] ) ? $submits['message'] : array();
$message['success'] = !empty( $message_form['success'] ) ? $message_form['success'] : $message['success'];
$message['error'] = !empty( $message_form['error'] ) ? $message_form['error'] : $message['error'];
$message['error_bot'] = !empty( $message_form['error_bot'] ) ? $message_form['error_bot'] : $message['error_bot'];
$message['error_unexpected'] = !empty( $message_form['error_unexpected'] ) ? $message_form['error_unexpected'] : $message['error_unexpected'];
$message['recaptcha_invalid'] = !empty( $message_form['recaptcha_invalid'] ) ? $message_form['recaptcha_invalid'] : $message['recaptcha_invalid'];
$message['recaptcha_error'] = !empty( $message_form['recaptcha_error'] ) ? $message_form['recaptcha_error'] : $message['recaptcha_error'];
// Bot Protection
if( isset( $submits[ $prefix . 'botcheck' ] ) ) {
$botpassed = true;
}
if( !empty( $submits[ $prefix . 'botcheck' ] ) ) {
$botpassed = false;
}
if( $botpassed == false ) {
echo '{ "alert": "error", "message": "' . $message['error_bot'] . '" }';
exit;
}
// reCaptcha
if( isset( $submits['g-recaptcha-response'] ) ) {
$recaptcha_data = array(
'secret' => $recaptcha_secret,
'response' => $submits['g-recaptcha-response']
);
$rc_verify = curl_init();
curl_setopt( $rc_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify" );
curl_setopt( $rc_verify, CURLOPT_POST, true );
curl_setopt( $rc_verify, CURLOPT_POSTFIELDS, http_build_query( $recaptcha_data ) );
curl_setopt( $rc_verify, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $rc_verify, CURLOPT_RETURNTRANSFER, true );
$rc_response = curl_exec( $rc_verify );
$g_response = json_decode( $rc_response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "' . $message['recaptcha_invalid'] . '" }';
exit;
}
}
$html_title = !empty( $submits['html_title'] ) ? $submits['html_title'] : 'Form Response';
$forcerecaptcha = ( !empty( $submits['force_recaptcha'] ) && $submits['force_recaptcha'] != 'false' ) ? true : false;
$replyto = !empty( $submits['replyto'] ) ? explode( ',', $submits['replyto'] ) : false;
if( $forcerecaptcha ) {
if( !isset( $submits['g-recaptcha-response'] ) ) {
echo '{ "alert": "error", "message": "' . $message['recaptcha_error'] . '" }';
exit;
}
}
$mail->Subject = !empty( $submits['subject'] ) ? $submits['subject'] : 'Form response from your website';
$mail->SetFrom( $sender['email'] , $sender['name'] );
if( !empty( $replyto ) ) {
if( count( $replyto ) > 1 ) {
$replyto_e = $submits[ $replyto[0] ];
$replyto_n = $submits[ $replyto[1] ];
$mail->AddReplyTo( $replyto_e , $replyto_n );
} elseif( count( $replyto ) == 1 ) {
$replyto_e = $submits[ $replyto[0] ];
$mail->AddReplyTo( $replyto_e );
}
}
foreach( $recipients as $recipient ) {
$mail->AddAddress( $recipient['email'] , $recipient['name'] );
}
$unsets = array( 'prefix', 'subject', 'replyto', 'message', $prefix . 'botcheck', 'g-recaptcha-response', 'force_recaptcha', $prefix . 'submit' );
foreach( $unsets as $unset ) {
unset( $submits[ $unset ] );
}
$fields = array();
foreach( $submits as $name => $value ) {
if( empty( $value ) ) continue;
$name = str_replace( $prefix , '', $name );
$name = ucwords( str_replace( '-', ' ', $name ) );
if( is_array( $value ) ) {
$value = implode( ', ', $value );
}
$fields[$name] = $value;
}
$response = array();
foreach( $fields as $fieldname => $fieldvalue ) {
$response[] = $fieldname . ': ' . $fieldvalue;
}
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = implode( "<br>", $response ) . $referrer;
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
if( $autores && !empty( $replyto_e ) ) {
$send_arEmail = $autoresponder->Send();
}
echo '{ "alert": "success", "message": "' . $message['success'] . '" }';
else:
echo '{ "alert": "error", "message": "' . $message['error'] . '<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "' . $message['error_unexpected'] . '" }';
}
?>
Not sure why it won't send, here is what I tried? Any advise? (And I removed my password from the code)
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
// If you intend you use SMTP, uncomment next line
require 'phpmailer/src/SMTP.php';
// Set the recipient email address here
$recipients = array();
$recipients[] = array(
'email' => 'borstweston#gmail.com',
'name' => 'Weston'
);
// Set the sender email address here
$sender = array(
'email' => 'borstweston#gmail.com',
'name' => 'Weston'
);
// reCaptcha Secret Key - Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = '';
// PHPMailer Initialization
$mail = new PHPMailer();
// If you intend you use SMTP, add your SMTP Code after this Line
$mail->IsSMTP(); // enable SMTP
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com.";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "borstweston#gmail.com";
$mail->Password = "";
$mail->SetFrom("borstweston#gmail.com");
$mail->Subject = "";
$mail->Body ="";
$mail->AddAddress($sendTo);
// End of SMTP
// Form Messages
$message = array(
'success' => 'Thank you for your message. It has been sent.',
'error' => 'There was an error trying to send your message. Please try again later.',
'error_bot' => 'Bot Detected! Message could not be send. Please try again.',
'error_unexpected' => 'There was an unexpected error trying to send your message. Please try again later.',
'recaptcha_invalid' => 'Captcha not Validated! Please Try Again.',
'recaptcha_error' => 'Captcha not Submitted! Please Try Again.'
);
// Form Processor
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$prefix = !empty( $_POST['prefix'] ) ? $_POST['prefix'] : '';
$submits = $_POST;
$botpassed = false;
$message_form = !empty( $submits['message'] ) ? $submits['message'] : array();
$message['success'] = !empty( $message_form['success'] ) ? $message_form['success'] : $message['success'];
$message['error'] = !empty( $message_form['error'] ) ? $message_form['error'] : $message['error'];
$message['error_bot'] = !empty( $message_form['error_bot'] ) ? $message_form['error_bot'] : $message['error_bot'];
$message['error_unexpected'] = !empty( $message_form['error_unexpected'] ) ? $message_form['error_unexpected'] : $message['error_unexpected'];
$message['recaptcha_invalid'] = !empty( $message_form['recaptcha_invalid'] ) ? $message_form['recaptcha_invalid'] : $message['recaptcha_invalid'];
$message['recaptcha_error'] = !empty( $message_form['recaptcha_error'] ) ? $message_form['recaptcha_error'] : $message['recaptcha_error'];
// Bot Protection
if( isset( $submits[ $prefix . 'botcheck' ] ) ) {
$botpassed = true;
}
if( !empty( $submits[ $prefix . 'botcheck' ] ) ) {
$botpassed = false;
}
if( $botpassed == false ) {
echo '{ "alert": "error", "message": "' . $message['error_bot'] . '" }';
exit;
}
// reCaptcha
if( isset( $submits['g-recaptcha-response'] ) ) {
$recaptcha_data = array(
'secret' => $recaptcha_secret,
'response' => $submits['g-recaptcha-response']
);
$rc_verify = curl_init();
curl_setopt( $rc_verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify" );
curl_setopt( $rc_verify, CURLOPT_POST, true );
curl_setopt( $rc_verify, CURLOPT_POSTFIELDS, http_build_query( $recaptcha_data ) );
curl_setopt( $rc_verify, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $rc_verify, CURLOPT_RETURNTRANSFER, true );
$rc_response = curl_exec( $rc_verify );
$g_response = json_decode( $rc_response );
if ( $g_response->success !== true ) {
echo '{ "alert": "error", "message": "' . $message['recaptcha_invalid'] . '" }';
exit;
}
}
$html_title = !empty( $submits['html_title'] ) ? $submits['html_title'] : 'Form Response';
$forcerecaptcha = ( !empty( $submits['force_recaptcha'] ) && $submits['force_recaptcha'] != 'false' ) ? true : false;
$replyto = !empty( $submits['replyto'] ) ? explode( ',', $submits['replyto'] ) : false;
if( $forcerecaptcha ) {
if( !isset( $submits['g-recaptcha-response'] ) ) {
echo '{ "alert": "error", "message": "' . $message['recaptcha_error'] . '" }';
exit;
}
}
$mail->Subject = !empty( $submits['subject'] ) ? $submits['subject'] : 'Form response from your website';
$mail->SetFrom( $sender['email'] , $sender['name'] );
if( !empty( $replyto ) ) {
if( count( $replyto ) > 1 ) {
$replyto_e = $submits[ $replyto[0] ];
$replyto_n = $submits[ $replyto[1] ];
$mail->AddReplyTo( $replyto_e , $replyto_n );
} elseif( count( $replyto ) == 1 ) {
$replyto_e = $submits[ $replyto[0] ];
$mail->AddReplyTo( $replyto_e );
}
}
foreach( $recipients as $recipient ) {
$mail->AddAddress( $recipient['email'] , $recipient['name'] );
}
$unsets = array( 'prefix', 'subject', 'replyto', 'message', $prefix . 'botcheck', 'g-recaptcha-response', 'force_recaptcha', $prefix . 'submit' );
foreach( $unsets as $unset ) {
unset( $submits[ $unset ] );
}
$fields = array();
foreach( $submits as $name => $value ) {
if( empty( $value ) ) continue;
$name = str_replace( $prefix , '', $name );
$name = ucwords( str_replace( '-', ' ', $name ) );
if( is_array( $value ) ) {
$value = implode( ', ', $value );
}
$fields[$name] = $value;
}
$response = array();
foreach( $fields as $fieldname => $fieldvalue ) {
$response[] = $fieldname . ': ' . $fieldvalue;
}
$referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';
$body = implode( "<br>", $response ) . $referrer;
$mail->MsgHTML( $body );
$sendEmail = $mail->Send();
if( $sendEmail == true ):
if( $autores && !empty( $replyto_e ) ) {
$send_arEmail = $autoresponder->Send();
}
echo '{ "alert": "success", "message": "' . $message['success'] . '" }';
else:
echo '{ "alert": "error", "message": "' . $message['error'] . '<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo . '" }';
endif;
} else {
echo '{ "alert": "error", "message": "' . $message['error_unexpected'] . '" }';
}
?>
If you fill everything correctly this should work. (I have tried it)
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
try {
$mail->IsSMTP(); // enable SMTP
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "Your Email Address";
$mail->Password = "Your Password";
$mail->SetFrom("From Name");
$mail->Subject = "Message Subject";
$mail->Body ="Message Body ";
$mail->AddAddress('Sent email to this address');
if($mail->Send()) {
// e-posta başarılı ile gönderildi
echo 'success';
} else {
echo 'error';
}
} catch (Exception $e) {
echo 'error : '.$e;
}
if not please share the error message you are getting.
I managed to get the info needed to create sequential number for CF7 through https://www.banna360.com/contact-from7-dynamic-number-generation/
function wpcf7_generate_rand_number( $wpcf7_data ) {
$properties = $wpcf7_data->get_properties();
$shortcode = '[rand-generator]';
$mail = $properties['mail']['body'];
$mail_2 = $properties['mail_2']['body'];
$subject = $properties['mail']['subject'];
$subject2 = $properties['mail_2']['subject'];
if( preg_match( "/{$shortcode}/", $mail ) || preg_match( "/[{$shortcode}]/", $mail_2 ) ) {
$option = 'wpcf7sg_' . $wpcf7_data->id();
$sequence_number = (int)get_option( $option ) + 1;
update_option( $option, $sequence_number );
$properties['mail']['body'] = str_replace( $shortcode, $sequence_number, $mail );
$properties['mail_2']['body'] = str_replace( $shortcode, $sequence_number, $mail_2 );
$properties['mail']['subject'] = str_replace( $shortcode, $sequence_number, $subject );
$properties['mail_2']['subject'] = str_replace( $shortcode, $sequence_number, $subject2 );
$wpcf7_data->set_properties( $properties );
}
}
add_action( 'wpcf7_before_send_mail', 'wpcf7_generate_rand_number' );
However, I need to specify a start number (eg. 1000001) instead of just starting from 1. Any idea how I do that with this code?
Thanks!
$sequence_number = (int)get_option( $option ) + 1;
if ($sequence_number == 1) {
$sequence_number = 1000001;
}
update_option( $option, $sequence_number );
After lots of efforts we found something for IPB remote login, but it's not working correctly. We are able to fetch member information but not able to set this member in session.
Please help us to the set session for IPB.
Here is the code:
remote_login.php
<?php
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
$path = '';
require_once $path . 'init.php';
\IPS\Session\Front::i();
$key = md5( md5( \IPS\Settings::i()->sql_user . \IPS\Settings::i()->sql_pass ) . \IPS\Settings::i()->board_start );
$login_type = 'email';
/* uncomment for more security */
// $ip_address = array('127.0.0.1', 'x.x.x.x'); // EDIT THIS LINE!!
// if(in_array($_SERVER['REMOTE_ADDR'], $ip_address) !== TRUE) {
// echo_json(array('status' => 'FAILD', 'msg' => 'BAD_IP_ADDR'));
// }
/* -~-~-~-~-~-~ Stop Editing -~-~-~-~-~-~ */
if( !\IPS\Request::i()->do || !\IPS\Request::i()->id || !\IPS\Request::i()->key || !\IPS\Login::compareHashes( \IPS\Request::i()->key, md5($key . \IPS\Request::i()->id))) {
echo_json(array('status' => 'FAILD', 'msg' => 'BAD_KEY'));
}
$member = \IPS\Member::load( \IPS\Request::i()->id, $login_type );
if( !$member->member_id ) {
echo_json(array('status' => 'FAILD', 'msg' => 'ACCOUNT_NOT_FOUND'));
}
switch(\IPS\Request::i()->do) {
case 'get_salt':
echo_json(array('status' => 'SUCCESS', 'pass_salt' => $member->members_pass_salt));
break;
case 'login':
if( \IPS\Login::compareHashes($member->members_pass_hash, \IPS\Request::i()->password) === TRUE ) {
/* Remove old failed login attempts */
if ( \IPS\Settings::i()->ipb_bruteforce_period and ( \IPS\Settings::i()->ipb_bruteforce_unlock or !isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) or $member->failed_logins[ \IPS\Request::i()->ipAddress() ] < \IPS\Settings::i()->ipb_bruteforce_attempts ) )
{
$removeLoginsOlderThan = \IPS\DateTime::create()->sub( new \DateInterval( 'PT' . \IPS\Settings::i()->ipb_bruteforce_period . 'M' ) );
$failedLogins = $member->failed_logins;
if ( is_array( $failedLogins ) )
{
foreach ( $failedLogins as $ipAddress => $times )
{
foreach ( $times as $k => $v )
{
if ( $v < $removeLoginsOlderThan->getTimestamp() )
{
unset( $failedLogins[ $ipAddress ][ $k ] );
}
}
}
$member->failed_logins = $failedLogins;
}
else
{
$member->failed_logins = array();
}
$member->save();
}
/* If we're still here, the login was fine, so we can reset the count and process login */
if ( isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) )
{
$failedLogins = $member->failed_logins;
unset( $failedLogins[ \IPS\Request::i()->ipAddress() ] );
$member->failed_logins = $failedLogins;
}
$member->last_visit = time();
$member->save();
/*==========================try to set session code start================*/
/* Create a unique session key and redirect */
\IPS\Session::i()->setMember( $member );
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P7D' ) );
\IPS\Request::i()->setCookie( 'member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'pass_hash', $member->member_login_key, $expire );
if ( $anonymous and !\IPS\Settings::i()->disable_anonymous )
{
\IPS\Request::i()->setCookie( 'anon_login', 1, $expire );
}
\IPS\Session::i()->setMember( $member );
\IPS\Session::i()->init();
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );
/*$member->checkLoginKey();
$expire = new \IPS\DateTime;
$expire->add( new \DateInterval( 'P1Y' ) );
\IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire );
\IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );*/
/*==========================try to set session code end================*/
echo_json(
array(
'status' => 'SUCCESS',
'connect_status' => ( $member->members_bitoptions['validating'] ) ? 'VALIDATING' : 'SUCCESS',
'email' => $member->email,
'name' => $member->name,
'connect_id' => $member->member_id,
'member' =>$member
)
);
}
break;
}
function echo_json(array $arr) {
echo json_encode($arr);
exit;
}
login.php
<?php
$ips_connect_key = '3325a51154becfc88fXXXXXXXXX';
$remote_login = 'IPB/remote_login.php';
$email = $_GET['email'];
$password = $_GET['password'];
$key = md5($ips_connect_key . $email);
// fetch salt first
$res = json_decode(file_get_contents($remote_login . "?do=get_salt&id={$email}&key={$key}"), true);
$hash = crypt( $password, '$2a$13$' . $res['pass_salt'] );
$res = json_decode(file_get_contents($remote_login . "?do=login&id={$email}&key={$key}&password={$hash}"), true);
$_COOKIE["ips4_member_id"]=41;
$_COOKIE['ips4_pass_hash']="e195d3939b62342481dfc32fcf360538";
$_COOKIE['ips4_IPSSessionFront']="sn359rogbto4j7jqhcqh10stl5";
print_r($res);
echo "<br/><br/><br/>";
print_r($_COOKIE);
calling login.php
login.php?email=XXXXX#gmail.com&password=XXXXXX!
Here we are able to get member information but not able to set that member as logged in.