Skip to content

Commit

Permalink
Merge pull request #32 from qteab/mailchimp
Browse files Browse the repository at this point in the history
add support for different audience_ids, FNAME, LNAME
  • Loading branch information
noaholsson authored Jun 26, 2023
2 parents 9a8f275 + 6e969e6 commit 17abcc4
Showing 1 changed file with 87 additions and 65 deletions.
152 changes: 87 additions & 65 deletions classes/Controllers/RestController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,20 @@

use DrewM\MailChimp\MailChimp;

if ( ! defined( 'ABSPATH' ) ) {
if (!defined('ABSPATH')) {
exit;
}

class RestController extends \WP_REST_Controller {
class RestController extends \WP_REST_Controller
{


// The namespace and version for the REST SERVER
public $qterest_namespace = 'qte/v';
public $qterest_version = '1';

public function register_routes() {
public function register_routes()
{

$namespace = $this->qterest_namespace . $this->qterest_version;

Expand All @@ -41,7 +43,7 @@ public function register_routes() {
array(
array(
'methods' => 'POST',
'callback' => array( $this, 'handle_contact' ),
'callback' => array($this, 'handle_contact'),
'permission_callback' => '__return_true',
),
)
Expand All @@ -53,50 +55,52 @@ public function register_routes() {
array(
array(
'methods' => 'POST',
'callback' => array( $this, 'handle_mailchimp_add_subscriber' ),
'callback' => array($this, 'handle_mailchimp_add_subscriber'),
'permission_callback' => '__return_true',
),
)
);
}

// Register our REST Server
public function hook_rest_server() {
add_action( 'rest_api_init', array( $this, 'register_routes' ) );
public function hook_rest_server()
{
add_action('rest_api_init', array($this, 'register_routes'));
}

public function handle_contact( \WP_REST_Request $request ) {
public function handle_contact(\WP_REST_Request $request)
{

$messages = array(
'name_empty' => get_translated_string( 'Name cannot be empty!' ),
'email_empty' => get_translated_string( 'Email cannot be empty!' ),
'email_invalid' => get_translated_string( 'Email is not valid!' ),
'invalid_recaptcha' => get_translated_string( 'Invalid reCAPTCHA!' ),
'failed' => get_translated_string( 'Something went wrong. Please try again later!' ),
'success' => get_translated_string( 'Thank you! We will contact you as fast as we can!' ),
'mail_subject' => get_translated_string( 'New contact request!' ),
'mail_body' => get_translated_string( '<p>New contact request is available. Click the link below to access it</p><br>{LINK}' ),
'name_empty' => get_translated_string('Name cannot be empty!'),
'email_empty' => get_translated_string('Email cannot be empty!'),
'email_invalid' => get_translated_string('Email is not valid!'),
'invalid_recaptcha' => get_translated_string('Invalid reCAPTCHA!'),
'failed' => get_translated_string('Something went wrong. Please try again later!'),
'success' => get_translated_string('Thank you! We will contact you as fast as we can!'),
'mail_subject' => get_translated_string('New contact request!'),
'mail_body' => get_translated_string('<p>New contact request is available. Click the link below to access it</p><br>{LINK}'),
'mail_to' => maybe_get_notification_email(),
);

$params = $request->get_content_type()['subtype'] === 'json' ? $request->get_json_params() : $request->get_body_params(); // Get contact request params
$params = SanitizeParams::sanitizeParams( $params );
$params = SanitizeParams::sanitizeParams($params);

/**
* Applys a filter to change the messages from for example a theme
*/
$messages = apply_filters( 'qterest_contact_messages', $messages, $params );
$messages = apply_filters('qterest_contact_messages', $messages, $params);

/**
* Get options for qterest
*/
$options = get_option( 'qterest_options' );
$options = get_option('qterest_options');

/**
* Maybe validate reCaptcha
*/
if ( is_recaptcha_enabled() && isset( $params['g-recaptcha-response'] ) ) {
if ( ! Recaptcha::make( $options[ Options::RECAPTCHA_SECRET_KEY ], new Client() )->validateResponse( $params['g-recaptcha-response'] ) ) {
if (is_recaptcha_enabled() && isset($params['g-recaptcha-response'])) {
if (!Recaptcha::make($options[Options::RECAPTCHA_SECRET_KEY], new Client())->validateResponse($params['g-recaptcha-response'])) {
return array(
'success' => false,
'error_msg' => $messages['invalid_recaptcha'],
Expand All @@ -107,7 +111,7 @@ public function handle_contact( \WP_REST_Request $request ) {
/**
* Checks that email isn't empty
*/
if ( empty( $params['email'] ) ) {
if (empty($params['email'])) {
return array(
'success' => false,
'error_msg' => $messages['email_empty'],
Expand All @@ -117,7 +121,7 @@ public function handle_contact( \WP_REST_Request $request ) {
/**
* Checks if email is valid
*/
if ( ! validate_email( $params['email'] ) ) {
if (!validate_email($params['email'])) {
return array(
'success' => false,
'error_msg' => $messages['email_invalid'],
Expand All @@ -126,43 +130,43 @@ public function handle_contact( \WP_REST_Request $request ) {

$post_id = wp_insert_post(
array(
'post_title' => $params['email'] . ' - ' . date( 'Y-m-d H:m:s' ),
'post_title' => $params['email'] . ' - ' . date('Y-m-d H:m:s'),
'post_type' => 'contact_requests',
'post_status' => 'publish',
'exclude_from_searcg' => true,
'show_in_rest' => false,
'meta_input' => array(
'request_content' => serialize( $params ),
'request_content' => serialize($params),
),
)
);

/**
* Checks if request got inserted
*/
if ( is_wp_error( $post_id ) ) {
if (is_wp_error($post_id)) {
return array(
'success' => false,
'error_msg' => $messages['failed'],
);
}

if ( $_FILES ) {
$attachment_ids = FileHandler::make( $post_id )->handleAllFiles();
if ($_FILES) {
$attachment_ids = FileHandler::make($post_id)->handleAllFiles();

$errors = array_filter(
$attachment_ids,
function ( $attachment_id ) {
return is_wp_error( $attachment_id );
function ($attachment_id) {
return is_wp_error($attachment_id);
}
);

if ( $errors ) {
if ($errors) {
return array(
'success' => false,
'error_msg' => $messages['failed'],
'error_data' => array_map(
function( $error ) {
function ($error) {
/** @var \WP_Error $error */
return $error->get_error_messages();
},
Expand All @@ -175,29 +179,36 @@ function( $error ) {
/**
* This hook can be used to change the post that was just inserted
*/
do_action( 'qterest_after_post_insertion', $post_id, $params );
do_action('qterest_after_post_insertion', $post_id, $params);

/**
* Gets and inserts the clients ip address
*/
update_post_meta( $post_id, 'request_ip_address', get_client_ip() );
update_post_meta($post_id, 'request_ip_address', get_client_ip());

$link = site_url( "wp-admin/post.php?post=$post_id&action=edit" );
$link = site_url("wp-admin/post.php?post=$post_id&action=edit");

$to = apply_filters( 'qterest_contact_mail_to', $messages['mail_to'], $params, $post_id );
$subject = apply_filters( 'qterest_contact_mail_subject', $messages['mail_subject'], $params, $post_id );
$body = apply_filters( 'qterest_contact_mail_body', $messages['mail_body'], $params );
$body = \preg_replace( '#{LINK}#', "<a href=\"$link\">$link</a>", $body );
$headers = apply_filters( 'qterest_contact_mail_headers', array( 'Content-Type: text/html; charset=UTF-8' ), $params, $post_id );
$attachments = apply_filters( 'qterest_contact_mail_attachments', array(), $attachment_ids ?? array(), $post_id );
$to = apply_filters('qterest_contact_mail_to', $messages['mail_to'], $params, $post_id);
$subject = apply_filters('qterest_contact_mail_subject', $messages['mail_subject'], $params, $post_id);
$body = apply_filters('qterest_contact_mail_body', $messages['mail_body'], $params);
$body = \preg_replace('#{LINK}#', "<a href=\"$link\">$link</a>", $body);
$headers = apply_filters('qterest_contact_mail_headers', array('Content-Type: text/html; charset=UTF-8'), $params, $post_id);
$attachments = apply_filters('qterest_contact_mail_attachments', array(), $attachment_ids ?? array(), $post_id);

/**
* This hook can be used to manipulate the mail
*/
do_action( 'qterest_contact_before_send_mail', $to, $subject, $body, $headers, $attachments );
do_action('qterest_contact_before_send_mail', $to, $subject, $body, $headers, $attachments);

if ( $to != null ) {
wp_mail( $to, $subject, $body, $headers, $attachments );
if ($to != null) {
wp_mail($to, $subject, $body, $headers, $attachments);
}

// Remove attachments after mail
if (apply_filters('qterest_contact_remove_attachments_after_request', false, $params, $post_id) == true) {
foreach ($attachment_ids as $attachment_id) {
wp_delete_attachment($attachment_id, true);
}
}

// Remove attachments after mail
Expand All @@ -213,31 +224,38 @@ function( $error ) {
);
}

public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
public function handle_mailchimp_add_subscriber(\WP_REST_Request $request)
{

$messages = array(
'invalid_api_key' => get_translated_string( 'Invalid MailChimp API key!' ),
'email_empty' => get_translated_string( 'Email cannot be empty!' ),
'email_invalid' => get_translated_string( 'Email is not valid!' ),
'invalid_recaptcha' => get_translated_string( 'Invalid reCAPTCHA!' ),
'failed' => get_translated_string( 'Something went wrong. Please try again later!' ),
'success' => get_translated_string( 'Thank you for subscribing to our newsletter!' ),
'invalid_api_key' => get_translated_string('Invalid MailChimp API key!'),
'email_empty' => get_translated_string('Email cannot be empty!'),
'email_invalid' => get_translated_string('Email is not valid!'),
'invalid_recaptcha' => get_translated_string('Invalid reCAPTCHA!'),
'failed' => get_translated_string('Something went wrong. Please try again later!'),
'success' => get_translated_string('Thank you for subscribing to our newsletter!'),
);

/**
* Applys a filter to change the messages from for example a theme
*/
$messages = apply_filters( 'qterest_mailchimp_messages', $messages );
$messages = apply_filters('qterest_mailchimp_messages', $messages);

$params = $request->get_content_type()['subtype'] === 'json' ? $request->get_json_params() : $request->get_body_params(); // Get mailchimp request params

/**
* Get options for qterest
*/
$options = get_option( 'qterest_options' );
$options = get_option('qterest_options');

$mailchimpMailListID = $options['qterest_field_mailchimp_mail_list'];

if ( is_recaptcha_enabled() && isset( $params['g-recaptcha-response'] ) ) {
if ( ! Recaptcha::make( $options[ Options::RECAPTCHA_SECRET_KEY ], new Client() )->validateResponse( $params['g-recaptcha-response'] ) ) {
if (isset($params['audience_id'])) {
$mailchimpMailListID = $params['audience_id'];
}

if (is_recaptcha_enabled() && isset($params['g-recaptcha-response'])) {
if (!Recaptcha::make($options[Options::RECAPTCHA_SECRET_KEY], new Client())->validateResponse($params['g-recaptcha-response'])) {
return array(
'success' => false,
'error_msg' => $messages['invalid_recaptcha'],
Expand All @@ -248,7 +266,7 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
/**
* Check if email is not empty
*/
if ( ! isset( $params['email'] ) && empty( $params['email'] ) ) {
if (!isset($params['email']) && empty($params['email'])) {
return array(
'success' => false,
'error_msg' => $messages['email_empty'],
Expand All @@ -258,7 +276,7 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
/**
* Check if email is valid
*/
if ( ! validate_email( $params['email'] ) ) {
if (!validate_email($params['email'])) {
return array(
'success' => false,
'error_msg' => $messages['email_invalid'],
Expand All @@ -268,7 +286,7 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
/**
* Check if MailChimp API key is valid
*/
if ( ! mailchimp_api_key_is_valid() ) {
if (!mailchimp_api_key_is_valid()) {
return array(
'success' => false,
'error_msg' => $messages['invalid_api_key'],
Expand All @@ -279,8 +297,8 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
* Try catch in case it throws exceptions
*/
try {
$MailChimp = new MailChimp( $options['qterest_field_mailchimp_api_key'] );
} catch ( \Exception $e ) {
$MailChimp = new MailChimp($options['qterest_field_mailchimp_api_key']);
} catch (\Exception $e) {
return array(
'success' => false,
'error_msg' => $e->getMessage(),
Expand All @@ -291,19 +309,23 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
* Add subscriber to MailChimp list
*/
$repsonse = $MailChimp->post(
"/lists/$options[qterest_field_mailchimp_mail_list]/members",
"/lists/$mailchimpMailListID/members",
array(
'email_address' => $params['email'],
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $params['firstName'] ?? '',
'LNAME' => $params['lastName'] ?? '',
),
)
);

/**
* Check if already subscribed and if subscribed make sure that the status is subscribed
*/
if ( $member_exists = $repsonse['title'] == 'Member Exists' ) {
if ($member_exists = $repsonse['title'] == 'Member Exists') {
$repsonse = $MailChimp->put(
"/lists/$options[qterest_field_mailchimp_mail_list]/members/" . $MailChimp->subscriberHash( $params['email'] ),
"/lists/$mailchimpMailListID/members/" . $MailChimp->subscriberHash($params['email']),
array(
'status' => 'subscribed',
)
Expand All @@ -313,7 +335,7 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
/**
* Check if user added or updated
*/
if ( ! isset( $repsonse['id'] ) ) {
if (!isset($repsonse['id'])) {
return array(
'success' => false,
'error_msg' => $messages['failed'],
Expand All @@ -323,7 +345,7 @@ public function handle_mailchimp_add_subscriber( \WP_REST_Request $request ) {
/**
* Hook to do stuff when a new subscriber is added.
*/
do_action( 'qterest_mailchimp_subscriber_added', $params['email'], $member_exists );
do_action('qterest_mailchimp_subscriber_added', $params['email'], $member_exists);

return array(
'success' => true,
Expand Down

0 comments on commit 17abcc4

Please sign in to comment.