Skip to content

Instantly share code, notes, and snippets.

@wpmudev-sls
Last active November 7, 2019 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/8163b31ec5bf8bfc69a8359c7c2bc7f4 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/8163b31ec5bf8bfc69a8359c7c2bc7f4 to your computer and use it in GitHub Desktop.
Forminator] - Add Mailchimp Tags to existing entry emails
<?php
/**
* Plugin Name: [Forminator] - Add Mailchimp Tags to existing entry emails
* Plugin URI: https://premium.wpmudev.org/
* Description: Adds Mailchimp Tag to entrys using a specified email field
* Author: Panos Lyrakis @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WPMUDEV_Forminator_Add_MailChimp_Tags' ) ) {
class WPMUDEV_Forminator_Add_MailChimp_Tags {
public $email_field = 'email-1';
private $limit = 3;
private $api_key = null;
private $endpoint = 'https://<dc>.api.mailchimp.com/3.0/';
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Forminator_Add_MailChimp_Tags();
}
return self::$_instance;
}
private function __construct() {
add_action( 'admin_menu', array( $this, 'admin_menu' ), 999 );
add_action( 'wp_ajax_wpmudev_add_ms_tag', array( $this, 'maybe_add_tag' ) );
}
public function maybe_add_tag() {
$current_key = filter_input( INPUT_POST, 'current_key', FILTER_VALIDATE_INT );
$form_id = filter_input( INPUT_POST, 'form_id', FILTER_VALIDATE_INT );
$list_id = filter_input( INPUT_POST, 'list_id', FILTER_DEFAULT );
$segment_id = filter_input( INPUT_POST, 'tag', FILTER_DEFAULT );
$offset = ( $current_key * (int) $this->limit );
$content = '';
$emails = $this->get_entries_emails( $form_id, $this->limit, $offset );
if ( empty( $emails ) ) {
$return = array(
'success' => true,
'content' => "All emails checked!",
'completed' => true
);
wp_send_json($return);
}
$this->prepare_api_data();
$args = array(
'verb' => 'POST', //'PATCH',
'list_id' => $list_id,
'action' => "/lists/{$list_id}/segments/{$segment_id}/members",
);
foreach ( $emails as $email ) {
$bg_color = "rgba(85, 239, 196, 0.8)";
$message = "Tag was added succesfully";
$md5_email = md5( strtolower( $email ) );
$body = array(
'apikey' => $this->api_key,
'email_address' => $email
);
$response = $this->mc_request( $args, $body );
if ( $response->code != 200 ) {
$bg_color = "rgba(255, 118, 117, 0.6)";
$message = "Tag could not be added";
}
$content .= "<tr style=\"background-color:{$bg_color}\"><td>{$email}</td><td>{$message}</td></tr>";
}
$return = array(
'success' => true,
'content' => $content,
'completed' => false
);
wp_send_json($return);
}
public function get_entries_emails( $form_id, $limit, $offset ) {
global $wpdb;
$emails = array();
$table_name = Forminator_Database_Tables::get_table_name( Forminator_Database_Tables::FORM_ENTRY );
$meta_table_name = Forminator_Database_Tables::get_table_name( Forminator_Database_Tables::FORM_ENTRY_META );
$sql = "SELECT m.meta_value FROM {$table_name} as e
LEFT JOIN $meta_table_name as m on e.entry_id = m.entry_id
WHERE e.form_id = %d AND e.is_spam = 0 AND m.meta_key='%s'
ORDER BY e.entry_id DESC
LIMIT %d OFFSET %d";
$sql = $wpdb->prepare( $sql, $form_id, $this->email_field, $limit, $offset );
$results = $wpdb->get_results( $sql, ARRAY_A );
if ( ! empty( $results ) ) {
$emails = array_column( $results, 'meta_value' );
}
return $emails;
}
private function list_forms(){
$forms = Forminator_Custom_Form_Model::model()->get_models( 99 );
if ( empty( $forms ) ) {
return '<h4>No forms found</h4>';
}
$out = "<ul>";
foreach ( $forms as $form ) {
$form_id = $form->id;
$form_name = $form->settings['formName'];
$link = add_query_arg( 'form_id', $form_id );
$out .= "<li>";
$out .= "<a href=\"{$link}\">{$form_name}</a>";
$out .= "</li>";
}
$out .= "</ul>";
return $out;
}
// Gets MC TAGS for form
private function get_form_segments( $form_id ) {
$form_data = (object) get_post_meta( $form_id, 'forminator_addon_mailchimp_form_settings', true );
if ( ! property_exists( $form_data, 'mail_list_id' ) ) {
return "
<div style=\"width:100; text-align: center;\">
<div class=\"notice notice-warning\">
<p>No MailChimp list has been set for form <strong>{$form_id}</strong></p>
</div>
</div>
";
}
$mailing_list_name = $form_data->mail_list_name;
$args = array(
'verb' => 'GET', //'GET',
'list_id' => $form_data->mail_list_id,
'action' => "lists/{$form_data->mail_list_id}/segments"
);
$response = $this->mc_request( $args );
if ( ! isset( $response->body ) ) {
return;
}
$segments_list = json_decode( $response->body );
if ( empty( $segments_list->segments ) ) {
return "
<div style=\"width:100; text-align: center;\">
<div class=\"notice notice-warning\">
<p>No tags have been found for MailChimp list <strong>{$mailing_list_name}</strong></p>
</div>
</div>
";
}
$out = "<div style=\"width: 100%; text-align:center;\">";
$out .= "<h3>Choose one of the tags bellow to add to all existing entries</h3>";
$out .= '<ul>';
foreach ( $segments_list->segments as $segment ) {
$link = add_query_arg( 'segment_id', $segment->id );
$out .= "<li>";
$out .= "<a class=\"add-mc-tag-btn\" data-segment=\"{$segment->id}\" href=\"{$link}\">{$segment->name}</a>";
$out .= "</li>";
}
$out .= '</ul>';
$out .= '</div>';
$out .= "<div id=\"results-report\"><table id=\"results-report-list\" class=\"wp-list-table widefat fixed\"></table></div>";
$out .= "<input type=\"hidden\" id=\"add-tags-form-id\" value=\"{$form_id}\" >";
$out .= "<input type=\"hidden\" id=\"add-tags-list-id\" value=\"{$form_data->mail_list_id}\" >";
$out .= $this->segments_list_js();
return $out;
}
public function segments_list_js() {
ob_start();
?>
<script type="text/javascript">
(($,d)=>{
const WPMUDEV_Add_MC_Tag = {
nonce: '<?php echo wp_create_nonce( "wpmudev_add_ms_tag" ); ?>',
form_id : $( '#add-tags-form-id' ).val(),
list_id : $( '#add-tags-list-id' ).val(),
results_output : $( '#results-report' ),
results_table: $( '#results-report-list' ),
current_key : 0,
run : function( tag ){
let data = {
action: 'wpmudev_add_ms_tag',
form_id : WPMUDEV_Add_MC_Tag.form_id,
security: WPMUDEV_Add_MC_Tag.nonce,
current_key: WPMUDEV_Add_MC_Tag.current_key,
tag: tag,
list_id : WPMUDEV_Add_MC_Tag.list_id
} ;
$.post( ajaxurl, data, function( response ) {
if( response.success ){
WPMUDEV_Add_MC_Tag.results_table.prepend( response.content );
WPMUDEV_Add_MC_Tag.current_key ++;
if ( ! response.completed ) {
WPMUDEV_Add_MC_Tag.run( tag );
} else {
WPMUDEV_Add_MC_Tag.results_output.prepend( $( '<h3 />', {text: "All entries have tag added!"} ) );
}
} else{
WPMUDEV_Add_MC_Tag.results_table.prepend( response.content );
}
});
}
}
$(d).ready( function(){
$( '.add-mc-tag-btn' ).on( 'click', function( e ){
e.preventDefault();
var tag = $( this ).data( 'segment' );
WPMUDEV_Add_MC_Tag.run( tag )
} );
} );
})(jQuery,document);
</script>
<?php
return ob_get_clean();
}
public function mc_request( $_args, $body = array() ) {
if ( ! isset( $_args[ 'verb' ] ) || ! isset( $_args[ 'list_id' ] ) || ! isset( $_args[ 'action' ] ) ) {
return false;
}
extract( $_args );
$url = trailingslashit( $this->endpoint ) . $action;
$args = array(
"method" => $verb,
"headers" => array(
'Authorization' => 'apikey '. $this->api_key,
'Content-Type' => 'application/json;charset=utf-8'
//'X-Trigger-Error' => 'APIKeyMissing',
),
"body" => wp_json_encode( $body )
);
$response = wp_remote_request( $url, $args );
$return = array(
'body' => wp_remote_retrieve_body( $response ),
'code' => wp_remote_retrieve_response_code( $response ),
'headers' => wp_remote_retrieve_headers( $response )
);
return (object) $return;
}
public function admin_menu() {
add_submenu_page(
'forminator',
'Add MailChimp Tags',
'Add MailChimp Tags',
'manage_options',
'forminator-add-mc-tags',
array( $this, 'admin_page_display' )
);
}
public function admin_page_display() {
if ( ! isset( $_GET[ 'form_id' ] ) || ! is_numeric( $_GET[ 'form_id' ] ) ) {
?>
<div style="width:100; text-align: center;">
<div class="notice notice-warning is-dismissible">
<p>You haven't set a form yet. Please choose from one bellow</p>
</div>
<h3>Choose a form</h3>
<?php print ($this->list_forms() ); ?>
</div>
<?php
return;
}
$form_id = intval( $_GET[ 'form_id' ] );
$this->prepare_api_data();
print( $this->get_form_segments( $form_id ) );
}
private function prepare_api_data() {
$options = get_option( 'forminator_addon_mailchimp_settings' );
$this->api_key = $options[ 'api_key' ];
$data_center = explode( '-', $this->api_key )[1];
$this->endpoint = str_replace( '<dc>', $data_center, $this->endpoint );
}
}
if ( ! function_exists( 'wpmudev_forminator_add_mailchimp_tags' ) ) {
function wpmudev_forminator_add_mailchimp_tags() {
return WPMUDEV_Forminator_Add_MailChimp_Tags::get_instance();
};
add_action( 'plugins_loaded', 'wpmudev_forminator_add_mailchimp_tags', 10 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment