Commit inicial - WordPress Análisis de Precios Unitarios

- WordPress core y plugins
- Tema Twenty Twenty-Four configurado
- Plugin allow-unfiltered-html.php simplificado
- .gitignore configurado para excluir wp-config.php y uploads

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-11-03 21:04:30 -06:00
commit a22573bf0b
24068 changed files with 4993111 additions and 0 deletions

View File

@@ -0,0 +1,364 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
add_action( 'admin_menu', 'tve_dash_api_admin_menu', 20 );
add_action( 'admin_enqueue_scripts', 'tve_dash_api_admin_scripts' );
add_action( 'admin_notices', 'tve_dash_api_admin_notices', 9 );
add_action( 'wp_ajax_tve_dash_api_form_retry', 'tve_dash_api_form_retry' );
add_action( 'wp_ajax_tve_dash_api_delete_log', 'tve_dash_api_delete_log' );
if ( wp_doing_ajax() ) {
add_action( 'wp_ajax_tve_dash_api_handle_save', 'tve_dash_api_handle_save' );
add_action( 'wp_ajax_tve_dash_api_handle_redirect', 'tve_dash_api_api_handle_redirect' );
} else {
add_action( 'admin_init', 'tve_dash_api_handle_save' );
}
/*
* TTW API Videos URLs
*/
if ( is_admin() ) {
add_action( 'current_screen', 'tve_api_video_urls' );
}
/**
* Run on dash api connect screen
* Build transient from TTW API with videos URLs
*/
function tve_api_video_urls() {
if ( tve_get_current_screen_key() === 'admin_page_tve_dash_api_connect' ) {
require_once __DIR__ . '/classes/ApiVideos.php';
$api_videos = new ApiVideos();
}
}
/**
* FILTERS
*/
add_filter( 'tve_dash_localize', 'tve_dash_api_filter_localize' );
add_filter( 'tve_dash_include_ui', 'tve_dash_api_filter_ui_hooks' );
function tve_dash_api_admin_menu() {
remove_submenu_page( 'thrive_admin_options', 'thrive_font_manager' );
add_submenu_page( '', __( 'API Connections', 'thrive-dash' ), __( 'API Connections', 'thrive-dash' ), TVE_DASH_CAPABILITY, 'tve_dash_api_connect', 'tve_dash_api_connect' );
add_submenu_page( '', __( 'API Connections Error Log', 'thrive-dash' ), __( 'API Connections Error Log', 'thrive-dash' ), TVE_DASH_CAPABILITY, 'tve_dash_api_error_log', 'tve_dash_api_error_log' );
}
/**
* check for any expired connections (expired access tokens), or tokens that are about to expire and display global warnings / error messages
*/
function tve_dash_api_admin_notices() {
if ( tve_get_current_screen_key( 'base' ) === 'admin_page_tve_dash_api_connect' ) {
return;
}
require_once __DIR__ . '/misc.php';
$connected_apis = Thrive_Dash_List_Manager::get_available_apis( true );
$warnings = array();
foreach ( $connected_apis as $api_instance ) {
if ( ! $api_instance instanceof Thrive_Dash_List_Connection_Abstract || $api_instance->param( '_nd' ) ) {
continue;
}
$warnings = array_merge( $warnings, $api_instance->get_warnings() );
}
$nonce = sprintf( '<span class="nonce" style="display:none">%s</span>', wp_create_nonce( 'tve_api_dismiss' ) );
$template = '<div class="%s notice is-dismissible tve-api-notice"><p>%s</p>%s</div>';
$html = '';
foreach ( $warnings as $err ) {
$html .= sprintf( $template, 'error', $err, $nonce );
}
echo $html; // phpcs:ignore
}
/**
* main entry point
*/
function tve_dash_api_connect() {
require_once __DIR__ . '/misc.php';
$available_apis = Thrive_Dash_List_Manager::get_available_apis();
foreach ( $available_apis as $key => $api ) {
/** @var Thrive_Dash_List_Connection_Abstract $api */
if ( $api->is_connected() || $api->is_related() ) {
unset( $available_apis[ $key ] );
}
}
$connected_apis = Thrive_Dash_List_Manager::get_available_apis( true );
foreach ( $connected_apis as $key => $api ) {
if ( ! $api instanceof Thrive_Dash_List_Connection_Abstract || $api->is_related() ) {
unset( $connected_apis[ $key ] );
}
}
$api_types = Thrive_Dash_List_Manager::$API_TYPES;
$api_types = apply_filters( 'tve_filter_api_types', $api_types );
$types = array();
foreach ( $api_types as $type => $label ) {
$types[] = array(
'type' => $type,
'label' => $label,
);
}
Thrive_Dash_List_Manager::flash_messages();
include __DIR__ . '/views/admin-list.php';
}
/**
* check to see if we currently need to save some credentials, early in the admin section (e.g. a redirect from Oauth)
*/
function tve_dash_api_handle_save() {
if ( ! current_user_can( TVE_DASH_CAPABILITY ) ) {
wp_die( '' );
}
require_once __DIR__ . '/misc.php';
$is_google_drive_response = ! empty( $_REQUEST['state'] ) && strpos( sanitize_text_field( $_REQUEST['state'] ), 'connection_google_drive' ) === 0;
$is_constant_contact_v3_response = ! empty( $_REQUEST['state'] ) && strpos( sanitize_text_field( $_REQUEST['state'] ), 'connection_constant_contact_v3' ) === 0;
/**
* either a POST from a regular form, or an oauth redirect
*/
if (
( ( ! $is_google_drive_response && empty( $_REQUEST['api'] ) && empty( $_REQUEST['oauth_token'] ) && empty( $_REQUEST['disconnect'] ) )
&& ( ( ! $is_constant_contact_v3_response && empty( $_REQUEST['api'] ) && empty( $_REQUEST['oauth_token'] ) && empty( $_REQUEST['disconnect'] ) ) ) )
) {
return;
}
if ( $is_google_drive_response ) {
$api = 'google_drive';
} elseif ( $is_constant_contact_v3_response ) {
$api = 'constantcontact_v3';
} else {
$api = sanitize_text_field( $_REQUEST['api'] );
}
$doing_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
$connection = Thrive_Dash_List_Manager::connection_instance( $api );
if ( is_null( $connection ) ) {
return;
}
$response = array(
'success' => false,
'message' => __( 'Unknown error occurred', 'thrive-dash' ),
);
if ( ! empty( $_REQUEST['disconnect'] ) ) {
$connection->disconnect()->success( $connection->get_title() . ' ' . __( 'is now disconnected', 'thrive-dash' ) );
//delete active conection for thrive ovation
$active_connection = get_option( 'tvo_api_delivery_service', false );
if ( $active_connection && $active_connection == $api ) {
delete_option( 'tvo_api_delivery_service' );
}
tve_dash_remove_api_from_one_click_signups( $api );
$response['success'] = true;
$response['message'] = __( 'Service disconnected', 'thrive-dash' );
} elseif ( ! empty( $_REQUEST['test'] ) ) {
$result = $connection->test_connection();
if ( is_array( $result ) && isset( $result['success'] ) && ! empty( $result['message'] ) ) {
$response = $result;
} else {
$response['success'] = is_string( $result ) ? false : $result;
$response['message'] = $response['success'] ? __( 'Connection works', 'thrive-dash' ) : __( 'Connection Error', 'thrive-dash' );
}
} else {
$saved = $connection->read_credentials();
$response['success'] = $saved === true;
$response['message'] = $saved === true ? __( 'Connection established', 'thrive-dash' ) : $saved;
}
/* Check if we need to upgrade an api */
if ( ! empty( $_REQUEST['api'] ) ) {
$upgraded_key = $_REQUEST['api'] . '-upgraded';
if ( ! empty( $_REQUEST[ $upgraded_key ] ) && $_REQUEST[ $upgraded_key ] === '1' && method_exists( $connection, 'upgrade' ) ) {
$response = $connection->upgrade();
}
}
if ( $doing_ajax ) {
exit( json_encode( $response ) );
}
$admin_url = admin_url( 'admin.php?page=tve_dash_api_connect' );
if ( $response['success'] !== true ) {
update_option( 'tve_dash_api_error', $response['message'] );
wp_redirect( $admin_url . '#failed/' . $api );
exit;
}
wp_redirect( $admin_url . '#done/' . $api );
exit();
}
/**
* Handles the creation of the authorization URL and redirection to that url for token generation purposes
*/
function tve_dash_api_api_handle_redirect() {
if ( ! current_user_can( TVE_DASH_CAPABILITY ) ) {
wp_die( '' );
}
if ( empty( $_REQUEST['api'] ) && empty( $_REQUEST['oauth_token'] ) && empty( $_REQUEST['disconnect'] ) ) {
return;
}
$doing_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX;
require_once __DIR__ . '/misc.php';
$connection = Thrive_Dash_List_Manager::connection_instance( sanitize_text_field( $_REQUEST['api'] ) );
if ( is_null( $connection ) ) {
return;
}
$response = array(
'success' => false,
'message' => __( 'Unknown error occurred', 'thrive-dash' ),
);
$credentials = ! empty( $_POST['connection'] ) ? map_deep( $_POST['connection'], 'sanitize_text_field' ) : array();
$connection->set_credentials( $credentials );
$result = $connection->getAuthorizeUrl();
$response['success'] = ! ( ( filter_var( $result, FILTER_VALIDATE_URL ) ) === false );
$response['message'] = ! $response['success'] ? 'An unknown error has occurred' : $result;
if ( $doing_ajax ) {
exit( json_encode( $response ) );
}
wp_redirect( admin_url( 'admin.php?page=tve_dash_api_connect' ) . '#failed/' . sanitize_text_field( $_REQUEST['api'] ) );
exit();
}
/**
* Enqueue specific scripts for api connections page
*
* @param string $hook
*/
function tve_dash_api_admin_scripts( $hook ) {
$accepted_hooks = array(
'admin_page_tve_dash_api_connect',
'admin_page_tve_dash_api_error_log',
);
if ( ! in_array( $hook, $accepted_hooks ) ) {
return;
}
if ( $hook === 'admin_page_tve_dash_api_error_log' ) {
tve_dash_enqueue_script(
'tve-dash-api-admin-logs',
TVE_DASH_URL . '/inc/auto-responder/dist/admin-logs-list.min.js',
array(
'tve-dash-main-js',
'jquery',
'backbone',
)
);
return;
}
/**
* global admin JS file for notifications
*/
tve_dash_enqueue_script(
'tve-dash-api-admin-global',
TVE_DASH_URL . '/inc/auto-responder/dist/admin-global.min.js',
array(
'tve-dash-main-js',
'jquery',
'backbone',
)
);
$api_response = array(
'message' => get_option( 'tve_dash_api_error' ),
);
if ( ! empty( $api_response['message'] ) ) {
wp_localize_script( 'tve-dash-api-admin-global', 'tve_dash_api_error', $api_response );
delete_option( 'tve_dash_api_error' );
}
}
/**
* for now, just a dump of the error logs from the table
*/
function tve_dash_api_error_log() {
include plugin_dir_path( __FILE__ ) . 'views/admin-error-logs.php';
}
/**
* hide notices for a specific API connection
*/
function tve_dash_api_hide_notice() {
if ( ! empty( $_POST['nonce'] ) && ! wp_verify_nonce( sanitize_text_field( $_POST['nonce'] ), 'tve_api_dismiss' ) ) {
exit( '-1' );
}
$key = ! empty( $_POST['key'] ) ? sanitize_text_field( $_POST['key'] ) : '';
require_once __DIR__ . '/misc.php';
$connection = Thrive_Dash_List_Manager::connection_instance( $key );
$connection->set_param( '_nd', 1 )->save();
exit( '1' );
}
/**
* remove api connection from one click signups (new name: Signup Segue)
*/
function tve_dash_remove_api_from_one_click_signups( $api_name ) {
$one_click_signups = get_posts( array( 'post_type' => 'tve_lead_1c_signup' ) );
foreach ( $one_click_signups as $item ) {
$connections = get_post_meta( $item->ID, 'tve_leads_api_connections', true );
foreach ( $connections as $j => $connection ) {
if ( $connection['apiName'] == $api_name ) {
unset( $connections[ $j ] );
}
}
update_post_meta( $item->ID, 'tve_leads_api_connections', $connections );
}
}
function tve_dash_api_filter_localize( $localize ) {
$localize['actions']['api_handle_save'] = 'tve_dash_api_handle_save';
$localize['actions']['api_handle_redirect'] = 'tve_dash_api_handle_redirect';
return $localize;
}
function tve_dash_api_filter_ui_hooks( $hooks ) {
//this hook includes the general scripts from dash
//$hooks[] = 'admin_page_tve_dash_api_error_log';
return $hooks;
}

View File

@@ -0,0 +1,12 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
require_once( dirname( __FILE__ ) . '/admin.php' );

View File

@@ -0,0 +1,210 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class ApiVideos {
/**
* @var string
*/
private $_ttw_api_url_transient = 'ttw_api_urls';
/**
* @var string
*/
private $_ttw_url;
/**
* Transient lifetime [1 day in seconds]
*
* @var int
*/
protected $_cache_life_time = 86400;
/**
* Used for obfuscation
*
* @var array
*/
private $_randomize
= array(
'a' => 'F',
'b' => 'g',
'c' => 'R',
'd' => '6j',
'e' => 'k9t',
'f' => '#U',
'g' => 'x',
'h' => 'E',
'i' => '_',
'j' => '6',
'k' => '^',
'l' => 'Y',
'm' => '7hI',
'n' => 'm',
'o' => 'pI',
'u' => '5',
'1' => '2W7',
'2' => 'g',
'9' => 'T',
'5' => '3',
':' => 'p',
'/' => 'u',
't' => 'I',
'p' => 'o',
'x' => 'a',
'y' => 'e',
'z' => 'i',
'w' => 'u',
'6' => 'h',
'U' => 't',
'89' => '/',
);
/**
* Used in case of TTW API call failed [/api_videos endpoint]
*
* @var array
*/
private $_fallback_urls
= array(
'mailchimp' => 'ndkVpoJCffU',
'aweber' => 'lBybVnifWw4',
'getresponse' => 'G0IMbKP1Otw',
'mailpoet' => 'bkVO6nqyClA',
'wordpress' => 'KMqwr6OT3DA',
'ontraport' => '6AwBXF8w85o',
'everwebinar' => 'Oy7AutRjWHE',
'icontact' => 'sjWGb3UdvN4',
'convertkit' => 'nPDX_a7_pAM',
'activecampaign' => 'z27CqJQtrvQ',
'sendy' => 'jHP6u3rqoF0',
'drip' => 'MnujttxYH-M',
'constantcontact' => 'a1y_GJcUwO4',
'madmimi' => 'OXQzK9uSzsA',
'webinarjamstudio' => 'y7Rz0l794DE',
'gotowebinar' => '2NkRXez97p0',
'hubspot' => 'gqjp4-hTJdc',
'postmark' => 'k8l-KeObrwk',
'infusionsoft' => 'Ak4tLh29aC4',
'recaptcha' => '4LM0cIIhOVA',
'sparkpost' => 'HCsuzWcYq4I',
'mailgun' => 'DBNW6hGWYyc',
'awsses' => 'eC35eUXqlHw',
'mailerlite' => 'OKigVCbG0YE',
'campaignmonitor' => 'wbPX2bXUNxA',
'facebook' => 'jR4tBDEuwE4',
'google' => 'YZ2eeWBJQ5w',
'twitter' => '9_pkwfTrTPc',
'mailrelay' => 'gLlRZ1wdIjM',
'sendgrid' => 'sLfWAgEE_fo',
'sendinblue' => 'tZ8Pp7WJnzk',
'sgautorepondeur' => 'N3zqX5dprUc',
'sendlane' => 'aqtKcGSJaog',
'google_drive' => 'LNCiLKxo7V4',
'dropbox' => '-zYbSNvp2JQ',
'fluentcrm' => 'AFfuQrv--S4',
'slack' => 'IeRaTyBLu9s',
'sendowl' => 'cN1UGZ3Vblo',
'zapier' => 'iD2-RsTflPU',
'sendfox' => 'VOQCwapziqs',
'zoho' => '50j3THWW7sQ',
'klicktipp' => 'MBzZNteFSz4',
);
/**
* ApiVideos constructor.
*/
public function __construct() {
// URLs based on env
$this->_set_urls();
// Check and set api videos URLs transient and call TTW API for them
$this->_check_videos_transient();
}
/**
* URLs setter
*/
private function _set_urls() {
$this->_ttw_url = esc_url( defined( 'THRV_ENV' ) && is_string( THRV_ENV ) ? THRV_ENV : 'https://thrivethemes.com' );
}
/**
* Obfuscation
*
* @param $string
* @param bool $flip
*
* @return string
*/
protected function _obfuscate( $string, $flip = false ) {
if ( $flip ) {
$this->_randomize = array_flip( $this->_randomize );
}
return (string) str_replace( array_keys( $this->_randomize ), $this->_randomize, $string );
}
/**
* @return bool
*/
protected function _build_videos_transient() {
$headers = array(
'Content-Type' => 'application/json',
'website' => get_site_url(),
'tpm' => 'no',
);
$tpm_data = get_option( 'tpm_connection', array() );
// Build auth header for users with TPM [token received from TTW API]
if ( ! empty( $tpm_data ) && ! empty( $tpm_data['ttw_salt'] ) ) {
$headers['Authorization'] = $tpm_data['ttw_salt'];
$headers['userid'] = ! empty( $tpm_data['ttw_id'] ) ? $tpm_data['ttw_id'] : '';
$headers['tpm'] = 'yes';
}
// Build auth header for users without TPM
if ( empty( $headers['Authorization'] ) ) {
$headers['Authorization'] = $this->_obfuscate( get_site_url() );
$headers['userid'] = $this->_obfuscate( get_site_url() . md5( date( 'Y-m-d' ) ), true );
}
$args = array(
'headers' => $headers,
'sslverify' => false,
'timeout' => 20,
);
$request = wp_remote_get( $this->_ttw_url . '/api/v1/public/api_videos', $args );
$body = json_decode( wp_remote_retrieve_body( $request ) );
return set_transient( $this->_ttw_api_url_transient, (array) $this->_fallback_urls, $this->_cache_life_time );
}
/**
* Verify is transient is set or set it
*/
protected function _check_videos_transient() {
$video_urls_transient = get_transient( $this->_ttw_api_url_transient );
if ( ! $video_urls_transient ) {
$this->_build_videos_transient();
}
}
}

View File

@@ -0,0 +1,673 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_AWeber extends Thrive_Dash_List_Connection_Abstract {
const APP_ID = '10fd90de';
const CONSUMER_KEY = 'AkkjPM2epMfahWNUW92Mk2tl';
const CONSUMER_SECRET = 'V9bzMop78pXTlPEAo30hxZF7dXYE6T6Ww2LAH95m';
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
/**
* get the authorization URL for the AWeber Application
*
* @return string
*/
public function getAuthorizeUrl() {
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
$callback_url = admin_url( 'admin.php?page=tve_dash_api_connect&api=aweber' );
list ( $request_token, $request_token_secret ) = $aweber->getRequestToken( $callback_url );
update_option( 'thrive_aweber_rts', $request_token_secret );
return $aweber->getAuthorizeUrl();
}
/**
* @return bool|void
*/
public function is_connected() {
return $this->param( 'token' ) && $this->param( 'secret' );
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'AWeber';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'aweber' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
$aweber->user->tokenSecret = get_option( 'thrive_aweber_rts' );
$aweber->user->requestToken = ! empty( $_REQUEST['oauth_token'] ) ? sanitize_text_field( $_REQUEST['oauth_token'] ) : '';
$aweber->user->verifier = ! empty( $_REQUEST['oauth_verifier'] ) ? sanitize_text_field( $_REQUEST['oauth_verifier'] ) : '';
try {
list( $accessToken, $accessTokenSecret ) = $aweber->getAccessToken();
$this->set_credentials( array(
'token' => $accessToken,
'secret' => $accessTokenSecret,
) );
} catch ( Exception $e ) {
$this->error( $e->getMessage() );
return false;
}
$result = $this->test_connection();
if ( $result !== true ) {
$this->error( sprintf( __( 'Could not test AWeber connection: %s', 'thrive-dash' ), $result ) );
return false;
}
$this->save();
/**
* Fetch all custom fields on connect so that we have them all prepared
* - TAr doesn't need to fetch them from API
*/
$this->get_api_custom_fields( array(), true, true );
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
try {
$aweber->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_AWeber( self::CONSUMER_KEY, self::CONSUMER_SECRET );
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
try {
$lists = array();
$account = $aweber->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
foreach ( $account->lists as $item ) {
/** @var Thrive_Dash_Api_AWeber_Entry $item */
$lists [] = array(
'id' => $item->data['id'],
'name' => $item->data['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* add a contact to a list
*
* @param $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
$account = $aweber->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
$listURL = "/accounts/{$account->id}/lists/{$list_identifier}";
$list = $account->loadFromUrl( $listURL );
# create a subscriber
$params = array(
'email' => $arguments['email'],
'ip_address' => tve_dash_get_ip(),
);
if ( ! empty( $arguments['name'] ) ) {
$params['name'] = $arguments['name'];
}
if ( isset( $arguments['url'] ) ) {
$params['custom_fields']['Web Form URL'] = $arguments['url'];
}
// create custom fields
$custom_fields = $list->custom_fields;
try {
$custom_fields->create( array( 'name' => 'Web Form URL' ) );
} catch ( Exception $e ) {
}
if ( ! empty( $arguments['phone'] ) && ( $phone_field_name = $this->phoneCustomFieldExists( $list ) ) ) {
$params['custom_fields'][ $phone_field_name ] = $arguments['phone'];
}
if ( ! empty( $arguments['aweber_tags'] ) ) {
$params['tags'] = explode( ',', trim( $arguments['aweber_tags'], ' ,' ) );
$params['tags'] = array_map( 'trim', $params['tags'] );
}
if ( ( $existing_subscribers = $list->subscribers->find( array( 'email' => $params['email'] ) ) ) && $existing_subscribers->count() === 1 ) {
$subscriber = $existing_subscribers->current();
if ( ! empty( $arguments['name'] ) ) {
$subscriber->name = $params['name'];
}
if ( ! empty( $params['custom_fields'] ) ) {
$subscriber->custom_fields = $params['custom_fields'];
}
if ( empty( $params['tags'] ) || ! is_array( $params['tags'] ) ) {
$params['tags'] = array();
}
$tags = array_values( array_diff( $params['tags'], $subscriber->tags->getData() ) );
if ( ! empty( $tags ) ) {
$subscriber->tags = array(
'add' => $tags,
);
}
$new_subscriber = $subscriber->save() == 209;
} else {
$new_subscriber = $list->subscribers->create( $params );
}
if ( ! $new_subscriber ) {
return sprintf( __( "Could not add contact: %s to list: %s", 'thrive-dash' ), $arguments['email'], $list->name );
}
// Update custom fields
// Make another call to update custom mapped fields in order not to break the subscription call,
// if custom data doesn't pass API custom fields validation
$mapping = thrive_safe_unserialize( base64_decode( isset( $arguments['tve_mapping'] ) ? $arguments['tve_mapping'] : '' ) );
if ( ! empty( $mapping ) || ! empty( $arguments['automator_custom_fields'] ) ) {
$this->updateCustomFields( $list_identifier, $arguments, $params );
}
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
protected function phoneCustomFieldExists( $list ) {
$customFieldsURL = $list->custom_fields_collection_link;
$customFields = $list->loadFromUrl( $customFieldsURL );
foreach ( $customFields as $custom ) {
if ( stripos( $custom->name, 'phone' ) !== false ) {
//return the name of the phone custom field cos users can set its name as: Phone/phone/pHone/etc
//used in custom_fields for subscribers parameters
/** @see add_subscriber */
return $custom->name;
}
}
return false;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function get_extra_settings( $params = array() ) {
return $params;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function render_extra_editor_settings( $params = array() ) {
$this->output_controls_html( 'aweber/tags', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{!email}';
}
/**
* @param array $params which may contain `list_id`
* @param bool $force make a call to API and invalidate cache
* @param bool $get_all where to get lists with their custom fields
*
* @return array
*/
public function get_api_custom_fields( $params, $force = false, $get_all = true ) {
$lists = $this->get_all_custom_fields( $force );
// Get custom fields for all list ids [used on localize in TAr]
if ( true === $get_all ) {
return $lists;
}
$list_id = isset( $params['list_id'] ) ? $params['list_id'] : null;
if ( '0' === $list_id ) {
$list_id = current( array_keys( $lists ) );
}
return array( $list_id => $lists[ $list_id ] );
}
/**
* Get all custom fields by list id
*
* @param $force calls the API and invalidate cache
*
* @return array|mixed
*/
public function get_all_custom_fields( $force ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_fields = array();
$lists = $this->_get_lists();
if ( is_array( $lists ) ) {
foreach ( $lists as $list ) {
if ( empty( $list['id'] ) ) {
continue;
}
$custom_fields[ $list['id'] ] = $this->getCustomFieldsByListId( $list['id'] );
}
}
$this->_save_custom_fields( $custom_fields );
return $custom_fields;
}
/**
* Get custom fields by list id
*
* @param $list_id
*
* @return array
*/
public function getCustomFieldsByListId( $list_id ) {
$fields = array();
if ( empty( $list_id ) ) {
return $fields;
}
try {
$account = $this->get_api()->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
$list_url = "/accounts/{$account->id}/lists/{$list_id}";
$list_obj = $account->loadFromUrl( $list_url );
// CF obj
$custom_fields_url = $list_obj->custom_fields_collection_link;
$custom_fields = $list_obj->loadFromUrl( $custom_fields_url );
foreach ( $custom_fields as $custom_field ) {
if ( ! empty( $custom_field->data['name'] ) && ! empty( $custom_field->data['id'] ) ) {
$fields[] = $this->_normalize_custom_field( $custom_field->data );
}
}
} catch ( Thrive_Dash_Api_AWeber_Exception $e ) {
}
return $fields;
}
/**
* Normalize custom field data
*
* @param $field
*
* @return array
*/
protected function _normalize_custom_field( $field ) {
$field = (array) $field;
return array(
'id' => isset( $field['id'] ) ? $field['id'] : '',
'name' => ! empty( $field['name'] ) ? $field['name'] : '',
'type' => '', // API does not have type
'label' => ! empty( $field['name'] ) ? $field['name'] : '',
);
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
}
/**
* Call the API in order to update subscriber's custom fields
*
* @param $list_identifier
* @param $arguments
* @param $data
*
* @return bool
*/
public function updateCustomFields( $list_identifier, $arguments, $data ) {
if ( ! $list_identifier || empty( $arguments ) || empty( $data['email'] ) ) {
return false;
}
$saved = false;
/** @var Thrive_Dash_Api_AWeber $aweber */
$aweber = $this->get_api();
$account = $aweber->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
$list_url = "/accounts/{$account->id}/lists/{$list_identifier}";
$list = $account->loadFromUrl( $list_url );
if ( empty( $arguments['automator_custom_fields'] ) ) {
$custom_fields = $this->buildMappedCustomFields( $list_identifier, $arguments );
} else {
$custom_fields = $arguments['automator_custom_fields'];
}
$existing_subscribers = $list->subscribers->find( array( 'email' => $data['email'] ) );
if ( $existing_subscribers && $existing_subscribers->count() === 1 && ! empty( $custom_fields ) ) {
$subscriber = $existing_subscribers->current();
$subscriber->custom_fields = $custom_fields;
$saved = $subscriber->save();
}
if ( ! $saved ) {
$this->api_log_error( $list_identifier, $custom_fields, __( 'Could not update custom fields', 'thrive-dash' ) );
}
return $saved;
}
/**
* Creates and prepare the mapping data from the subscription form
*
* @param $list_identifier
* @param $args
* @param array $custom_fields
*
* @return array
*/
public function buildMappedCustomFields( $list_identifier, $args, $custom_fields = array() ) {
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $custom_fields;
}
$mapped_form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
if ( is_array( $mapped_form_data ) && $list_identifier ) {
$api_custom_fields = $this->buildCustomFieldsList();
// Loop trough allowed custom fields names
foreach ( $this->get_mapped_field_ids() as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from the form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $mapped_form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $mapped_form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$args[ $cf_form_name ] = $this->process_field( $args[ $cf_form_name ] );
$mapped_form_field_id = $mapped_form_data[ $cf_form_name ][ $this->_key ];
$field_label = $api_custom_fields[ $list_identifier ][ $mapped_form_field_id ];
$cf_form_name = str_replace( '[]', '', $cf_form_name );
if ( ! empty( $args[ $cf_form_name ] ) ) {
$args[ $cf_form_name ] = $this->process_field( $args[ $cf_form_name ] );
$custom_fields[ $field_label ] = sanitize_text_field( $args[ $cf_form_name ] );
}
}
}
}
}
return $custom_fields;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = array();
if ( $automation_data['mailing_list'] ) {
$api_custom_fields = $this->buildCustomFieldsList();
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
$field_label = $api_custom_fields[ $automation_data['mailing_list'] ][ $pair['key'] ];
$mapped_data[ $field_label ] = $value;
}
}
}
return $mapped_data;
}
/**
* Create a simpler structure with [list_id] => [ field_id => field_name]
*
* @return array
*/
public function buildCustomFieldsList() {
$parsed = array();
foreach ( $this->get_all_custom_fields( false ) as $list_id => $merge_field ) {
array_map(
function ( $var ) use ( &$parsed, $list_id ) {
$parsed[ $list_id ][ $var['id'] ] = $var['name'];
},
$merge_field
);
}
return $parsed;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return false|int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_AWeber $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$this->add_subscriber( $list_id, $args );
$account = $api->getAccount( $this->param( 'token' ), $this->param( 'secret' ) );
$list_url = "/accounts/{$account->id}/lists/{$list_id}";
$list = $account->loadFromUrl( $list_url );
$existing_subscribers = $list->subscribers->find( array( 'email' => $email ) );
if ( $existing_subscribers && $existing_subscribers->count() === 1 ) {
$subscriber = $existing_subscribers->current();
$prepared_fields = $this->prepare_custom_fields_for_api( $custom_fields, $list_id );
$subscriber->custom_fields = array_merge( $subscriber->data['custom_fields'], $prepared_fields );
$subscriber->save();
return $subscriber->id;
}
} catch ( Exception $e ) {
return false;
}
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
protected function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
if ( empty( $list_identifier ) ) { // list identifier required here
return array();
}
$api_fields = $this->get_api_custom_fields( array( 'list_id' => $list_identifier ), true );
if ( empty( $api_fields[ $list_identifier ] ) ) {
return array();
}
$prepared_fields = array();
foreach ( $api_fields[ $list_identifier ] as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( (int) $field['id'] === (int) $key && $custom_field ) {
$prepared_fields[ $field['name'] ] = $custom_field;
unset( $custom_fields[ $key ] ); // avoid unnecessary loops
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list' => array( 'api_fields' ), 'tag_input' => array() ) );
}
public function get_automator_tag_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'tag_input' ) );
}
public function has_custom_fields() {
return true;
}
}

View File

@@ -0,0 +1,646 @@
<?php /** @noinspection ALL */
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_ActiveCampaign extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'ActiveCampaign';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
public function has_custom_fields() {
return true;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'activecampaign' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$api_url = ! empty( $_POST['connection']['api_url'] ) ? sanitize_text_field( $_POST['connection']['api_url'] ) : '';
$api_key = ! empty( $_POST['connection']['api_key'] ) ? sanitize_text_field( $_POST['connection']['api_key'] ) : '';
if ( empty( $api_key ) || empty( $api_url ) || empty( $_POST['connection'] ) ) {
return $this->error( __( 'Both API URL and API Key fields are required', 'thrive-dash' ) );
}
$this->set_credentials( compact( 'api_url', 'api_key' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to ActiveCampaign using the provided details. Response was: <strong>%s</strong>', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Fetch all custom fields on connect so that we have them all prepared
* - TAr doesn't need to get them from API
*/
$this->get_api_custom_fields( array(), true, true );
return $this->success( __( 'ActiveCampaign connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_ActiveCampaign $api */
$api = $this->get_api();
try {
$api->call( 'account_view', array() );
return true;
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
$api_url = $this->param( 'api_url' );
$api_key = $this->param( 'api_key' );
return new Thrive_Dash_Api_ActiveCampaign( $api_url, $api_key );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
try {
$raw = $this->get_api()->getLists();
$lists = array();
foreach ( $raw as $list ) {
$lists [] = array(
'id' => $list['id'],
'name' => $list['name'],
);
}
return $lists;
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
$this->_error = $e->getMessage();
return false;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* get all Subscriber Forms from this API service
*
* @return array|bool for error
*/
protected function _get_forms() {
try {
$raw = $this->get_api()->get_forms();
$forms = array();
$lists = $this->get_lists();
foreach ( $lists as $list ) {
$forms[ $list['id'] ][0] = array(
'id' => 0,
'name' => __( 'none', 'thrive-dash' ),
);
}
foreach ( $raw as $form ) {
foreach ( $form['lists'] as $list_id ) {
if ( empty( $forms[ $list_id ] ) ) {
$forms[ $list_id ] = array();
}
/**
* for some reason, I've seen an instance where forms were duplicated (2 or more of the same form were displayed in the list)
*/
$forms[ $list_id ][ $form['id'] ] = array(
'id' => $form['id'],
'name' => $form['name'],
);
}
}
return $forms;
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
$this->_error = $e->getMessage();
return false;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* delete a contact from the list
*
* @param string $email
* @param array $arguments
*
* @return mixed
*/
public function delete_subscriber( $email, $arguments = array() ) {
$api = $this->get_api();
$contact = $api->call( 'contact_view_email', array( 'email' => $email ) );
if ( isset( $contact['result_code'] ) && $contact['result_code'] == 1 ) {
$body = array( 'id' => $contact['id'] );
$result = $api->call( 'contact_delete', $body, array() );
return isset( $result['result_code'] ) && $result['result_code'] == 1;
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_ActiveCampaign $api */
$api = $this->get_api();
$name_array = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$name_array = array(
'firstname' => $first_name,
'lastName' => $last_name,
);
}
// Get contact
try {
$contact = $api->call( 'contact_view_email', array( 'email' => $arguments['email'] ) );
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
$update = false;
if ( isset( $contact['result_code'] ) && $contact['result_code'] == 1 ) {
foreach ( $contact['lists'] as $list ) {
if ( $list['listid'] == $list_identifier ) {
$update = true;
}
}
}
// Prepared args for passing to subscribe/update methods
$prepared_args = array(
'email' => ! empty( $arguments['email'] ) ? sanitize_email( $arguments['email'] ) : '',
'phone' => empty( $arguments['phone'] ) ? '' : sanitize_text_field( $arguments['phone'] ),
'form_id' => empty( $arguments['activecampaign_form'] ) ? 0 : sanitize_text_field( $arguments['activecampaign_form'] ),
'organizationName' => '',
'tags' => ! empty( $arguments['activecampaign_tags'] ) ? trim( $arguments['activecampaign_tags'], ',' ) : '',
'ip' => null,
);
$prepared_args = array_merge( $prepared_args, $name_array );
// Add or update subscriber
try {
/**
* Try to add/update contact on a single api call so linkted automation will be properly triggered
*/
if ( ! empty( $arguments['tve_mapping'] ) ) {
$prepared_args['custom_fields'] = $this->buildMappedCustomFields( $arguments );
} else if ( ! empty( $arguments['automator_custom_fields'] ) ) {
$prepared_args['custom_fields'] = $arguments['automator_custom_fields'];
}
if ( isset( $contact['result_code'] ) && ( empty( $contact['result_code'] ) || false === $update ) ) {
$api->add_subscriber( $list_identifier, $prepared_args );
} else {
$prepared_args['contact'] = $contact;
$api->updateSubscriber( $list_identifier, $prepared_args );
}
$return = true;
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
$return = $e->getMessage();
} catch ( Exception $e ) {
$return = $e->getMessage();
}
/**
* Add/update action failed so we try again by doing two separate requests
* one for add/update contact and another one for updating custom fields
*/
if ( true !== $return ) {
try {
if ( isset( $contact['result_code'] ) && ( empty( $contact['result_code'] ) || false === $update ) ) {
$api->add_subscriber( $list_identifier, $prepared_args );
} else {
$prepared_args['contact'] = $contact;
$api->updateSubscriber( $list_identifier, $prepared_args );
}
$return = true;
} catch ( Thrive_Dash_Api_ActiveCampaign_Exception $e ) {
$return = $e->getMessage();
} catch ( Exception $e ) {
$return = $e->getMessage();
}
// Update custom fields
// Make another call to update custom mapped fields in order not to break the subscription call,
// if custom data doesn't pass API custom fields validation
if ( true === $return && ! empty( $arguments['tve_mapping'] ) ) {
unset( $prepared_args['tags'] );
$this->updateCustomFields( $list_identifier, $arguments, $prepared_args );
}
}
return $return;
}
/**
* Update custom fields
*
* @param string|int $list_identifier
* @param array $arguments form data
* @param array $prepared_args prepared array for subscription
*
* @return bool|string
*/
public function updateCustomFields( $list_identifier, $arguments, $prepared_args ) {
if ( ! $list_identifier || empty( $arguments ) || empty( $prepared_args ) ) {
return false;
}
/** @var Thrive_Dash_Api_ActiveCampaign $api */
$api = $this->get_api();
try {
// Refresh the contact data for mapping custom fields
$prepared_args['contact'] = $api->call( 'contact_view_email', array( 'email' => $arguments['email'] ) );
// Build mapped fields array
$prepared_args['custom_fields'] = $this->buildMappedCustomFields( $arguments );
$api->updateSubscriber( $list_identifier, $prepared_args );
$return = true;
} catch ( Exception $e ) {
// Log api errors
$this->api_log_error( $list_identifier, $prepared_args, __METHOD__ . ': ' . $e->getMessage() );
$return = $e->getMessage();
}
return $return;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*
* @return array
*/
public function get_extra_settings( $params = array() ) {
$params['forms'] = $this->_get_forms();
if ( ! is_array( $params['forms'] ) ) {
$params['forms'] = array();
}
return $params;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function render_extra_editor_settings( $params = array() ) {
$params['forms'] = $this->_get_forms();
if ( ! is_array( $params['forms'] ) ) {
$params['forms'] = array();
}
$this->output_controls_html( 'activecampaign/forms-list', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '%EMAIL%';
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
return $this->get_all_custom_fields( $force );
}
/**
* @param (bool) $force
*
* @return array|mixed
*/
public function get_all_custom_fields( $force ) {
$custom_data = array();
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
// Needed custom fields type
$allowed_types = array(
'text',
'url',
'number',
'hidden',
);
// Build custom fields for every list
$custom_fields = $this->get_api()->getCustomFields();
if ( is_array( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
if ( ! empty( $field['type'] ) && in_array( $field['type'], $allowed_types, true ) && 1 === (int) $field['visible'] ) {
$custom_data[] = $this->normalize_custom_field( $field );
}
}
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* @param array $field
*
* @return array
*/
protected function normalize_custom_field( $field ) {
$field = (array) $field;
return array(
'id' => ! empty( $field['id'] ) ? $field['id'] : '',
'name' => ! empty( $field['perstag'] ) ? $field['perstag'] : '',
'type' => $field['type'],
'label' => ! empty( $field['title'] ) ? $field['title'] : '',
);
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function buildMappedCustomFields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
if ( is_array( $form_data ) ) {
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$mapped_api_id = $form_data[ $cf_form_name ][ $this->_key ];
$cf_form_name = str_replace( '[]', '', $cf_form_name );
if ( ! empty( $args[ $cf_form_name ] ) ) {
$args[ $cf_form_name ] = $this->process_field( $args[ $cf_form_name ] );
$mapped_data["field[{$mapped_api_id}, 0]"] = sanitize_text_field( $args[ $cf_form_name ] );
}
}
}
}
}
return $mapped_data;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = array();
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
$mapped_data["field[{$pair['key']}, 0]"] = $value;
}
}
return $mapped_data;
}
/**
* get relevant data from webhook trigger
*
* @param $request WP_REST_Request
*
* @return array
*/
public function get_webhook_data( $request ) {
$contact = $request->get_param( 'contact' );
return array( 'email' => empty( $contact['email'] ) ? '' : $contact['email'] );
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return false|int|mixed
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_ActiveCampaign $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$this->add_subscriber( $list_id, $args );
$args['contact'] = $api->call( 'contact_view_email', array( 'email' => $email ) );
$args['custom_fields'] = $this->prepare_custom_fields_for_api( $custom_fields );
$api->updateSubscriber( $list_id, $args );
return $args['contact']['id'];
} catch ( Exception $e ) {
return false;
}
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
protected function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
foreach ( $custom_fields as $key => $custom_field ) {
if ( $custom_field ) {
$prepared_fields["field[{$key}], 0"] = sanitize_text_field( $custom_field );
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list' => array( 'form_list' ), 'api_fields' => array(), 'tag_input' => array() ) );
}
public function get_custom_fields_by_list( $list = null ) {
return $this->get_available_custom_fields();
}
public function has_forms() {
return true;
}
}

View File

@@ -0,0 +1,337 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Awsses extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Amazon SES';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'awsses' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid Amazon Web Services Simple Email Service key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid Amazon Web Services Simple Email Service key', 'thrive-dash' ) );
}
$secretkey = ! empty( $_POST['connection']['secretkey'] ) ? sanitize_text_field( $_POST['connection']['secretkey'] ) : '';
if ( empty( $secretkey ) ) {
return $ajax_call ? __( 'You must provide a valid Amazon Web Services Simple Email Service secret key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid Amazon Web Services Simple Email Service secret key', 'thrive-dash' ) );
}
$email = ! empty( $_POST['connection']['email'] ) ? sanitize_email( $_POST['connection']['email'] ) : '';
if ( empty( $email ) ) {
return $ajax_call ? __( 'Email field must not be empty', 'thrive-dash' ) : $this->error( __( 'Email field must not be empty', 'thrive-dash' ) );
}
$country = ! empty( $_POST['connection']['country'] ) ? sanitize_text_field( $_POST['connection']['country'] ) : '';
$credentials = array(
'key' => $key,
'secretkey' => $secretkey,
'email' => $email,
'country' => $country,
);
$this->set_credentials( $credentials );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to Amazon Web Services Simple Email Service using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to Amazon Web Services Simple Email Service using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
$this->success( __( 'Amazon Web Services Simple Email Service connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$awsses = $this->get_api();
if ( isset( $_POST['connection']['email'] ) ) {
$from_email = sanitize_email( $_POST['connection']['email'] );
$to = sanitize_email( $_POST['connection']['email'] );
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'awsses' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
$to = $credentials['email'];
}
}
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads Amazon Web Services Simple Email Service API.';
$text_content = 'This is a test email from Thrive Leads Amazon Web Services Simple Email Service API.';
try {
$messsage = new Thrive_Dash_Api_Awsses_SimpleEmailServiceMessage();
$messsage->addTo( $to );
$messsage->setFrom( $from_email );
$messsage->setSubject( $subject );
$messsage->setMessageFromString( $text_content, $html_content );
$awsses->sendEmail( $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'awsses' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$awsses = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'awsses' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
try {
$messsage = new Thrive_Dash_Api_Awsses_SimpleEmailServiceMessage();
$messsage->addTo( $data['email'] );
$messsage->setFrom( $from_email );
$messsage->setSubject( $data['subject'] );
$messsage->setMessageFromString( empty ( $data['text_content'] ) ? '' : $data['text_content'], empty ( $data['html_content'] ) ? '' : $data['html_content'] );
$awsses->sendEmail( $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$awsses = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'awsses' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
if ( ! empty( $data['from_name'] ) ) {
$from_email = $data['from_name'] . ' < ' . $from_email . ' >';
}
try {
$message = new Thrive_Dash_Api_Awsses_SimpleEmailServiceMessage();
$message->addTo( $data['emails'] );
$message->setFrom( $from_email );
$message->setSubject( $data['subject'] );
$message->setMessageFromString( empty ( $data['text_content'] ) ? '' : $data['text_content'], empty ( $data['html_content'] ) ? '' : $data['html_content'] );
if ( ! empty( $data['reply_to'] ) ) {
$message->addReplyTo( $data['reply_to'] );
}
if ( ! empty( $data['cc'] ) ) {
$message->addCC( $data['cc'] );
}
if ( ! empty( $data['bcc'] ) ) {
$message->addBCC( $data['bcc'] );
}
$awsses->sendEmail( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$message = new Thrive_Dash_Api_Awsses_SimpleEmailServiceMessage();
$message->addTo( $data['sender_email'] );
$message->setFrom( $from_email );
$message->addReplyTo( $from_email );
$message->setSubject( $data['confirmation_subject'] );
$message->setMessageFromString( empty ( $data['confirmation_text'] ) ? '' : $data['confirmation_text'], empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'] );
$awsses->sendEmail( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$awsses = $this->get_api();
$credentials = $this->get_credentials();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = $credentials['email'];
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
} else {
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
}
$text_content = strip_tags( $html_content );
$messsage = new Thrive_Dash_Api_Awsses_SimpleEmailServiceMessage();
$messsage->addTo( $post_data['email'] );
$messsage->setFrom( $from_email );
$messsage->setSubject( $subject );
$messsage->setMessageFromString( $text_content, $html_content );
return $awsses->sendEmail( $messsage );
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
switch ( $this->param( 'country' ) ) {
case 'ireland':
$country = "email.eu-west-1.amazonaws.com";
break;
case 'useast':
$country = "email.us-east-1.amazonaws.com";
break;
case 'uswest':
$country = "email.us-west-2.amazonaws.com";
break;
}
return new Thrive_Dash_Api_Awsses( $this->param( 'key' ), $this->param( 'secretkey' ), $country );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,536 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_CampaignMonitor extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'Campaign Monitor';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'campaignmonitoremail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'campaignmonitor' );
}
/**
* Just saves the key in the database for optin and email api
*
* @return string|void
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$email = ! empty( $_POST['connection']['email'] ) ? sanitize_email( $_POST['connection']['email'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid Campaign Monitor key', 'thrive-dash' ) );
}
$this->set_credentials( compact( 'key', 'email' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Campaign Monitor using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_CampaignMonitorEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'campaignmonitoremail' );
if ( isset( $_POST['connection']['new_connection'] ) && (int) $_POST['connection']['new_connection'] === 1 ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
return $this->success( __( 'Campaign Monitor connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_CampaignMonitor $cm */
$cm = $this->get_api();
try {
$clients = $cm->get_clients();
$client = current( $clients );
$cm->get_client_lists( $client['id'] );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_CampaignMonitor( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
$lists = array();
try {
/** @var Thrive_Dash_Api_CampaignMonitor $cm */
$cm = $this->get_api();
$clients = $cm->get_clients();
$client = current( $clients );
$lists = $cm->get_client_lists( $client['id'] );
} catch ( Exception $e ) {
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
$subscriber = array();
/** @var Thrive_Dash_Api_CampaignMonitor $cm */
$cm = $this->get_api();
$subscriber['EmailAddress'] = $arguments['email'];
$subscriber['Resubscribe'] = true;
$subscriber['RestartSubscriptionBasedAutoresponders'] = true;
if ( ! empty( $arguments['name'] ) ) {
$subscriber['Name'] = $arguments['name'];
}
/** @var Thrive_Dash_Api_CampaignMonitor_List $list */
$list = $cm->get_list( $list_identifier );
$subscriber['CustomFields'] = empty( $arguments['CustomFields'] ) ? array() : $arguments['CustomFields'];
if ( ! empty( $arguments['phone'] ) ) {
$custom_fields = $list->get_custom_fields();
$_list_has_phone = false;
if ( ! empty( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
if ( isset( $field['name'] ) && $field['name'] === 'Phone' ) {
$_list_has_phone = true;
break;
}
}
}
if ( $_list_has_phone === false ) {
$custom_field = array(
'FieldName' => 'Phone',
'DataType' => 'Number',
'Options' => array(),
'VisibleInPreferenceCenter' => true,
);
$list->create_custom_field( $custom_field );
}
$subscriber['CustomFields'][] = array(
'Key' => 'Phone',
'Value' => (string) $arguments['phone'],
);
}
$_custom_fields = $this->_generate_custom_fields( array_merge( $arguments, array( 'list_id' => $list_identifier ) ) );
$subscriber['CustomFields'] = array_merge( $subscriber['CustomFields'], $_custom_fields );
if ( ! empty( $arguments['automator_custom_fields'] ) ) {
$subscriber['CustomFields'] = array_merge( $subscriber['CustomFields'], $arguments['automator_custom_fields'] );
}
$list->add_subscriber( $subscriber );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* delete a contact from the list
*
* @param string $email
* @param array $arguments
*
* @return mixed
*/
public function delete_subscriber( $email, $arguments = array() ) {
$api = $this->get_api();
if ( ! empty( $arguments['list_identifier'] ) && ! empty( $email ) ) {
$list = $api->get_list( $arguments['list_identifier'] );
$list->delete_subscriber( $email );
return true;
}
return false;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[email]';
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'campaignmonitoremail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
/**
* @param array $params which may contain `list_id`
* @param bool $force make a call to API and invalidate cache
* @param bool $get_all where to get lists with their custom fields
*
* @return array
*/
public function get_api_custom_fields( $params, $force = false, $get_all = true ) {
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
/** @var Thrive_Dash_Api_CampaignMonitor $cm */
$cm = $this->get_api();
$custom_data = array();
$lists = array();
$allowed_types = array(
'Text',
);
try {
$clients = $cm->get_clients();
$client = current( $clients );
$lists = $cm->get_client_lists( $client['id'] );
} catch ( Exception $e ) {
}
foreach ( $lists as $list ) {
$custom_data[ $list['id'] ] = array();
try {
$custom_fields = $cm->get_list_custom_fields( $list['id'] );
foreach ( $custom_fields as $item ) {
if ( isset( $item['DataType'] ) && in_array( $item['DataType'], $allowed_types ) ) {
$custom_data[ $list['id'] ][] = $this->normalize_custom_field( $item );
}
}
} catch ( Exception $e ) {
}
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* @param array $field
*
* @return array
*/
protected function normalize_custom_field( $field = array() ) {
return array(
'id' => ! empty( $field['Key'] ) ? $field['Key'] : '',
'name' => ! empty( $field['FieldName'] ) ? $field['FieldName'] : '',
'type' => ! empty( $field['DataType'] ) ? $field['DataType'] : '',
'label' => ! empty( $field['FieldName'] ) ? $field['FieldName'] : '',
);
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = [];
foreach ( $automation_data['api_fields'] as $pair ) {
$mapped_data[] = array(
'Key' => $pair['key'],
'Value' => sanitize_text_field( $pair['value'] ),
);
}
return $mapped_data;
}
/**
* Generate custom fields array
*
* @param array $args
*
* @return array
*/
private function _generate_custom_fields( $args ) {
$custom_fields = $this->get_api_custom_fields( array() );
if ( empty( $custom_fields[ $args['list_id'] ] ) ) {
return array();
}
$custom_fields = $custom_fields[ $args['list_id'] ];
$mapped_custom_fields = $this->build_mapped_custom_fields( $args );
$result = array();
foreach ( $mapped_custom_fields as $key => $custom_field ) {
$field_key = strpos( $custom_field['type'], 'mapping_' ) !== false ? $custom_field['type'] . '_' . $key : $key;
$field_key = str_replace( '[]', '', $field_key );
if ( ! empty( $args[ $field_key ] ) ) {
$args[ $field_key ] = $this->process_field( $args[ $field_key ] );
}
$is_in_list = array_filter(
$custom_fields,
function ( $field ) use ( $custom_field ) {
return $custom_field['value'] === $field['id'];
}
);
if ( ! empty( $is_in_list ) && isset( $args[ $field_key ] ) ) {
$result[] = array(
'Key' => $custom_field['value'],
'Value' => sanitize_text_field( $args[ $field_key ] ),
);
}
}
return $result;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function build_mapped_custom_fields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_CampaignMonitor $aweber */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$args['CustomFields'] = $this->prepare_custom_fields_for_api( $custom_fields, $list_id );
$this->add_subscriber( $list_id, $args );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
protected function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
if ( empty( $list_identifier ) ) { // list identifier required here
return array();
}
$api_fields = $this->get_api_custom_fields( null, true );
if ( empty( $api_fields[ $list_identifier ] ) ) {
return array();
}
$prepared_fields = array();
foreach ( $api_fields[ $list_identifier ] as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $field['id'] === $key ) {
$prepared_fields[] = array(
'Key' => $key,
'Value' => $custom_field,
);
unset( $custom_fields[ $key ] ); // avoid unnecessary loops
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function has_custom_fields() {
return true;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list' => array( 'api_fields' ) ) );
}
}

View File

@@ -0,0 +1,341 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_CampaignMonitorEmail extends Thrive_Dash_List_Connection_Abstract {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string
*/
public function get_title() {
return 'Campaign Monitor';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'campaignmonitoremail' );
}
/**
* Just saves the key in the database
*
* @return mixed|Thrive_Dash_List_Connection_Abstract
* @throws Exception
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$email = ! empty( $_POST['connection']['email'] ) ? sanitize_email( $_POST['connection']['email'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid Campaign Monitor key', 'thrive-dash' ) );
}
$this->set_credentials( compact( 'key', 'email' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Campaign Monitor using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Try to connect to the autoresponder too
*/
/** @var Thrive_Dash_List_Connection_CampaignMonitor $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'campaignmonitor' );
$r_result = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection']['new_connection'] = isset( $_POST['connection']['new_connection'] ) ? sanitize_text_field( $_POST['connection']['new_connection'] ) : 1;
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
return $this->success( __( 'Campaign Monitor connected successfully', 'thrive-dash' ) );
}
/**
* Tests if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
* @throws Exception
*/
public function test_connection() {
/** @var Thrive_Dash_Api_CampaignMonitor $cm */
$cm = $this->get_api();
$from_email = '';
$to = '';
if ( isset( $_POST['connection']['email'] ) ) {
$from_email = sanitize_email( $_POST['connection']['email'] );
$to = sanitize_email( $_POST['connection']['email'] );
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'campaignmonitoremail' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
$to = $credentials['email'];
}
}
$args = array(
'Subject' => 'API connection test',
'From' => $from_email,
'BBC' => null,
'Html' => 'This is a test email from Thrive Leads Campaign Monitor API.',
'Text' => 'This is a test email from Thrive Leads Campaign Monitor API.',
'To' => array(
$to,
),
'TrackOpens' => true,
'TrackClicks' => true,
'InlineCSS' => true,
);
try {
$clients = $cm->get_clients();
$current_client = current( $clients );
/** @var Thrive_Dash_Api_CampaignMonitor_ClassicEmail $email */
$email = $cm->transactional();
$email->set_client( $current_client['id'] );
$email->send( $args );
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'campaignmonitoremail' );
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*/
public function sendEmail( $post_data ) {
$cm = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject === '' ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$credentials = Thrive_Dash_List_Manager::credentials( 'campaignmonitoremail' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
$html_content = $asset->post_content;
if ( $html_content === '' ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$to = $post_data['email'];
if ( ! empty( $visitor_name ) ) {
$to = $visitor_name . ' <' . $to . '>';
}
$message = array(
'Subject' => $subject,
'Html' => $html_content,
'Text' => $text_content,
'BBC' => null,
'From' => $from_email,
'To' => $to,
'TrackOpens' => true,
'TrackClicks' => true,
'InlineCSS' => true,
);
try {
$clients = $cm->get_clients();
$current_client = current( $clients );
/** @var Thrive_Dash_Api_CampaignMonitor_ClassicEmail $email */
$email = $cm->transactional();
$email->set_client( $current_client['id'] );
$email->send( $message );
} catch ( Exception $e ) {
throw new Exception( $e->getMessage() );
}
return true;
}
/**
* Instantiates the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_CampaignMonitor( $this->param( 'key' ) );
}
/**
* Gets all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
return array();
}
/**
* Adds contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
return true;
}
/**
* Send emails to the user
*
* @param array $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$cm = $this->get_api();
$message = array(
'Subject' => $data['subject'],
'Html' => $data['html_content'],
'Text' => '',
'BBC' => $data['bcc'],
'CC' => $data['cc'],
'From' => $data['from_name'] . '< ' . $data['from_email'] . ' >',
'ReplyTo' => empty( $data['reply_to'] ) ? '' : $data['reply_to'],
'To' => $data['emails'],
);
try {
$clients = $cm->get_clients();
$current_client = current( $clients );
/** @var Thrive_Dash_Api_CampaignMonitor_ClassicEmail $email */
$email = $cm->transactional();
$email->set_client( $current_client['id'] );
$email->send( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
if ( ! empty( $data['send_confirmation'] ) ) {
$confirmation_email = array(
'Subject' => $data['confirmation_subject'],
'Html' => $data['confirmation_html'],
'Text' => '',
'BBC' => '',
'CC' => '',
'From' => $data['from_name'] . '< ' . $data['from_email'] . ' >',
'To' => array( $data['sender_email'] ),
'ReplyTo' => $data['from_email'],
);
try {
$clients = $cm->get_clients();
$current_client = current( $clients );
/** @var Thrive_Dash_Api_CampaignMonitor_ClassicEmail $email */
$email = $cm->transactional();
$email->set_client( $current_client['id'] );
$email->send( $confirmation_email );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
}

View File

@@ -0,0 +1,182 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_ConstantContact extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* Application API Key
*/
const TOKEN_URL = 'https://api.constantcontact.com/mashery/account/';
/**
* @return string the API connection title
*/
public function get_title() {
return 'Constant Contact (Archived)';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'constant-contact' );
}
public function getTokenUrl() {
return self::TOKEN_URL;
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$api_key = ! empty( $_POST['connection']['api_key'] ) ? sanitize_text_field( $_POST['connection']['api_key'] ) : '';
$api_token = ! empty( $_POST['connection']['api_token'] ) ? sanitize_text_field( $_POST['connection']['api_token'] ) : '';
if ( empty( $api_key ) || empty( $api_token ) ) {
return $this->error( __( 'You must provide a valid Constant Contact API Key and API token', 'thrive-dash' ) );
}
$this->set_credentials( array( 'api_key' => $api_key, 'api_token' => $api_token ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Constant Contact using the provided API Key and API Token (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Constant Contact connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
try {
/** @var Thrive_Dash_Api_ConstantContact $api */
$api = $this->get_api();
$api->getLists();
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_ConstantContact( $this->param( 'api_key' ), $this->param( 'api_token' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
try {
$lists = array();
/** @var Thrive_Dash_Api_ConstantContact $api */
$api = $this->get_api();
foreach ( $api->getLists() as $item ) {
$lists[] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
/** @var Thrive_Dash_Api_ConstantContact $api */
$api = $this->get_api();
$user = array(
'email' => $arguments['email'],
);
list( $first_name, $last_name ) = explode( " ", ! empty( $arguments['name'] ) ? $arguments['name'] . " " : ' ' );
if ( ! empty( $arguments['phone'] ) ) {
$user['work_phone'] = $arguments['phone'];
}
if ( ! empty( $first_name ) ) {
$user['first_name'] = $first_name;
}
if ( ! empty( $last_name ) ) {
$user['last_name'] = $last_name;
}
$api->addContact( $list_identifier, $user );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{Email Address}';
}
}

View File

@@ -0,0 +1,347 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_ConstantContactV3 extends Thrive_Dash_List_Connection_Abstract {
public static function get_type() {
return 'autoresponder';
}
public function get_title() {
return 'Constant Contact';
}
/**
* Builds an authorization URI - the user will be redirected to that URI and asked to give app access
*
* @return string
*/
public function getAuthorizeUrl() {
$this->save(); // save the client_id and client_secret for later use
return $this->get_api()->get_authorize_url();
}
/**
* whether or not this list is connected to the service (has been authenticated)
*
* @return bool
*/
public function is_connected() {
return $this->param( 'access_token' ) && $this->param( 'refresh_token' );
}
public function output_setup_form() {
$this->output_controls_html( 'constant-contact-v3' );
}
/**
* Called during the redirect from constant contact oauth flow
*
* _REQUEST contains a `code` parameter which needs to be sent back to g.api in exchange for an access token
*
* @return bool|mixed|string|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
$code = empty( $_REQUEST['code'] ) ? '' : $_REQUEST['code'];
if ( empty( $code ) ) {
return $this->error( 'Missing `code` parameter' );
}
try {
/* get access token from constant contact API */
$response = $this->get_api()->get_access_token( $code );
if ( empty( $response['access_token'] ) ) {
throw new Thrive_Dash_Api_ConstantContactV3_Exception( 'Missing token from response data' );
}
$this->_credentials = array(
'client_id' => $this->param( 'client_id' ),
'client_secret' => $this->param( 'client_secret' ),
'access_token' => $response['access_token'],
'expires_at' => time() + $response['expires_in'],
'refresh_token' => $response['refresh_token'],
);
$this->save();
/**
* Fetch all custom fields on connect so that we have them all prepared
* - TAr doesn't need to get them from API
*/
$this->get_api_custom_fields( array(), true, true );
} catch ( Thrive_Dash_Api_ConstantContactV3_Exception $e ) {
echo 'caught ex: ' . esc_html( $e->getMessage() );
$this->_credentials = array();
$this->save();
$this->error( $e->getMessage() );
return false;
}
return true;
}
/**
* Test the connection to the service.
*
* @return void
*/
public function test_connection() {
$result = array(
'success' => true,
'message' => __( 'Connection works', 'thrive-dash' ),
);
try {
$this->get_api()->get_account_details(); // this will throw the exception if there is a connection problem
} catch ( Thrive_Dash_Api_ConstantContactV3_Exception $e ) {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
return $result;
}
/**
* Instantiate the service and set any available data
*
* @return Thrive_Dash_Api_ConstantContactV3_Service
*/
protected function get_api_instance() {
$api = new Thrive_Dash_Api_ConstantContactV3_Service(
$this->param( 'client_id' ),
$this->param( 'client_secret' ),
$this->param( 'access_token' )
);
/* check for expired token and renew it */
if ( $this->param( 'refresh_token' ) && $this->param( 'expires_at' ) && time() > (int) $this->param( 'expires_at' ) ) {
$data = $api->refresh_access_token( $this->param( 'refresh_token' ) );
$this->_credentials['access_token'] = $data['access_token'];
$this->_credentials['refresh_token'] = $data['refresh_token'];
$this->_credentials['expires_at'] = time() + $data['expires_in'];
$this->save();
}
return $api;
}
protected function _get_lists() {
return $this->get_api()->getLists();
}
/**
* Add a subscriber to a list.
*
* @param string $list_identifier Contact list identifier.
* @param array $arguments Subscriber data.
* @return bool
*/
public function add_subscriber( $list_identifier, $arguments ) {
// add logic here.
$params = array(
'list_memberships' => array( $list_identifier ),
);
if ( $arguments['email'] ) {
$params['email_address'] = $arguments['email'];
}
if ( $arguments['name'] ) {
$split_name = $this->_splitFullName( $arguments['name'] );
$params['first_name'] = $split_name['first_name'];
$params['last_name'] = $split_name['last_name'];
}
if ( $arguments['first_name'] ) {
$params['first_name'] = $arguments['first_name'];
}
if ( $arguments['last_name'] ) {
$params['last_name'] = $arguments['last_name'];
}
if ( $arguments['phone'] ) {
$params['phone_number'] = $arguments['phone'];
}
$params = array_merge( $params, $this->_generateMappingFields( $arguments ) );
return $this->get_api()->addSubscriber( $params );
}
/**
* Get first name and last name from full name.
*
* @param string $full_name full name.
* @return array
*/
private function _splitFullName( $full_name = '' ) {
$full_name = trim( preg_replace( '/\s+/', ' ', $full_name ) );
$result = [
'first_name' => '',
'last_name' => '',
];
if ( empty( $full_name ) ) {
return $result;
}
$name_parts = explode( ' ', $full_name );
if ( count( $name_parts ) === 1 ) {
$result['first_name'] = $name_parts[0];
return $result;
}
$result['first_name'] = array_shift( $name_parts );
$result['last_name'] = implode( ' ', $name_parts );
return $result;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{$email}';
}
/**
* Get the custom fields for the API.
*
* @param array $params Parameters.
* @param boolean $force Force.
* @param boolean $get_all Get all.
* @return array
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
// Serve from cache if exists and requested.
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_data = $this->get_api()->getAllFields();
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* Generate mapping fields array
*
* @param array $args
*
* @return array
*/
private function _generateMappingFields( $args = array() ) {
$mapping_fields = array();
$tve_mapping = unserialize( base64_decode( $args['tve_mapping'] ) );
if ( ! is_array( $tve_mapping ) || 0 === count( $tve_mapping ) ) {
return $mapping_fields;
}
foreach ( $tve_mapping as $key => $value ) {
$field_name = reset( $value );
$field_type = $value['_field'];
$field_value = $args[ $key ];
if ( 'date' === $field_type ) {
$field_value = $this->formatDateValue( $field_value );
}
if ( ! empty( $args[ $key ] ) ) {
// check if the field name is in this format 87a47d98-c8ef-11ef-a282-fa163eb4f69a then it is a custom field.
if ( preg_match( '/[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}/', $field_name ) ) {
$mapping_fields['custom_fields'][] = array(
'custom_field_id' => $field_name,
'value' => $field_value,
);
} else {
$mapping_fields[ $field_name ] = $field_value;
if ( 'birthday_day' === $field_name || 'birthday_month' === $field_name ) {
$mapping_fields[ $field_name ] = (int) $field_value;
}
}
}
}
return $mapping_fields;
}
/**
* Format date value to d/m/Y format.
*
* @param String $date_string Date string.
* @return String
*/
private function formatDateValue( $date_string ) {
$formatted_date = '';
// check if $date_string is in the format of M, d, Y.
if ( preg_match( '/[a-zA-Z]{3}, [0-9]{1,2}, [0-9]{4}/', $date_string ) ) {
$date_string = str_replace( ', ', '-', $date_string );
$formatted_date = gmdate( 'm/d/Y', strtotime( $date_string ) );
return $formatted_date;
}
// check if $date_string is in the format of d/m/Y but not m/d/Y.
if ( preg_match( '/^(0?[1-9]|[12][0-9]|3[01])\/(0?[1-9]|1[0-2])\/\d{4}$/', $date_string ) ) {
$date_parts = explode( '/', $date_string );
if ( checkdate( $date_parts[1], $date_parts[0], $date_parts[2] ) ) {
$formatted_date = gmdate( 'm/d/Y', strtotime( str_replace( '/', '-', $date_string ) ) );
return $formatted_date;
}
}
$formatted_date = gmdate( 'm/d/Y', strtotime( $date_string ) );
return $formatted_date;
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Define support for custom fields.
*
* @return boolean
*/
public function has_custom_fields() {
return true;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields' ) );
}
}

View File

@@ -0,0 +1,467 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_ConvertKit extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'ConvertKit / Seva';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'convertkit' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid ConvertKit API Key', 'thrive-dash' ) );
}
$this->set_credentials( array( 'key' => $key ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to ConvertKit: %s', 'thrive-dash' ), $this->_error ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'ConvertKit connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_ConvertKit
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_ConvertKit( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* ConvertKit has both sequences and forms
*
* @return array|string for error
*/
protected function _get_lists() {
/**
* just try getting the lists as a connection test
*/
try {
/** @var $api Thrive_Dash_Api_ConvertKit */
$api = $this->get_api();
$lists = array();
$data = $api->get_forms();
if ( ! empty( $data ) ) {
foreach ( $data as $form ) {
if ( ! empty( $form['archived'] ) ) {
continue;
}
$lists[] = array(
'id' => $form['id'],
'name' => $form['name'],
);
}
}
return $lists;
} catch ( Thrive_Dash_Api_ConvertKit_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
/** @var $api Thrive_Dash_Api_ConvertKit */
$api = $this->get_api();
$arguments['custom_fields_ids'] = $this->buildMappedCustomFields( $arguments );
$arguments['fields'] = new stdClass();
if ( ! empty( $arguments['custom_fields_ids'] ) ) {
$arguments['fields'] = $this->_generateCustomFields( $arguments );
} else if ( ! empty( $arguments['automator_custom_fields'] ) ) {
$arguments['fields'] = $arguments['automator_custom_fields'];
unset( $arguments['automator_custom_fields'] );
}
$api->subscribeForm( $list_identifier, $arguments );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Get custom fields
*
* @return array
*/
public function getCustomFields() {
/** @var Thrive_Dash_Api_ConvertKit $api */
$api = $this->get_api();
$fields = $api->getCustomFields();
return isset( $fields['custom_fields'] ) ? $fields['custom_fields'] : array();
}
/**
* @param array $args
*
* @return object
* @throws Thrive_Dash_Api_ConvertKit_Exception
*/
protected function _generateCustomFields( $args ) {
/** @var Thrive_Dash_Api_ConvertKit $api */
$api = $this->get_api();
$fields = $this->_getCustomFields( false );
$response = array();
$ids = $this->buildMappedCustomFields( $args );
foreach ( $fields as $field ) {
foreach ( $ids as $key => $id ) {
if ( (int) $field['id'] === (int) $id['value'] ) {
/**
* Ex cf: ck_field_84479_first_custom_field
* Needed Result: first_custom_field
*/
$_name = $field['name'];
$_name = str_replace( 'ck_field_', '', $_name );
$_name = explode( '_', $_name );
unset( $_name[0] );
$_name = implode( '_', $_name );
$name = strpos( $id['type'], 'mapping_' ) !== false ? $id['type'] . '_' . $key : $key;
$cf_form_name = str_replace( '[]', '', $name );
if ( ! empty( $args[ $cf_form_name ] ) ) {
$response[ $_name ] = $this->process_field( $args[ $cf_form_name ] );
}
}
}
}
if ( ! empty( $args['phone'] ) ) {
$phone_fields = $api->phoneFields( $args['phone'] );
$response['phone'] = isset( $phone_fields['phone'] ) ? $phone_fields['phone'] : '';
}
return (object) $response;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return object
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = [];
$fields = $this->_getCustomFields( false );
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
foreach ( $fields as $field ) {
if ( (int) $field['id'] === (int) $pair['key'] ) {
/**
* Ex cf: ck_field_84479_first_custom_field
* Needed Result: first_custom_field
*/
$_name = $field['name'];
$_name = str_replace( 'ck_field_', '', $_name );
$_name = explode( '_', $_name );
unset( $_name[0] );
$_name = implode( '_', $_name );
$mapped_data[ $_name ] = $value;
}
}
}
}
return (object) $mapped_data;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{subscriber.email_address}}';
}
/**
* @param $force
*
* @return array
*/
protected function _getCustomFields( $force ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
/** @var $api Thrive_Dash_Api_ConvertKit */
$api = $this->get_api();
$fields = $api->getCustomFields();
$fields = isset( $fields['custom_fields'] ) ? $fields['custom_fields'] : array();
foreach ( $fields as $key => $field ) {
$fields[ $key ] = $this->normalize_custom_field( $field );
}
$this->_save_custom_fields( $fields );
return $fields;
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array
* @throws Thrive_Dash_Api_ConvertKit_Exception
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
$response = $this->_getCustomFields( $force );
return is_array( $response ) ? $response : array();
}
protected function normalize_custom_field( $data ) {
$data['type'] = 'text';
return parent::normalize_custom_field( $data );
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function buildMappedCustomFields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields ex array( 'cf_name' => 'some nice cf value' )
* @param array $extra
*
* @return false|int|mixed
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
if ( empty( $extra['list_identifier'] ) ) {
return false;
}
try {
/** @var $api Thrive_Dash_Api_ConvertKit */
$api = $this->get_api();
$args = array(
'fields' => (object) $this->prepare_custom_fields_for_api( $custom_fields ),
'email' => $email,
'name' => ! empty( $extra['name'] ) ? $extra['name'] : '',
);
$subscriber = $api->subscribeForm( $extra['list_identifier'], $args );
return $subscriber['subscriber']['id'];
} catch ( Exception $e ) {
return false;
}
}
/**
* delete a contact from the list
*
* @param string $email
* @param array $arguments
*
* @return mixed
*/
public function delete_subscriber( $email, $arguments = array() ) {
$api = $this->get_api();
$result = $api->unsubscribeUser( $email, $arguments );
return isset( $result['subscriber']['id'] );
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->_getCustomFields( true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$cf_prefix = 'ck_field_';
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( (int) $field['id'] === (int) $key && $custom_field ) {
$str_to_replace = $cf_prefix . $field['id'] . '_';
$cf_key = str_replace( $str_to_replace, '', $field['name'] );
$prepared_fields[ $cf_key ] = $custom_field;
unset( $custom_fields[ $key ] ); // avoid unnecessary loops
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list' => array( 'api_fields' ), 'tag_input' => array() ) );
}
public function has_custom_fields() {
return true;
}
}

View File

@@ -0,0 +1,587 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Drip extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{ subscriber.email }}';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Drip';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
public function has_custom_fields() {
return true;
}
/**
* @return bool
*/
public function has_optin() {
return true;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'drip' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$token = ! empty( $_POST['connection']['token'] ) ? sanitize_text_field( $_POST['connection']['token'] ) : '';
$client_id = ! empty( $_POST['connection']['client_id'] ) ? sanitize_text_field( $_POST['connection']['client_id'] ) : '';
if ( empty( $token ) || empty( $client_id ) ) {
return $this->error( __( 'You must provide a valid Drip token and Client ID', 'thrive-dash' ) );
}
$this->set_credentials( array( 'token' => $token, 'client_id' => $client_id ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Drip using the provided Token and Client ID (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Drip connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
try {
/** @var Thrive_Dash_Api_Drip $api */
$api = $this->get_api();
$accounts = $api->get_accounts();
if ( empty( $accounts ) || ! is_array( $accounts ) ) {
return __( 'Drip connection could not be validated!', 'thrive-dash' );
}
foreach ( $accounts['accounts'] as $account ) {
if ( $account['id'] === $this->param( 'client_id' ) ) {
return true;
}
}
return false;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
}
$phone = ! empty( $arguments['phone'] ) ? $arguments['phone'] : '';
$arguments['drip_optin'] = ! isset( $arguments['drip_optin'] ) ? 's' : $arguments['drip_optin'];
$double_optin = ! ( isset( $arguments['drip_optin'] ) && 's' === $arguments['drip_optin'] );
$field_first_name = isset( $arguments['drip_first_name_field'] ) ? $arguments['drip_first_name_field'] : 'thrive_first_name';
$field_last_name = isset( $arguments['drip_last_name_field'] ) ? $arguments['drip_last_name_field'] : 'thrive_last_name';
$url = wp_get_referer();
try {
/** @var Thrive_Dash_Api_Drip $api */
$api = $this->get_api();
$proprieties = new stdClass();
if ( isset( $first_name ) ) {
$proprieties->{$field_first_name} = $first_name;
}
if ( isset( $last_name ) ) {
$proprieties->{$field_last_name} = $last_name;
}
if ( isset( $phone ) ) {
$proprieties->thrive_phone = $phone;
}
$tags = ! empty( $arguments['drip_tags'] ) ? explode( ',', $arguments['drip_tags'] ) : array();
if ( isset( $arguments['drip_type'] ) && 'automation' === $arguments['drip_type'] ) {
$proprieties->thrive_referer = $url;
$proprieties->thrive_ip_address = sanitize_text_field( $_SERVER['REMOTE_ADDR'] ); //phpcs:ignore
if ( ! empty( $arguments['drip_field'] ) ) {
foreach ( $arguments['drip_field'] as $field => $field_value ) {
$proprieties->{$field} = $field_value;
}
}
}
if ( ! empty( $arguments['tve_mapping'] ) ) {
$fields = $this->prepare_api_custom_fields( $arguments );
$proprieties = (object) array_merge( (array) $proprieties, $fields );
} else if ( ! empty( $arguments['automator_custom_fields'] ) ) {
$proprieties = (object) array_merge( (array) $proprieties, $arguments['automator_custom_fields'] );
}
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$api->apply_tag( $arguments['email'], $tag, $this->param( 'client_id' ) );
}
}
$user = array(
'account_id' => $this->param( 'client_id' ),
'campaign_id' => $list_identifier,
'email' => $arguments['email'],
'ip_address' => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ), // phpcs:ignore
'custom_fields' => $proprieties,
'status' => 'active',
);
if ( isset( $arguments['drip_type'] ) && 'list' === $arguments['drip_type'] ) {
$user['double_optin'] = $double_optin;
}
$lead = $api->create_or_update_subscriber( $user );
if ( empty( $user ) ) {
return __( 'User could not be subscribed', 'thrive-dash' );
}
if ( 'tag' !== $arguments['drip_type'] && ( ! isset( $arguments['drip_field'] ) || 'list' === $arguments['drip_type'] ) ) {
$client = array_shift( $lead['subscribers'] );
$api->subscribe_subscriber(
array(
'account_id' => $this->param( 'client_id' ),
'campaign_id' => $list_identifier,
'email' => $client['email'],
'double_optin' => $double_optin,
'tags' => $tags,
)
);
}
$api->record_event(
array(
'account_id' => $this->param( 'client_id' ),
'action' => 'Submitted a Thrive Leads form',
'email' => $arguments['email'],
'properties' => $proprieties,
)
);
return true;
} catch ( Thrive_Dash_Api_Drip_Exception_Unsubscribed $e ) {
//todo: rewrite this try
try {
$api->delete_subscriber( $user );
return $this->add_subscriber( $list_identifier, $arguments );
} catch ( Exception $e ) {
return $e->getMessage();
}
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Allow the user to choose whether to have a single or a double optin for the form being edited
* It will hold the latest selected value in a cookie so that the user is presented by default with the same option selected the next time he edits such a form
*
* @param array $params
*
* @return mixed
*/
public function get_extra_settings( $params = array() ) {
$processed_params = array();
$params['optin'] = empty( $params['optin'] ) ? ( isset( $_COOKIE['tve_api_drip_optin'] ) ? sanitize_text_field( $_COOKIE['tve_api_drip_optin'] ) : 'd' ) : $params['optin'];
setcookie( 'tve_api_drip_optin', $params['optin'], strtotime( '+6 months' ), '/' );
if ( ! empty( $params ) ) {
foreach ( $params as $k => $v ) {
if ( strpos( $k, 'field[' ) !== false ) {
$key = str_replace( 'field[', '', $k );
$processed_params['proprieties'][ $key ] = $v;
} else {
$processed_params[ $k ] = $v;
}
}
}
return $processed_params;
}
/**
* Allow the user to choose whether to have a single or a double optin for the form being edited
* It will hold the latest selected value in a cookie so that the user is presented by default with the same option selected the next time he edits such a form
*
* @param array $params
*/
public function render_extra_editor_settings( $params = array() ) {
$processed_params = array();
$params['optin'] = empty( $params['optin'] ) ? ( isset( $_COOKIE['tve_api_drip_optin'] ) ? sanitize_text_field( $_COOKIE['tve_api_drip_optin'] ) : 'd' ) : $params['optin'];
setcookie( 'tve_api_drip_optin', $params['optin'], strtotime( '+6 months' ), '/' );
if ( ! empty( $params ) ) {
foreach ( $params as $k => $v ) {
if ( strpos( $k, 'field[' ) !== false ) {
$key = str_replace( 'field[', '', $k );
$processed_params['proprieties'][ $key ] = $v;
} else {
$processed_params[ $k ] = $v;
}
}
}
$this->output_controls_html( 'drip/optin-type', $processed_params );
$this->output_controls_html( 'drip/proprieties', $processed_params );
}
public function render_before_lists_settings( $params = array() ) {
$this->output_controls_html( 'drip/select-type', $params );
}
/**
* instantiate the API code required for this connection
*
* @return mixed
* @throws Exception
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Drip( $this->param( 'token' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
try {
/** @var Thrive_Dash_Api_Drip $api */
$api = $this->get_api();
$campaigns = $api->get_campaigns(
array(
'account_id' => $this->param( 'client_id' ),
'status' => 'all',
)
);
if ( empty( $campaigns ) || ! is_array( $campaigns ) ) {
$this->_error = __( 'There is not Campaign in your Drip account to be fetched !', 'thrive-dash' );
return false;
}
$lists = array();
foreach ( $campaigns['campaigns'] as $campaign ) {
$lists[] = array(
'id' => $campaign['id'],
'name' => $campaign['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
* @throws Exception
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
return $this->get_all_custom_fields( $force );
}
/**
* Gets a list of fields from API or from cache
*
* @param (bool) $force true for fresh data or false from cache
*
* @return array|mixed
* @throws Exception
*/
public function get_all_custom_fields( $force ) {
$custom_data = array();
// Serves from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
/** @var Thrive_Dash_Api_Drip $api */
$api = $this->get_api();
// Build custom fields for every list
$custom_fields = $api->get_custom_fields(
array(
'account_id' => $this->param( 'client_id' ),
)
);
if ( is_array( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
$custom_data[] = $this->normalize_custom_field( $field );
}
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* Brings an API field under a known form that TAr can understand
*
* @param string $field
*
* @return array
*/
protected function normalize_custom_field( $field ) {
return array(
'id' => $field,
'name' => $field,
'type' => $field,
'label' => $field,
);
}
/**
* Based on custom inputs set in form and their mapping
* - prepares a custom fields for Drip
*
* @param array $arguments POST sent by optin form
*
* @return array with drip custom field name as key and the value of inputs filled by the visitor
*/
public function prepare_api_custom_fields( $arguments ) {
$fields = array();
if ( empty( $arguments['tve_mapping'] ) ) {
return $fields;
}
$serialized = base64_decode( $arguments['tve_mapping'] );
$mapping = array();
if ( $serialized ) {
$mapping = thrive_safe_unserialize( $serialized );
}
if ( empty( $mapping ) ) {
return $fields;
}
foreach ( $mapping as $name => $field ) {
$name = str_replace( '[]', '', $name );
if ( ! empty( $field[ $this->_key ] ) && ! empty( $arguments[ $name ] ) ) {
$custom_field_name = $field[ $this->_key ];
$custom_field_value = $arguments[ $name ];
$fields[ $custom_field_name ] = is_array( $custom_field_value ) ? implode( ', ', $custom_field_value ) : $custom_field_value;
}
}
return $fields;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = array();
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
$mapped_data[ $pair['key'] ] = $value;
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return false|int|mixed
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_Drip $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$this->add_subscriber( $list_id, $args );
$user = array(
'account_id' => $this->param( 'client_id' ),
'campaign_id' => $list_id,
'email' => $email,
'ip_address' => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ), // phpcs:ignore
'custom_fields' => (object) $this->prepare_custom_fields_for_api( $custom_fields ),
);
$lead = $api->create_or_update_subscriber( $user );
return $lead['subscribers'][0]['id'];
} catch ( Exception $e ) {
return false;
}
}
/**
* get relevant data from webhook trigger
*
* @param $request WP_REST_Request
*
* @return array
*/
public function get_webhook_data( $request ) {
$contact = $request->get_param( 'subscriber' );
return array( 'email' => empty( $contact['email'] ) ? '' : $contact['email'] );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $field['id'] === $key && $custom_field ) {
$prepared_fields[ $key ] = $custom_field;
unset( $custom_fields[ $key ] ); // avoid unnecessary loops
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'optin', 'api_fields', 'tag_input' ) );
}
}

View File

@@ -0,0 +1,503 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
/**
* Thrive Themes - https://thrivethemes.com
*/
/**
* Handle Email connection for Lead Generation.
* This connection will always be available but won't be displayed in TD, because no action is needed for it
*
* Class Thrive_Dash_List_Connection_Email
*/
class Thrive_Dash_List_Connection_Email extends Thrive_Dash_List_Connection_Abstract {
/**
* @return string the API connection title
*/
public function get_title() {
return 'Email';
}
/**
* Remove the api from dashboard
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Email connection will always be available
*
* @return bool
*/
public function is_connected() {
return true;
}
/**
* Noting to do here
*/
public function output_setup_form() {
}
/**
* @return true
*/
public function read_credentials() {
$this->set_credentials( array( 'connected' => true ) );
$this->save();
return true;
}
/**
* @return bool
*/
public function test_connection() {
return true;
}
/**
* Send the emails on lg submit, the name may be a bit inappropriate, but we have to stay with the general implementation
*
* @param array $list_identifier
* @param array $arguments
*
* @return array|string
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! is_array( $list_identifier ) ) {
return __( 'Failed to send email', 'thrive-dash' );
}
$response = array();
foreach ( $list_identifier as $connection ) {
$_list = $connection['list'];
if ( 'own_site' === $_list ) {
$_list = 'email';
}
$_instance = Thrive_Dash_List_Manager::connection_instance( $_list );
if ( ! method_exists( $_instance, 'sendMultipleEmails' ) ) {
continue;
}
$connection = array_merge( $connection, $arguments );
$response[ $_instance->get_key() ] = $_instance->sendMultipleEmails( $this->prepare_data_for_email_service( $connection ) );
}
return $response;
}
protected function get_api_instance() {
}
protected function _get_lists() {
return $this->get_connected_email_providers();
}
/**
* Get connected email providers
*
* @return array
*/
public function get_connected_email_providers() {
if ( function_exists( 'wp_mail_smtp' ) ) {
$own_site_name = 'WP Mail SMTP';
} else {
$own_site_name = 'Send emails from this site';
}
$providers = array(
array(
'id' => 'own_site',
'name' => $own_site_name,
),
);
foreach ( Thrive_Dash_List_Manager::get_available_apis( true, [ 'include_types' => [ 'email' ] ] ) as $email_provider ) {
/**
* @var Thrive_Dash_List_Connection_Abstract $email_provider
*/
$providers[] = array(
'id' => $email_provider->get_key(),
'name' => $email_provider->get_title(),
);
}
return $providers;
}
/**
* @param array $arguments
*
* @return bool
*/
public function sendMultipleEmails( $arguments ) {
$headers = 'Content-Type: text/html; charset=UTF-8 ' . "\r\n"
. 'From: ' . $arguments['from_name'] . ' <' . $arguments['from_email'] . ' > ' . "\r\n"
. 'Reply-To: ' . $arguments['reply_to'] . "\r\n"
. 'CC: ' . implode( ', ', $arguments['cc'] ) . "\r\n"
. 'BCC: ' . implode( ', ', $arguments['bcc'] ) . "\r\n";
$email_sent = wp_mail(
$arguments['emails'],
$arguments['subject'],
$arguments['html_content'],
$headers
);
/* Send confirmation email */
if ( $email_sent && $arguments['send_confirmation'] ) {
$arguments['reply_to'] = $arguments['from_email'];
$headers = 'Content-Type: text/html; charset=UTF-8 ' . "\r\n"
. 'From: ' . $arguments['from_name'] . ' <' . $arguments['from_email'] . ' > ' . "\r\n"
. 'Reply-To: ' . $arguments['reply_to'] . "\r\n";
$email_sent = wp_mail(
$arguments['sender_email'],
$arguments['confirmation_subject'],
$arguments['confirmation_html'],
$headers
);
}
return $email_sent;
}
/**
* Get any extra settings needed by the api
*
* @param array $arguments
*
* @return array
*/
public function get_extra_settings( $arguments = array() ) {
$response = array();
foreach ( Thrive_Dash_List_Manager::get_available_apis( true, [ 'include_types' => [ 'email' ] ] ) as $email_provider ) {
/**
* @var Thrive_Dash_List_Connection_Abstract $email_provider
*/
$response[ $email_provider->get_key() ] = array(
'from_email' => $email_provider->get_email_param(),
);
}
return $response;
}
/**
* Prepare data for email service
*
* @param array $arguments
*
* @return array
*/
public function prepare_data_for_email_service( $arguments ) {
$emails = array_map(
function ( $item ) {
return sanitize_email( trim( $item ) );
},
explode( ',', $arguments['to'] )
);
$cc = array();
$bcc = array();
if ( ! empty( $arguments['cc'] ) ) {
$cc = array_map(
function ( $item ) {
return sanitize_email( trim( $item ) );
},
explode( ',', $arguments['cc'] )
);
}
if ( ! empty( $arguments['bcc'] ) ) {
$bcc = array_map(
function ( $item ) {
return sanitize_email( trim( $item ) );
},
explode( ',', $arguments['bcc'] )
);
}
$confirmation_html = '';
$send_confirmation = false;
if ( ! empty( $arguments['send_confirmation_email'] ) && $arguments['send_confirmation_email'] ) {
$confirmation_html = $this->replace_shortcodes( $arguments['email_confirmation_message'], $arguments );
$send_confirmation = true;
}
$data = array(
'emails' => $emails,
'subject' => html_entity_decode( sanitize_text_field( $this->replace_shortcodes( $arguments['email_subject'], $arguments, true ) ) ),
'from_name' => sanitize_text_field( $arguments['from_name'] ),
'from_email' => sanitize_email( $arguments['from_email'] ),
'html_content' => $this->replace_shortcodes( $arguments['email_message'], $arguments ),
'reply_to' => sanitize_email( $arguments['email'] ),
'bcc' => $bcc,
'cc' => $cc,
'send_confirmation' => $send_confirmation,
'confirmation_html' => $confirmation_html,
'confirmation_subject' => html_entity_decode( sanitize_text_field( $this->replace_shortcodes( $arguments['email_confirmation_subject'], $arguments, true ) ) ),
'sender_email' => sanitize_email( trim( $arguments['email'] ) ),
);
/**
* Allow filter email output
*
* @param array $data
* @param array $arguments
*/
return apply_filters( 'tve_dash_email_data', $data, $arguments );
}
/**
* Get form fields of the form
*
* @param $message
* @param $args
* @param $time
*
* @return string
*/
public function get_email_fields( $message, $args, $time ) {
$has_shortcode = strpos( $args['email_message'], '[ form_fields ]' );
$labels = ! empty( $args['tve_labels'] ) ? thrive_safe_unserialize( base64_decode( $args['tve_labels'] ) ) : array();
if ( strpos( $message, '[all_form_fields]' ) !== false ) {
$has_shortcode = true;
}
ob_start();
include dirname( dirname( dirname( __FILE__ ) ) ) . '/views/includes/email.php';
$html = ob_get_clean();
$html .= $this->generate_custom_fields_html( $args, $labels );
return preg_replace( "/[\r\n]+/", "", $html );
}
/**
* Get all custom fields from request args
*
* @param array $args
*
* @return array
*/
private function _get_custom_fields( $args ) {
if ( empty( $args['tve_mapping'] ) ) {
$mapping = array();
} else {
$mapping = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
}
$apis = Thrive_Dash_List_Manager::get_available_apis( true, [ 'include_types' => [ 'email', 'other' ] ] );
$custom_fields = array();
$excluded_fields = array( 'name', 'email', 'phone' );
foreach ( $apis as $api ) {
/** @var Thrive_Dash_List_Connection_Abstract $api */
$cf = $api->get_custom_fields();
$cf = wp_list_pluck( $cf, 'id' );
$custom_fields = array_merge( $custom_fields, $cf );
}
$custom_fields = array_unique( $custom_fields );
$custom_fields = array_filter(
$custom_fields,
function ( $field ) use ( $excluded_fields, $args ) {
if ( ! in_array( $field, $excluded_fields ) && array_key_exists( $field, $args ) ) {
return $field;
}
}
);
return array_merge( $custom_fields, array_keys( $mapping ) );
}
/**
* Generate the html for custom fields added in lg
*
* @param array $args
* @param array $labels
*
* @return string
*/
public function generate_custom_fields_html( $args, $labels ) {
$html = '';
foreach ( $this->_get_custom_fields( $args ) as $field ) {
$label = ! empty( $labels[ $field ] ) ? sanitize_text_field( $labels[ $field ] ) : __( 'Extra Data', 'thrive-dash' );
$is_extra_data = ! empty( $labels[ $field ] ) ? false : true;
if ( strpos( $field, 'textarea' ) !== false ) { /* preserve textarea formatting */
$value = ! empty( $args[ $field ] ) ? sanitize_textarea_field( $args[ $field ] ) : '';
} else {
$field = str_replace( '[]', '', $field );
if ( ! empty( $args[ $field ] ) ) {
$args[ $field ] = $this->process_field( $args[ $field ] );
}
$value = ! empty( $args[ $field ] ) ? sanitize_text_field( $args[ $field ] ) : '';
}
$value = stripslashes( nl2br( $value ) );
/**
* Filters a field value sent in the email message.
*
* @param string $value value to be sent in the email message
* @param string $field Field name that's being processed
* @param array $args form submission data
*
* @return string
*/
$value = apply_filters( 'thrive_email_message_field', $value, $field, $args );
if ( 'password' === $field || 'confirm_password' === $field ) {
$value = '******';
}
$_html = $is_extra_data && empty( $value ) ? '' : '<b>' . $label . ':</b> <span>' . $value . '</span><br>';
$html .= $_html;
}
return $html;
}
public function replace_shortcodes( $message, $args, $is_inline_field = false ) {
$timezone = get_option( 'gmt_offset' );
$time = date( 'H:i', time() + 3600 * ( $timezone + date( 'I' ) ) );
$first_name = empty( $args['name'] ) ? '' : $this->get_name_parts( $args['name'] )[0];
$fields_html = $this->get_email_fields( $message, $args, $time );
$to_replace = array(
'[wp_site_title]',
'[form_url_slug]',
'[first_name]',
'[user_email]',
'[phone]',
'[date]',
'[time]',
'[page_url]',
'[ip_address]',
'[device_settings]',
);
$values = array(
wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
trim( parse_url( $args['url'], PHP_URL_PATH ), '/' ),
$first_name,
$args['email'],
$args['phone'],
date_i18n( 'jS F, Y' ),
$time,
$args['url'],
tve_dash_get_ip(),
htmlspecialchars( isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ) : '' ),
);
if ( ! $is_inline_field ) {
$to_replace[] = '[all_form_fields]';
$to_replace[] = '[ form_fields ]';
$values[] = $fields_html;
$values[] = $fields_html;
}
/**
* Add custom fields to the shortcodes to be replaced in messages
*/
foreach ( $this->_get_custom_fields( $args ) as $field ) {
$to_replace[] = '[' . $field . ']';
$field = str_replace( '[]', '', $field );
if ( ! empty( $args[ $field ] ) ) {
$args[ $field ] = $this->process_field( $args[ $field ] );
}
$value = ! empty( $args[ $field ] ) ? sanitize_textarea_field( $args[ $field ] ) : '';
$value = stripslashes( nl2br( str_replace( ' ', '&nbsp;', $value ) ) );
$values[] = $value;
}
$message = str_replace( $to_replace, $values, $message );
/**
* Filter the email message being sent.
*
* @param string $message
* @param array $args submitted post data
*
* @return string
*/
$message = apply_filters( 'thrive_api_email_message', $message, $args );
return nl2br( $message );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[user_email]';
}
protected function set_custom_default_fields_mapping() {
$this->_default_form_fields = apply_filters(
'tve_dash_mapped_default_fields',
array(
array(
'id' => 'email',
'placeholder' => __( 'Email', 'thrive-dash' ),
'unique' => true,
'mandatory' => false,
),
array(
'id' => 'name',
'placeholder' => __( 'Name', 'thrive-dash' ),
'unique' => true,
'mandatory' => false,
),
array(
'id' => 'phone',
'placeholder' => __( 'Phone', 'thrive-dash' ),
'unique' => true,
'mandatory' => false,
),
) );
}
}

View File

@@ -0,0 +1,212 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_EverWebinar extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'webinar';
}
/**
* @return string
*/
public function get_title() {
return 'EverWebinar';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'everwebinar' );
}
/**
* @return mixed|Thrive_Dash_List_Connection_Abstract
*
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid EverWebinar key', 'thrive-dash' ) );
}
$this->set_credentials( array( 'key' => $key ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to EverWebinar using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'EverWebinar connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string
*/
public function test_connection() {
try {
$webinars = $this->get_api()->get_webinars();
if ( ! $webinars ) {
return false;
}
return true;
} catch ( Thrive_Dash_Api_EverWebinar_Exception $e ) {
return $e->getMessage();
}
}
/**
* Compose name from email address
*
* @param $email_address
* @param string $split
*
* @return string
*/
public function nameFromEmail( $email_address, $split = '@' ) {
return ucwords( str_replace( array(
'_',
'.',
'-',
'+',
',',
':',
), ' ', strtolower( substr( $email_address, 0, strripos( $email_address, $split ) ) ) ) );
}
/**
* add contact to list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|mixed|Thrive_Dash_List_Connection_Abstract
*/
public function add_subscriber( $list_identifier, $arguments ) {
$args = array( 'schedule' => 0 );
if ( is_array( $arguments ) ) {
if ( isset( $arguments['everwebinar_schedule'] ) ) {
$args['schedule'] = $arguments['everwebinar_schedule'];
}
if ( isset( $arguments['email'] ) && ! empty( $arguments['email'] ) ) {
$args['email'] = $arguments['email'];
}
if ( isset( $arguments['name'] ) && ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$args['first_name'] = $first_name;
$args['last_name'] = $last_name;
}
if ( ! empty( $args['email'] ) && empty( $arguments['name'] ) ) {
// First name is a required param, so we are building it for register forms with only email input
$args['first_name'] = $this->nameFromEmail( $args['email'] );
}
if ( isset( $arguments['phone'] ) && ! empty( $arguments['phone'] ) ) {
$args['phone'] = $arguments['phone'];
}
}
try {
$api = $this->get_api();
$webnar = $api->get_webinar_schedules( array( 'webinar_id' => $list_identifier ) );
if ( isset( $webnar['schedules'] ) ) {
$schedules = array_values( $webnar['schedules'] );
$args['schedule'] = $schedules[0]['schedule_id'];
}
$api->register_to_webinar( $list_identifier, $args );
} catch ( Exception $e ) {
return $this->error( $e->getMessage() );
}
return true;
}
/**
* @param array $params
*
* @return array
*/
public function get_extra_settings( $params = array() ) {
$webinar_id = '';
try {
// Used on webinar select/change ajax [in admin Lead generation]
if ( isset( $params['webinar_id'] ) ) {
$webinar_id = $params['webinar_id'];
} else {
$webinars = $this->get_api()->get_webinars();
if ( is_array( $webinars ) && isset( $webinars[0]['id'] ) ) {
$webinar_id = $webinars[0]['id'];
}
}
$params = $this->get_api()->get_webinar_schedules( array( 'webinar_id' => $webinar_id ) );
} catch ( Thrive_Dash_Api_EverWebinar_Exception $e ) {
}
return $params;
}
/**
* @return mixed|Thrive_Dash_Api_EverWebinar
* @throws Thrive_Dash_Api_EverWebinar_Exception
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_EverWebinar( array(
'apiKey' => $this->param( 'key' ),
)
);
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_EverWebinar $ever_webinar */
$ever_webinar = $this->get_api();
try {
return $ever_webinar->get_webinars();
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
}

View File

@@ -0,0 +1,216 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_Facebook extends Thrive_Dash_List_Connection_Abstract {
private static $scopes = 'email,public_profile';
protected $_key = 'facebook';
public $success_message = 'You are cool!';
/**
* Thrive_Dash_List_Connection_Facebook constructor.
*/
public function __construct() {
$this->set_credentials( Thrive_Dash_List_Manager::credentials( $this->_key ) );
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'social';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Facebook';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'facebook' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$app_id = ! empty( $_REQUEST['app_id'] ) ? sanitize_text_field( $_REQUEST['app_id'] ) : '';
$app_secret = ! empty( $_REQUEST['app_secret'] ) ? sanitize_text_field( $_REQUEST['app_secret'] ) : '';
if ( empty( $app_id ) || empty( $app_secret ) ) {
return $this->error( __( 'Both Client ID and Client Secret fields are required', 'thrive-dash' ) );
}
$this->set_credentials( array(
'app_id' => $app_id,
'app_secret' => $app_secret,
) );
/* app has been authorized */
if ( isset( $_REQUEST['code'] ) ) {
$this->get_api()->getUser();
$this->save();
return true;
}
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'You must give access to Facebook <a target="_blank" href="' . $this->getAuthorizeUrl() . '">here</a>.', 'thrive-dash' ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Facebook connected successfully!', 'thrive-dash' ) );
}
/**
* test if the secret key is correct and it exists.
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_Facebook $api */
$api = $this->get_api();
$user = $api->getUser();
$ready = false;
if ( $user ) {
try {
$info = $api->api( '/me' );
if ( is_array( $info ) ) {
$ready = true;
}
} catch ( Tve_Facebook_Api_Exception $e ) {
$ready = array(
'success' => false,
'message' => __( 'You must give access to Facebook <a target="_blank" href="' . $this->getAuthorizeUrl() . '">here</a>.', 'thrive-dash' ),
);
}
} else {
$ready = array(
'success' => false,
'message' => __( 'You must give access to Facebook <a target="_blank" href="' . $this->getAuthorizeUrl() . '">here</a>.', 'thrive-dash' ),
);
}
return $ready;
}
/**
* @return string
*/
public function getAuthorizeUrl() {
/** @var Thrive_Dash_Api_Facebook $api */
$api = $this->get_api();
return $api->getLoginUrl( array(
'scope' => self::$scopes,
'redirect_uri' => add_query_arg( array(
'page' => 'tve_dash_api_connect',
'api' => 'facebook',
'app_id' => $this->param( 'app_id' ),
'app_secret' => $this->param( 'app_secret' ),
), admin_url( 'admin.php' ) ),
) );
}
/**
* Those functions do not apply
*
* @return Thrive_Dash_Api_Facebook
*/
protected function get_api_instance() {
$params = array(
'appId' => $this->param( 'app_id' ),
'secret' => $this->param( 'app_secret' ),
);
return new Thrive_Dash_Api_Facebook( $params );
}
/**
* @param $fbid
* @param $comment_id
*
* @return array|string|void
*/
public function get_comment( $fbid, $comment_id ) {
/** @var Thrive_Dash_Api_Facebook $api */
$api = $this->get_api();
$comment = array();
$user = $api->getUser();
if ( $user ) {
try {
$response = $api->api( '/' . $fbid . '_' . $comment_id );
if ( is_array( $response ) ) {
$comment = array(
'id' => $response['from']['id'],
'name' => $response['from']['name'],
'picture' => 'https://graph.facebook.com/' . $response['from']['id'] . '/picture?type=large',
'message' => $response['message'],
);
}
} catch ( Tve_Facebook_Api_Exception $e ) {
$comment = __( 'Error! The Facebook link provided is invalid', 'thrive-dash' );
}
} else {
$comment = __( 'Your Facebook connection expired. Go to API Connections to reactivate it!', 'thrive-dash' );
}
return $comment;
}
/**
* @return string
*/
public function custom_success_message() {
return ' ';
}
protected function _get_lists() {
}
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_FacebookPixel extends Thrive_Dash_List_Connection_Abstract {
public function get_title() {
return 'Facebook (Meta) Marketing API';
}
public static function get_type() {
return 'collaboration';
}
public function output_setup_form() {
$this->output_controls_html( 'facebookpixel' );
}
public function read_credentials() {
$access_token = ! empty( $_REQUEST['connection']['access_token'] ) ? sanitize_text_field( $_REQUEST['connection']['access_token'] ) : '';
$pixel_id = ! empty( $_REQUEST['connection']['pixel_id'] ) ? sanitize_text_field( $_REQUEST['connection']['pixel_id'] ) : '';
if ( empty( $access_token ) || empty( $pixel_id ) ) {
return $this->error( __( 'Both Pixel ID and Access token fields are required', 'thrive-dash' ) );
}
$this->set_credentials( array(
'pixel_id' => $pixel_id,
'access_token' => $access_token,
) );
$result = $this->test_connection();
if ( $result['success'] !== true ) {
return empty( $result['message'] ) ? $this->error( __( 'Incorrect Pixel ID or Access token, please try again.', 'thrive-dash' ) ) : $result['message'];
}
$this->save();
return $this->success( __( 'Facebook Pixel connected successfully', 'thrive-dash' ) );
}
public function test_connection() {
return $this->get_api()->send_test_event();
}
/**
* No need to implement this method
*
* @param $list_identifier
* @param $arguments
*
* @return mixed|void
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
public function custom_success_message() {
return ' ';
}
/**
* Those functions do not apply
*
* @return Thrive_Dash_Api_FacebookPixel
*/
protected function get_api_instance() {
$params = array(
'pixel_id' => $this->param( 'pixel_id' ),
'access_token' => $this->param( 'access_token' ),
);
return new Thrive_Dash_Api_FacebookPixel( $params );
}
/**
* No need to implement this method
*/
protected function _get_lists() {
}
}

View File

@@ -0,0 +1,246 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_FileUpload_Dropbox
extends Thrive_Dash_List_Connection_Abstract
implements Thrive_Dash_List_Connection_FileUpload_Interface {
public static function get_type() {
return 'storage';
}
public function get_title() {
return 'Dropbox';
}
/**
* whether or not this list is connected to the service (has been authenticated)
*
* @return bool
*/
public function is_connected() {
return (bool) $this->param( 'access_token' );
}
public function output_setup_form() {
$this->output_controls_html( 'dropbox' );
}
/**
* Builds an authorization URI - the user will be redirected to that URI and asked to give app access
*
* @return string
*/
public function getAuthorizeUrl() {
$this->save(); // save the client_id and client_secret for later use
return $this->get_api()->get_authorize_url();
}
/**
* Called during the redirect from dropbox oauth flow
*
* _REQUEST contains a `code` parameter which needs to be sent back to g.api in exchange for an access token
*
* @return bool|mixed|string|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
$code = empty( $_REQUEST['code'] ) ? '' : sanitize_text_field( $_REQUEST['code'] );
if ( empty( $code ) ) {
return $this->error( 'Missing `code` parameter' );
}
try {
/* get access token from dropbox */
$response = $this->get_api()->get_access_token( $code );
if ( empty( $response['access_token'] ) ) {
throw new Thrive_Dash_Api_Dropbox_Exception( 'Missing token from response data' );
}
$this->_credentials = array(
'client_id' => $this->param( 'client_id' ),
'client_secret' => $this->param( 'client_secret' ),
'access_token' => $response['access_token'],
'expires_at' => time() + $response['expires_in'],
'refresh_token' => $response['refresh_token'],
);
$this->save();
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
$this->_credentials = array();
$this->save();
$this->error( $e->getMessage() );
return false;
}
return true;
}
public function test_connection() {
$result = array(
'success' => true,
'message' => __( 'Connection works', 'thrive-dash' ),
);
try {
/**
* Just trigger a "check user" API call
* https://www.dropbox.com/developers/documentation/http/documentation#check-user
*/
$this->get_api()->check_user();
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
return $result;
}
/**
* Upload a file to the storage
*
* @param string $file_contents contents of the uploaded file
* @param string $folder_id folder identification
* @param array $metadata file metadata props, such as name
*
* @return string|WP_Error stored file id or WP_Error if any exceptions occured
*/
public function upload( $file_contents, $folder_id, $metadata ) {
$dropbox_request = array(
'path' => trim( $folder_id, '/' ) . '/' . $metadata['name'],
'autorename' => false,
);
try {
$file = $this->get_api()->upload( $file_contents, $dropbox_request );
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
if ( $folder_id && strpos( $e->getMessage(), 'path/no_write_permission' ) !== false ) {
/* try again, uploading to the root folder of the app */
return $this->upload( $file_contents, '', $metadata );
}
return new WP_Error( 'tcb_file_upload_error', $e->getMessage() );
}
return $file['id'];
}
/**
* Rename an uploaded file by applying a callback function on its name
* The callback function should return the new filename
*
* @param string $file_id file ID from dropbox
* @param callable $callback function to apply to get the new filename
*
* @return array information about the renamed file
*/
public function rename_file( $file_id, $callback ) {
$file = $this->get_file_data( $file_id );
if ( ! is_callable( $callback ) || empty( $file['path'] ) ) {
return $file;
}
try {
$new_name = $callback( $file['name'] );
$new_path = rtrim( dirname( $file['path'] ), '/' ) . '/' . $new_name;
if ( $new_name !== $file['name'] ) {
$this->get_api()->move_file( $file['path'], $new_path );
$file['url'] = dirname( $file['url'] ) . '/' . $callback( basename( $file['url'] ) );
$file['path'] = $new_path;
$file['name'] = $new_name;
}
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
}
return $file;
}
/**
* Deletes an uploaded file
*
* @param string $file_id
*
* @return true|WP_Error
*/
public function delete( $file_id ) {
try {
$this->get_api()->delete( $file_id );
$result = true;
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
$result = new WP_Error( 'tcb_file_upload_error', $e->getMessage() );
}
return $result;
}
/**
* Retrieve the full URL to a file stored on drive
*
* @param string $file_id
*
* @return array containing URL and original name
*/
public function get_file_data( $file_id ) {
// fallback to a default home url (??)
$data = array(
'url' => 'https://www.dropbox.com/home',
'name' => $file_id,
);
try {
$file = $this->get_api()->get_file( $file_id );
$data['url'] = $file['url'];
$data['name'] = $file['name'];
$data['path'] = $file['path_display'];
} catch ( Thrive_Dash_Api_Dropbox_Exception $e ) {
$data['error'] = $e->getMessage();
}
return $data;
}
public function add_subscriber( $list_identifier, $arguments ) {
}
/**
* Instantiate the service and set any available data
*
* @return Thrive_Dash_Api_Dropbox_Service
* @throws Thrive_Dash_Api_Dropbox_Exception
*/
protected function get_api_instance() {
$api = new Thrive_Dash_Api_Dropbox_Service(
$this->param( 'client_id' ),
$this->param( 'client_secret' ),
$this->param( 'access_token' )
);
/* check for expired token and renew it */
if ( $this->param( 'refresh_token' ) && $this->param( 'expires_at' ) && time() > (int) $this->param( 'expires_at' ) ) {
$data = $api->refresh_access_token( $this->param( 'refresh_token' ) );
$this->_credentials['access_token'] = $data['access_token'];
$this->_credentials['expires_at'] = time() + $data['expires_in'];
$this->save();
}
return $api;
}
protected function _get_lists() {
}
}

View File

@@ -0,0 +1,233 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_FileUpload_GoogleDrive
extends Thrive_Dash_List_Connection_Abstract
implements Thrive_Dash_List_Connection_FileUpload_Interface {
public static function get_type() {
return 'storage';
}
public function get_title() {
return 'Google Drive';
}
/**
* Builds an authorization URI - the user will be redirected to that URI and asked to give app access
*
* @return string
*/
public function getAuthorizeUrl() {
$this->save(); // save the client_id and client_secret for later use
return $this->get_api()->get_authorize_url();
}
/**
* whether or not this list is connected to the service (has been authenticated)
*
* @return bool
*/
public function is_connected() {
return $this->param( 'access_token' ) && $this->param( 'refresh_token' );
}
public function output_setup_form() {
$this->output_controls_html( 'google-drive' );
}
/**
* Called during the redirect from google oauth flow
*
* _REQUEST contains a `code` parameter which needs to be sent back to g.api in exchange for an access token
*
* @return bool|mixed|string|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
$code = empty( $_REQUEST['code'] ) ? '' : $_REQUEST['code'];
if ( empty( $code ) ) {
return $this->error( 'Missing `code` parameter' );
}
try {
/* get access token from googleapis */
$response = $this->get_api()->get_access_token( $code );
if ( empty( $response['access_token'] ) ) {
throw new Thrive_Dash_Api_Google_Exception( 'Missing token from response data' );
}
$this->_credentials = array(
'client_id' => $this->param( 'client_id' ),
'client_secret' => $this->param( 'client_secret' ),
'access_token' => $response['access_token'],
'expires_at' => time() + $response['expires_in'],
'refresh_token' => $response['refresh_token'],
);
$this->save();
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
echo 'caught ex: ' . esc_html( $e->getMessage() );
$this->_credentials = array();
$this->save();
$this->error( $e->getMessage() );
return false;
}
return true;
}
public function test_connection() {
$result = array(
'success' => true,
'message' => __( 'Connection works', 'thrive-dash' ),
);
try {
$this->get_api()->get_files();
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
$result['success'] = false;
$result['message'] = $e->getMessage();
}
return $result;
}
/**
* Upload a file to the storage
*
* @param string $file_contents contents of the uploaded file
* @param string $folder_id folder identification
* @param array $metadata file metadata props, such as name
*
* @return string|WP_Error stored file id or WP_Error if any exceptions occured
*/
public function upload( $file_contents, $folder_id, $metadata ) {
$metadata['parents'] = array( $folder_id );
try {
$file = $this->get_api()->multipart_upload( $file_contents, $metadata );
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
return new WP_Error( 'tcb_file_upload_error', $e->getMessage() );
}
return $file['id'];
}
/**
* Deletes an uploaded file
*
* @param string $file_id
*
* @return true|WP_Error
*/
public function delete( $file_id ) {
try {
$this->get_api()->delete( $file_id );
$result = true;
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
$result = new WP_Error( 'tcb_file_upload_error', $e->getMessage() );
}
return $result;
}
/**
* Retrieve the full URL to a file stored on drive
*
* @param string $file_id
*
* @return array containing URL and original name
*/
public function get_file_data( $file_id ) {
// fallback to a default representation of a google file url
$data = array(
'url' => sprintf( 'https://drive.google.com/file/d/%s/view?usp=drivesdk', $file_id ),
'name' => $file_id,
);
try {
$file = $this->get_api()->get_file( $file_id, 'webViewLink,name' );
if ( ! empty( $file['webViewLink'] ) ) {
$data['url'] = $file['webViewLink'];
$data['name'] = $file['name'];
}
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
}
return $data;
}
/**
* Rename an uploaded file by applying a callback function on its name
* The callback function should return the new filename
*
* @param string $file_id file ID from google
* @param callable $callback function to apply to get the new filename
*
* @return array information about the renamed file
*/
public function rename_file( $file_id, $callback ) {
// fallback to a default representation of a google file url
$file = $this->get_file_data( $file_id );
/* if file[name] is identical to file_id this means we could not retrieve actual filedata from the api */
if ( ! is_callable( $callback ) || $file['name'] === $file_id ) {
return $file;
}
try {
$new_name = $callback( $file['name'] );
if ( $new_name !== $file['name'] ) {
$this->get_api()->update_file_metadata( $file_id, array(
'name' => $new_name,
) );
$file['name'] = $new_name;
}
} catch ( Thrive_Dash_Api_Google_Exception $e ) {
}
return $file;
}
/**
* Instantiate the service and set any available data
*
* @return Thrive_Dash_Api_Google_Service
*/
protected function get_api_instance() {
$api = new Thrive_Dash_Api_Google_Service(
$this->param( 'client_id' ),
$this->param( 'client_secret' ),
$this->param( 'access_token' )
);
/* check for expired token and renew it */
if ( $this->param( 'refresh_token' ) && $this->param( 'expires_at' ) && time() > (int) $this->param( 'expires_at' ) ) {
$data = $api->refresh_access_token( $this->param( 'refresh_token' ) );
$this->_credentials['access_token'] = $data['access_token'];
$this->_credentials['expires_at'] = time() + $data['expires_in'];
$this->save();
}
return $api;
}
protected function _get_lists() {
}
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
/**
* Interface Thrive_Dash_List_Connection_FileUpload_Interface
*
* Holds definitions for all the necessary functionality for connecting a file upload service with a Form element
*/
interface Thrive_Dash_List_Connection_FileUpload_Interface {
/**
* Upload a file to the storage
*
* @param string $file_contents contents of the uploaded file
* @param string $folder_id folder identification
* @param array $metadata file metadata props, such as name
*
* @return string|WP_Error stored file id or WP_Error if any exceptions occured
*/
public function upload( $file_contents, $folder_id, $metadata );
/**
* Retrieve data about a stored file
*
* @param string $file_id
*
* @return array containing URL and original name
*/
public function get_file_data( $file_id );
/**
* Deletes an uploaded file
*
* @param string $file_id
*
* @return true|WP_Error
*/
public function delete( $file_id );
/**
* Rename an uploaded file by applying a callback function on its name
* The callback function should return the new filename
*
* @param string $file_id file ID from google
* @param callable $callback function to apply to get the new filename
*
* @return array information about the renamed file
*/
public function rename_file( $file_id, $callback );
}

View File

@@ -0,0 +1,388 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
use FluentCrm\App\Models\CustomContactField;
class Thrive_Dash_List_Connection_FluentCRM extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'FluentCRM';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
/**
* @return bool
*/
public function has_optin() {
return true;
}
/**
* check whether or not the FluentCRM plugin is installed
*/
public function pluginInstalled() {
return function_exists( 'FluentCrmApi' );
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'fluentcrm' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
if ( ! $this->pluginInstalled() ) {
return $this->error( __( 'FluentCRM plugin must be installed and activated.', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection', array() ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( '<strong>' . $result . '</strong>)' );
}
/**
* finally, save the connection details
*/
$this->save();
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
if ( ! $this->pluginInstalled() ) {
return __( 'FluentCRM plugin must be installed and activated.', 'thrive-dash' );
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! $this->pluginInstalled() ) {
return __( 'FluentCRM plugin is not installed / activated', 'thrive-dash' );
}
$name_array = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$name_array = array(
'first_name' => $first_name,
'last_name' => $last_name,
);
}
if ( ! empty( $arguments['phone'] ) ) {
$prepared_args['phone'] = $arguments['phone'];
}
if ( ! empty( $arguments['tve_mapping'] ) ) {
$prepared_args['custom_values'] = $this->buildMappedCustomFields( $arguments );
}
$prepared_args['tags'] = array();
$tag_key = $this->get_tags_key();
if ( ! empty( $arguments[ $tag_key ] ) ) {
$prepared_args['tags'] = $this->importTags( $arguments[ $tag_key ] );
}
if ( isset( $arguments['fluentcrm_optin'] ) && 'd' === $arguments['fluentcrm_optin'] ) {
$prepared_args['status'] = 'pending';
}
$data = [
'email' => $arguments['email'],
'lists' => array( $list_identifier ),
];
$data = array_merge( $data, $name_array, $prepared_args );
try {
$fluent = FluentCrmApi( 'contacts' );
$contact = $fluent->createOrUpdate( $data );
if ( $contact->status === 'pending' ) {
$contact->sendDoubleOptinEmail();
}
} catch ( Exception $exception ) {
return $exception->getMessage();
}
return true;
}
/**
* Import tags
*
* @return array true for success or error message for failure
*/
public function importTags( $tags ) {
$imported_tags = array();
$inserted_tags = array();
if ( ! empty( $tags ) ) {
$tags = explode( ',', trim( $tags, ' ,' ) );
foreach ( $tags as $tag ) {
$inserted_tags[] = array(
'title' => $tag,
);
}
$inserted_tags = FluentCrmApi( 'tags' )->importBulk( $inserted_tags );//[1,2,3]
foreach ( $inserted_tags as $new_tag ) {
$imported_tags[] = $new_tag->id;
}
}
return $imported_tags;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function buildMappedCustomFields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
if ( is_array( $form_data ) ) {
foreach ( $this->get_mapped_field_ids() as $mapped_field ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$custom_fields = preg_grep( "#^{$mapped_field}#i", array_keys( $form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $custom_fields ) && is_array( $custom_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $custom_fields as $cf_name ) {
if ( empty( $form_data[ $cf_name ][ $this->_key ] ) ) {
continue;
}
$field_id = $form_data[ $cf_name ][ $this->_key ];
$cf_name = str_replace( '[]', '', $cf_name );
if ( ! empty( $args[ $cf_name ] ) ) {
$args[ $cf_name ] = $this->process_field( $args[ $cf_name ] );
$mapped_data[ $field_id ] = sanitize_text_field( $args[ $cf_name ] );
}
}
}
}
}
return $mapped_data;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
// no API instance needed here
return null;
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
if ( ! $this->pluginInstalled() ) {
$this->_error = __( 'FluentCRM plugin could be found.', 'thrive-dash' );
return false;
}
$lists = array();
$list_api = FluentCrmApi( 'lists' );
// Get all the lists
$all_lists = $list_api->all();
foreach ( $all_lists as $list ) {
$lists[] = array(
'id' => $list->id,
'name' => $list->title,
);
}
return $lists;
}
public function get_tags() {
if ( ! $this->pluginInstalled() ) {
$this->_error = __( 'FluentCRM plugin could be found.', 'thrive-dash' );
return array();
}
$tags = array();
$tag_api = FluentCrmApi( 'tags' );
// Get all the tags
$all_tags = $tag_api->all();
foreach ( $all_tags as $tag ) {
$tags[] = array(
'id' => $tag->id,
'text' => $tag->title,
'selected' => false,
);
}
return $tags;
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
return $this->get_all_custom_fields( $force );
}
/**
* @param (bool) $force
*
* @return array|mixed
*/
public function get_all_custom_fields( $force ) {
$custom_data = array();
if ( class_exists( 'FluentCrm\App\Models\CustomContactField' ) ) {
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_fields = ( new CustomContactField )->getGlobalFields()['fields'];
if ( is_array( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
if ( ! empty( $field['type'] ) && $field['type'] === 'text' ) {
$custom_data[] = $this->normalize_custom_field( $field );
}
}
}
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* Normalize custom field data
*
* @param $field
*
* @return array
*/
protected function normalize_custom_field( $field ) {
$field = (array) $field;
return array(
'id' => isset( $field['slug'] ) ? $field['slug'] : '',
'name' => ! empty( $field['label'] ) ? $field['label'] : '',
'type' => ! empty( $field['type'] ) ? $field['type'] : '',
'label' => ! empty( $field['label'] ) ? $field['label'] : '',
);
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{contact.email}}';
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields', 'optin', 'tag_input' ) );
}
}

View File

@@ -0,0 +1,574 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_GetResponse extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'GetResponse';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'get-response' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$connection = $this->post( 'connection' );
$version = (string) ( isset( $connection['version'] ) ? $connection['version'] : '' );
if ( empty( $connection['key'] ) ) {
return $this->error( __( 'You must provide a valid GetResponse key', 'thrive-dash' ) );
}
if ( $version === '3' && empty( $connection['url'] ) ) {
return $this->error( __( 'You must provide a valid GetResponse V3 API URL', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to GetResponse using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'GetResponse connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$gr = $this->get_api();
/**
* just try getting a list as a connection test
*/
$credentials = $this->get_credentials();
try {
if ( ! $credentials['version'] || $credentials['version'] == 2 ) {
/** @var Thrive_Dash_Api_GetResponse $gr */
$gr->getCampaigns();
} else {
/** @var Thrive_Dash_Api_GetResponseV3 $gr */
$gr->ping();
}
} catch ( Thrive_Dash_Api_GetResponse_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_GetResponse|Thrive_Dash_Api_GetResponseV3
*/
protected function get_api_instance() {
if ( ! $this->param( 'version' ) || $this->param( 'version' ) == 2 ) {
return new Thrive_Dash_Api_GetResponse( $this->param( 'key' ) );
}
$getresponse = new Thrive_Dash_Api_GetResponseV3( $this->param( 'key' ), $this->param( 'url' ) );
$enterprise_param = $this->param( 'enterprise' );
if ( ! empty( $enterprise_param ) ) {
$getresponse->enterprise_domain = $this->param( 'enterprise' );
}
return $getresponse;
}
/**
* get all Subscriber Lists from this API service
*
* @return array|false
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_GetResponse $gr */
$gr = $this->get_api();
try {
$lists = array();
$items = $gr->getCampaigns();
$credentials = $this->get_credentials();
if ( ! $credentials['version'] || $credentials['version'] == 2 ) {
foreach ( $items as $key => $item ) {
$lists [] = array(
'id' => $key,
'name' => $item->name,
);
}
} else {
foreach ( $items as $item ) {
$lists [] = array(
'id' => $item->campaignId,
'name' => $item->name,
);
}
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* delete a contact from the list
*
* @param string $email
* @param array $arguments
*
* @return mixed
*/
public function delete_subscriber( $email, $arguments = array() ) {
$api = $this->get_api();
if ( ! empty( $email ) ) {
$contacts = $api->searchContacts(
array(
'query' => array(
'email' => $email,
),
)
);
if ( ! empty( $contacts ) ) {
foreach ( $contacts as $contact ) {
$api->deleteContact( $contact->contactId, array() );
}
}
return true;
}
return false;
}
/**
* add a contact to a list
*
* @param string $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_GetResponseV3 $api */
$api = $this->get_api();
$credentials = $this->get_credentials();
$return = true;
$version = empty( $credentials['version'] ) ? 2 : (int) $credentials['version'];
try {
if ( 2 === $version ) {
if ( empty( $arguments['name'] ) ) {
$arguments['name'] = ' ';
}
/** @var Thrive_Dash_Api_GetResponse $api */
$api->addContact( $list_identifier, $arguments['name'], $arguments['email'], 'standard', (int) empty( $arguments['get-response_cycleday'] ) ? 0 : $arguments['get-response_cycleday'] );
} else {
$params = array(
'email' => $arguments['email'],
'dayOfCycle' => empty( $arguments['get-response_cycleday'] ) ? 0 : $arguments['get-response_cycleday'],
'campaign' => array(
'campaignId' => $list_identifier,
),
'ipAddress' => tve_dash_get_ip(),
);
if ( ! empty( $arguments['name'] ) ) {
$params['name'] = $arguments['name'];
}
// forward already inserted custom fields
if ( ! empty( $arguments['CustomFields'] ) ) {
$params['customFieldValues'] = $arguments['CustomFields'];
}
// Set / Create & set Phone as custom field
if ( ! empty( $arguments['phone'] ) ) {
$params = array_merge( $params, $this->setCustomPhone( $arguments, $params ) );
}
// Build custom fields data
$existing_custom_fields = ! empty( $params['customFieldValues'] ) ? $params['customFieldValues'] : array();
$mapped_custom_fields = $this->buildMappedCustomFields( $arguments, $existing_custom_fields );
if ( ! empty( $mapped_custom_fields ) ) {
$params = array_merge( $params, $mapped_custom_fields );
}
try {
/**
* this contact may be in other list but try to add it in the current on
*/
$api->addContact( $params );
return true;
} catch ( Exception $e ) {
}
/**
* we're talking about the same email but
* it is the same contact in multiple list
*/
$contacts = $api->searchContacts(
array(
'query' => array(
'email' => $params['email'],
),
)
);
if ( ! empty( $contacts ) ) {
foreach ( $contacts as $contact ) {
/**
* Update the subscriber only in current list
*/
if ( $contact->campaign->campaignId === $params['campaign']['campaignId'] ) {
$api->updateContact( $contact->contactId, $params );
}
}
}
}
} catch ( Exception $e ) {
$return = $e->getMessage();
}
return $return;
}
/**
* Build or add to existing custom fields array
*
* @param array $args
* @param array $mapped_data
*
* @return array
*/
public function buildMappedCustomFields( $args, $mapped_data = array() ) {
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) || ! is_array( $mapped_data ) ) {
return array();
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
if ( is_array( $form_data ) ) {
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$mapped_api_id = $form_data[ $cf_form_name ][ $this->_key ];
$cf_form_name = str_replace( '[]', '', $cf_form_name );
if ( ! empty( $args[ $cf_form_name ] ) ) {
$args[ $cf_form_name ] = $this->process_field( $args[ $cf_form_name ] );
$mapped_data[] = array(
'customFieldId' => $mapped_api_id,
'value' => array( sanitize_text_field( $args[ $cf_form_name ] ) ),
);
}
}
}
}
}
return ! empty( $mapped_data ) ? array( 'customFieldValues' => $mapped_data ) : array();
}
/**
* Set / create&set a new phone custom field
*
* @param $arguments
* @param array $params
*
* @return array
*/
public function setCustomPhone( $arguments, $params = array() ) {
if ( empty( $arguments ) || ! is_array( $params ) ) {
return array();
}
$custom_fields = $this->get_api()->getCustomFields();
if ( is_array( $custom_fields ) ) {
$phone_field = array_values( wp_list_filter( $custom_fields, array( 'name' => 'thrvphone' ) ) );
/**
* We use a custom field to add phone filed for getResponse
* This because getResponse has a strict validation for built in phone number and very often added contacts
* with this custom field will fail
*/
if ( empty( $phone_field ) ) {
$field_args = array(
'name' => 'thrvphone',
'type' => 'number',
'hidden' => false,
'values' => array(),
);
$phone_field = $this->get_api()->setCustomField( $field_args );
}
if ( ! empty( $phone_field[0]->customFieldId ) ) {
$phone_value = str_replace( array( '-', '+', ' ' ), '', trim( $arguments['phone'] ) );
$params['customFieldValues'] = array(
array(
'customFieldId' => $phone_field[0]->customFieldId,
'value' => array( $phone_value ),
),
);
}
}
return $params;
}
/**
* Render extra html API setup form
*
* @param array $params
*
* @return array
*/
public function get_extra_settings( $params = array() ) {
return $params;
}
/**
* Render extra html API setup form
*
* @param array $params
*
* @see api-list.php
*
*/
public function render_extra_editor_settings( $params = array() ) {
$this->output_controls_html( 'getresponse/cycleday', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[[email]]';
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
// Needed custom fields type [every API can have different naming type]
$allowed_types = array(
'text',
'url',
);
$custom_data = array();
try {
/** @var Thrive_Dash_Api_GetResponseV3 $api */
$custom_fields = $this->get_api()->getCustomFields();
if ( is_array( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
if ( ! empty( $field->type ) && in_array( $field->type, $allowed_types, true ) ) {
$custom_data[] = $this->normalize_custom_field( $field );
}
}
}
$this->_save_custom_fields( $custom_data );
} catch ( Thrive_Dash_Api_GetResponse_Exception $e ) {
}
return $custom_data;
}
/**
* @param array $field
*
* @return array
*/
protected function normalize_custom_field( $field ) {
$field = (object) $field;
return array(
'id' => ! empty( $field->customFieldId ) ? $field->customFieldId : '',
'name' => ! empty( $field->name ) ? $field->name : '',
'type' => ! empty( $field->type ) ? $field->type : '',
'label' => ! empty( $field->name ) ? $field->name : '',
);
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$args['CustomFields'] = $this->prepare_custom_fields_for_api( $custom_fields, $list_id );
$this->add_subscriber( $list_id, $args );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
if ( empty( $custom_fields ) ) {
return $prepared_fields;
}
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $field['id'] == $key ) {
$prepared_fields[] = array(
'customFieldId' => $field['id'],
'value' => array( $custom_field ),
);
}
}
}
return $prepared_fields;
}
}

View File

@@ -0,0 +1,355 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_GoToWebinar extends Thrive_Dash_List_Connection_Abstract {
/**
* @var string
*/
private $_consumer_key = 'Mtm8i2IdR2mOkAY3uVoW5f4TdGaBxpkY';
/**
* @var string
*/
private $_consumer_secret = 'qjr8KW9Ga6G2AJjE';
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'webinar';
}
/**
* check if the expires_at field is in the past
* GoToWebinar auth access tokens expire after about one year
*
* @return bool
*/
public function isExpired() {
if ( ! $this->is_connected() ) {
return false;
}
$expires_at = $this->param( 'expires_at' );
return time() > $expires_at;
}
/**
* get the expiry date and time user-friendly formatted
*/
public function getExpiryDate() {
return date( 'l, F j, Y H:i:s', $this->param( 'expires_at' ) );
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'GoToWebinar';
}
/**
* these are called webinars, not lists
*
* @return string
*/
public function get_list_sub_title() {
return __( 'Choose from the following upcoming webinars', 'thrive-dash' );
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'gotowebinar' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
if ( empty( $_POST['gtw_email'] ) || empty( $_POST['gtw_password'] ) ) {
return $this->error( __( 'Email and password are required', 'thrive-dash' ) );
}
$email = sanitize_text_field( $_POST['gtw_email'] );
$password = sanitize_text_field( $_POST['gtw_password'] );
$v = array(
'version' => ! empty( $_POST['connection']['version'] ) ? sanitize_text_field( $_POST['connection']['version'] ) : '',
'versioning' => ! empty( $_POST['connection']['versioning'] ) ? sanitize_text_field( $_POST['connection']['versioning'] ) : '',
);
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
try {
$api->directLogin( $email, $password, $v );
$credentials = $api->get_credentials();
// Add inbox notification for v2 connection
if ( TD_Inbox::instance()->api_is_connected( $this->get_key() ) && ! empty( $credentials['version'] ) && 2 === (int) $credentials['version'] && ! empty( $credentials['versioning'] ) ) {
$this->add_notification( 'added_v2' );
// Remove notification from api connection
TVE_Dash_InboxManager::instance()->remove_api_connection( $this->get_key() );
}
$this->set_credentials( $credentials );
/**
* finally, save the connection details
*/
$this->save();
return $this->success( 'GoToWebinar connected successfully' );
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to GoToWebinar using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
}
/**
* @param string $type
*
* @return bool
*/
public function add_notification( $type = '' ) {
if ( empty( $type ) ) {
return false;
}
$message = array();
$inbox_manager = TVE_Dash_InboxManager::instance();
switch ( $type ) {
case 'added_v2':
$message = array(
'title' => __( 'Your GoToWebinar Connection has been Updated!', 'thrive-dash' ),
'info' => 'Good job - you\'ve just upgraded your GoToWebinar connection to 2.0.<br /><br />
You don\'t need to make any changes to your existing forms - they will carry on working as before. <br /><br />
However, we highly recommend that you sign up through one of your webinar forms to make sure that everything is working as expected.<br /><br />
If you experience any issues, let our <a href="https://thrivethemes.com/forums/forum/general-discussion/" target="_blank">support team</a> know and we\'ll get to the bottom of this for you. <br /><br />
From your team at Thrive Themes ',
'type' => TD_Inbox_Message::TYPE_INBOX,
);
break;
}
if ( empty( $message ) ) {
return false;
}
try {
$message_obj = new TD_Inbox_Message( $message );
$inbox_manager->prepend( $message_obj );
$inbox_manager->push_notifications();
} catch ( Exception $e ) {
}
}
/**
* @return mixed|string
*/
public function getUsername() {
$credentials = (array) $this->get_credentials();
if ( ! empty( $credentials['username'] ) ) {
return $credentials['username'];
}
return '';
}
/**
* @return mixed|string
*/
public function getPassword() {
$credentials = (array) $this->get_credentials();
if ( ! empty( $credentials['password'] ) ) {
return $credentials['password'];
}
return '';
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
$phone = isset( $arguments['phone'] ) ? $arguments['phone'] : null;
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
if ( empty( $last_name ) ) {
$last_name = $first_name;
}
if ( empty( $first_name ) && empty( $last_name ) ) {
list( $first_name, $last_name ) = $this->get_name_from_email( $arguments['email'] );
}
try {
$api->registerToWebinar( $list_identifier, $first_name, $last_name, $arguments['email'], $phone );
return true;
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
*
* @return int the number of days in which this token will expire
*/
public function expiresIn() {
$expires_at = $this->param( 'expires_at' );
return (int) ( ( $expires_at - time() ) / ( 3600 * 24 ) );
}
/**
* check if the connection is about to expire in less than 30 days or it's already expired
*/
public function get_warnings() {
if ( ! $this->is_connected() ) {
return array();
}
$fix = '<a href="' . admin_url( 'admin.php?page=tve_dash_api_connect' ) . '#edit/' . $this->get_key() . '">' . __( 'Click here to renew the token', 'thrive-dash' ) . '</a>';
if ( $this->isExpired() ) {
return array(
sprintf( __( 'Thrive API Connections: The access token for %s has expired on %s.', 'thrive-dash' ), '<strong>' . $this->get_title() . '</strong>', '<strong>' .
$this->getExpiryDate() . '</strong>' ) . ' ' . $fix . '.',
);
}
$diff = $this->expiresIn();
if ( $diff > 30 ) {
return array();
}
$message = $diff == 0
?
__( 'Thrive API Connections: The access token for %s will expire today.', 'thrive-dash' )
:
( $diff == 1
?
__( 'Thrive API Connections: The access token for %s will expire tomorrow.', 'thrive-dash' )
:
__( 'Thrive API Connections: The access token for %s will expire in %s days.', 'thrive-dash' ) );
return array(
sprintf( $message, '<strong>' . $this->get_title() . '</strong>', '<strong>' . $diff . '</strong>' ) . ' ' . $fix . '.',
);
}
/**
* instantiate the API code required for this connection
*
* @return mixed|Thrive_Dash_Api_GoToWebinar
* @throws Thrive_Dash_Api_GoToWebinar_Exception
*/
protected function get_api_instance() {
$access_token = $organizer_key = null;
$settings = array();
if ( $this->is_connected() && ! $this->isExpired() ) {
$access_token = $this->param( 'access_token' );
$organizer_key = $this->param( 'organizer_key' );
$settings = array(
'version' => $this->param( 'version' ),
'versioning' => $this->param( 'versioning' ),
// used on class instances from [/v1/, /v2/ etc] namespace folder
'expires_in' => $this->param( 'expires_in' ),
'auth_type' => $this->param( 'auth_type' ),
'refresh_token' => $this->param( 'refresh_token' ),
'username' => $this->param( 'username' ),
'password' => $this->param( 'password' ),
);
}
$settings['auth_key'] = base64_encode( $this->_consumer_key . ':' . $this->_consumer_secret );
return new Thrive_Dash_Api_GoToWebinar( $this->_consumer_key, $access_token, $organizer_key, $settings );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
$lists = array();
try {
$all = $api->getUpcomingWebinars();
foreach ( $all as $item ) {
preg_match( '#register/(\d+)$#', $item['registrationUrl'], $m );
$id_from_registration_url = isset( $m[1] ) ? $m[1] : '';
$lists [] = array(
'id' => ! empty( $item['webinarKey'] ) ? $item['webinarKey'] : $id_from_registration_url,
'name' => $item['subject'] . ' (' . date( 'Y-m-d H:i:s', strtotime( $item['times'][0]['startTime'] ) ) . ')',
);
}
return $lists;
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_Google extends Thrive_Dash_List_Connection_Abstract {
protected $_key = 'google';
/**
* Thrive_Dash_List_Connection_Google constructor.
*/
public function __construct() {
$this->set_credentials( Thrive_Dash_List_Manager::credentials( $this->_key ) );
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'social';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Google';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'google' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$client_id = ! empty( $_POST['client_id'] ) ? sanitize_text_field( $_POST['client_id'] ) : '';
$client_secret = ! empty( $_POST['client_secret'] ) ? sanitize_text_field( $_POST['client_secret'] ) : '';
$api_key = ! empty( $_POST['api_key'] ) ? sanitize_text_field( $_POST['api_key'] ) : '';
if ( empty( $client_id ) || empty( $client_secret ) ) {
return $this->error( __( 'Both Client ID and Client Secret fields are required', 'thrive-dash' ) );
}
$this->set_credentials( array( 'client_id' => $client_id, 'client_secret' => $client_secret, 'api_key' => $api_key ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Incorrect Client ID.', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Google connected successfully!', 'thrive-dash' ) );
}
/**
* test if the secret key is correct, and it exists.
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
//TODO: implement testing the connection
return true;
}
/**
* @return string
*/
public function custom_success_message() {
return ' ';
}
/*
* Those functions do not apply
*/
protected function get_api_instance() {
}
protected function _get_lists() {
}
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,161 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_HubSpot extends Thrive_Dash_List_Connection_Abstract {
/**
* @return string the API connection title
*/
public function get_title() {
return 'HubSpot';
}
/**
* @return string
*/
public function get_list_sub_title() {
return __( 'Choose from the following contact lists', 'thrive-dash' );
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'hubspot' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$connection = $this->post( 'connection' );
$key = $connection['key'];
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid HubSpot key', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to HubSpot using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'HubSpot connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$api = $this->get_api();
/**
* just try getting the static contact lists as a connection test
*/
try {
$api->getContactLists(); // this will throw the exception if there is a connection problem
} catch ( Thrive_Dash_Api_HubSpot_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
$key = $this->param( 'key' );
$version = $this->param( 'version' );
if ( ! empty( $version ) && $version == 2 ) {
return new Thrive_Dash_Api_HubSpotV2( $key );
}
return new Thrive_Dash_Api_HubSpot( $key );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
$api = $this->get_api();
try {
$lists = array();
$contactLists = $api->getContactLists();
foreach ( $contactLists as $key => $item ) {
$lists [] = array(
'id' => $item['listId'],
'dynamic' => ! empty( $item['dynamic'] ),
'name' => $item['name'],
);
}
return $lists;
} catch ( Thrive_Dash_Api_HubSpot_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* add a contact to a static list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
$api = $this->get_api();
try {
$name = empty( $arguments['name'] ) ? '' : $arguments['name'];
$phone = empty( $arguments['phone'] ) ? '' : $arguments['phone'];
$api->registerToContactList( $list_identifier, $name, $arguments['email'], $phone );
return true;
} catch ( Thrive_Dash_Api_HubSpot_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{contact.email}}';
}
}

View File

@@ -0,0 +1,833 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Infusionsoft extends Thrive_Dash_List_Connection_Abstract {
/**
* @var array Allowed custom fields
*/
protected $_custom_fields = array();
/**
* Thrive_Dash_List_Connection_Infusionsoft constructor.
*
* @param $key
*/
public function __construct( $key ) {
parent::__construct( $key );
// DataType ID for text and website
$this->_custom_fields = array(
15 => 'text',
18 => 'url',
);
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'Keap (Infusionsoft)';
}
public function get_list_sub_title() {
return __( 'Choose your Tag Name List', 'thrive-dash' );
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
/**
* @param array|string $tags
* @param array $data
*
* @return array
*/
public function push_tags( $tags, $data = array() ) {
$data['tqb_tags'] = implode( ', ', $tags );
return $data;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'infusionsoft' );
}
/**
* just save the key in the database
*
* @return mixed
*/
public function read_credentials() {
$client_id = ! empty( $_POST['connection']['client_id'] ) ? sanitize_text_field( $_POST['connection']['client_id'] ) : '';
$key = ! empty( $_POST['connection']['api_key'] ) ? sanitize_text_field( $_POST['connection']['api_key'] ) : '';
if ( empty( $key ) || empty( $client_id ) ) {
return $this->error( __( 'Client ID and API key are required', 'thrive-dash' ) );
}
$this->set_credentials( array( 'client_id' => $client_id, 'api_key' => $key ) );
$result = $this->test_connection();
if ( true !== $result ) {
/* translators: %s: error message */
$error = __( 'Could not connect to Keap (Infusionsoft) using the provided credentials (<strong>%s</strong>)', 'thrive-dash' );
return $this->error( sprintf( $error, $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( 'Keap (Infusionsoft) connected successfully' );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/**
* just try getting a list as a connection test
*/
$result = $this->_get_lists();
if ( is_array( $result ) ) {
return true;
}
/* At this point, $result will be a string */
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed|Thrive_Dash_Api_Infusionsoft
* @throws Thrive_Dash_Api_Infusionsoft_InfusionsoftException
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Infusionsoft( $this->param( 'client_id' ), $this->param( 'api_key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
try {
/** @var Thrive_Dash_Api_Infusionsoft $api */
$api = $this->get_api();
$query_data = array(
'GroupName' => '%',
);
$selected_fields = array( 'Id', 'GroupName' );
$response = $api->data( 'query', 'ContactGroup', 1000, 0, $query_data, $selected_fields );
if ( empty( $response ) ) {
return array();
}
$tags = $response;
/**
* Infusionsoft has a limit of 1000 results to fetch, we should get all tags if the user has more
*/
$i = 1;
while ( count( $response ) === 1000 ) {
$response = $api->data( 'query', 'ContactGroup', 1000, $i, $query_data, $selected_fields );
$tags = array_merge( $tags, $response );
$i ++;
}
$lists = array();
foreach ( $tags as $item ) {
$lists[] = array(
'id' => $item['Id'],
'name' => $item['GroupName'],
);
}
return $lists;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* delete a contact from the list
*
* @param string $email
* @param array $arguments
*
* @return mixed
*/
public function delete_subscriber( $email, $arguments = array() ) {
$api = $this->get_api();
if ( ! empty( $email ) && ! empty( $arguments['list_identifier'] ) ) {
$contact = $this->get_contact( $arguments['list_identifier'], $email );
if ( ! empty( $contact ) ) {
$user_hash = md5( $email );
$api->request( 'lists/' . $arguments['list_identifier'] . '/members/' . $user_hash, array(), 'DELETE' );
}
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
/** @var Thrive_Dash_Api_Infusionsoft $api */
$api = $this->get_api();
$name_array = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$name_array = array(
'FirstName' => $first_name,
'LastName' => $last_name,
);
}
$phone_array = array();
if ( ! empty( $arguments['name'] ) ) {
$phone_array = array(
'Phone1' => $arguments['phone'],
);
}
$data = array(
'Email' => $arguments['email'],
);
$data = array_merge( $data, $name_array, $phone_array );
$contact_id = $api->contact( 'addWithDupCheck', $data, 'Email' );
if ( $contact_id ) {
$api->APIEmail( 'optIn', $data['Email'], 'thrive opt in' );
$today = date( 'Ymj\TG:i:s' );
$creation_notes = 'A web form was submitted with the following information:';
$ip_address = tve_dash_get_ip();
if ( ! empty( $arguments['url'] ) ) {
$creation_notes .= "\nReferring URL: " . $arguments['url'];
}
$creation_notes .= "\nIP Address: " . $ip_address;
$creation_notes .= "\ninf_field_Email: " . $arguments['email'];
if ( ! empty( $first_name ) ) {
$creation_notes .= "\ninf_field_LastName: " . $last_name;
$creation_notes .= "\ninf_field_FirstName: " . $first_name;
}
$add_note = array(
'ContactId' => $contact_id,
'CreationDate' => $today,
'CompletionDate' => $today,
'ActionDate' => $today,
'EndDate' => $today,
'ActionType' => 'Other',
'ActionDescription' => 'Thrive Leads Note',
'CreationNotes' => $creation_notes,
);
$api->data( 'add', 'ContactAction', $add_note );
if ( ! empty( $arguments['tve_affiliate'] ) ) {
$api->data( 'add', 'Referral', array(
'AffiliateId' => $arguments['tve_affiliate'],
'ContactId' => $contact_id,
'DateSet' => $today,
'IPAddress' => $ip_address,
'Source' => 'thrive opt in',
) );
}
}
$contact = $api->contact(
'load',
$contact_id,
array(
'Id',
'Email',
'Groups',
)
);
$existing_groups = empty( $contact['Groups'] ) ? array() : explode( ',', $contact['Groups'] );
if ( ! in_array( $list_identifier, $existing_groups ) ) {
$api->contact( 'addToGroup', $contact_id, $list_identifier );
}
do_action( 'tvd_after_infusionsoft_contact_added', $this, $contact, $list_identifier, $arguments );
// Update custom fields
// Make another call to update custom mapped fields in order not to break the subscription call,
// if custom data doesn't pass API custom fields validation
if ( ! empty( $arguments['tve_mapping'] ) || ! empty( $arguments['automator_custom_fields'] ) ) {
$this->updateCustomFields( $contact_id, $arguments );
}
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '~Contact.Email~';
}
/**
* Retrieve the contact's tags.
* Tags in Infusionsoft are named Groups
*
* @param int $contact_id
*
* @return array
*/
public function get_contact_tags( $contact_id ) {
$tags = array();
if ( empty( $contact_id ) ) {
return $tags;
}
$api = $this->get_api();
$query_data = array(
'ContactId' => $contact_id,
);
$selected_fields = array(
'GroupId',
'ContactGroup',
);
$saved_tags = $api->data( 'query', 'ContactGroupAssign', 9999, 0, $query_data, $selected_fields );
if ( ! empty( $saved_tags ) ) {
/**
* set the group id as key in tags array and
* set as value the group name
*/
foreach ( $saved_tags as $item ) {
$tags[ $item['GroupId'] ] = $item['ContactGroup'];
}
}
return $tags;
}
/**
* Retrieve all tags(groups) form Infusionsoft for current connection
*
* @return array
*/
public function get_tags( $use_cache = true ) {
$tags = array();
if ( $use_cache ) {
$lists = $this->get_lists();
foreach ( $lists as $list ) {
$tags[ $list['id'] ] = $list['name'];
}
return $tags;
}
$api = $this->get_api();
$query_data = array(
'Id' => '%',
);
$selected_fields = array(
'Id',
'GroupName',
);
$saved_tags = $api->data( 'query', 'ContactGroup', 1000, 0, $query_data, $selected_fields );
$data = $saved_tags;
/**
* Infusionsoft has a limit of 1000 results to fetch, we should get all tags if the user has more
*/
$i = 1;
while ( count( $saved_tags ) === 1000 ) {
$saved_tags = $api->data( 'query', 'ContactGroup', 1000, $i, $query_data, $selected_fields );
$data = array_merge( $data, $saved_tags );
$i ++;
}
if ( ! empty( $data ) ) {
foreach ( $data as $item ) {
$tags[ $item['Id'] ] = $item['GroupName'];
}
}
return $tags;
}
/**
* Add a new Tag(Group) to Infusionsoft
*
* @param $tag_name
*
* @return int|null id
*/
public function create_tag( $tag_name ) {
$query_data = array(
'GroupName' => $tag_name,
);
$selected_fields = array(
'Id',
'GroupName',
);
$tags = $this->get_api()->data( 'query', 'ContactGroup', 1, 0, $query_data, $selected_fields );
if ( is_array( $tags ) && ! empty( $tags ) ) {
$tag = $tags[0];
if ( isset( $tag['Id'] ) ) {
return $tag['Id'];
}
}
$id = $this->get_api()->data(
'add',
'ContactGroup',
array(
'GroupName' => $tag_name,
)
);
$this->get_lists( false );
return ! empty( $id ) ? $id : null;
}
/**
* @param array $params which may contain `list_id`
* @param bool $force make a call to API and invalidate cache
* @param bool $get_all where to get lists with their custom fields
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
$custom_fields = array();
try {
$custom_fields = $this->get_all_custom_fields( $force );
} catch ( Thrive_Dash_Api_Infusionsoft_InfusionsoftException $e ) {
}
return $custom_fields;
}
/**
* Get all custom fields
*
* @param $force calls the API and invalidate cache
*
* @return array|mixed
*/
public function get_all_custom_fields( $force ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_fields = array();
// https://developer.infusionsoft.com/docs/table-schema/#DataFormField [custom fields Ids]
// There is no IN operator in Infusionsoft XML-RPC that works with other fields beside id type, so will do separate calls bellow for each type
// https://developer.infusionsoft.com/docs/xml-rpc/#data-query-a-data-table
// Make sure we grab all custom fields [there are clients with more than 1k records.. been there, done that]
foreach ( array_keys( $this->_custom_fields ) as $field_id ) {
if ( empty( $field_id ) || ! is_int( $field_id ) ) {
continue;
}
$custom_fields = $this->_getCustomFieldsById( $field_id, $custom_fields );
}
$this->_save_custom_fields( $custom_fields );
return $custom_fields;
}
/**
* Get API custom text fields and append them to $custom_fields array
*
* @param int $field_id
* @param array $custom_fields
*
* @return array
*/
protected function _getCustomFieldsById( $field_id, $custom_fields = array() ) {
if ( empty( $field_id ) || ! is_int( $field_id ) || ! is_array( $custom_fields ) ) {
return $custom_fields;
}
/** @var Thrive_Dash_Api_Infusionsoft $api */
$api = $this->get_api();
$limit = 1000; // API pull limit
$page = 0;
do {
$response = $api->data(
'query',
'DataFormField',
$limit,
$page,
array(
'DataType' => (int) $field_id,
'GroupId' => '~<>~0', //I suspect the group ID set to 0 is their way of soft deleting custom fields
),
array(
'GroupId',
'Name',
'Label',
)
);
if ( ! empty( $response ) && is_array( $response ) ) {
$custom_fields = array_merge( $custom_fields, array_map( array(
$this,
'normalize_custom_field',
), $response ) );
}
$page ++;
} while ( count( $response ) === $limit );
return $custom_fields;
}
/**
* Normalize custom field data
*
* @param $field
*
* @return array
*/
protected function normalize_custom_field( $field ) {
$field = (array) $field;
return array(
'id' => isset( $field['Name'] ) ? $field['Name'] : '',
'name' => ! empty( $field['Label'] ) ? $field['Label'] : '',
'type' => ! empty( $field['DataType'] ) && array_key_exists( (int) $field['DataType'], $this->_custom_fields ) ? $this->_custom_fields[ $field['DataType'] ] : '',
'label' => ! empty( $field['Label'] ) ? $field['Label'] : '',
);
}
/**
* Append custom fields to defaults
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
$fields = array_merge( parent::get_custom_fields(), $this->_mapped_custom_fields );
return $fields;
}
/**
* Call the API in order to update subscriber's custom fields
*
* @param int $contact_id
* @param array $arguments
*
* @return bool
*/
public function updateCustomFields( $contact_id, $arguments ) {
if ( ! is_int( $contact_id ) || empty( $arguments ) ) {
return false;
}
$saved = false;
try {
if ( empty( $arguments['automator_custom_fields'] ) ) {
$custom_fields = $this->buildMappedCustomFields( $arguments );
} else {
$custom_fields = $arguments['automator_custom_fields'];
}
if ( ! empty( $custom_fields ) ) {
$api = $this->get_api();
$api->contact(
'update',
$contact_id,
$custom_fields
);
$saved = true;
}
} catch ( Thrive_Dash_Api_Infusionsoft_InfusionsoftException $e ) {
$this->api_log_error( $contact_id, array( 'infusion_custom_fields' => $custom_fields ), $e->getMessage() );
}
return $saved;
}
/**
* Creates and prepare the mapping data from the update call
*
* @param array $args form arguments
* @param array $custom_fields array of custom fields where to append/update
*
* @return array
*/
public function buildMappedCustomFields( $args, $custom_fields = array() ) {
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $custom_fields;
}
$mapped_form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
if ( is_array( $mapped_form_data ) ) {
// Loop trough allowed custom fields names
foreach ( $this->get_mapped_field_ids() as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from the form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $mapped_form_data ) );
// Matched "form data" for current allowed name
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
// Pull form allowed data, sanitize it and build the custom fields array
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $mapped_form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$mapped_form_field_id = $mapped_form_data[ $cf_form_name ][ $this->_key ];
$cf_form_name = str_replace( '[]', '', $cf_form_name );
if ( ! empty( $args[ $cf_form_name ] ) ) {
$args[ $cf_form_name ] = $this->process_field( $args[ $cf_form_name ] );
// Build key => value pairs as the API needs
$custom_fields[ '_' . $mapped_form_field_id ] = sanitize_text_field( $args[ $cf_form_name ] );
}
}
}
}
}
return $custom_fields;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = array();
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
$mapped_data["_{$pair['key']}"] = $value;
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return false
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_Infusionsoft $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
unset( $extra['name'], $extra['list_identifier'] );
$args = array_merge( $extra, $args );
$custom_fields = $this->prepare_custom_fields_for_api( $custom_fields );
add_action(
'tvd_after_infusionsoft_contact_added',
static function ( $instance, $contact, $list_identifier, $arguments ) use ( $api, $custom_fields ) {
$api->contact(
'update',
$contact['Id'],
$custom_fields
);
},
10,
4
);
$this->add_subscriber( $list_id, $args );
} catch ( Exception $e ) {
return false;
}
}
public function getTags() {
return $this->get_tags();
}
/**
* get relevant data from webhook trigger
*
* @param $request WP_REST_Request
*
* @return array
*/
public function get_webhook_data( $request ) {
$contact = $request->get_param( 'email' );
return array( 'email' => empty( $contact ) ? '' : $contact );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $field['id'] === $key && $custom_field ) {
$prepared_fields[ '_' . $key ] = $custom_field;
unset( $custom_fields[ $key ] ); // avoid unnecessary loops
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields' ) );
}
public function get_automator_tag_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'tag_select' ) );
}
public function update_tags( $email, $tags = '', $extra = array() ) {
$args = $this->get_args_for_tags_update( $email, $tags, $extra );
return $this->add_subscriber( $tags, $args );
}
public function has_custom_fields() {
return true;
}
}

View File

@@ -0,0 +1,328 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_KlickTipp extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'KlickTipp';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
public function push_tags( $tags, $data = array() ) {
if ( ! $this->has_tags() && ( ! is_array( $tags ) || ! is_string( $tags ) ) ) {
return $data;
}
$_key = $this->get_tags_key();
if ( ! isset( $data[ $_key ] ) ) {
$data[ $_key ] = array();
}
if ( isset( $data['klicktipp_tag'] ) ) {
$data[ $_key ][] = $data['klicktipp_tag'];
}
$existing_tags = $this->getTags();
/** @var Thrive_Dash_Api_KlickTipp $api */
$api = $this->get_api();
try {
$api->login();
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to Klick Tipp using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
foreach ( $tags as $key => $tag ) {
$tag = trim( $tag );
if ( empty( $tags ) ) {
continue;
}
if ( ! in_array( $tag, $existing_tags ) ) {
try {
$data[ $_key ][] = (int) $api->createTag( $tag );
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
$this->error = $e->getMessage();
}
} else {
$data[ $_key ][] = array_search( $tag, $existing_tags );
}
}
return $data;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'klicktipp' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$user = ! empty( $_POST['connection']['kt_user'] ) ? sanitize_text_field( $_POST['connection']['kt_user'] ) : '';
$password = ! empty( $_POST['connection']['kt_password'] ) ? sanitize_text_field( $_POST['connection']['kt_password'] ) : '';
if ( empty( $user ) || empty( $password ) ) {
return $this->error( __( 'Email and password are required', 'thrive-dash' ) );
}
$this->set_credentials( array(
'user' => $user,
'password' => $password,
) );
/** @var Thrive_Dash_Api_KlickTipp $api */
$api = $this->get_api();
try {
$api->login();
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Klick Tipp using the provided data: %s', 'thrive-dash' ), $this->_error ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Klick Tipp connected successfully!', 'thrive-dash' ) );
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to Klick Tipp using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_KlickTipp( $this->param( 'user' ), $this->param( 'password' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_KlickTipp $api */
$api = $this->get_api();
try {
$api->login();
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to Klick Tipp using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
try {
$all = $api->getLists();
$lists = array();
foreach ( $all as $id => $name ) {
if ( ! empty( $name ) ) {
$lists[] = array(
'id' => $id,
'name' => $name,
);
}
}
return $lists;
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* Subscribe an email. Requires to be logged in.
*
* @param mixed $list_identifier The id subscription process.
* @param mixed $arguments (optional) Additional fields of the subscriber.
*
* @return An object representing the Klicktipp subscriber object.
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_KlickTipp $api */
$api = $this->get_api();
try {
$api->login();
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to Klick Tipp using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
/**
* not sure if this is ok
*/
$arguments['tagid'] = isset( $arguments['klicktipp_tag'] ) ? $arguments['klicktipp_tag'] : 0;
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
}
$fields = array();
if ( ! empty( $first_name ) ) {
$fields['fieldFirstName'] = $first_name;
}
if ( ! empty( $last_name ) ) {
$fields['fieldLastName'] = $last_name;
}
// Add phone
if ( ! empty( $arguments['phone'] ) ) {
$fields['fieldPhone'] = sanitize_text_field( $arguments['phone'] );
}
try {
$api->subscribe(
$arguments['email'],
$list_identifier,
$arguments['tagid'],
! empty( $fields ) ? $fields : ''
);
// Tag user by email, array tags
if ( ! empty( $arguments['klicktipp_tags'] ) ) {
$api->tagByEmail( $arguments['email'], $arguments['klicktipp_tags'] );
}
/**
* get redirect url if needed
*/
$return = true;
if ( isset( $_POST['_submit_option'] ) && $_POST['_submit_option'] == 'klicktipp-redirect' ) {
$return = $api->subscription_process_redirect( $list_identifier, $arguments['email'] );
}
$api->logout();
return $return;
} catch ( Thrive_Dash_Api_KlickTipp_Exception $e ) {
return $e->getMessage();
}
}
/**
* Gets a list of tags through GET /tag API
*
* @return array
*/
public function getTags() {
$tags = array();
try {
/** @var Thrive_Dash_Api_KlickTipp $api */
$api = $this->get_api();
$tags = $api->getTags();
} catch ( Exception $e ) {
}
return $tags;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function get_extra_settings( $params = array() ) {
$params['tags'] = $this->getTags();
if ( ! is_array( $params['tags'] ) ) {
$params['tags'] = array();
}
return $params;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function render_extra_editor_settings( $params = array() ) {
$params['tags'] = $this->getTags();
if ( ! is_array( $params['tags'] ) ) {
$params['tags'] = array();
}
$this->output_controls_html( 'klicktipp/tags', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '%Subscriber:EmailAddress%';
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields', 'tag_select' ) );
}
public function get_automator_tag_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'tag_select' ) );
}
}

View File

@@ -0,0 +1,155 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_MadMimi extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'MadMimi';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'madmimi' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$username = ! empty( $_POST['connection']['username'] ) ? sanitize_text_field( $_POST['connection']['username'] ) : '';
if ( empty( $key ) || empty( $username ) ) {
return $this->error( __( 'Username and API Key are required', 'thrive-dash' ) );
}
$this->set_credentials( array( 'key' => $key, 'username' => $username ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to MadMimi using the provided data', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'MadMimi connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_MadMimi $api */
$api = $this->get_api();
/**
* just try getting the list of the promotions as a connection test
*/
try {
$api->getAudienceLists(); // this will throw the exception if there is a connection problem
} catch ( Thrive_Dash_Api_MadMimi_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_MadMimi( $this->param( 'key' ), $this->param( 'username' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_MadMimi $api */
$api = $this->get_api();
try {
$lists = array();
$audienceList = $api->getAudienceLists();
foreach ( $audienceList as $key => $item ) {
$lists [] = array(
'id' => $item['name'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Thrive_Dash_Api_MadMimi_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_MadMimi $api */
$api = $this->get_api();
try {
$api->registerToAudienceList( $list_identifier, $arguments['name'], $arguments['email'] );
return true;
} catch ( Thrive_Dash_Api_MadMimi_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '(email)';
}
}

View File

@@ -0,0 +1,296 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
use MailPoet\API\API;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_MailPoet extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
/**
* Mailpoet 3 changed the shortcodes from user:email to subscriber:email
*/
if ( defined( 'MAILPOET_VERSION' ) && version_compare( MAILPOET_VERSION, '3', '>' ) ) {
return '[subscriber:email]';
}
return '[user:email]';
}
/**
* @return string
*/
public function get_title() {
return 'MailPoet';
}
/**
* check whether or not the MailPoet plugin is installed
*/
public function pluginInstalled() {
$installed = array();
if ( class_exists( 'MailPoet\Config\Initializer', false ) ) {
$installed[] = 3;
}
if ( class_exists( 'WYSIJA' ) ) {
$installed[] = 2;
}
return $installed;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'mailpoet' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
if ( ! $this->pluginInstalled() ) {
return $this->error( __( 'MailPoet plugin must be installed and activated.', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( '<strong>' . $result . '</strong>)' );
}
/**
* finally, save the connection details
*/
$this->save();
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
if ( ! $this->pluginInstalled() ) {
return __( 'At least one MailPoet plugin must be installed and activated.', 'thrive-dash' );
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! $this->pluginInstalled() ) {
return __( 'MailPoet plugin is not installed / activated', 'thrive-dash' );
}
list( $firstname, $lastname ) = $this->get_name_parts( $arguments['name'] );
$credentials = $this->get_credentials();
if ( ! isset( $credentials['version'] ) || $credentials['version'] == 2 ) {
$user_data = array(
'email' => $arguments['email'],
'firstname' => $firstname,
'lastname' => $lastname,
);
$data_subscriber = array(
'user' => $user_data,
'user_list' => array( 'list_ids' => array( $list_identifier ) ),
);
/** @var WYSIJA_help_user $user_helper */
$user_helper = WYSIJA::get( 'user', 'helper' );
$result = $user_helper->addSubscriber( $data_subscriber );
if ( $result === false ) {
$messages = $user_helper->getMsgs();
if ( isset( $messages['xdetailed-errors'] ) ) {
return implode( '<br><br>', $messages['xdetailed-errors'] );
} elseif ( isset( $messages['error'] ) ) {
return implode( '<br><br>', $messages['error'] );
}
return __( 'Subscriber could not be saved', 'thrive-dash' );
}
} else {
$user_data = array(
'email' => $arguments['email'],
'first_name' => $firstname,
'last_name' => $lastname,
);
// Compatibility with latest version 3.21.0+
if ( class_exists( 'MailPoet\API\API' ) ) {
$mailpoet = new API();
$errors = array();
$subscriber = array();
// Get subscriber
try {
$subscriber = $mailpoet::MP( 'v1' )->getSubscriber( $arguments['email'] );
} catch ( Exception $exception ) {
$errors[] = $exception->getMessage();
}
// Create subscriber if not exists
if ( is_array( $subscriber ) && empty( $subscriber['id'] ) ) {
try {
$subscriber = $mailpoet::MP( 'v1' )->addSubscriber( $user_data, array(), array() );
} catch ( Exception $exception ) {
$errors[] = $exception->getMessage();
}
}
// Add subscriber to list
if ( is_array( $subscriber ) && ! empty( $subscriber['email'] ) ) {
try {
$mailpoet::MP( 'v1' )->subscribeToList( $subscriber['email'], $list_identifier, $user_data );
return true;
} catch ( Exception $exception ) {
return $exception->getMessage();
}
}
if ( $errors ) {
return implode( '<br/>', $errors );
}
return false;
}
if ( ! class_exists( 'MailPoet\Models\Subscriber' ) ) {
$this->_error = __( 'No MailPoet plugin could be found.', 'thrive-dash' );
return false;
}
$result = call_user_func( array(
'MailPoet\Models\Subscriber',
'subscribe'
), $user_data, array( $list_identifier ) );
if ( $result->getErrors() ) {
return implode( '<br><br>', $result->getErrors() );
}
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
// no API instance needed here
return null;
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
if ( ! $this->pluginInstalled() ) {
$this->_error = __( 'No MailPoet plugin could be found.', 'thrive-dash' );
return false;
}
$lists = array();
$credentials = $this->get_credentials();
// Version 2 check [DB option] that uses different classes
if ( ! isset( $credentials['version'] ) || 2 === (int) $credentials['version'] ) {
$model_list = WYSIJA::get( 'list', 'model' );
$lists = $model_list->get( array( 'name', 'list_id' ), array( 'is_enabled' => 1 ) );
foreach ( $lists as $i => $list ) {
$lists[ $i ]['id'] = $list['list_id'];
}
} else {
// Compatibility with latest version 3.21.0+
if ( class_exists( 'MailPoet\API\API' ) ) {
$mailpoet = new API();
$subscription_lists = $mailpoet::MP( 'v1' )->getLists();
if ( is_array( $subscription_lists ) && ! empty( $subscription_lists ) ) {
foreach ( $subscription_lists as $list ) {
$lists [] = array(
'id' => $list['id'],
'name' => $list['name'],
);
}
}
return $lists;
}
if ( ! class_exists( 'MailPoet\Models\Segment' ) ) {
$this->_error = __( 'No MailPoet plugin could be found.', 'thrive-dash' );
return false;
}
$segments = call_user_func( array(
'MailPoet\Models\Segment',
'getSegmentsWithSubscriberCount'
), 'default' );
if ( ! empty( $segments ) ) {
foreach ( $segments as $segment ) {
$lists [] = array(
'id' => $segment['id'],
'name' => $segment['name'],
);
}
}
}
return $lists;
}
}

View File

@@ -0,0 +1,235 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_MailRelay extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'MailRelay';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailrelayemail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'mailrelay' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$connection = $this->post( 'connection' );
$key = ! empty( $connection['key'] ) ? $connection['key'] : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid MailRelay key', 'thrive-dash' ) );
}
$connection['url'] = isset( $connection['domain'] ) ? $connection['domain'] : $connection['url'];
$url = ! empty( $connection['url'] ) ? $connection['url'] : '';
if ( filter_var( $url, FILTER_VALIDATE_URL ) === false || empty( $url ) ) {
return $this->error( __( 'You must provide a valid MailRelay URL', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to MailRelay using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_MailRelayEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailrelayemail' );
if ( isset( $connection['new_connection'] ) && (int) $connection['new_connection'] === 1 ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection'] = $connection;
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
return $this->success( __( 'MailRelay connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_MailRelay $mr */
$mr = $this->get_api();
try {
$mr->get_list();
} catch ( Thrive_Dash_Api_MailRelay_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_MailRelay|Thrive_Dash_Api_MailRelayV1
*/
protected function get_api_instance() {
$url = $this->param( 'url' );
$api_key = $this->param( 'key' );
$instance = new Thrive_Dash_Api_MailRelay(
array(
'host' => $url,
'apiKey' => $api_key,
)
);
if ( false !== strpos( $url, 'ipzmarketing' ) ) {
$instance = new Thrive_Dash_Api_MailRelayV1( $url, $api_key );
}
return $instance;
}
/**
* get all Subscriber Lists from this API service
*
* @return array
* @throws Thrive_Dash_Api_MailRelay_Exception
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_MailRelay $api */
$api = $this->get_api();
$body = $api->get_list();
$lists = array();
foreach ( $body as $item ) {
$lists [] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
$args = array();
/** @var Thrive_Dash_Api_MailRelay $api */
$api = $this->get_api();
$args['email'] = $arguments['email'];
if ( ! empty( $arguments['name'] ) ) {
$args['name'] = $arguments['name'];
}
if ( ! empty( $arguments['phone'] ) ) {
$args['customFields']['f_phone'] = $arguments['phone'];
}
try {
$api->add_subscriber( $list_identifier, $args );
} catch ( Thrive_Dash_Api_MailRelay_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[email]';
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailrelayemail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
}

View File

@@ -0,0 +1,363 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_MailRelayEmail extends Thrive_Dash_List_Connection_Abstract {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string
*/
public function get_title() {
return 'MailRelay';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'mailrelayemail' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$connection = $this->post( 'connection' );
$key = ! empty( $connection['key'] ) ? $connection['key'] : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid MailRelay key', 'thrive-dash' ) );
}
$connection['domain'] = isset( $connection['url'] ) ? $connection['url'] : $connection['domain'];
$url = ! empty( $connection['domain'] ) ? $connection['domain'] : '';
if ( filter_var( $url, FILTER_VALIDATE_URL ) === false || empty( $url ) ) {
return $this->error( __( 'You must provide a valid MailRelay URL', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to MailRelay using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Try to connect to the autoresponder too
*/
/** @var Thrive_Dash_List_Connection_MailRelay $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailrelay' );
$r_result = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection'] = $connection;
$_POST['connection']['new_connection'] = isset( $connection['new_connection'] ) ? absint( $connection['new_connection'] ) : 1;
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
return $this->success( __( 'MailRelay connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_MailRelay $mr */
$mr = $this->get_api();
$email = get_option( 'admin_email' );
$args = array(
'subject' => 'API connection test',
'html' => 'This is a test email from Thrive Leads MailRelay API.',
'emails' => array(
array(
'name' => '',
'email' => $email,
),
),
);
try {
$mr->sendEmail( $args );
} catch ( Thrive_Dash_Api_MailRelay_Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'mailrelayemail' );
}
return true;
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$mr = $this->get_api();
try {
$message = array(
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'subject' => $data['subject'],
'emails' => array(
array(
'email' => $data['email'],
'name' => '',
),
),
);
$mr->sendEmail( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$mr = $this->get_api();
/**
* prepare $to
*/
$to = array();
$extra_emails = array();
if ( isset( $data['cc'] ) ) {
$extra_emails = $data['cc'];
}
if ( isset( $data['bcc'] ) ) {
$extra_emails = array_merge( $extra_emails, $data['bcc'] );
}
$emails = is_array( $extra_emails ) ? array_merge( $data['emails'], $extra_emails ) : $data['emails'];
foreach ( $emails as $email ) {
$temp = array(
'email' => $email,
'name' => '',
);
$to[] = $temp;
}
try {
$message = array(
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'subject' => $data['subject'],
'emails' => $to,
);
$mr->sendEmail( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$message = array(
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'subject' => $data['confirmation_subject'],
'emails' => array(
array(
'email' => $data['sender_email'],
'name' => '',
),
),
);
$mr->sendEmail( $message );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$mr = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$credentials = Thrive_Dash_List_Manager::credentials( 'mailrelayemail' );
if ( isset( $credentials ) ) {
$from_email = get_option( 'admin_email' );
} else {
return false;
}
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$html_content = str_replace( '"', "'", $html_content );
$message = array(
'subject' => $subject,
'html' => $html_content,
'emails' => array(
array(
'name' => $visitor_name,
'email' => $post_data['email'],
),
),
);
$result = $mr->sendEmail( $message );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
if ( false !== strpos( $this->param( 'domain' ), 'ipzmarketing' ) ) {
$instance = new Thrive_Dash_Api_MailRelayV1( $this->param( 'domain' ), $this->param( 'key' ) );
} else {
$instance = new Thrive_Dash_Api_MailRelay( array(
'host' => $this->param( 'domain' ),
'apiKey' => $this->param( 'key' ),
) );
}
return $instance;
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,443 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_MailerLite extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'MailerLite';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'mailerlite' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$connection = $this->post( 'connection' );
$key = ! empty( $connection['key'] ) ? ( $connection['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid MailerLite key', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to MailerLite using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'MailerLite connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$mailer = $this->get_api();
/**
* just try getting a list as a connection test
*/
try {
$groupsApi = $mailer->groups();
$groupsApi->get();
} catch ( Thrive_Dash_Api_MailerLite_MailerLiteSdkException $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
* @throws Thrive_Dash_Api_MailerLite_MailerLiteSdkException
*/
protected function get_api_instance() {
$key = $this->param( 'key' );
$version = $this->param( 'version' );
if ( ! empty( $version ) && (int) $version === 2 ) {
return new Thrive_Dash_Api_MailerLiteV2( $key );
}
return new Thrive_Dash_Api_MailerLite( $key );
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
$api = $this->get_api();
try {
$groups_api = $api->groups();
$groups_api->limit( 10000 );
$lists_obj = $groups_api->get();
$lists = array();
foreach ( $lists_obj as $item ) {
$lists [] = array(
'id' => $item->id,
'name' => $item->name,
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( 'Please re-check your API connection details.', 'thrive-dash' );
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
$api = $this->get_api();
$version = (int) $this->param( 'version' );
if ( isset( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
}
if ( isset( $arguments['phone'] ) ) {
$phone = $arguments['phone'];
}
$args['fields'] = array();
$args['email'] = $arguments['email'];
if ( ! empty( $first_name ) ) {
$args['fields']['name'] = $first_name;
$args['name'] = $first_name;
}
if ( ! empty( $last_name ) ) {
$args['fields']['last_name'] = $last_name;
}
if ( ! empty( $phone ) ) {
$args['fields']['phone'] = $phone;
}
$args['resubscribe'] = 1;
try {
$groupsApi = $api->groups();
if ( empty( $arguments['automator_custom_fields'] ) ) {
$args['fields'] = array_merge( $args['fields'], $this->_generateCustomFields( $arguments ) );
} else {
$args['fields'] = array_merge( $args['fields'], $arguments['automator_custom_fields'] );
}
$groupsApi->add_subscriber( $list_identifier, $args );
return true;
} catch ( Thrive_Dash_Api_MailerLite_MailerLiteSdkException $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown MailerLite Error', 'thrive-dash' );
} catch ( Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown Error', 'thrive-dash' );
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{$email}';
}
/**
* @param $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_data = array();
$allowed_types = $this->get_api()->fields()->get_allowed_types();
try {
$custom_fields = $this->get_api()->fields()->get();
if ( is_array( $custom_fields ) ) {
foreach ( $custom_fields as $field ) {
if ( ! empty( $field->type ) && in_array( $field->type, $allowed_types, true ) ) {
$custom_data[] = $this->get_api()->fields()->get_normalize_custom_field( $field );
}
}
}
} catch ( Exception $e ) {
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* Generate custom fields array
*
* @param array $args
*
* @return array
*/
private function _generateCustomFields( $args ) {
$custom_fields = $this->get_api_custom_fields( array() );
$ids = $this->buildMappedCustomFields( $args );
$result = array();
foreach ( $ids as $key => $id ) {
$field = array_filter(
$custom_fields,
function ( $item ) use ( $id ) {
return (int) $item['id'] === (int) $id['value'];
}
);
$field = array_values( $field );
if ( ! isset( $field[0] ) ) {
continue;
}
$_name = $field[0]['key'] ?: $field[0]['name'];
$chunks = explode( ' ', $_name );
$chunks = array_map( 'strtolower', $chunks );
$field_key = implode( '_', $chunks );
$name = strpos( $id['type'], 'mapping_' ) !== false ? $id['type'] . '_' . $key : $key;
$cf_form_name = str_replace( '[]', '', $name );
$value = isset( $args[ $cf_form_name ] ) ? $this->process_field( $args[ $cf_form_name ] ) : '';
if ( $value ) {
$result[ $field_key ] = $value;
}
}
return $result;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return array
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = [];
$fields = $this->get_api_custom_fields( array() );
foreach ( $automation_data['api_fields'] as $pair ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
foreach ( $fields as $field ) {
if ( (int) $field['id'] === (int) $pair['key'] ) {
$_name = $field['key'] ?: $field['name'];
$_name = explode( ' ', $_name );
$_name = array_map( 'strtolower', $_name );
$_name = implode( '_', $_name );
$mapped_data[ $_name ] = $value;
}
}
}
}
return $mapped_data;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function buildMappedCustomFields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return false|int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
$api = $this->get_api();
$groupsApi = $api->groups();
$subscribersApi = $api->subscribers();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
'name' => ! empty( $extra['name'] ) ? $extra['name'] : '',
'fields' => array(),
);
$this->add_subscriber( $list_id, $args );
$args['fields'] = $this->prepare_custom_fields_for_api( $custom_fields );
$groupsApi->add_subscriber( $list_id, $args );
$subscriber = $subscribersApi->search( $email );
return ! empty( $subscriber[0] ) ? $subscriber[0]->id : 0;
} catch ( Exception $e ) {
return false;
}
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( array( 'list_id' => $list_identifier ), true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( (int) $field['id'] === (int) $key && $custom_field ) {
$_name = $field['key'] ?: $field['name'];
$chunks = explode( ' ', $_name );
$chunks = array_map( 'strtolower', $chunks );
$cf_key = implode( '_', $chunks );
$prepared_fields[ $cf_key ] = $custom_field;
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields' ) );
}
public function has_custom_fields() {
return true;
}
}

View File

@@ -0,0 +1,328 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Mailgun extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Mailgun';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'mailgun' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$domain = ! empty( $_POST['connection']['domain'] ) ? sanitize_text_field( $_POST['connection']['domain'] ) : '';
$zone = ! empty( $_POST['connection']['zone'] ) ? sanitize_text_field( $_POST['connection']['zone'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid Mailgun key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid Mailgun key', 'thrive-dash' ) );
}
if ( empty( $domain ) ) {
return $ajax_call ? __( 'The domain name field must not be empty', 'thrive-dash' ) : $this->error( __( 'The domain name field must not be empty', 'thrive-dash' ) );
}
$this->set_credentials( compact( 'key', 'domain', 'zone' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to Mailgun using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to Mailgun using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
$this->success( __( 'Mailgun connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_Mailgun $mailgun */
$mailgun = $this->get_api();
if ( isset( $_POST['connection']['domain'] ) ) {
$domain = sanitize_text_field( $_POST['connection']['domain'] );
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'mailgun' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
}
}
$from_email = get_option( 'admin_email' );
$to = $from_email;
$subject = 'API connection test';
$text_content = $html_content = 'This is a test email from Thrive Leads Mailgun API.';
try {
$mailgun->sendMessage( "$domain",
array(
'from' => $from_email,
'to' => $to,
'subject' => $subject,
'text' => $text_content,
'html' => $html_content,
'multipart' => true,
) );
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'mailgun' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$mailgun = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'mailgun' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
} else {
return false;
}
$from_email = get_option( 'admin_email' );
try {
$messsage = array(
'from' => $from_email,
'to' => $data['email'],
'subject' => $data['subject'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'multipart' => true,
);
$mailgun->sendMessage( "$domain", $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$mailgun = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'mailgun' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
} else {
return false;
}
$from_email = get_option( 'admin_email' );
try {
$messsage = array(
'from' => $from_email,
'to' => $data['emails'],
'subject' => $data['subject'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'h:Reply-To' => empty ( $data['reply_to'] ) ? '' : $data['reply_to'],
'multipart' => true,
);
$mailgun->sendMessage( "$domain", $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$messsage = array(
'from' => $from_email,
'to' => array( $data['sender_email'] ),
'subject' => $data['confirmation_subject'],
'text' => '',
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'h:Reply-To' => $from_email,
'multipart' => true,
);
$mailgun->sendMessage( "$domain", $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$mailgun = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = get_option( 'admin_email' );
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$from_name = '<' . $post_data['name'] . '>';
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$from_name = "";
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$credentials = Thrive_Dash_List_Manager::credentials( 'mailgun' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
}
$result = $mailgun->sendMessage( "$domain",
array(
'from' => $from_email,
'to' => $visitor_name . "<" . $post_data['email'] . ">",
'subject' => $subject,
'text' => $text_content,
'html' => $html_content,
'multipart' => true,
) );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
$zone = $this->param( 'zone' );
$endpoint = $zone && $zone === 'europe' ? 'api.eu.mailgun.net' : 'api.mailgun.net';
return new Thrive_Dash_Api_Mailgun( $this->param( 'key' ), $endpoint );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,185 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Mailster extends Thrive_Dash_List_Connection_Abstract {
/**
* @return string
*/
public function get_title() {
return 'Mailster';
}
public function output_setup_form() {
$this->output_controls_html( 'mailster' );
}
/**
* @return bool|mixed|string|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
if ( false === $this->pluginInstalled() ) {
return __( 'Mailster plugin not installed or activated', 'thrive-dash' );
}
$this->set_credentials( array( 'connected' => true ) );
$result = $this->test_connection();
if ( true !== $result ) {
return $this->error( '<strong>' . $result . '</strong>)' );
}
$this->save();
return true;
}
/**
* @return bool|string
*/
public function test_connection() {
if ( false === $this->pluginInstalled() ) {
return __( 'Mailster plugin not installed or activated', 'thrive-dash' );
}
return true;
}
/**
* Add subscriber
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( false === $this->pluginInstalled() ) {
return __( 'Mailster plugin not installed or activated', 'thrive-dash' );
}
$mailster_instance = mailster( 'subscribers' );
$args = array(
'email' => $arguments['email'],
'status' => isset( $arguments['mailster_optin'] ) && 'd' === $arguments['mailster_optin'] ? 0 : 1,
);
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$args['firstname'] = $first_name;
$args['lastname'] = $last_name;
}
$subscriber = $mailster_instance->get_by_mail( $arguments['email'] );
$subscriber_id = is_object( $subscriber )
? $mailster_instance->update( $args, true, true )
: $mailster_instance->add( $args );
if ( null !== $subscriber_id ) {
$mailster_instance->assign_lists( $subscriber_id, $list_identifier );
$mailster_instance->add_custom_value( $subscriber_id, $this->_get_custom_fields_from_args( $arguments ) );
return true;
}
return __( 'Mailster failed to add the subscriber', 'thrive-dash' );
}
/**
* Get the custom fields from available args
*
* @param $args
*
* @return array
*/
private function _get_custom_fields_from_args( $args ) {
$result = array();
foreach ( $this->get_custom_fields() as $field ) {
if ( isset( $args[ $field['id'] ] ) ) {
$result[ $field['id'] ] = $args[ $field['id'] ];
}
}
return $result;
}
protected function get_api_instance() {
}
/**
* @return bool|string|array
*/
protected function _get_lists() {
if ( false === $this->pluginInstalled() ) {
return __( 'Mailster plugin not installed or activated', 'thrive-dash' );
}
$lists = array();
foreach ( mailster( 'lists' )->get() as $list ) {
$lists[] = array(
'id' => $list->ID,
'name' => $list->name,
);
}
return $lists;
}
/**
* Chack if Mailster plugin is installed and activated
*
* @return bool
*/
public function pluginInstalled() {
return function_exists( 'mailster' );
}
/**
* Get custom fields
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
/**
* Add our default custom fields
*/
foreach ( array( 'name', 'phone' ) as $field ) {
mailster()->add_custom_field( $field );
}
$fields = mailster()->get_custom_fields();
$fields = wp_list_filter( $fields, array( 'type' => 'textfield' ) );
$response = array();
foreach ( $fields as $key => $field ) {
if ( ! empty( $field['name'] ) ) {
$response[] = array(
'id' => $key,
'placeholder' => $field['name'],
);
}
}
return $response;
}
}

View File

@@ -0,0 +1,482 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Mandrill extends Thrive_Dash_List_Connection_Abstract {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Mandrill';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailchimp' );
if ( $related_api->is_connected() ) {
$credentials = $related_api->get_credentials();
$this->set_param( 'mailchimp_key', $credentials['key'] );
}
$this->output_controls_html( 'mandrill' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$mailchimp_key = ! empty( $_POST['connection']['mailchimp_key'] ) ? sanitize_text_field( $_POST['connection']['mailchimp_key'] ) : '';
$email = ! empty( $_POST['connection']['email'] ) ? sanitize_text_field( $_POST['connection']['email'] ) : '';
if ( isset( $_POST['connection']['mandrill-key'] ) && isset( $_POST['connection']['key'] ) ) {
$_POST['connection']['mailchimp_key'] = sanitize_text_field( $_POST['connection']['key'] );
$_POST['connection']['key'] = sanitize_text_field( $_POST['connection']['mandrill-key'] );
}
if ( empty( $_POST['connection']['key'] ) ) {
return $this->error( __( 'You must provide a valid Mandrill key', 'thrive-dash' ) );
}
if ( empty( $email ) ) {
return $this->error( __( 'Email field must not be empty', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
/**
* Doing this because Mandrill devs are retarded and because it's unprofessional for the end user to read 'gibberish'
*/
preg_match( '#"?(.+?)\{(.+)\}(")?$#', json_decode( $result ), $matches );
if ( ! empty( $matches ) ) {
$result = json_decode( '{' . $matches[2] . '}', true );
$message = false;
foreach ( $result as $level1 ) {
foreach ( $level1 as $level2 ) {
if ( ! $message ) {
$message = $level2;
}
}
}
} else {
$message = $result;
}
return $this->error( sprintf( __( 'Could not connect to Mandrill using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $message ? $message : '' ) );
}
/**
* finally, save the connection details
*/
$this->save();
if ( ! empty( $mailchimp_key ) ) {
/**
* Try to connect to the email service too
*/
/** @var Thrive_Dash_List_Connection_Mandrill $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'mailchimp' );
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
}
return $this->success( __( 'Mandrill connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$mandrill = $this->get_api();
if ( isset( $_POST['connection']['email'] ) ) {
$from_email = sanitize_text_field( $_POST['connection']['email'] );
$to = $from_email;
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'mandrill' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
$to = $credentials['email'];
} else {
return false;
}
}
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads Mandrill API.';
$text_content = 'This is a test email from Thrive Leads Mandrill API.';
$message = array(
'html' => $html_content,
'text' => $text_content,
'subject' => $subject,
'from_email' => $from_email,
'from_name' => '',
'to' => array(
array(
'email' => $to,
'name' => '',
'type' => 'to',
),
),
'headers' => array( 'Reply-To' => $from_email ),
'merge' => true,
'merge_language' => 'mailchimp',
);
$async = false;
$ip_pool = 'Main Pool';
try {
$result = $mandrill->messages->send( $message, $async, $ip_pool );
if ( isset( $result['body'] ) ) {
$body = json_decode( $result['body'] );
$body = $body[0];
if ( $body->status == 'rejected' ) {
if ( $body->reject_reason == 'unsigned' ) {
return $this->error( __( "The email filled in was not verified by Mandrill", 'thrive-dash' ) );
}
return $this->error( __( "Mandrill couldn't connect", 'thrive-dash' ) );
}
}
} catch ( Thrive_Dash_Api_Mandrill_Exceptions $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'mandrill' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$mandrill = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'mandrill' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
try {
$message = array(
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'subject' => $data['subject'],
'from_email' => $from_email,
'from_name' => '',
'to' => array(
array(
'email' => $data['email'],
'name' => '',
'type' => 'to',
),
),
'headers' => array( 'Reply-To' => $from_email ),
'merge' => true,
'merge_language' => 'mailchimp',
);
$async = false;
$ip_pool = 'Main Pool';
$mandrill->messages->send( $message, $async, $ip_pool );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$mandrill = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'mandrill' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
/**
* prepare $to
*/
$to = array();
$cc = isset( $data['cc'] ) ? $data['cc'] : array();
$bcc = isset( $data['bcc'] ) ? $data['bcc'] : array();
foreach ( $data['emails'] as $email ) {
$temp = array(
'email' => $email,
'name' => '',
'type' => 'to',
);
$to[] = $temp;
}
foreach ( $cc as $email ) {
$temp = array(
'email' => $email,
'name' => '',
'type' => 'cc',
);
$to[] = $temp;
}
foreach ( $bcc as $email ) {
$temp = array(
'email' => $email,
'name' => '',
'type' => 'bcc',
);
$to[] = $temp;
}
try {
$message = array(
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'subject' => $data['subject'],
'from_email' => $from_email,
'from_name' => ! empty( $data['from_name'] ) ? $data['from_name'] : '',
'to' => $to,
'headers' => array( 'Reply-To' => empty ( $data['reply_to'] ) ? '' : $data['reply_to'] ),
'merge' => true,
'merge_language' => 'mailchimp',
);
$async = false;
$ip_pool = 'Main Pool';
$mandrill->messages->send( $message, $async, $ip_pool );
} catch ( Exception $e ) {
return $e->getMessage();
}
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$message = array(
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'text' => '',
'subject' => $data['confirmation_subject'],
'from_email' => $from_email,
'from_name' => ! empty( $data['from_name'] ) ? $data['from_name'] : '',
'to' => array(
array(
'email' => $data['sender_email'],
'name' => '',
'type' => 'to',
),
),
'headers' => array( 'Reply-To' => $from_email ),
'merge' => true,
'merge_language' => 'mailchimp',
);
$async = false;
$ip_pool = 'Main Pool';
$mandrill->messages->send( $message, $async, $ip_pool );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$mandrill = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$credentials = Thrive_Dash_List_Manager::credentials( 'mandrill' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$from_name = $post_data['name'];
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$from_name = "";
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$message = array(
'html' => $html_content,
'text' => $text_content,
'subject' => $subject,
'from_email' => $from_email,
'from_name' => '',
'to' => array(
array(
'email' => $post_data['email'],
'name' => $visitor_name,
'type' => 'to',
),
),
'headers' => array( 'Reply-To' => $from_email ),
'merge' => true,
'merge_language' => 'mailchimp',
);
$async = false;
$ip_pool = 'Main Pool';
$result = $mandrill->messages->send( $message, $async, $ip_pool );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Mandrill( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Ontraport extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Ontraport';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'ontraport' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$app_id = ! empty( $_POST['connection']['app_id'] ) ? sanitize_text_field( $_POST['connection']['app_id'] ) : '';
if ( empty( $key ) || empty( $app_id ) ) {
return $this->error( __( 'You must provide a valid Ontraport AppID/APIKey', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Ontraport: %s', 'thrive-dash' ), $this->_error ) );
}
/**
* finally, save the connection details
*/
$this->save();
$this->success( __( 'Ontraport connected successfully', 'thrive-dash' ) );
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_Ontraport
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Ontraport( $this->param( 'app_id' ), $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* Ontraport has both sequences and forms
*
* @return array|string for error
*/
protected function _get_lists() {
/**
* just try getting the lists as a connection test
*/
try {
$lists = array();
/** @var $op Thrive_Dash_Api_Ontraport */
$op = $this->get_api();
$data = $op->get_campaigns();
if ( ! empty( $data ) ) {
foreach ( $data as $id => $list ) {
$lists[] = array(
'id' => $id,
'name' => $list['name'],
);
}
}
return $lists;
} catch ( Thrive_Dash_Api_Ontraport_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
/**
* Get campaigns
*
* @param array $params
*
* @return array
*/
public function get_extra_settings( $params = array() ) {
$lists = array();
try {
$data = $this->get_api()->get_sequences();
if ( ! empty( $data ) ) {
foreach ( $data as $id => $list ) {
$lists['sequences'][] = array(
'id' => $id,
'name' => $list['name'],
);
}
}
} catch ( Exception $e ) {
return $lists;
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
list( $firstname, $lastname ) = $this->get_name_parts( $arguments['name'] );
$data = array(
'firstname' => $firstname,
'lastname' => $lastname,
'email' => $arguments['email'],
'type' => ! empty( $arguments['ontraport_ontraport_type'] ) ? $arguments['ontraport_ontraport_type'] : '',
);
if ( ! empty( $arguments['phone'] ) ) {
$data['phone'] = $arguments['phone'];
}
$this->get_api()->add_contact( $list_identifier, $data );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
public static function get_email_merge_tag() {
return '[Email]';
}
}

View File

@@ -0,0 +1,289 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Postmark extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Postmark';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'postmark' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$email = ! empty( $_POST['connection']['email'] ) ? sanitize_text_field( $_POST['connection']['email'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid Postmark key', 'thrive-dash' ) );
}
if ( empty( $email ) ) {
return $this->error( __( 'Email field must not be empty', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to Postmark using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Postmark connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$postmark = $this->get_api();
if ( isset( $_POST['connection']['email'] ) ) {
$from_email = sanitize_email( $_POST['connection']['email'] );
$to = $from_email;
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'postmark' );
if ( isset( $credentials ) ) {
$from_email = $credentials['email'];
$to = $credentials['email'];
}
}
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads Postmark API.';
$text_content = 'This is a test email from Thrive Leads Postmark API.';
try {
$postmark->sendEmail( $from_email, $to, $subject, $html_content, $text_content );
} catch ( Thrive_Dash_Api_Postmark_Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'postmark' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
/**
* @var $postmark Thrive_Dash_Api_Postmark
*/
$postmark = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'postmark' );
if ( is_array( $credentials ) && ! empty( $credentials['email'] ) ) {
$from_email = $credentials['email'];
} else {
return false;
}
if ( ! empty( $data['from_name'] ) ) {
$from_email = $data['from_name'] . ' < ' . $from_email . ' >';
}
try {
$postmark->sendEmail(
$from_email,
$data['email'],
$data['subject'],
empty ( $data['html_content'] ) ? '' : $data['html_content'],
empty ( $data['text_content'] ) ? '' : $data['text_content'],
null,
null,
empty ( $data['reply_to'] ) ? '' : $data['reply_to'],
empty( $data['cc'] ) ? '' : implode( ', ', $data['cc'] ),
empty( $data['bcc'] ) ? '' : implode( ', ', $data['bcc'] )
);
} catch ( Thrive_Dash_Api_Postmark_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
/**
* we should never fucking do that
* pls find a way to send all the emails at once
*/
foreach ( $data['emails'] as $email ) {
$data['email'] = $email;
$this->sendCustomEmail( $data );
}
/**
* Send confirmation email
*/
if ( ! empty( $data['send_confirmation'] ) ) {
$confirmation = array(
'email' => $data['sender_email'],
'from_name' => $data['from_name'],
'html_content' => $data['confirmation_html'],
'subject' => $data['confirmation_subject'],
);
$credentials = Thrive_Dash_List_Manager::credentials( 'postmark' );
if ( is_array( $credentials ) && ! empty( $credentials['email'] ) ) {
$confirmation['reply_to'] = $credentials['email'];
}
$this->sendCustomEmail( $confirmation );
}
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$postmark = $this->get_api();
$credentials = $this->get_credentials();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = $credentials['email'];
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$result = $postmark->sendEmail(
$from_email,
$post_data['email'],
$subject,
$html_content,
$text_content
);
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Postmark( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_ReCaptcha extends Thrive_Dash_List_Connection_Abstract {
public function __construct( $key ) {
parent::__construct( $key );
add_filter( 'tcb_spam_prevention_tools', [$this, 'add_spam_prevention_tool'] );
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'recaptcha';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'ReCaptcha';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'recaptcha' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$site = ! empty( $_POST['site_key'] ) ? sanitize_text_field( $_POST['site_key'] ) : '';
$secret = ! empty( $_POST['secret_key'] ) ? sanitize_text_field( $_POST['secret_key'] ) : '';
if ( empty( $site ) || empty( $secret ) ) {
return $this->error( __( 'Both Site Key and Secret Key fields are required', 'thrive-dash' ) );
}
//recreate credential object
$credentials = array(
'connection' => $this->post( 'connection' ),
'site_key' => $site,
'secret_key' => $secret,
);
$this->set_credentials( $credentials );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Incorrect Secret Key.', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'ReCaptcha connected successfully!', 'thrive-dash' ) );
}
/**
* test if the secret key is correct and it exists.
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$CAPTCHA_URL = 'https://www.google.com/recaptcha/api/siteverify';
$_capthca_params = array(
'response' => '',
'secret' => $this->param( 'secret_key' ),
);
$request = tve_dash_api_remote_post( $CAPTCHA_URL, array( 'body' => $_capthca_params ) );
$response = json_decode( wp_remote_retrieve_body( $request ), true );
if ( ! empty( $response ) && isset( $response['error-codes'] ) && in_array( 'invalid-input-secret', $response['error-codes'] ) ) {
return false;
}
return true;
}
public function getSiteKey() {
$this->get_credentials();
return $this->param( 'site_key' );
}
public function add_spam_prevention_tool( $sp_tools ) {
array_push($sp_tools, $this->_key);
return $sp_tools;
}
/**
* @return string
*/
public function custom_success_message() {
return ' ';
}
/*
* Those functions do not apply
*/
protected function get_api_instance() {
}
protected function _get_lists() {
}
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,199 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SGAutorepondeur extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'SG Autorepondeur';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sg-autorepondeur' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
if ( empty( $_POST['connection']['memberid'] ) ) {
return $this->error( __( 'You must provide a valid SG-Autorepondeur Member ID', 'thrive-dash' ) );
}
if ( empty( $_POST['connection']['key'] ) ) {
return $this->error( __( 'You must provide a valid SG-Autorepondeur key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to SG-Autorepondeur using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'SG Autorepondeur connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/**
* just try getting a list as a connection test
*/
try {
/** @var Thrive_Dash_Api_SGAutorepondeur $sg */
$sg = $this->get_api();
$sg->call( 'get_list' );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_SGAutorepondeur( $this->param( 'memberid' ), $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
try {
/** @var Thrive_Dash_Api_SGAutorepondeur $sg */
$sg = $this->get_api();
$sg->set( 'limite', array( 0, 9999 ) );
$raw = $sg->call( 'get_list' );
$lists = array();
if ( empty( $raw->reponse ) ) {
return array();
}
foreach ( $raw->reponse as $item ) {
$lists [] = array(
'id' => $item->listeid,
'name' => $item->nom,
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( "Please re-check your API connection details.", 'thrive-dash' );
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
/** @var Thrive_Dash_Api_SGAutorepondeur $api */
$api = $this->get_api();
$email = strtolower( $arguments['email'] );
$api->set( 'listeid', $list_identifier );
$api->set( 'email', $email );
/**
* The names are inversed for a reason, SG will not accept
* sending only the first_name, so the first name needs to be set as the name
*/
if ( ! empty( $first_name ) && empty( $last_name ) ) {
$api->set( 'name', $first_name );
} elseif ( ! empty( $first_name ) && ! empty( $last_name ) ) {
$api->set( 'first_name', $first_name );
$api->set( 'name', $last_name );
}
if ( isset( $arguments['phone'] ) && ! empty( $arguments['phone'] ) ) {
$api->set( 'telephone', $arguments['phone'] );
}
try {
$api->call( 'set_subscriber' );
return true;
} catch ( Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown SG-Autorepondeur Error', 'thrive-dash' );
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '++email++';
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
return $this;
}
}

View File

@@ -0,0 +1,277 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SendGrid extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'SendGrid';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'sendgrid' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid SendGrid key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to SendGrid using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_SendGridEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
if ( isset( $_POST['connection']['new_connection'] ) && intval( $_POST['connection']['new_connection'] ) === 1 ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
return $this->success( __( 'SendGrid connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_SendGrid $sg */
$sg = $this->get_api();
try {
$sg->client->contactdb()->lists()->get();
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_SendGrid
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_SendGrid( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_SendGrid $api */
$api = $this->get_api();
$response = $api->client->contactdb()->lists()->get();
if ( $response->statusCode() != 200 ) {
$body = $response->body();
$this->_error = ucwords( $body->errors['0']->message );
return false;
}
$body = $response->body();
$lists = array();
foreach ( $body->lists as $item ) {
$lists [] = array(
'id' => $item->id,
'name' => $item->name,
);
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
$args = new stdClass();
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
/** @var Thrive_Dash_Api_SendGrid $api */
$api = $this->get_api();
$args->email = $arguments['email'];
if ( ! empty( $first_name ) ) {
$args->first_name = $first_name;
}
if ( ! empty( $last_name ) ) {
$args->last_name = $last_name;
}
if ( ! empty( $arguments['phone'] ) ) {
$custom_field_id = '';
try {
$response = $api->client->contactdb()->custom_fields()->get();
$fields = $response->body();
foreach ( $fields->custom_fields as $custom_field ) {
if ( isset( $custom_field->name ) && ( $custom_field->name === 'phone' ) ) {
$custom_field_id = $custom_field->id;
}
}
if ( $custom_field_id ) {
try {
$response = $api->client->contactdb()->custom_fields()->_( $custom_field_id )->get();
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
$result = $response->body();
if ( isset( $result->errors ) ) {
$request_body = json_decode( '{
"name": "phone",
"type": "number"
}' );
$api->client->contactdb()->custom_fields()->post( $request_body );
}
$args->phone = $arguments['phone'];
}
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
}
try {
$response = $api->client->contactdb()->recipients()->post( array( $args ) );
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
$body = $response->body();
if ( $body->error_count == 0 ) {
$request_body = null;
$recipient_id = $body->persisted_recipients[0];
try {
$api->client->contactdb()->lists()->_( $list_identifier )->recipients()->_( $recipient_id )->post( $request_body );
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
return true;
}
return __( 'Unknown Sendgrid Error', 'thrive-dash' );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{$email}';
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
}

View File

@@ -0,0 +1,352 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SendGridEmail extends Thrive_Dash_List_Connection_Abstract {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SendGrid';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendgridemail' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid SendGrid key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid SendGrid key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to SendGrid using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to SendGrid using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Try to connect to the autoresponder too
*/
/** @var Thrive_Dash_List_Connection_SendGrid $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgrid' );
$r_result = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection']['new_connection'] = isset( $_POST['connection']['new_connection'] ) ? sanitize_text_field( $_POST['connection']['new_connection'] ) : 1;
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
$this->success( __( 'SendGrid connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_SendGridEmail $sg */
$sg = $this->get_api();
$email = new Thrive_Dash_Api_SendGridEmail_Email();
/**
* Try sending the email
*/
try {
$from_email = get_option( 'admin_email' );
$to = $from_email;
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads SendGrid Email API.';
$text_content = 'This is a test email from Thrive Leads SendGrid Email API.';
$email
->addTo( $to )
->setFrom( $from_email )
->setSubject( $subject )
->setText( $text_content )
->setHtml( $html_content );
$sg->send( $email );
} catch ( Thrive_Dash_Api_SendGridEmail_Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'sendgridemail' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$sg = $this->get_api();
$email = new Thrive_Dash_Api_SendGridEmail_Email();
$from_email = get_option( 'admin_email' );
/**
* Try sending the email
*/
try {
$email
->addTo( $data['email'] )
->setFrom( $from_email )
->setSubject( $data['subject'] )
->setText( empty ( $data['text_content'] ) ? '' : $data['text_content'] )
->setHtml( empty ( $data['html_content'] ) ? '' : $data['html_content'] );
$sg->send( $email );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$sg = $this->get_api();
$email = new Thrive_Dash_Api_SendGridEmail_Email();
$from_email = get_option( 'admin_email' );
$to = array_shift( $data['emails'] );
/**
* Try sending the email
*/
try {
$email
->addTo( $to )
->setFrom( $from_email )
->setFromName( empty( $data['from_name'] ) ? '' : $data['from_name'] )
->setReplyTo( empty( $data['reply_to'] ) ? '' : $data['reply_to'] )
->setCcs( empty( $data['cc'] ) ? array() : $data['cc'] )
->setBccs( empty( $data['bcc'] ) ? array() : $data['bcc'] )
->setSubject( $data['subject'] )
->setText( empty ( $data['text_content'] ) ? '' : $data['text_content'] )
->setHtml( empty ( $data['html_content'] ) ? '' : $data['html_content'] );
foreach ( $data['emails'] as $item ) {
$email->addCc( $item );
}
$sg->send( $email );
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$confirmation_email = new Thrive_Dash_Api_SendGridEmail_Email();
$confirmation_email
->addTo( array( $data['sender_email'] ) )
->setFrom( $from_email )
->setFromName( empty( $data['from_name'] ) ? '' : $data['from_name'] )
->setReplyTo( $from_email )
->setSubject( $data['confirmation_subject'] )
->setText( '' )
->setHtml( empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'] );
$sg->send( $confirmation_email );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
if ( empty( $post_data['_asset_group'] ) ) {
return true;
}
$sg = $this->get_api();
$email = new Thrive_Dash_Api_SendGridEmail_Email();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( empty( $subject ) ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = get_option( 'admin_email' );
$html_content = $asset->post_content;
if ( empty( $html_content ) ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$the_files = '';
foreach ( $files as $file ) {
$the_files .= '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/><br/>';
}
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$from_name = "";
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$email
->addTo( $post_data['email'], $visitor_name )
->setFrom( $from_email )
->setSubject( $subject )
->setText( $text_content )
->setHtml( $html_content );
/**
* Try sending the email
*/
$result = $sg->send( $email );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
$options = array(
'host' => 'api.sendgrid.com',
'endpoint' => '/api/mail.send.json',
'port' => null,
'url' => null,
);
return new Thrive_Dash_Api_SendGridEmail( $this->param( 'key' ), $options );
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
return true;
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
return true;
}
}

View File

@@ -0,0 +1,208 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_SendLayer extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SendLayer';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendlayer' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid SendLayer key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid SendLayer key', 'thrive-dash' ) );
}
$this->set_credentials( compact( 'key' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to SendLayer using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to SendLayer using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
$this->success( __( 'SendLayer connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_SendLayer $sendlayer */
$sendlayer = $this->get_api();
$from_email = get_option( 'admin_email' );
$to = array( array( 'email' => $from_email ) );
$name = $from_email;
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$name = $user->display_name;
}
$subject = 'API connection test';
$text_content = $html_content = 'This is a test email from Thrive Leads SendLayer API.';
try {
$sendlayer->sendMessage([
'name' => $name,
'from' => $from_email,
'to' => $to,
'subject' => $subject,
'text' => $text_content,
'html' => $html_content,
'multipart' => true,
]);
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'sendlayer' );
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$sendlayer = $this->get_api();
$emails = !empty($data['emails']) ? $data['emails'] : array();
$formatted_emails = array();
foreach($emails as $email) {
array_push($formatted_emails, array('email' => $email));
}
$from_email = get_option( 'admin_email' );
try {
$messsage = array(
'name' => empty ( $data['from_name'] ) ? '' : $data['from_name'],
'from' => $from_email,
'to' => $formatted_emails,
'subject' => $data['subject'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'h:Reply-To' => empty ( $data['reply_to'] ) ? '' : $data['reply_to'],
'tags' => empty( $data['email_tags'] ) ? [] : $data['email_tags'],
'multipart' => true,
);
$sendlayer->sendMessage($messsage);
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) && !empty($data['sender_email']) ) {
try {
$messsage = array(
'name' => $from_email,
'from' => $from_email,
'to' => array(
array( 'email' => $data['sender_email'] )
),
'subject' => $data['confirmation_subject'],
'text' => '',
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'h:Reply-To' => $from_email,
'multipart' => true,
);
$sendlayer->sendMessage( $messsage );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
$endpoint = "https://console.sendlayer.com/api";
return new Thrive_Dash_Api_SendLayer( $this->param( 'key' ), $endpoint );
}
/**
* get all Subscriber Lists from this API service
*
* used for abstract class
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* used for abstract class
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SendOwl extends Thrive_Dash_List_Connection_Abstract {
const sendowl_url = 'https://www.sendowl.com';
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'sellings';
}
/**
* @return string
*/
public function get_title() {
return 'SendOwl';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendowl' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid SendOwl key', 'thrive-dash' ) );
}
$url = self::sendowl_url;
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to SendOwl using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'SendOwl connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_SendOwl $so */
$so = $this->get_api();
try {
$so->getProducts();
} catch ( Thrive_Dash_Api_SendOwl_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
if ( empty( $this->param( 'key' ) ) || empty( $this->param( 'secret' ) ) ) {
return null;
}
return new Thrive_Dash_Api_SendOwl( array(
'apiKey' => $this->param( 'key' ),
'secretKey' => $this->param( 'secret' ),
)
);
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
return array();
}
}

View File

@@ -0,0 +1,150 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Sendfox extends Thrive_Dash_List_Connection_Abstract {
/**
* Return api connection title
*
* @return string
*/
public function get_title() {
return 'Sendfox';
}
/**
* Output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendfox' );
}
/**
* read data from post, test connection and save the details
*
* show error message on failure
*
* @return mixed|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
if ( empty( $_POST['connection']['api_key'] ) ) {
return $this->error( __( 'Api key is required', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'Could not connect to Sendfox using provided api key.', 'thrive-dash' ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Sendfox connected successfully', 'thrive-dash' ) );
}
/**
* @return bool|string
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
public function add_subscriber( $list_identifier, $arguments ) {
try {
/**
* @var $api Thrive_Dash_Api_Sendfox
*/
$api = $this->get_api();
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$subscriber_args = array(
'email' => $arguments['email'],
'first_name' => $first_name,
'last_name' => $last_name,
);
$api->add_subscriber( $list_identifier, $subscriber_args );
return true;
} catch ( Exception $e ) {
return false;
}
}
/**
* @return mixed|Thrive_Dash_Api_Sendfox
* @throws Exception
*/
protected function get_api_instance() {
$api_key = $this->param( 'api_key' );
return new Thrive_Dash_Api_Sendfox( $api_key );
}
/**
* @return array|bool
*/
protected function _get_lists() {
$result = array();
try {
/**
* @var $api Thrive_Dash_Api_Sendfox
*/
$api = $this->get_api();
$lists = $api->getLists();
if ( isset( $lists['data'] ) && is_array( $lists['data'] ) ) {
/* First page of lists */
$result = $lists['data'];
/* For multiple pages */
if ( ! empty( $lists['total'] ) ) {
$lists_total = (int) $lists['total'];
$list_per_page = (int) $lists['per_page'];
$pagination_needed = (int) ( $lists_total / $list_per_page ) + 1;
/* Request pages >=2 and merge lists */
if ( $pagination_needed >= 2 ) {
for ( $i = 2; $i <= $pagination_needed; $i ++ ) {
$response_pages = $api->getListsOnPage( $i );
if ( isset( $response_pages['data'] ) && is_array( $response_pages['data'] ) ) {
$result = array_merge( $result, $response_pages['data'] );
}
}
}
}
}
} catch ( Exception $e ) {
}
return $result;
}
}

View File

@@ -0,0 +1,520 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Sendinblue extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SendinBlue';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'sendinblue' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid SendinBlue key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid SendinBlue key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to SendinBlue using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to SendinBlue using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_SendinblueEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
if ( isset( $_POST['connection']['new_connection'] ) && intval( $_POST['connection']['new_connection'] ) === 1 ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
$this->success( __( 'SendinBlue connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$sendinblue = $this->get_api();
try {
$sendinblue->get_account();
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Sendinblue( "https://api.sendinblue.com/v2.0", $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_Sendinblue $sendinblue */
$sendinblue = $this->get_api();
$data = array(
"page" => 1,
"page_limit" => 50,
);
try {
$lists = array();
$raw = $sendinblue->get_lists( $data );
if ( empty( $raw['data'] ) ) {
return array();
}
foreach ( $raw['data'] as $item ) {
$lists [] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( "Please re-check your API connection details.", 'thrive-dash' );
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! is_array( $arguments ) ) {
$arguments = (array) $arguments;
}
$merge_tags = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$merge_tags = array(
'NAME' => $first_name,
'FIRSTNAME' => $first_name,
'SURNAME' => $last_name,
'VORNAME' => $first_name,
'NACHNAME' => $last_name,
'LASTNAME' => $last_name,
);
}
/** @var Thrive_Dash_Api_Sendinblue $api */
$api = $this->get_api();
if ( ! empty( $arguments['phone'] ) ) {
// SendinBlue does not accept phone numbers starting with 0 or other special chars
$the_phone = ltrim( ( preg_replace( '/[^0-9]/', '', $arguments['phone'] ) ), '0' );
$merge_tags['SMS'] = $the_phone;
$merge_tags['PHONE'] = $the_phone;
$merge_tags['TELEFON'] = $the_phone;
}
$data = array(
'email' => $arguments['email'],
'attributes' => array_merge( $merge_tags, $this->_generate_custom_fields( $arguments ) ),
'listid' => array( $list_identifier ),
);
try {
$api->create_update_user( $data );
return true;
} catch ( Thrive_Dash_Api_SendinBlue_Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown SendinBlue Error', 'thrive-dash' );
} catch ( Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown Error', 'thrive-dash' );
}
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{ contact.EMAIL }}';
}
/**
* @param array $params which may contain `list_id`
* @param bool $force make a call to API and invalidate cache
* @param bool $get_all where to get lists with their custom fields
*
* @return array
*/
public function get_api_custom_fields( $params, $force = false, $get_all = true ) {
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
/** @var Thrive_Dash_Api_Sendinblue $api */
$api = $this->get_api();
try {
$attributes = $api->get_attributes();
} catch ( Thrive_Dash_Api_SendinBlue_Exception $e ) {
// Maybe log this
}
$custom_fields = array();
$excluded_fields = array(
'NAME',
'FIRSTNAME',
'SURNAME',
'VORNAME',
'LASTNAME',
'SMS',
'PHONE',
'TELEFON',
);
if ( ! empty( $attributes['data']['normal_attributes'] ) ) {
foreach ( (array) $attributes['data']['normal_attributes'] as $attribute ) {
if ( ! empty( $attribute['type'] ) && ! in_array( $attribute['name'], $excluded_fields ) && 'text' === $attribute['type'] ) {
$custom_fields[] = $this->normalize_custom_field( $attribute );
}
}
}
$this->_save_custom_fields( $custom_fields );
return $custom_fields;
}
/**
* @param array $field
*
* @return array
*/
protected function normalize_custom_field( $field = array() ) {
return array(
'id' => ! empty( $field['name'] ) ? $field['name'] : '',
'name' => ! empty( $field['name'] ) ? $field['name'] : '',
'type' => ! empty( $field['type'] ) ? $field['type'] : '',
'label' => ! empty( $field['name'] ) ? $field['name'] : '',
);
}
/**
* Generate custom fields array
*
* @param array $args
*
* @return array
*/
private function _generate_custom_fields( $args ) {
$custom_fields = $this->get_api_custom_fields( array() );
$ids = $this->build_mapped_custom_fields( $args );
$result = array();
foreach ( $ids as $key => $id ) {
$field = array_filter(
$custom_fields,
function ( $item ) use ( $id ) {
return $item['id'] === $id['value'];
}
);
$field = array_values( $field );
if ( ! isset( $field[0] ) ) {
continue;
}
$name = strpos( $id['type'], 'mapping_' ) !== false ? $id['type'] . '_' . $key : $key;
$cf_form_name = str_replace( '[]', '', $name );
$result[ $field[0]['name'] ] = $this->process_field( $args[ $cf_form_name ] );
}
return $result;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function build_mapped_custom_fields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_Sendinblue $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$this->add_subscriber( $list_id, $args );
$args['attributes'] = $this->prepare_custom_fields_for_api( $custom_fields );
$subscriber = $api->create_update_user( $args );
return ! empty( $subscriber['data']['id'] ) ? $subscriber['data']['id'] : 0;
} catch ( Exception $e ) {
return false;
}
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $custom_field && $field['id'] === $key ) {
$prepared_fields[ $key ] = $custom_field;
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
/**
* Checks if a connection is V3
*
* @return bool
*/
public function is_v3() {
$is_v3 = $this->param( 'v3' );
return ! empty( $is_v3 );
}
/**
* Upgrades a connection from V2 to V3, by generating a V3 key
*
* @return string
*/
public function upgrade() {
$api = $this->get_api();
$api_key = $this->param( 'key' );
$upgrade_response = array();
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
try {
$upgrade_response = $api->upgrade_to_v3( $api_key );
$new_key = $upgrade_response['data']['value'];
$connection = array(
'v3' => true,
'key' => $new_key,
'new_connection' => '0',
);
$this->set_credentials( $connection );
/* Update also the credentials of the related api */
if ( $related_api->is_connected() ) {
$related_api->set_credentials( $connection );
$related_api->save();
}
$this->save();
} catch ( Exception $e ) {
return $e->getMessage();
}
return $upgrade_response;
}
}

View File

@@ -0,0 +1,408 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_SendinblueEmail extends Thrive_Dash_List_Connection_Abstract {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SendinBlue';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendinblueemail' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $ajax_call ? __( 'You must provide a valid SendinBlue key', 'thrive-dash' ) : $this->error( __( 'You must provide a valid SendinBlue key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $ajax_call ? sprintf( __( 'Could not connect to SendinBlue using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) : $this->error( sprintf( __( 'Could not connect to SendinBlue using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Try to connect to the autoresponder too
*/
/** @var Thrive_Dash_List_Connection_Sendinblue $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblue' );
$r_result = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection']['new_connection'] = isset( $_POST['connection']['new_connection'] ) ? absint( $_POST['connection']['new_connection'] ) : 1;
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
$this->success( __( 'SendinBlue connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
$to = $from_email;
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads SendinBlue API.';
$text_content = 'This is a test email from Thrive Leads SendinBlue API.';
try {
$data = array(
"to" => array( $to => "" ),
"from" => array( $from_email, "" ),
"subject" => $subject,
"html" => $html_content,
"text" => $text_content,
);
$sendinblue->send_email( $data );
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'sendinblueemail' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
try {
$options = array(
"to" => array( $data['email'] => '' ),
"from" => array( $from_email, "" ),
"subject" => $data['subject'],
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
);
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
$to = array();
$extra_emails = array();
if ( isset( $data['cc'] ) ) {
$extra_emails = $data['cc'];
}
if ( isset( $data['bcc'] ) ) {
$extra_emails = array_merge( $extra_emails, $data['bcc'] );
}
foreach ( array_merge( $data['emails'], $extra_emails ) as $email ) {
$to[ $email ] = '';
}
try {
$options = array(
'to' => $to,
'from' => array( $from_email, ! empty( $data['from_name'] ) ? '"' . $data['from_name'] . '"' : "" ),
'subject' => $data['subject'],
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'replyto' => array( empty ( $data['reply_to'] ) ? '' : $data['reply_to'], "" ),
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
);
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$options = array(
'to' => array( $data['sender_email'] => '' ),
'from' => array( $from_email, ! empty( $data['from_name'] ) ? '"' . $data['from_name'] . '"' : "" ),
'subject' => $data['confirmation_subject'],
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'text' => '',
'replyto' => array( $from_email, '' ),
);
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
if ( empty( $post_data['_asset_group'] ) ) {
return true;
}
$sendinblue = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = get_option( 'admin_email' );
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$from_name = "";
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$data = array(
"to" => array( $post_data['email'] => $visitor_name ),
"from" => array( $from_email, "" ),
"subject" => $subject,
"html" => $html_content,
"text" => $text_content,
);
$result = $sendinblue->send_email( $data );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Sendinblue( "https://api.sendinblue.com/v2.0", $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
$sendinblue = $this->get_api();
$data = array(
"page" => 1,
"page_limit" => 50,
);
try {
$lists = array();
$raw = $sendinblue->get_lists( $data );
if ( empty( $raw['data'] ) ) {
return array();
}
foreach ( $raw['data']['lists'] as $item ) {
$lists [] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( "Please re-check your API connection details.", 'thrive-dash' );
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$api = $this->get_api();
$merge_tags = array(
'NAME' => $first_name,
'SURNAME' => $last_name,
);
$data = array(
"email" => $arguments['email'],
"attributes" => $merge_tags,
"listid" => array( $list_identifier ),
);
try {
$api->create_update_user( $data );
return true;
} catch ( Thrive_Dash_Api_SendinBlue_Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown SendinBlue Error', 'thrive-dash' );
} catch ( Exception $e ) {
return $e->getMessage() ? $e->getMessage() : __( 'Unknown Error', 'thrive-dash' );
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{EMAIL}';
}
/**
* Checks if a connection is V3
*
* @return bool
*/
public function is_v3() {
$is_v3 = $this->param( 'v3' );
return ! empty( $is_v3 );
}
}

View File

@@ -0,0 +1,435 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SendinblueEmailV3 extends Thrive_Dash_List_Connection_SendinblueEmail {
/**
* Return if the connection is in relation with another connection so we won't show it in the API list
*
* @return bool
*/
public function is_related() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SendinBlue';
}
/**
* Output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendinblueemail' );
}
/**
* Should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? $_POST['connection']['key'] : '';
if ( empty( $key ) ) {
$message = 'You must provide a valid Brevo key';
return $ajax_call ? __( $message, 'thrive-dash' ) : $this->error( __( $message, 'thrive-dash' ) );
}
/* For V3 we need to add this on the credentials list */
$_POST['connection']['v3'] = true;
$this->set_credentials( $_POST['connection'] );
$result = $this->test_connection();
if ( $result !== true ) {
$message = 'Could not connect to Brevo using the provided key (<strong>%s</strong>)';
return $ajax_call ? sprintf( __( $message, 'thrive-dash' ), $result ) : $this->error( sprintf( __( $message, 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/**
* Try to connect to the autoresponder too
*/
/** @var Thrive_Dash_List_Connection_SendinblueV3 $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblue' );
$response = true;
if ( ! $related_api->is_connected() ) {
$_POST['connection']['new_connection'] = isset( $_POST['connection']['new_connection'] ) ? $_POST['connection']['new_connection'] : 1;
$response = $related_api->read_credentials();
}
if ( $response !== true ) {
$this->disconnect();
return $this->error( $response );
}
$this->success( __( 'SendinBlue connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* Test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
if ( ! $this->is_v3() ) {
return parent::test_connection();
}
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
$to = $from_email;
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads SendinBlue API.';
$text_content = $html_content;
try {
$data = array(
'to' => array( array( 'email' => $to ) ),
'sender' => array( 'email' => $from_email ),
'subject' => $subject,
'htmlContent' => $html_content,
'textContent' => $text_content,
);
$sendinblue->send_email( $data );
} catch ( Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection === false ) {
update_option( 'tve_api_delivery_service', 'sendinblueemail-v3' );
}
return true;
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
if ( ! $this->is_v3() ) {
return parent::sendCustomEmail( $data );
}
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
try {
$options = array(
'to' => array( array( 'email' => $data['email'] ) ),
'sender' => array( 'email' => $from_email ),
'subject' => $data['subject'],
);
if ( ! empty ( $data['html_content'] ) ) {
$options['htmlContent'] = $data['html_content'];
}
if ( ! empty ( $data['text_content'] ) ) {
$options['textContent'] = $data['text_content'];
}
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
if ( ! $this->is_v3() ) {
return parent::sendMultipleEmails( $data );
}
$sendinblue = $this->get_api();
$from_email = get_option( 'admin_email' );
$to = array();
$extra_emails = array();
foreach ( array_merge( $data['emails'], $extra_emails ) as $email ) {
$to[] = array( 'email' => $email );
}
try {
$options = array(
'to' => $to,
'sender' => array( 'email' => $from_email ),
'subject' => $data['subject'],
'htmlContent' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
);
if ( ! empty ( $data['text_content'] ) ) {
$options['textContent'] = $data['text_content'];
}
if ( ! empty( $data['from_name'] ) ) {
$options['sender']['name'] = $data['from_name'];
}
if ( ! empty( $data['reply_to'] ) ) {
$options['reply_to'] = $data['reply_to'];
}
if ( ! empty( $data['cc'] ) ) {
$options['cc'] = $data['cc'];
}
if ( ! empty( $data['bcc'] ) ) {
$options['bcc'] = $data['bcc'];
}
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
/* Send confirmation email */
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$options = array(
'to' => array( array( 'email' => $data['sender_email'] ) ),
'sender' => array( 'email' => $from_email ),
'subject' => $data['confirmation_subject'],
'htmlContent' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'replyTo' => array( 'email' => $from_email ),
);
if ( ! empty( $data['from_name'] ) ) {
$options['sender']['name'] = $data['from_name'];
}
if ( ! empty ( $data['text_content'] ) ) {
$options['textContent'] = $data['text_content'];
}
$sendinblue->send_email( $options );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
if ( ! $this->is_v3() ) {
return parent::sendEmail( $post_data );
}
if ( empty( $post_data['_asset_group'] ) ) {
return true;
}
$sendinblue = $this->get_api();
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject === '' ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from_email = get_option( 'admin_email' );
$html_content = $asset->post_content;
if ( $html_content === '' ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
$visitor_name = isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ? $post_data['name'] : '';
$html_content = str_replace( '[lead_name]', $visitor_name, $html_content );
$subject = str_replace( '[lead_name]', $visitor_name, $subject );
$text_content = strip_tags( $html_content );
$to = array( 'email' => $post_data['email'] );
if ( ! empty( $visitor_name ) ) {
$to['name'] = $visitor_name;
}
$data = array(
'to' => array( $to ),
'sender' => array( 'email' => $from_email ),
'subject' => $subject,
'htmlContent' => $html_content,
'textContent' => $text_content,
);
return $sendinblue->send_email( $data );
}
/**
* Instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_SendinblueV3
* @throws Exception
*/
protected function get_api_instance() {
if ( ! $this->is_v3() ) {
return parent::get_api_instance();
}
return new Thrive_Dash_Api_SendinblueV3( 'https://api.sendinblue.com/v3', $this->param( 'key' ) );
}
/**
* Get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
if ( ! $this->is_v3() ) {
return parent::_get_lists();
}
$sendinblue = $this->get_api();
$limit = 50;
$offset = 1;
try {
$lists = array();
$raw = $sendinblue->getLists( $limit, $offset );
if ( empty( $raw['data'] ) ) {
return array();
}
foreach ( $raw['data']['lists'] as $item ) {
$lists [] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( 'Please re-check your API connection details.', 'thrive-dash' );
return false;
}
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string|void
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! $this->is_v3() ) {
return parent::add_subscriber( $list_identifier, $arguments );
}
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$api = $this->get_api();
$merge_tags = array(
'NAME' => $first_name,
'SURNAME' => $last_name,
);
$data = array(
'email' => $arguments['email'],
'attributes' => $merge_tags,
'listid' => array( $list_identifier ),
);
try {
$api->create_update_user( $data );
return true;
} catch ( Thrive_Dash_Api_SendinBlue_Exception $e ) {
return $e->getMessage() ?: __( 'Unknown SendinBlue Error', 'thrive-dash' );
} catch ( Exception $e ) {
return $e->getMessage() ?: __( 'Unknown Error', 'thrive-dash' );
}
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{EMAIL}';
}
}

View File

@@ -0,0 +1,550 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Connection_SendinblueV3 extends Thrive_Dash_List_Connection_Sendinblue {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Brevo';
}
/**
* Output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'sendinblue-v3' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$ajax_call = defined( 'DOING_AJAX' ) && DOING_AJAX;
$key = ! empty( $_POST['connection']['key'] ) ? $_POST['connection']['key'] : '';
if ( empty( $key ) ) {
$message = 'You must provide a valid Brevo key';
return $ajax_call ? __( $message, 'thrive-dash' ) : $this->error( __( $message, 'thrive-dash' ) );
}
$this->set_credentials( $_POST['connection'] );
$result = $this->test_connection();
if ( $result !== true ) {
$message = 'Could not connect to Brevo using the provided key (<strong>%s</strong>)';
return $ajax_call ? sprintf( __( $message, 'thrive-dash' ), $result ) : $this->error( sprintf( __( $message, 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_SendinblueEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
if ( isset( $_POST['connection']['new_connection'] ) && (int) $_POST['connection']['new_connection'] ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
$this->success( __( 'Brevo connected successfully', 'thrive-dash' ) );
if ( $ajax_call ) {
return true;
}
}
/**
* Test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
if ( ! $this->is_v3() ) {
return parent::test_connection();
}
$sendinblue = $this->get_api();
try {
$sendinblue->getAccount();
} catch ( Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_SendinblueV3
* @throws Exception
*/
protected function get_api_instance() {
if ( ! $this->is_v3() ) {
return parent::get_api_instance();
}
return new Thrive_Dash_Api_SendinblueV3( 'https://api.sendinblue.com/v3', $this->param( 'key' ) );
}
/**
* Get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
if ( ! $this->is_v3() ) {
return parent::_get_lists();
}
/** @var Thrive_Dash_Api_Sendinblue $sendinblue */
$sendinblue = $this->get_api();
$data = array(
'limit' => 50,
'offset' => 0,
);
try {
$lists = array();
$raw = $sendinblue->getLists( $data );
if ( empty( $raw['lists'] ) ) {
return array();
}
if ( ! empty( $raw['count'] ) && $raw['count'] > $data['limit'] ) {
$total_loaded = count( $raw['lists'] );
$remaining_pages = (int) ( $raw['count'] / $data['limit'] ) + 1;
if ( $remaining_pages >= 2 ) {
for ( $i = 2; $i <= $remaining_pages; $i ++ ) {
$data['offset'] = $total_loaded;
$response = $sendinblue->getLists( $data );
if ( isset( $response['lists'] ) && is_array( $response['lists'] ) ) {
$raw['lists'] = array_merge( $raw['lists'], $response['lists'] );
}
$total_loaded = count( $raw['lists'] );
}
}
}
foreach ( $raw['lists'] as $item ) {
$lists [] = array(
'id' => $item['id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Exception $e ) {
$this->_error = $e->getMessage() . ' ' . __( 'Please re-check your API connection details.', 'thrive-dash' );
return false;
}
}
/**
* Add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
if ( ! is_array( $arguments ) ) {
$arguments = (array) $arguments;
}
if ( ! $this->is_v3() ) {
return parent::add_subscriber( $list_identifier, $arguments );
}
$merge_tags = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$merge_tags = array(
'NAME' => $first_name,
'FIRSTNAME' => $first_name,
'SURNAME' => $last_name,
'VORNAME' => $first_name,
'NACHNAME' => $last_name,
'LASTNAME' => $last_name,
'NOM' => $last_name,
'PRENOM' => $first_name,
);
}
/** @var Thrive_Dash_Api_SendinblueV3 $api */
$api = $this->get_api();
if ( ! empty( $arguments['phone'] ) ) {
// SendinBlue does not accept phone numbers starting with 0 or other special chars
$the_phone = ltrim( ( preg_replace( '/[^0-9]/', '', $arguments['phone'] ) ), '0' );
$merge_tags['SMS'] = $the_phone;
$merge_tags['PHONE'] = $the_phone;
$merge_tags['TELEFON'] = $the_phone;
}
if ( empty( $arguments['automator_custom_fields'] ) ) {
$attributes = array_merge( $merge_tags, $this->_generate_custom_fields( $arguments ) );
} else {
$attributes = array_merge( $merge_tags, $arguments['automator_custom_fields'] );
}
$data = array(
'email' => $arguments['email'],
'listIds' => array( (int) $list_identifier ),
'updateEnabled' => true,
);
if ( ! empty( $attributes ) ) {
$data['attributes'] = $attributes;
}
try {
$api->create_update_user( $data );
return true;
} catch ( Exception $e ) {
return $e->getMessage() ?: __( 'Unknown Error', 'thrive-dash' );
}
}
/**
* Disconnect (remove) this API connection
*/
public function disconnect() {
if ( ! $this->is_v3() ) {
return parent::disconnect();
}
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendinblueemail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{{ contact.EMAIL }}';
}
/**
* @param array $params which may contain `list_id`
* @param bool $force make a call to API and invalidate cache
* @param bool $get_all where to get lists with their custom fields
*
* @return array
*/
public function get_api_custom_fields( $params, $force = false, $get_all = true ) {
if ( ! $this->is_v3() ) {
return parent::get_api_custom_fields( $params, $force, $get_all );
}
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
/** @var Thrive_Dash_Api_Sendinblue $api */
$api = $this->get_api();
try {
$attributes = $api->get_attributes();
} catch ( Thrive_Dash_Api_SendinBlue_Exception $e ) {
// Maybe log this
}
$custom_fields = array();
$excluded_fields = array(
'NAME',
'FIRSTNAME',
'SURNAME',
'VORNAME',
'LASTNAME',
'SMS',
'PHONE',
'TELEFON',
);
if ( ! empty( $attributes['attributes'] ) ) {
foreach ( $attributes['attributes'] as $attribute ) {
if ( ! empty( $attribute['category'] ) && $attribute['category'] === 'normal' && ! empty( $attribute['type'] ) && ! in_array( $attribute['name'], $excluded_fields ) && 'text' === $attribute['type'] ) {
$custom_fields[] = $this->normalize_custom_field( $attribute );
}
}
}
$this->_save_custom_fields( $custom_fields );
return $custom_fields;
}
/**
* @param array $field
*
* @return array
*/
protected function normalize_custom_field( $field = array() ) {
return array(
'id' => ! empty( $field['name'] ) ? $field['name'] : '',
'name' => ! empty( $field['name'] ) ? $field['name'] : '',
'type' => ! empty( $field['type'] ) ? $field['type'] : '',
'label' => ! empty( $field['name'] ) ? $field['name'] : '',
);
}
/**
* Generate custom fields array
*
* @param array $args
*
* @return array
*/
private function _generate_custom_fields( $args ) {
$custom_fields = $this->get_api_custom_fields( array() );
$ids = $this->build_mapped_custom_fields( $args );
$result = array();
foreach ( $ids as $key => $id ) {
$field = array_filter(
$custom_fields,
function ( $item ) use ( $id ) {
return $item['id'] === $id['value'];
}
);
$field = array_values( $field );
if ( ! isset( $field[0] ) ) {
continue;
}
$name = strpos( $id['type'], 'mapping_' ) !== false ? $id['type'] . '_' . $key : $key;
$cf_form_name = str_replace( '[]', '', $name );
$result[ $field[0]['name'] ] = $this->process_field( $args[ $cf_form_name ] );
}
return $result;
}
/**
* Build custom fields mapping for automations
*
* @param $automation_data
*
* @return object
*/
public function build_automation_custom_fields( $automation_data ) {
$mapped_data = [];
$fields = $this->get_api_custom_fields( array() );
foreach ( $automation_data['api_fields'] as $pair ) {
foreach ( $fields as $field ) {
if ( $field['id'] == $pair['key'] ) {
$value = sanitize_text_field( $pair['value'] );
if ( $value ) {
$mapped_data[ $field['name'] ] = $value;
}
}
}
}
return $mapped_data;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function build_mapped_custom_fields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
if ( ! $this->is_v3() ) {
return parent::add_custom_fields( $email, $custom_fields = array(), $extra = array() );
}
try {
/** @var Thrive_Dash_Api_Sendinblue $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
$args = array(
'email' => $email,
);
if ( ! empty( $extra['name'] ) ) {
$args['name'] = $extra['name'];
}
$this->add_subscriber( $list_id, $args );
$args['attributes'] = $this->prepare_custom_fields_for_api( $custom_fields );
$subscriber = $api->create_update_user( $args );
return ! empty( $subscriber['data']['id'] ) ? $subscriber['data']['id'] : 0;
} catch ( Exception $e ) {
return false;
}
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( $custom_field && $field['id'] === $key ) {
$prepared_fields[ $key ] = $custom_field;
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields' ) );
}
public function has_custom_fields() {
return true;
}
}

View File

@@ -0,0 +1,172 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Sendlane extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'SendLane';
}
/**
* @return bool
*/
public function has_tags() {
return true;
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendlane' );
}
/**
* @return mixed|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
$connection = $this->post( 'connection', array() );
if ( empty( $connection['api_url'] ) || empty( $connection['api_key'] ) || empty( $connection['hash_key'] ) ) {
return $this->error( __( 'All fields are required!', 'thrive-dash' ) );
}
$this->set_credentials( $connection );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'Could not connect to SendLane using the provided details', 'thrive-dash' ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'SendLane connected successfully', 'thrive-dash' ) );
}
/**
* @return bool
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
/**
* @return mixed|Thrive_Dash_Api_Sendlane
* @throws Thrive_Dash_Api_Sendlane_Exception
*/
protected function get_api_instance() {
$api_url = $this->param( 'api_url' );
$api_key = $this->param( 'api_key' );
$hash_key = $this->param( 'hash_key' );
return new Thrive_Dash_Api_Sendlane( $api_key, $hash_key, $api_url );
}
/**
* @return array|bool
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_Sendlane $api */
$api = $this->get_api();
$result = $api->call( 'lists' );
$api->setConnectionStatus( $result['status'] );
/**
* Invalid connection
*/
if ( ! isset( $result['data'] ) || ! is_array( $result['data'] ) ) {
return false;
}
/**
* Valid connection but no lists found
*/
if ( isset( $result['data']['info'] ) ) {
return array();
}
/**
* Add id and name fields for each list
*/
foreach ( $result['data'] as $key => $list ) {
$result['data'][ $key ]['id'] = $list['list_id'];
$result['data'][ $key ]['name'] = $list['list_name'];
}
return $result['data'];
}
/**
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed|string
*/
public function add_subscriber( $list_identifier, $arguments ) {
$name_array = array();
if ( ! empty( $arguments['name'] ) ) {
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$name_array = array(
'first_name' => $first_name,
'last_name' => $last_name,
);
}
/** @var Thrive_Dash_Api_Sendlane $api */
$api = $this->get_api();
$args = array(
'list_id' => $list_identifier,
'email' => $arguments['email'],
);
$args = array_merge( $args, $name_array );
if ( isset( $arguments['sendlane_tags'] ) ) {
$args['tag_names'] = trim( $arguments['sendlane_tags'] );
}
if ( isset( $arguments['phone'] ) ) {
$args['phone'] = $arguments['phone'];
}
return $api->call( 'list-subscriber-add', $args );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return 'VAR_EMAIL';
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'mailing_list', 'api_fields', 'tag_input' ) );
}
}

View File

@@ -0,0 +1,159 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Sendy extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Sendy';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendy' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$url = ! empty( $_POST['connection']['url'] ) ? sanitize_text_field( $_POST['connection']['url'] ) : '';
$lists = ! empty( $_POST['connection']['lists'] ) ? array_map( 'sanitize_text_field', $_POST['connection']['lists'] ) : array();
$lists = array_map( 'trim', $lists );
$lists = array_filter( $lists );
if ( empty( $url ) || empty( $lists ) ) {
return $this->error( 'Invalid URL or Lists IDs' );
}
$_POST['connection']['lists'] = $lists;
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'Could not connect to Sendy', 'thrive-dash' ) );
}
$this->save();
return $this->success( 'Sendy connected successfully' );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_Sendy $api */
$api = $this->get_api();
return $api->testUrl();
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Sendy( $this->param( 'url' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
$lists = array();
foreach ( $this->param( 'lists' ) as $id ) {
$lists[] = array(
'id' => $id,
'name' => "#" . $id,
);
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_Sendy $api */
$api = new Thrive_Dash_Api_Sendy( $this->param( 'url' ) );
try {
$api->subscribe( $arguments['email'], $list_identifier, $arguments['name'], $phone = isset( $arguments['phone'] ) ? $arguments['phone'] : null );
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
return false;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function get_extra_settings( $params = array() ) {
return $params;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function render_extra_editor_settings( $params = array() ) {
$this->output_controls_html( 'sendy/note', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[Email]';
}
}

View File

@@ -0,0 +1,174 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Slack extends Thrive_Dash_List_Connection_Abstract {
const SERVICE_URL = 'https://service-api.thrivethemes.com/integrations/slack';
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'collaboration';
}
/**
* get the authorization URL for the Slack Application
*
* @return string
*/
public function get_authorize_url() {
$query_params = [
'redirect_uri' => admin_url( 'admin.php?page=tve_dash_api_connect&api=slack' ),
];
$query_params['p'] = $this->calc_hash( $query_params );
$query_params = http_build_query(
$query_params,
'&'
);
return sprintf(
'%s%s%s',
static::SERVICE_URL,
false === strpos( static::SERVICE_URL, '?' ) ? '?' : '&',
$query_params
);
}
public function calc_hash( $data ) {
$secret_key = '@#$()%*%$^&*(#@$%@#$%93827456MASDFJIK3245';
return md5( $secret_key . serialize( $data ) . $secret_key );
}
/**
* @return bool|void
*/
public function is_connected() {
return ! empty( $this->param( 'token' ) );
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Slack';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'slack' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$slack = $this->get_api();
try {
$access_token = $slack->get_access_token();
$this->set_credentials( array(
'token' => $access_token,
) );
} catch ( Exception $e ) {
$this->error( $e->getMessage() );
return false;
}
$result = $this->test_connection();
if ( $result !== true ) {
$this->error( sprintf( __( 'Could not test Slack connection: %s', 'thrive-dash' ), $result ) );
return false;
}
$this->save();
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$slack = $this->get_api();
try {
return $slack->verify_token( $this->param( 'token' ) );
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Slack();
}
public function _get_lists() {
return false;
}
public function add_subscriber( $list_identifier, $arguments ) {
return false;
}
public function get_channel_list() {
$slack = $this->get_api();
$credentials = $this->get_credentials();
if ( ! empty( $credentials['token'] ) ) {
return $slack->get_channel_list( $credentials['token'] );
}
return [];
}
public function post_message( $channel, $args ) {
$slack = $this->get_api();
$credentials = $this->get_credentials();
if ( ! empty( $credentials['token'] ) ) {
return $slack->post_message( $credentials['token'], $channel, $args );
}
return [];
}
public function custom_success_message() {
$link = '<a href="http://help.thrivethemes.com/en/articles/6593007-how-to-set-up-a-notification-in-slack-using-thrive-automator">' . __( 'See how this is done', 'thrive-dash' ) . '</a>';
return __( 'You can now use Slack actions in Thrive Automator', 'thrive-dash' ) .' '. $link;
}
}

View File

@@ -0,0 +1,386 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_SparkPost extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'email';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'SparkPost';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sparkpost' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
$email = ! empty( $_POST['connection']['domain'] ) ? sanitize_text_field( $_POST['connection']['domain'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid SparkPost key', 'thrive-dash' ) );
}
if ( empty( $email ) ) {
return $this->error( __( 'Email field must not be empty', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to SparkPost using the provided key. <strong>%s</strong>', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'SparkPost connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$sparkpost = $this->get_api();
if ( isset( $_POST['connection']['domain'] ) ) {
$domain = sanitize_text_field( $_POST['connection']['domain'] );
} else {
$credentials = Thrive_Dash_List_Manager::credentials( 'sparkpost' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
}
}
$to = get_option( 'admin_email' );
$subject = 'API connection test';
$html_content = 'This is a test email from Thrive Leads SparkPost API.';
$text_content = 'This is a test email from Thrive Leads SparkPost API.';
try {
$options = array(
'from' => $domain,
'html' => $html_content,
'text' => $text_content,
'subject' => $subject,
'recipients' => array(
array(
'address' => array(
'email' => $to,
),
),
),
);
$sparkpost->transmission->send( $options );
} catch ( Thrive_Dash_Api_SparkPost_Exception $e ) {
return $e->getMessage();
}
$connection = get_option( 'tve_api_delivery_service', false );
if ( $connection == false ) {
update_option( 'tve_api_delivery_service', 'sparkpost' );
}
return true;
/**
* just try getting a list as a connection test
*/
}
/**
* Send custom email
*
* @param $data
*
* @return bool|string true for success or error message for failure
*/
public function sendCustomEmail( $data ) {
$sparkpost = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'sparkpost' );
if ( isset( $credentials ) ) {
$domain = $credentials['domain'];
}
try {
$options = array(
'from' => $domain,
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'subject' => $data['subject'],
'recipients' => array(
array(
'address' => array(
'email' => $data['email'],
),
),
),
);
$sparkpost->transmission->send( $options );
} catch ( Thrive_Dash_Api_SparkPost_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Send the same email to multiple addresses
*
* @param $data
*
* @return bool|string
*/
public function sendMultipleEmails( $data ) {
$sparkpost = $this->get_api();
$credentials = Thrive_Dash_List_Manager::credentials( 'sparkpost' );
if ( isset( $credentials ) ) {
$from_email = $credentials['domain'];
}
$recipients = $this->_prepareRecipients( $data );
if ( ! empty( $data['from_name'] ) ) {
$domain = [
'name' => $data['from_name'],
'email' => $from_email,
];
} else {
$domain = $from_email;
}
try {
$options = array(
'from' => $domain,
'html' => empty ( $data['html_content'] ) ? '' : $data['html_content'],
'text' => empty ( $data['text_content'] ) ? '' : $data['text_content'],
'subject' => $data['subject'],
'recipients' => $recipients,
);
if ( ! empty( $data['reply_to'] ) ) {
$options['replyTo'] = $data['reply_to'];
}
$sparkpost->transmission->send( $options );
} catch ( Thrive_Dash_Api_SparkPost_Exception $e ) {
return $e->getMessage();
}
if ( ! empty( $data['send_confirmation'] ) ) {
try {
$confirmation = array(
'from' => $domain,
'html' => empty ( $data['confirmation_html'] ) ? '' : $data['confirmation_html'],
'text' => '',
'subject' => $data['confirmation_subject'],
'recipients' => array(
array(
'address' => array(
'email' => $data['sender_email'],
),
),
),
'replyTo' => $from_email,
);
$sparkpost->transmission->send( $confirmation );
} catch ( Thrive_Dash_Api_SparkPost_Exception $e ) {
return $e->getMessage();
}
}
return true;
}
/**
* Prepare email recipients
*
* @param array $data
*
* @return array
*/
private function _prepareRecipients( $data ) {
$recipients = array();
$first_email = current( $data['emails'] );
$data['cc'] = ! empty( $data['cc'] ) ? $data['cc'] : array();
$data['bcc'] = ! empty( $data['bcc'] ) ? $data['bcc'] : array();
$extra = array_merge( $data['cc'], $data['bcc'] );
foreach ( array_unique( $data['emails'] ) as $email ) {
$recipients[] = array(
'address' => array(
'email' => $email,
),
);
}
foreach ( array_unique( $extra ) as $email ) {
$recipients[] = array(
'address' => array(
'email' => $email,
'header_to' => $first_email,
),
);
}
return $recipients;
}
/**
* Send the email to the user
*
* @param $post_data
*
* @return bool|string
* @throws Exception
*
*/
public function sendEmail( $post_data ) {
$sparkpost = $this->get_api();
$credentials = $this->get_credentials();
if ( empty( $post_data['_asset_group'] ) ) {
return false;
}
$asset = get_post( $post_data['_asset_group'] );
if ( empty( $asset ) || ! ( $asset instanceof WP_Post ) || $asset->post_status !== 'publish' ) {
throw new Exception( sprintf( __( 'Invalid Asset Group: %s. Check if it exists or was trashed.', 'thrive-dash' ), $post_data['_asset_group'] ) );
}
$files = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_files', true );
$subject = get_post_meta( $post_data['_asset_group'], 'tve_asset_group_subject', true );
if ( $subject == "" ) {
$subject = get_option( 'tve_leads_asset_mail_subject' );
}
$from = $credentials['domain'];
$html_content = $asset->post_content;
if ( $html_content == "" ) {
$html_content = get_option( 'tve_leads_asset_mail_body' );
}
$attached_files = array();
foreach ( $files as $file ) {
$attached_files[] = '<a href="' . $file['link'] . '">' . $file['link_anchor'] . '</a><br/>';
}
$the_files = implode( '<br/>', $attached_files );
$html_content = str_replace( '[asset_download]', $the_files, $html_content );
$html_content = str_replace( '[asset_name]', $asset->post_title, $html_content );
$subject = str_replace( '[asset_name]', $asset->post_title, $subject );
if ( isset( $post_data['name'] ) && ! empty( $post_data['name'] ) ) {
$html_content = str_replace( '[lead_name]', $post_data['name'], $html_content );
$subject = str_replace( '[lead_name]', $post_data['name'], $subject );
$visitor_name = $post_data['name'];
} else {
$html_content = str_replace( '[lead_name]', '', $html_content );
$subject = str_replace( '[lead_name]', '', $subject );
$visitor_name = '';
}
$text_content = strip_tags( $html_content );
$options = array(
'from' => $from,
'html' => $html_content,
'text' => $text_content,
'subject' => $subject,
'options' => array(),
'recipients' => array(
array(
'address' => array(
'email' => $post_data['email'],
),
),
),
);
$result = $sparkpost->transmission->send( $options );
return $result;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_SparkPost( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
}
/**
* Get from email value
*
* @return string
*/
public function get_email_param() {
return $this->param( 'domain' );
}
}

View File

@@ -0,0 +1,246 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Turnstile extends Thrive_Dash_List_Connection_Abstract {
public function __construct( $key ) {
parent::__construct( $key );
add_filter( 'tcb_spam_prevention_tools', [ $this, 'add_spam_prevention_tool' ] );
add_action( 'tve_load_turnstile', [ $this, 'enqueue_turnstile_scripts' ] );
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'recaptcha';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Turnstile';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
do_action( 'tve_load_turnstile' );
$this->output_controls_html( 'turnstile' );
}
public function enqueue_turnstile_scripts() {
tve_dash_enqueue_script( 'tve-dash-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$site = ! empty( $_POST['site_key'] ) ? sanitize_text_field( $_POST['site_key'] ) : '';
$secret = ! empty( $_POST['secret_key'] ) ? sanitize_text_field( $_POST['secret_key'] ) : '';
$token = ! empty( $_POST['api_token'] ) ? sanitize_text_field( $_POST['api_token'] ) : '';
$theme = ! empty( $_POST['theme'] ) ? sanitize_text_field( $_POST['theme'] ) : '';
$language = ! empty( $_POST['language'] ) ? sanitize_text_field( $_POST['language'] ) : '';
$appearance = ! empty( $_POST['appearance'] ) ? sanitize_text_field( $_POST['appearance'] ) : '';
$size = ! empty( $_POST['size'] ) ? sanitize_text_field( $_POST['size'] ) : '';
//extra i believe we don't need following fields for api call
if ( empty( $site ) || empty( $secret ) ) {
return $this->error( __( 'Both Site Key and Secret Key fields are required', 'thrive-dash' ) );
}
//recreate credential object
$credentials = array(
'connection' => $this->post( 'connection' ),
'site_key' => $site,
'secret_key' => $secret,
'api_token' => $token,
'theme' => $theme,
'language' => $language,
'appearance' => $appearance,
'size' => $size,
);
$old_token = $this->param( 'api_token' );
$this->set_credentials( $credentials );
if ( strcmp( $old_token, $token ) !== 0 ) {
if ( empty( $token ) ) {
return $this->error( __( 'Token is missing!', 'thrive-dash' ) );
}
$result = $this->test_connection();
if ( $result !== true ) {
$errorMessage = ! empty( $result['message'] ) ? $result['message'] : __( 'Incorrect Secret Key.', 'thrive-dash' );
return $this->error( sprintf( $errorMessage, $result ) );
}
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Turnstile connected successfully!', 'thrive-dash' ) );
}
/**
* test if the secret key is correct and it exists.
*
* @return bool|array true for success or error details array for failure
*/
public function test_connection() {
$CAPTCHA_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$_capthca_params = array(
'response' => $this->param( 'api_token' ),
'secret' => $this->param( 'secret_key' ),
);
$request = tve_dash_api_remote_post( $CAPTCHA_URL, array( 'body' => $_capthca_params ) );
$response = json_decode( wp_remote_retrieve_body( $request ), true );
if ( ! empty( $response['error-codes'] ) ) {
$errorLists = $this->getErrorLists();
foreach ( $response['error-codes'] as $errorCode ) {
if ( 'timeout-or-duplicate' === $errorCode ) {
break;
}
if ( ! empty( $errorLists[ $errorCode ] ) ) {
return array(
'success' => false,
'message' => $errorLists[ $errorCode ],
'code' => $errorCode,
);
}
}
}
return true;
}
public function getErrorLists() {
$errorLists = array(
'missing-input-secret' => __( 'The secret parameter was not passed', 'thrive-dash' ),
'invalid-input-secret' => __( 'The secret parameter was invalid or did not exist', 'thrive-dash' ),
'missing-input-response' => __( 'The response parameter was not passed', 'thrive-dash' ),
'invalid-input-response' => __( 'The response parameter is invalid or has expired', 'thrive-dash' ),
'invalid-widget-id' => __( 'The widget ID extracted from the parsed site secret key was invalid or did not exist', 'thrive-dash' ),
'invalid-parsed-secret' => __( 'The secret extracted from the parsed site secret key was invalid', 'thrive-dash' ),
'bad-request' => __( 'The request was rejected because it was malformed', 'thrive-dash' ),
'internal-error' => __( 'An internal error happened while validating the response. The request can be retried', 'thrive-dash' ),
);
return $errorLists;
}
public function getSiteKey() {
$this->get_credentials();
return $this->param( 'site_key' );
}
public function add_spam_prevention_tool( $sp_tools ) {
array_push( $sp_tools, $this->_key );
return $sp_tools;
}
public function supportedLanguages() {
$languages = array(
'auto' => __( 'Auto', 'thrive-dash' ),
'en' => __( 'English (United States)', 'thrive-dash' ),
'ar' => __( 'Arabic (Egypt)', 'thrive-dash' ),
'bg' => __( 'Bulgarian (Bulgaria)', 'thrive-dash' ),
'cs' => __( 'Czech (Czech Republic)', 'thrive-dash' ),
'da' => __( 'Danish (Denmark)', 'thrive-dash' ),
'de' => __( 'German (Germany)', 'thrive-dash' ),
'el' => __( 'Greek (Greece)', 'thrive-dash' ),
'es' => __( 'Spanish (Spain)', 'thrive-dash' ),
'fa' => __( 'Farsi (Iran)', 'thrive-dash' ),
'fi' => __( 'Finnish (Finland)', 'thrive-dash' ),
'fr' => __( 'French (France)', 'thrive-dash' ),
'he' => __( 'Hebrew (Israel)', 'thrive-dash' ),
'hi' => __( 'Hindi (India)', 'thrive-dash' ),
'hr' => __( 'Croatian (Croatia)', 'thrive-dash' ),
'hu' => __( 'Hungarian (Hungary)', 'thrive-dash' ),
'id' => __( 'Indonesian (Indonesia)', 'thrive-dash' ),
'it' => __( 'Italian (Italy)', 'thrive-dash' ),
'ja' => __( 'Japanese (Japan)', 'thrive-dash' ),
'ko' => __( 'Korean (Korea)', 'thrive-dash' ),
'lt' => __( 'Lithuanian (Lithuania)', 'thrive-dash' ),
'ms' => __( 'Malay (Malaysia)', 'thrive-dash' ),
'nb' => __( 'Norwegian Bokmål (Norway)', 'thrive-dash' ),
'nl' => __( 'Dutch (Netherlands)', 'thrive-dash' ),
'pl' => __( 'Polish (Poland)', 'thrive-dash' ),
'pt' => __( 'Portuguese (Brazil)', 'thrive-dash' ),
'ro' => __( 'Romanian (Romania)', 'thrive-dash' ),
'ru' => __( 'Russian (Russia)', 'thrive-dash' ),
'sk' => __( 'Slovak (Slovakia)', 'thrive-dash' ),
'sl' => __( 'Slovenian (Slovenia)', 'thrive-dash' ),
'sr' => __( 'Serbian (Bosnia and Herzegovina)', 'thrive-dash' ),
'sv' => __( 'Swedish (Sweden)', 'thrive-dash' ),
'th' => __( 'Thai (Thailand)', 'thrive-dash' ),
'tlh' => __( 'Klingon (QonoS)', 'thrive-dash' ),
'tr' => __( 'Turkish (Turkey)', 'thrive-dash' ),
'uk' => __( 'Ukrainian (Ukraine)', 'thrive-dash' ),
'vi' => __( 'Vietnamese (Vietnam)', 'thrive-dash' ),
'zh-cn' => __( 'Chinese (Simplified, China)', 'thrive-dash' ),
'zh-tw' => __( 'Chinese (Traditional, Taiwan)', 'thrive-dash' ),
);
$result = array();
foreach ( $languages as $code => $name ) {
$result[ $code ] = array(
"value" => $code,
"name" => $name,
"html" => sprintf( '<option value="%s" <#- (item && item.language === "%s") ? selected="selected" : "" #> >%s</option>', $code, $code, $name ),
);
}
return $result;
}
/**
* @return string
*/
public function custom_success_message() {
return ' ';
}
/*
* Those functions do not apply
*/
protected function get_api_instance() {
}
protected function _get_lists() {
}
public function add_subscriber( $list_identifier, $arguments ) {
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
/**
* Class Thrive_Dash_List_Connection_Twitter
*/
class Thrive_Dash_List_Connection_Twitter extends Thrive_Dash_List_Connection_Abstract {
protected $_key = 'twitter';
private $url = 'https://api.twitter.com/1.1/';
/**
* Thrive_Dash_List_Connection_Twitter constructor.
*/
public function __construct() {
$this->set_credentials( Thrive_Dash_List_Manager::credentials( $this->_key ) );
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'social';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Twitter';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'twitter' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$access_token = ! empty( $_POST['access_token'] ) ? sanitize_text_field( $_POST['access_token'] ) : '';
$token_secret = ! empty( $_POST['token_secret'] ) ? sanitize_text_field( $_POST['token_secret'] ) : '';
$api_key = ! empty( $_POST['api_key'] ) ? sanitize_text_field( $_POST['api_key'] ) : '';
$api_secret = ! empty( $_POST['api_secret'] ) ? sanitize_text_field( $_POST['api_secret'] ) : '';
if ( empty( $access_token ) || empty( $token_secret ) || empty( $api_key ) || empty( $api_secret ) ) {
return $this->error( __( 'All fields are required', 'thrive-dash' ) );
}
$this->set_credentials( array(
'access_token' => $access_token,
'token_secret' => $token_secret,
'api_key' => $api_key,
'api_secret' => $api_secret,
) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Incorrect credentials.', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'Twitter connected successfully!', 'thrive-dash' ) );
}
/**
* test if the credentials are correct.
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$call = $this->url . 'account/verify_credentials.json';
/** @var Thrive_Dash_Api_Twitter $api */
$api = $this->get_api();
$call = $api->buildOauth( $call, 'GET' )->performRequest();
$response = json_decode( $call, true );
return empty( $response['errors'] );
}
/**
* Get Twitter comment
*
* @param $id
*
* @return array|string|void
*/
public function get_comment( $id ) {
/** @var Thrive_Dash_Api_Twitter $api */
$api = $this->get_api();
$call = $this->url . 'statuses/show.json';
$response = json_decode( $api->setGetfield( '?id=' . $id )->buildOauth( $call, 'GET' )->performRequest(), true );
if ( ! empty( $response ) && is_array( $response ) ) {
/* build the user picture so we can get the original one, not the small one */
$user_picture = 'https://twitter.com/' . $response['user']['screen_name'] . '/profile_image?size=original';
$comment = array(
'screen_name' => $response['user']['screen_name'],
'name' => $response['user']['name'],
'text' => $response['text'],
'url' => $response['user']['url'],
'picture' => $user_picture,
);
} else {
$comment = __( 'An error occured while getting the comment. Please verify your Twitter connection!', 'thrive-dash' );
}
return $comment;
}
/**
* @return string
*/
public function custom_success_message() {
return ' ';
}
public function add_subscriber( $list_identifier, $arguments ) {
}
/**
* @return Thrive_Dash_Api_Twitter
*/
protected function get_api_instance() {
$params = array(
'oauth_access_token' => $this->param( 'access_token' ),
'oauth_access_token_secret' => $this->param( 'token_secret' ),
'consumer_key' => $this->param( 'api_key' ),
'consumer_secret' => $this->param( 'api_secret' ),
);
return new Thrive_Dash_Api_Twitter( $params );
}
protected function _get_lists() {
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_WebinarJamStudio extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'webinar';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'WebinarJamStudio';
}
/**
* these are called webinars, not lists
*
* @return string
*/
public function get_list_sub_title() {
return 'Choose from the following upcoming webinars';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'webinarjamstudio' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid WebinarJamStudio key', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to WebinarJamStudio using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'WebinarJamStudio connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_WebinarJamStudio $api */
$api = $this->get_api();
/**
* just try getting the list of the webinars as a connection test
*/
try {
$api->getUpcomingWebinars(); // this will throw the exception if there is a connection problem
} catch ( Thrive_Dash_Api_WebinarJamStudio_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_WebinarJamStudio $api */
$api = $this->get_api();
try {
$name = empty( $arguments['name'] ) ? '' : $arguments['name'];
$phone = ! isset( $arguments['phone'] ) || empty( $arguments['phone'] ) ? '' : $arguments['phone'];
$webinar = $api->getWebinar( $list_identifier );
$schedule = 0;
if ( 4 === $api->getWebinarJamApiVersion() ) {
$schedule = isset( $webinar['webinar']['schedules'][0]['schedule'] ) ? $webinar['webinar']['schedules'][0]['schedule'] : $schedule;
}
$api->registerToWebinar( $list_identifier, $name, $arguments['email'], $phone, $schedule );
return true;
} catch ( Thrive_Dash_Api_WebinarJamStudio_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_WebinarJamStudio( $this->param( 'key' ), $this->param( 'version' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_WebinarJamStudio $api */
$api = $this->get_api();
try {
$lists = array();
$webinars = $api->getUpcomingWebinars();
foreach ( $webinars as $key => $item ) {
$lists [] = array(
'id' => $item['webinar_id'],
'name' => $item['name'],
);
}
return $lists;
} catch ( Thrive_Dash_Api_WebinarJamStudio_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
}

View File

@@ -0,0 +1,480 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Wordpress extends Thrive_Dash_List_Connection_Abstract {
protected $api_error_type = 'string';
private $acf_identifier = 'tve_acf_';
/**
* Set current error type output
*
* @param string $type
*
* @return $this
*/
public function set_error_type( $type = 'string' ) {
$this->api_error_type = $type;
return $this;
}
/**
* WordPress API Connection is always "connected"
*
* @return bool
*/
public function is_connected() {
return true;
}
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'other';
}
/**
* @return string
*/
public function get_title() {
return 'WordPress account';
}
/**
* this requires a special naming here, as it's about wordpress roles, not lists of subscribers
*
* @return string
*/
public function get_list_sub_title() {
return 'Choose the role which should be assigned to your subscribers';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'wordpress' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$registration_disabled = isset( $_POST['registration_disabled'] ) ? sanitize_text_field( $_POST['registration_disabled'] ) : 0;
$this->set_credentials( array(
'connected' => true,
'registration_disabled' => (int) $registration_disabled,
) );
/**
* finally, save the connection details
*/
$this->save();
return true;
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/**
* wordpress integration is always supported
*/
return true;
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
// no API instance needed here
return null;
}
/**
* get all Subscriber Lists from this API service
*
* @return array
*/
protected function _get_lists() {
$roles = array();
foreach ( $this->_getRoles() as $key => $role_data ) {
$roles[] = array(
'id' => $key,
'name' => $role_data['name'],
);
}
return $roles;
}
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
return $this->get_all_custom_fields( $force );
}
/**
* Get all custom fields by list id
*
* @param $force calls the API and invalidate cache
*
* @return array|mixed
*/
public function get_all_custom_fields( $force ) {
// Serve from cache if exists and requested
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$default_fields = array(
array(
'id' => 'nickname',
'label' => 'Nickname',
'name' => 'nickname',
'type' => 'TEXT',
),
array(
'id' => 'description',
'label' => 'Biographical Info',
'name' => 'description',
'type' => 'TEXT',
),
array(
'id' => 'user_url',
'label' => 'Website',
'name' => 'user_url',
'type' => 'TEXT',
),
);
$custom_fields = array();
$roles = $this->_get_lists();
if ( is_array( $roles ) ) {
foreach ( $roles as $role ) {
if ( empty( $role['id'] ) ) {
continue;
}
$fields = $default_fields;
foreach ( tvd_get_acf_user_external_fields( $role['id'] ) as $field ) {
$fields[ $field['name'] ] = array(
'id' => $this->acf_identifier . $field['name'],
'label' => $field['label'],
'name' => $field['name'],
'type' => 'TEXT',
);
}
$custom_fields[ $role['id'] ] = $fields;
}
}
$this->_save_custom_fields( $custom_fields );
return $custom_fields;
}
/**
* List of accepted roles
*
* @return array[]
*/
protected function _getRoles() {
/* get_editable_roles only loaded in the admin sections */
if ( ! function_exists( 'get_editable_roles' ) ) {
require_once( ABSPATH . '/wp-admin/includes/user.php' );
}
$user_roles = get_editable_roles();
unset( $user_roles['administrator'], $user_roles['editor'] );
return $user_roles;
}
/**
* Construct an error object to be sent as result. Depending on $this->api_error_type, formats the message as a string or an assoc array
*
* @param string|array $message
* @param string $field
*/
protected function build_field_error( $message, $field ) {
if ( $this->api_error_type !== 'string' && ! is_array( $message ) ) {
$message = array(
'field' => $field,
'error' => $message,
);
}
return $this->error( $message );
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string|Thrive_Dash_List_Connection_Wordpress
*/
public function add_subscriber( $list_identifier, $arguments ) {
/**
* If current request is not "trusted" ( form settings not saved in the database ), the only accepted role is "subscriber"
*/
if ( empty( $arguments['$$trusted'] ) ) {
$list_identifier = 'subscriber';
}
$error = null;
if ( $this->isDisabled() ) {
$error = $this->build_field_error( __( 'Registration has been disabled', 'thrive-dash' ), '' );
} elseif ( is_user_logged_in() ) {
$error = $this->build_field_error( __( 'You are already logged in. Please Logout in order to create a new user.', 'thrive-dash' ), '' );
} elseif ( empty( $arguments['email'] ) ) {
/* Use the same error messages as WordPress */
$error = $this->build_field_error( __( '<strong>Error</strong>: Please type your email address.' ), 'email' );
} elseif ( ! is_email( $arguments['email'] ) ) {
$error = $this->build_field_error( __( '<strong>Error</strong>: The email address isn&#8217;t correct.' ), 'email' );
}
if ( $error !== null ) {
return $error;
}
/* get profile fields from mapping */
$profile_fields = array( 'first_name', 'last_name', 'nickname', 'description', 'user_url' );
if ( ! empty( $arguments['tve_mapping'] ) ) {
foreach ( Thrive_Dash_List_Manager::decode_connections_string( $arguments['tve_mapping'] ) as $field_name => $spec ) {
$field_name = str_replace( '[]', '', $field_name );
if ( ! empty( $spec['wordpress'] ) ) {
if ( strpos( $field_name, 'mapping_' ) !== false ) {
$arguments[ $spec['wordpress'] ] = $this->process_field( $arguments[ $field_name ] );
}
if ( isset( $arguments[ $field_name ] ) && in_array( $spec['_field'], $profile_fields, true ) ) {
/* map specific user fields */
$arguments[ $spec['_field'] ] = $arguments[ $field_name ];
}
}
}
}
$username = $arguments['email'];
$user_id = username_exists( $username );
/**
* if we already have this username
*/
if ( $user_id ) {
$username .= rand( 3, 5 );
$user_id = null;
$arguments['username'] = $username;
}
if ( ! empty( $arguments['name'] ) ) {
list( $arguments['first_name'], $arguments['last_name'] ) = $this->get_name_parts( $arguments['name'] );
}
/**
* check if passwords parameters exist and if they are the same in case they're two
*/
if ( isset( $arguments['password'] ) ) {
if ( isset( $arguments['confirm_password'] ) && $arguments['password'] !== $arguments['confirm_password'] ) {
return $this->error( __( 'Passwords do not match', 'thrive-dash' ) );
}
if ( ! $user_id && email_exists( $arguments['email'] ) === false ) {
$user_data = array(
'user_login' => $username,
'user_pass' => $arguments['password'],
'user_email' => $arguments['email'],
);
foreach ( $profile_fields as $profile_field ) {
if ( ! empty( $arguments[ $profile_field ] ) ) {
$user_data[ $profile_field ] = $arguments[ $profile_field ];
}
}
$user_data['role'] = 'subscriber';
if ( array_key_exists( $list_identifier, $this->_getRoles() ) ) {
$user_data['role'] = $list_identifier;
}
/**
* Filter user data before creating a new user
*/
$user_data = apply_filters( 'tvd_create_user_data', $user_data );
$user_id = wp_insert_user( $user_data );
if ( $user_id ) {
$data = $arguments;
unset( $data['password'], $data['confirm_password'] );
do_action( 'thrive_register_form_through_wordpress_user', $user_id, $data );
$slug = strtolower( trim( preg_replace( '/[^A-Za-z0-9-]+/', '-', $data['_tcb_id'] ) ) );
do_action( 'thrive_register_form_through_wordpress_user_' . $slug, $user_id, $data );
}
} else {
return $this->build_field_error( __( '<strong>Error</strong>: This email is already registered. Please choose another one.' ), 'email' );
}
} else {
/* create a sanitized user_login string */
$sanitized_user_login = trim( sanitize_user( $arguments['email'], true ) );
$user_id = register_new_user( $sanitized_user_login, $arguments['email'] );
}
if ( $user_id instanceof WP_Error ) {
return $user_id->get_error_message();
}
$userdata = array( 'ID' => $user_id );
foreach ( $profile_fields as $profile_field ) {
if ( ! empty( $arguments[ $profile_field ] ) ) {
$userdata[ $profile_field ] = $arguments[ $profile_field ];
$has_profile_update = true;
}
}
if ( isset( $has_profile_update ) ) {
wp_update_user( $userdata );
}
if ( tvd_has_external_fields_plugins() ) {
// if is acf plugin active, run through all of them and update the custom fields for the user
foreach ( $arguments as $key => $field ) {
if ( strpos( $key, $this->acf_identifier ) === 0 ) {
$id = explode( $this->acf_identifier, $key )[1];
update_field( $id, $field, 'user_' . $user_id );
}
}
}
if ( isset( $has_profile_update ) ) {
//WP has an hook for his action which expects 2 parameters
//we fake the second param
$old_data = new stdClass();
$old_data->user_pass = '';
do_action( 'profile_update', $user_id, $old_data, $userdata );
}
/**
* also, assign the selected role to the newly created user
*/
$user = new WP_User( $user_id );
do_action( 'tvd_after_create_wordpress_account', $user, $arguments );
return true;
}
/**
* Get API custom form fields. By default we have only name and phone
*
* @param array $params
*
* @return array
*/
public function get_custom_fields( $params = array() ) {
return array(
array(
'id' => 'name',
'placeholder' => __( 'Name', 'thrive-cb' ),
),
array(
'id' => 'password',
'placeholder' => __( 'Password', 'thrive-cb' ),
),
array(
'id' => 'confirm_password',
'placeholder' => __( 'Confirm password', 'thrive-cb' ),
),
);
}
/**
* This cannot be tested
*
* @return bool
*/
public function can_test() {
return false;
}
/**
* This cannot be deleted
*
* @return bool
*/
public function can_delete() {
return false;
}
/**
* Whether or not registration is currently disabled
*/
public function isDisabled() {
return ! empty( $this->_credentials['registration_disabled'] );
}
public function prepare_json() {
$message = $this->isDisabled() ? esc_attr__( 'Connection disabled', 'thrive-dash' ) : esc_attr__( 'Connection enabled', 'thrive-dash' );
return parent::prepare_json() + array(
'status_icon' => '<span data-tooltip="' . $message . '" class="tvd-api-status-icon tvd-tooltipped status-' . ( $this->isDisabled() ? 'red' : 'green' ) . '"></span>',
);
}
/**
* Get localization data needed for setting up this connection within a form
*
* @return array
*/
public function get_data_for_setup() {
/* build an error message */
$error_message = sprintf(
__( 'Your connection with WordPress is currently disabled and will not accept registrations. Enable your WordPress connection from the %sAPI dashboard %shere%s', 'thrive-dash' ),
'<strong>',
'<a href="' . admin_url( 'admin.php?page=tve_dash_api_connect#edit/wordpress/autoclose' ) . '" target="_blank">',
'</a></strong>'
);
return array(
'has_error' => $this->isDisabled(),
'error_html' => $error_message,
);
}
}

View File

@@ -0,0 +1,337 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Zapier extends Thrive_Dash_List_Connection_Abstract {
/**
* Needed to decide webhook's name
*
* @var string
*/
protected $_hook_prefix = 'td_';
/**
* Needed to decide webhook's name
*
* @var string
*/
protected $_hook_suffix = '_webhook';
/**
* Accepted subscribe parameters
*
* @var array
*/
protected $_accepted_params
= array(
'first_name',
'last_name',
'full_name',
'name',
'email',
'message',
'phone',
'url',
'tags',
'number',
'date',
'zapier_send_ip',
'zapier_tags',
'zapier_source_url',
'zapier_thriveleads_group',
'zapier_thriveleads_type',
'zapier_thriveleads_name',
'optin_hook',
);
/**
* @return string
*/
public function get_title() {
return 'Zapier';
}
/**
* Template
*/
public function output_setup_form() {
$this->output_controls_html( 'zapier' );
}
/**
* Read credentials from $_POST and try to save them
*
* @return string|true
*/
public function read_credentials() {
$this->set_credentials(
array(
'api_key' => ! empty( $_POST['connection']['api_key'] ) ? sanitize_text_field( $_POST['connection']['api_key'] ) : '',
'blog_url' => ! empty( $_POST['connection']['blog_url'] ) ? sanitize_text_field( $_POST['connection']['blog_url'] ) : '',
)
);
$_test_passed = $this->test_connection();
if ( true === $_test_passed ) {
$this->save();
}
return $_test_passed;
}
/**
* Delete Zapier saved options
*
* @return $this|Thrive_Dash_List_Connection_Abstract
*/
public function before_disconnect() {
foreach ( array( 'td_api_key', 'td_optin_webhook', 'td_cf-optin_webhook' ) as $option_name ) {
delete_option( $option_name );
}
return $this;
}
/**
* @return true|string true on SUCCESS or error message on FAILURE
*/
public function test_connection() {
$_is_working = true;
/** @var Thrive_Dash_Api_Zapier $api */
$api = $this->get_api();
/** @var WP_Error|bool $response */
$response = $api->authenticate();
if ( is_wp_error( $response ) ) {
$_is_working = $response->get_error_message();
}
return $_is_working;
}
/**
* Calls a Zapier trigger in order to start the created Zapier flow with different integrations
* based on the received hook URL [for Lead Generation / or Contact Form]
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed|Thrive_Dash_List_Connection_Abstract
*/
public function add_subscriber( $list_identifier, $arguments ) {
$params = $this->_prepare_args( $arguments );
$subscribe_url = $this->_get_hook_url( $arguments );
if ( ! empty( $subscribe_url ) ) {
return $this->get_api()->trigger_subscribe( $subscribe_url, $params );
}
return $this->error( __( 'There was an error sending your message, please make sure your Zap is activated or contact support.', 'thrive-dash' ) );
}
/**
* Get the proper hook URL from options
*
* @param $arguments
*
* @return string
*/
private function _get_hook_url( $arguments ) {
// for Lead Generation
$hook_name = 'optin';
// for Contact Form
if ( ! empty( $arguments['optin_hook'] ) && in_array( 'optin_hook', $this->_accepted_params, true ) ) {
$hook_name = filter_var( $arguments['optin_hook'], FILTER_SANITIZE_STRING );
}
// Get subscribed hook option
return (string) get_option( $this->_get_option_name( $hook_name ), '' );
}
/**
* Build and sanitize param array
*
* @param $arguments
*
* @return array
*/
private function _prepare_args( $arguments ) {
$params = array();
if ( empty( $arguments ) || ! is_array( $arguments ) ) {
return $params;
}
foreach ( $arguments as $param => $value ) {
$param = (string) $param;
switch ( strtolower( $param ) ) {
case 'zapier_send_ip':
if ( 1 === (int) $value ) {
$params['ip_address'] = tve_dash_get_ip();
}
break;
case 'zapier_tags':
$params['tags'] = ! empty( $value ) ? filter_var_array( explode( ',', $value ), FILTER_SANITIZE_STRING ) : array();
break;
case 'zapier_thriveleads_group':
// Get title by Group ID
$params['thriveleads_group'] = (int) $value > 0 ? get_the_title( (int) $value ) : '';
break;
case 'zapier_thriveleads_type':
$params['thriveleads_type'] = filter_var( $value, FILTER_SANITIZE_STRING );
break;
case 'zapier_thriveleads_name':
$params['thriveleads_name'] = filter_var( $value, FILTER_SANITIZE_STRING );
break;
case 'url':
$params['website'] = filter_var( $value, FILTER_SANITIZE_URL );
break;
case 'number':
$params['number'] = filter_var( $value, FILTER_SANITIZE_NUMBER_INT );
break;
case 'date':
$params['date'] = filter_var( $value, FILTER_SANITIZE_STRING );
break;
default:
if ( ! empty( $value ) ) {
$params[ $param ] = filter_var( $value, FILTER_SANITIZE_STRING );
}
break;
}
}
$params['source_url'] = filter_var( $_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL ); // phpcs:ignore
// Format/Rename all the fields.
$messages = array();
$checkbox_count = 1;
$file_url_count = 1;
foreach ( $arguments as $key => $val ) {
if ( strpos( $key, 'mapping_textarea_' ) === 0 ) {
$messages[] = $arguments[ $key ];
} elseif ( strpos( $key, 'mapping_checkbox_' ) === 0 ) {
$params[ 'checkbox_' . $checkbox_count ] = $arguments[ $key ];
$checkbox_count++;
} elseif ( strpos( $key, 'mapping_file' ) === 0 ) {
$params[ 'file_url_' . $file_url_count ] = $val;
$file_url_count++;
}
}
if ( ! empty( $messages ) ) {
$params['message'] = $messages;
}
// print_r($params); die();
return $params;
}
/**
* @return mixed|Thrive_Dash_Api_Zapier
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Zapier( $this->param( 'api_key' ), $this->param( 'blog_url' ) );
}
/**
* @return array|bool
*/
protected function _get_lists() {
return array();
}
/**
* @return string
*/
public static function get_type() {
return 'integrations';
}
/**
* Used to populate the api value on connecting card
*
* @return string
*/
public function get_api_key() {
$api_key = get_option( 'td_api_key', null );
if ( empty( $api_key ) ) {
$api_key = tve_dash_generate_api_key();
update_option( 'td_api_key', $api_key );
}
return $api_key;
}
/**
* Used to populate the input value on connecting card
*
* @return string
*/
public function get_blog_url() {
return site_url();
}
/**
* @param $hook_name
*
* @return string
*/
protected function _get_option_name( $hook_name ) {
return $this->_hook_prefix . $hook_name . $this->_hook_suffix;
}
/**
* get relevant data from webhook trigger
*
* @param $request WP_REST_Request
*
* @return array
*/
public function get_webhook_data( $request ) {
$contact = $request->get_param( 'email' );
return array( 'email' => empty( $contact ) ? '' : $contact );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '';
}
public function get_automator_add_autoresponder_mapping_fields() {
return array( 'autoresponder' => array( 'tag_input', 'api_fields' ) );
}
}

View File

@@ -0,0 +1,396 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Zoho extends Thrive_Dash_List_Connection_Abstract {
/**
* Api title
*
* @return string
*/
public function get_title() {
return 'Zoho';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'zoho' );
}
/**
* @return mixed|Thrive_Dash_List_Connection_Abstract
* @throws Exception
*/
public function read_credentials() {
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'Could not connect to Zoho using provided credentials.', 'thrive-dash' ) );
}
$this->_save();
$this->saveOauthCredentials();
return $this->success( __( 'Zozo connected successfully', 'thrive-dash' ) );
}
/**
* Save oauth details
*
* @throws Exception
*/
public function saveOauthCredentials() {
/**
* @var $api Thrive_Dash_Api_Zoho
*/
$api = $this->get_api();
$this->_credentials = array_merge( $this->_credentials, $api->getOauth()->getTokens() );
$this->_save();
}
/**
* Remove access code value from credentials since it's only valid once
* Save the connection details
*/
private function _save() {
unset( $this->_credentials['access_code'] );
$this->save();
}
/**
* @return bool|string
*/
public function test_connection() {
return is_array( $this->_get_lists() );
}
/**
* Add subscriber to a list
*
* @param string $list_identifier
* @param array $arguments
*
* @return bool|mixed|string
*/
public function add_subscriber( $list_identifier, $arguments ) {
try {
/**
* @var $api Thrive_Dash_Api_Zoho
*/
$api = $this->get_api();
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
$contact_info = array(
'Contact Email' => $arguments['email'],
'First Name' => $first_name,
'Last Name' => $last_name,
);
if ( ! empty( $arguments['phone'] ) ) {
$contact_info['Phone'] = sanitize_text_field( $arguments['phone'] );
}
$contact_info = array_merge( $contact_info, $this->_generateCustomFields( $arguments ) );
$args = array(
'listkey' => $list_identifier,
'contactinfo' => json_encode( $contact_info ),
);
$api->add_subscriber( $args );
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
* @return mixed|Thrive_Dash_Api_Zoho
* @throws Exception
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Zoho( $this->get_credentials() );
}
/**
* Get lists
*
* @return array|bool
*/
protected function _get_lists() {
$lists = array();
try {
/**
* @var $api Thrive_Dash_Api_Zoho
*/
$api = $this->get_api();
$result = $api->getLists();
if ( isset( $result['status'] ) && 'error' === $result['status'] ) {
return false;
}
if ( ! empty( $result['list_of_details'] ) && is_array( $result['list_of_details'] ) ) {
foreach ( $result['list_of_details'] as $list ) {
$lists[] = array(
'id' => $list['listkey'],
'name' => $list['listname'],
);
}
}
if ( $api->getOauth()->isAccessTokenNew() ) {
$this->saveOauthCredentials();
}
} catch ( Exception $e ) {
return false;
}
return $lists;
}
/**
* @param array $params
* @param bool $force
* @param bool $get_all
*
* @return array|mixed
*/
public function get_api_custom_fields( $params, $force = false, $get_all = false ) {
$cached_data = $this->get_cached_custom_fields();
if ( false === $force && ! empty( $cached_data ) ) {
return $cached_data;
}
$custom_data = array();
try {
/** @var Thrive_Dash_Api_Zoho $api */
$api = $this->get_api();
$custom_fields = $api->getCustomFields();
if ( empty( $custom_fields['response']['fieldnames']['fieldname'] ) ) {
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
foreach ( $custom_fields['response']['fieldnames']['fieldname'] as $field ) {
if ( 'custom' !== $field['TYPE'] ) {
continue;
}
$custom_data[] = $this->_normalizeCustomFields( $field );
}
} catch ( Exception $e ) {
}
$this->_save_custom_fields( $custom_data );
return $custom_data;
}
/**
* Normalize custom field data
*
* @param $field
*
* @return array
*/
protected function _normalizeCustomFields( $field ) {
$field = (array) $field;
return array(
'id' => isset( $field['FIELD_ID'] ) ? (string) $field['FIELD_ID'] : '',
'name' => ! empty( $field['FIELD_DISPLAY_NAME'] ) ? $field['FIELD_DISPLAY_NAME'] : '',
'type' => 'custom',
'label' => ! empty( $field['FIELD_DISPLAY_NAME'] ) ? $field['FIELD_DISPLAY_NAME'] : '',
);
}
/**
* Generate custom fields array
*
* @param array $args
*
* @return array
*/
private function _generateCustomFields( $args ) {
$custom_fields = $this->get_api_custom_fields( array() );
$ids = $this->buildMappedCustomFields( $args );
$result = array();
foreach ( $ids as $key => $id ) {
$field = array_filter(
$custom_fields,
function ( $item ) use ( $id ) {
return $item['id'] === $id['value'];
}
);
$field = array_values( $field );
if ( ! isset( $field[0] ) ) {
continue;
}
$name = strpos( $id['type'], 'mapping_' ) !== false ? $id['type'] . '_' . $key : $key;
$cf_form_name = str_replace( '[]', '', $name );
$result[ $field[0]['name'] ] = $this->process_field( $args[ $cf_form_name ] );
}
return $result;
}
/**
* Build mapped custom fields array based on form params
*
* @param $args
*
* @return array
*/
public function buildMappedCustomFields( $args ) {
$mapped_data = array();
// Should be always base_64 encoded of a serialized array
if ( empty( $args['tve_mapping'] ) || ! tve_dash_is_bas64_encoded( $args['tve_mapping'] ) || ! is_serialized( base64_decode( $args['tve_mapping'] ) ) ) {
return $mapped_data;
}
$form_data = thrive_safe_unserialize( base64_decode( $args['tve_mapping'] ) );
$mapped_fields = $this->get_mapped_field_ids();
foreach ( $mapped_fields as $mapped_field_name ) {
// Extract an array with all custom fields (siblings) names from form data
// {ex: [mapping_url_0, .. mapping_url_n] / [mapping_text_0, .. mapping_text_n]}
$cf_form_fields = preg_grep( "#^{$mapped_field_name}#i", array_keys( $form_data ) );
if ( ! empty( $cf_form_fields ) && is_array( $cf_form_fields ) ) {
foreach ( $cf_form_fields as $cf_form_name ) {
if ( empty( $form_data[ $cf_form_name ][ $this->_key ] ) ) {
continue;
}
$field_id = str_replace( $mapped_field_name . '_', '', $cf_form_name );
$mapped_data[ $field_id ] = array(
'type' => $mapped_field_name,
'value' => $form_data[ $cf_form_name ][ $this->_key ],
);
}
}
}
return $mapped_data;
}
/**
* @param $email
* @param array $custom_fields
* @param array $extra
*
* @return int
*/
public function add_custom_fields( $email, $custom_fields = array(), $extra = array() ) {
try {
/** @var Thrive_Dash_Api_Zoho $api */
$api = $this->get_api();
$list_id = ! empty( $extra['list_identifier'] ) ? $extra['list_identifier'] : null;
list( $first_name, $last_name ) = $this->get_name_parts( ! empty( $extra['name'] ) ? $extra['name'] : '' );
$cf = array(
'Contact Email' => $email,
'First Name' => $first_name,
'Last Name' => $last_name,
);
$args = array(
'listkey' => $list_id,
'contactinfo' => json_encode( array_merge( $cf, $this->prepare_custom_fields_for_api( $custom_fields ) ) ),
);
$api->add_subscriber( $args );
} catch ( Exception $e ) {
return false;
}
}
/**
* Get available custom fields for this api connection
*
* @param null $list_id
*
* @return array
*/
public function get_available_custom_fields( $list_id = null ) {
return $this->get_api_custom_fields( null, true );
}
/**
* Prepare custom fields for api call
*
* @param array $custom_fields
* @param null $list_identifier
*
* @return array
*/
public function prepare_custom_fields_for_api( $custom_fields = array(), $list_identifier = null ) {
$prepared_fields = array();
$api_fields = $this->get_api_custom_fields( null, true );
foreach ( $api_fields as $field ) {
foreach ( $custom_fields as $key => $custom_field ) {
if ( (string) $field['id'] === (string) $key ) {
$prepared_fields[ $field['name'] ] = $custom_field;
}
}
if ( empty( $custom_fields ) ) {
break;
}
}
return $prepared_fields;
}
}

View File

@@ -0,0 +1,168 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_iContact extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'iContact';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'iContact' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$apiId = ! empty( $_POST['connection']['appId'] ) ? sanitize_text_field( $_POST['connection']['appId'] ) : '';
$apiUsername = ! empty( $_POST['connection']['apiUsername'] ) ? sanitize_text_field( $_POST['connection']['apiUsername'] ) : '';
$apiPassword = ! empty( $_POST['connection']['apiPassword'] ) ? sanitize_text_field( $_POST['connection']['apiPassword'] ) : '';
if ( empty( $apiId ) || empty( $apiUsername ) || empty( $apiPassword ) ) {
return $this->error( __( 'You must provide a valid iContact AppID/Username/Password', 'thrive-dash' ) );
}
$this->set_credentials( $this->post( 'connection' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to iContact: %s', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
return $this->success( __( 'iContact connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
$lists = $this->_get_lists();
if ( $lists === false ) {
return $this->_error;
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_iContact
*/
protected function get_api_instance() {
return Thrive_Dash_Api_iContact::getInstance()->setConfig( $this->get_credentials() );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
$api = $this->get_api();
$lists = array();
try {
$data = $api->getLists();
if ( count( $data ) ) {
foreach ( $data as $item ) {
$lists[] = array(
'id' => $item->listId,
'name' => $item->name,
);
}
}
} catch ( Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
return $lists;
}
/**
* add a contact to a list
*
* @param array $list_identifier
* @param array $arguments
*
* @return mixed true -> success; string -> error;
*/
public function add_subscriber( $list_identifier, $arguments ) {
$sEmail = $arguments['email'];
$sStatus = 'normal';
$sPrefix = null;
$sPhone = null;
list( $sFirstName, $sLastName ) = $this->get_name_parts( $arguments['name'] );
$sSuffix = null;
$sStreet = null;
$sStreet2 = null;
$sCity = null;
$sState = null;
$sPostalCode = null;
$sPhone = empty( $arguments['phone'] ) ? '' : $arguments['phone'];
try {
/** @var Thrive_Dash_Api_iContact $api */
$api = $this->get_api();
$contact = $api->addContact( $sEmail, $sStatus, $sPrefix, $sFirstName, $sLastName, $sSuffix, $sStreet, $sStreet2, $sCity, $sState, $sPostalCode, $sPhone );
if ( empty( $contact ) || ! is_object( $contact ) || empty( $contact->contactId ) ) {
throw new Thrive_Dash_Api_iContact_Exception( 'Unable to save contact' );
}
$api->subscribeContactToList( $contact->contactId, $list_identifier );
return true;
} catch ( Thrive_Dash_Api_iContact_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
}

View File

@@ -0,0 +1,337 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_GoToWebinar extends Thrive_Dash_List_Connection_Abstract {
/**
* @var string
*/
private $_consumer_key = 'Mtm8i2IdR2mOkAY3uVoW5f4TdGaBxpkY';
/**
* @var string
*/
private $_consumer_secret = 'qjr8KW9Ga6G2AJjE';
/**
* Return the connection type
*
* @return string
*/
public static function get_type() {
return 'webinar';
}
/**
* Check if the expires_in field is in the past
* GoToWebinar auth access tokens expire after about one year
*
* @return bool
*/
public function isExpired() {
if ( ! $this->is_connected() ) {
return false;
}
$expires_in = $this->param( 'expires_in' );
return time() > $expires_in;
}
/**
* get the expiry date and time user-friendly formatted
*/
public function getExpiryDate() {
return date( 'l, F j, Y H:i:s', $this->param( 'expires_in' ) );
}
/**
* API connection title
*
* @return string
*/
public function get_title() {
return 'GoToWebinar';
}
/**
* @return string
*/
public function get_list_sub_title() {
return __( 'Choose from the following upcoming webinars', 'thrive-dash' );
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'gotowebinar' );
}
/**
* should handle: read data from post / get, test connection and save the details
* on error, it should register an error message (and redirect?)
*
* @return mixed|Thrive_Dash_List_Connection_Abstract
*/
public function read_credentials() {
if ( empty( $_POST['gtw_email'] ) || empty( $_POST['gtw_password'] ) ) {
return $this->error( __( 'Email and password are required', 'thrive-dash' ) );
}
$email = $this->post( 'gtw_email' );
$password = $this->post( 'gtw_password' );
$v = array(
'version' => ! empty( $_POST['connection']['version'] ) ? sanitize_text_field( $_POST['connection']['version'] ) : '',
'versioning' => ! empty( $_POST['connection']['versioning'] ) ? sanitize_text_field( $_POST['connection']['versioning'] ) : '',
'username' => $email,
'password' => $password,
);
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
try {
// Login and setters
$api->directLogin( $email, $password, $v );
$credentials = $api->get_credentials();
// Add inbox notification for v2 connection
if ( TD_Inbox::instance()->api_is_connected( $this->get_key() ) && ! empty( $credentials['version'] ) && 2 === (int) $credentials['version'] && ! empty( $credentials['versioning'] ) ) {
$this->add_notification( 'added_v2' );
// Remove notification from api connection
TVE_Dash_InboxManager::instance()->remove_api_connection( $this->get_key() );
}
// Set credentials
$this->set_credentials( $credentials );
// Save the connection details
$this->save();
return $this->success( __( 'GoToWebinar connected successfully', 'thrive-dash' ) );
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
return $this->error( sprintf( __( 'Could not connect to GoToWebinar using the provided data (%s)', 'thrive-dash' ), $e->getMessage() ) );
}
}
/**
* @param string $type
*
* @return bool
*/
public function add_notification( $type = '' ) {
if ( empty( $type ) ) {
return false;
}
$message = array();
$inbox_manager = TVE_Dash_InboxManager::instance();
switch ( $type ) {
case 'added_v2':
$message = array(
'title' => __( 'Your GoToWebinar Connection has been Updated!', 'thrive-dash' ),
'info' => __(
'Good job - youve just upgraded your GoToWebinar connection to 2.0. <br /><br />
You dont need to make any changes to your existing forms - they will carry on working as before. <br /><br />
However, we highly recommend that you sign up through one of your webinar forms to make sure that everything is working as expected.<br /><br />
If you experience any issues, let our <a href="https://thrivethemes.com/forums/forum/general-discussion/" target="_blank">support team</a> know and well get to the bottom of this for you. <br /><br />
From your team at Thrive Themes ',
'thrive-dash'
),
'type' => TD_Inbox_Message::TYPE_INBOX,
);
break;
}
if ( empty( $message ) ) {
return false;
}
try {
$message_obj = new TD_Inbox_Message( $message );
$inbox_manager->prepend( $message_obj );
$inbox_manager->push_notifications();
} catch ( Exception $e ) {
}
}
/**
* @return mixed|string
*/
public function getUsername() {
$credentials = (array) $this->get_credentials();
if ( ! empty( $credentials['username'] ) ) {
return $credentials['username'];
}
return '';
}
/**
* @return mixed|string
*/
public function getPassword() {
$credentials = (array) $this->get_credentials();
if ( ! empty( $credentials['password'] ) ) {
return $credentials['password'];
}
return '';
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string
*/
public function test_connection() {
try {
/** @var Thrive_Dash_Api_GoToWebinar * */
$api = $this->get_api();
$webinars = $api->getUpcomingWebinars();
if ( ! empty( $webinars ) ) {
return true;
}
return false;
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
return $e->getMessage();
}
}
/**
* Add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|mixed|string
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
$phone = isset( $arguments['phone'] ) ? $arguments['phone'] : null;
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
if ( empty( $last_name ) ) {
$last_name = $first_name;
}
if ( empty( $first_name ) && empty( $last_name ) ) {
list( $first_name, $last_name ) = $this->get_name_from_email( $arguments['email'] );
}
try {
$api->registerToWebinar( $list_identifier, $first_name, $last_name, $arguments['email'], $phone );
return true;
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
return $e->getMessage();
} catch ( Exception $e ) {
return $e->getMessage();
}
}
/**
*
* @return int the number of days in which this token will expire
*/
public function expiresIn() {
$expires_in = $this->param( 'expires_in' );
$diff = (int) ( ( $expires_in - time() ) / ( 3600 * 24 ) );
return $diff;
}
/**
* No need for v2
*/
public function get_warnings() {
return array();
}
/**
* @return mixed|Thrive_Dash_Api_GoToWebinar
* @throws Thrive_Dash_Api_GoToWebinar_Exception
*/
protected function get_api_instance() {
$access_token = null;
$organizer_key = null;
$settings = array();
if ( $this->is_connected() && ! $this->isExpired() ) {
$access_token = $this->param( 'access_token' );
$organizer_key = $this->param( 'organizer_key' );
$settings = array(
'version' => $this->param( 'version' ),
'versioning' => $this->param( 'versioning' ), // used on class instances from [/v1/, /v2/ etc] namespace folder
'expires_in' => $this->param( 'expires_in' ),
'auth_type' => $this->param( 'auth_type' ),
'refresh_token' => $this->param( 'refresh_token' ),
'username' => $this->param( 'username' ),
'password' => $this->param( 'password' ),
);
}
return new Thrive_Dash_Api_GoToWebinar( base64_encode( $this->_consumer_key . ':' . $this->_consumer_secret ), $access_token, $organizer_key, $settings );
}
/**
* Get all webinars from this API service
*
* @return array|bool
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_GoToWebinar $api */
$api = $this->get_api();
$lists = array();
try {
$all = $api->getUpcomingWebinars();
foreach ( $all as $item ) {
$lists [] = array(
'id' => $item['webinarKey'],
'name' => $item['subject'],
);
}
return $lists;
} catch ( Thrive_Dash_Api_GoToWebinar_Exception $e ) {
$this->_error = $e->getMessage();
return false;
}
}
}

View File

@@ -0,0 +1,241 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
/**
* Class Thrive_Dash_List_Connection_SendGrid
* Version 2 of the SendGrid wrapper
* - instead of "contactdb" endpoint it uses "marketing"
*/
class Thrive_Dash_List_Connection_SendGrid extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string
*/
public function get_title() {
return 'SendGrid';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
if ( $related_api->is_connected() ) {
$this->set_param( 'new_connection', 1 );
}
$this->output_controls_html( 'sendgrid' );
}
/**
* just save the key in the database
*
* @return mixed|void
*/
public function read_credentials() {
$key = ! empty( $_POST['connection']['key'] ) ? sanitize_text_field( $_POST['connection']['key'] ) : '';
if ( empty( $key ) ) {
return $this->error( __( 'You must provide a valid SendGrid key', 'thrive-dash' ) );
}
$this->set_credentials( map_deep( $_POST['connection'], 'sanitize_text_field' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( sprintf( __( 'Could not connect to SendGrid using the provided key (<strong>%s</strong>)', 'thrive-dash' ), $result ) );
}
/**
* finally, save the connection details
*/
$this->save();
/** @var Thrive_Dash_List_Connection_SendGridEmail $related_api */
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
if ( isset( $_POST['connection']['new_connection'] ) && intval( $_POST['connection']['new_connection'] ) === 1 ) {
/**
* Try to connect to the email service too
*/
$r_result = true;
if ( ! $related_api->is_connected() ) {
$r_result = $related_api->read_credentials();
}
if ( $r_result !== true ) {
$this->disconnect();
return $this->error( $r_result );
}
} else {
/**
* let's make sure that the api was not edited and disconnect it
*/
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
}
return $this->success( __( 'SendGrid connected successfully', 'thrive-dash' ) );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_SendGrid $sg */
$sg = $this->get_api();
try {
$sg->client->marketing()->lists()->get();
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* instantiate the API code required for this connection
*
* @return Thrive_Dash_Api_SendGrid
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_SendGrid( $this->param( 'key' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool
*/
protected function _get_lists() {
/** @var Thrive_Dash_Api_SendGrid $api */
$api = $this->get_api();
$response = $api->client->marketing()->lists()->get();
if ( $response->statusCode() != 200 ) {
$body = $response->body();
$this->_error = ucwords( $body->errors['0']->message );
return false;
}
$body = $response->body();
$lists = array();
foreach ( $body->result as $item ) {
$lists [] = array(
'id' => $item->id,
'name' => $item->name,
);
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return bool|string true for success or string error message for failure
*/
public function add_subscriber( $list_identifier, $arguments ) {
$contact = new stdClass();
list( $first_name, $last_name ) = $this->get_name_parts( $arguments['name'] );
/** @var Thrive_Dash_Api_SendGrid $api */
$api = $this->get_api();
$contact->email = $arguments['email'];
if ( ! empty( $first_name ) ) {
$contact->first_name = $first_name;
}
if ( ! empty( $last_name ) ) {
$contact->last_name = $last_name;
}
if ( ! empty( $arguments['phone'] ) ) {
$contact->phone_number = $arguments['phone'];
}
$contact->list_ids = array( $list_identifier );
try {
$args = array(
'list_ids' => array( $list_identifier ),
'contacts' => array( $contact ),
);
$api->client->marketing()->contacts()->put( $args );
} catch ( Thrive_Dash_Api_SendGrid_Exception $e ) {
return $e->getMessage();
}
return true;
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '{$email}';
}
/**
* disconnect (remove) this API connection
*/
public function disconnect() {
$this->set_credentials( array() );
Thrive_Dash_List_Manager::save( $this );
/**
* disconnect the email service too
*/
$related_api = Thrive_Dash_List_Manager::connection_instance( 'sendgridemail' );
$related_api->set_credentials( array() );
Thrive_Dash_List_Manager::save( $related_api );
return $this;
}
}

View File

@@ -0,0 +1,166 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
class Thrive_Dash_List_Connection_Sendy extends Thrive_Dash_List_Connection_Abstract {
/**
* Return the connection type
*
* @return String
*/
public static function get_type() {
return 'autoresponder';
}
/**
* @return string the API connection title
*/
public function get_title() {
return 'Sendy';
}
/**
* output the setup form html
*
* @return void
*/
public function output_setup_form() {
$this->output_controls_html( 'sendy' );
}
/**
* should handle: read data from post / get, test connection and save the details
*
* on error, it should register an error message (and redirect?)
*
* @return mixed
*/
public function read_credentials() {
$url = ! empty( $_POST['connection']['url'] ) ? esc_url_raw( $_POST['connection']['url'] ) : '';
$lists = ! empty( $_POST['connection']['lists'] ) ? map_deep( $_POST['connection']['lists'], 'sanitize_text_field' ) : array();
$lists = array_map( 'trim', $lists );
$lists = array_filter( $lists );
if ( empty( $url ) || empty( $lists ) ) {
return $this->error( 'Invalid URL or Lists IDs' );
}
$_POST['connection']['lists'] = $lists;
$this->set_credentials( map_deep( $_POST['connection'], 'sanitize_text_field' ) );
$result = $this->test_connection();
if ( $result !== true ) {
return $this->error( __( 'Could not connect to Sendy', 'thrive-dash' ) );
}
$this->save();
return $this->success( 'Sendy connected successfully' );
}
/**
* test if a connection can be made to the service using the stored credentials
*
* @return bool|string true for success or error message for failure
*/
public function test_connection() {
/** @var Thrive_Dash_Api_Sendy $api */
$api = $this->get_api();
return $api->testUrl();
}
/**
* instantiate the API code required for this connection
*
* @return mixed
*/
protected function get_api_instance() {
return new Thrive_Dash_Api_Sendy( $this->param( 'url' ) );
}
/**
* get all Subscriber Lists from this API service
*
* @return array|bool for error
*/
protected function _get_lists() {
$lists = array();
foreach ( $this->param( 'lists' ) as $id ) {
$lists[] = array(
'id' => $id,
'name' => "#" . $id,
);
}
return $lists;
}
/**
* add a contact to a list
*
* @param mixed $list_identifier
* @param array $arguments
*
* @return mixed
*/
public function add_subscriber( $list_identifier, $arguments ) {
/** @var Thrive_Dash_Api_Sendy $api */
$api = new Thrive_Dash_Api_Sendy( $this->param( 'url' ) );
try {
$api->subscribe(
$arguments['email'],
$list_identifier,
$this->param( 'api_key' ),
$arguments['name'],
$phone = isset( $arguments['phone'] ) ? $arguments['phone'] : null
);
return true;
} catch ( Exception $e ) {
return $e->getMessage();
}
return false;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function get_extra_settings( $params = array() ) {
return $params;
}
/**
* output any (possible) extra editor settings for this API
*
* @param array $params allow various different calls to this method
*/
public function render_extra_editor_settings( $params = array() ) {
$this->output_controls_html( 'sendy/note', $params );
}
/**
* Return the connection email merge tag
*
* @return String
*/
public static function get_email_merge_tag() {
return '[Email]';
}
}

View File

@@ -0,0 +1,493 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden
}
class Thrive_Dash_List_Manager {
/**
* @var bool
*/
public static $ADMIN_HAS_ERROR = false;
/**
* @var string[]
*/
public static $API_TYPES = [
'autoresponder' => 'Email Marketing',
'webinar' => 'Webinars',
'other' => 'Other',
'recaptcha' => 'Recaptcha',
'social' => 'Social',
'sellings' => 'Sales',
'integrations' => 'Integration Services',
'email' => 'Email Delivery',
'storage' => 'File Storage',
'collaboration' => 'Collaboration',
];
/**
* @var string[]
*/
public static $AVAILABLE = [
'email' => 'Thrive_Dash_List_Connection_Email',
'activecampaign' => 'Thrive_Dash_List_Connection_ActiveCampaign',
'aweber' => 'Thrive_Dash_List_Connection_AWeber',
'campaignmonitor' => 'Thrive_Dash_List_Connection_CampaignMonitor',
'constantcontact_v3' => 'Thrive_Dash_List_Connection_ConstantContactV3',
'convertkit' => 'Thrive_Dash_List_Connection_ConvertKit',
'drip' => 'Thrive_Dash_List_Connection_Drip',
'facebook' => 'Thrive_Dash_List_Connection_Facebook',
'fluentcrm' => 'Thrive_Dash_List_Connection_FluentCRM',
'get-response' => 'Thrive_Dash_List_Connection_GetResponse',
'google' => 'Thrive_Dash_List_Connection_Google',
'gotowebinar' => 'Thrive_Dash_List_Connection_GoToWebinar',
'hubspot' => 'Thrive_Dash_List_Connection_HubSpot',
'icontact' => 'Thrive_Dash_List_Connection_iContact',
'infusionsoft' => 'Thrive_Dash_List_Connection_Infusionsoft',
'klicktipp' => 'Thrive_Dash_List_Connection_KlickTipp',
'madmimi' => 'Thrive_Dash_List_Connection_MadMimi',
'mailchimp' => 'Thrive_Dash_List_Connection_Mailchimp',
'mailerlite' => 'Thrive_Dash_List_Connection_MailerLite',
'mailpoet' => 'Thrive_Dash_List_Connection_MailPoet',
'mailrelay' => 'Thrive_Dash_List_Connection_MailRelay',
'ontraport' => 'Thrive_Dash_List_Connection_Ontraport',
'recaptcha' => 'Thrive_Dash_List_Connection_ReCaptcha',
'turnstile' => 'Thrive_Dash_List_Connection_Turnstile',
'sendgrid' => 'Thrive_Dash_List_Connection_SendGrid',
'sendinblue' => 'Thrive_Dash_List_Connection_SendinblueV3',
'sendy' => 'Thrive_Dash_List_Connection_Sendy',
'sg-autorepondeur' => 'Thrive_Dash_List_Connection_SGAutorepondeur',
'twitter' => 'Thrive_Dash_List_Connection_Twitter',
'webinarjamstudio' => 'Thrive_Dash_List_Connection_WebinarJamStudio',
'wordpress' => 'Thrive_Dash_List_Connection_Wordpress',
'mailster' => 'Thrive_Dash_List_Connection_Mailster',
'sendfox' => 'Thrive_Dash_List_Connection_Sendfox',
'zoho' => 'Thrive_Dash_List_Connection_Zoho',
/* notification manger - these are now included in the dashboard - services for email notifications */
'awsses' => 'Thrive_Dash_List_Connection_Awsses',
'campaignmonitoremail' => 'Thrive_Dash_List_Connection_CampaignMonitorEmail',
'mailgun' => 'Thrive_Dash_List_Connection_Mailgun',
'sendlayer' => 'Thrive_Dash_List_Connection_SendLayer',
'mandrill' => 'Thrive_Dash_List_Connection_Mandrill',
'mailrelayemail' => 'Thrive_Dash_List_Connection_MailRelayEmail',
'postmark' => 'Thrive_Dash_List_Connection_Postmark',
'sendgridemail' => 'Thrive_Dash_List_Connection_SendGridEmail',
'sendinblueemail' => 'Thrive_Dash_List_Connection_SendinblueEmailV3',
'sparkpost' => 'Thrive_Dash_List_Connection_SparkPost',
'sendowl' => 'Thrive_Dash_List_Connection_SendOwl',
'sendlane' => 'Thrive_Dash_List_Connection_Sendlane',
'everwebinar' => 'Thrive_Dash_List_Connection_EverWebinar',
/* integrations services */
'zapier' => 'Thrive_Dash_List_Connection_Zapier',
/* File Storage */
'google_drive' => 'Thrive_Dash_List_Connection_FileUpload_GoogleDrive',
'dropbox' => 'Thrive_Dash_List_Connection_FileUpload_Dropbox',
/* Collaboration */
'slack' => 'Thrive_Dash_List_Connection_Slack',
'facebookpixel' => 'Thrive_Dash_List_Connection_FacebookPixel',
];
private static $_available = [];
public static $api_instances = [];
public static $all_credentials = [];
/**
* If the snake_case version of the function does not exist, attempt to call the camelCase version.
* Can be deleted after we switch everything to snake_case.
*
* @param $method_name
* @param $arguments
*
* @return mixed
*/
public static function __callStatic( $method_name, $arguments ) {
$camel_case_method_name = tve_dash_to_camel_case( $method_name );
/* in order to fit the old name of 'getAvailableAPIs' and 'getAvailableApisByType', this extra replace has to be done - ugly, but temporary */
$camel_case_method_name = str_replace( 'getAvailableApis', 'getAvailableAPIs', $camel_case_method_name );
return method_exists( __CLASS__, $camel_case_method_name ) ? call_user_func_array( [
static::class,
$camel_case_method_name,
], $arguments ) : null;
}
/**
* @var array
*/
public static $default_api_filter = [
'include_types' => [], /* by default everything is included */
'exclude_types' => [], /* only taken into account if 'include' is empty ( they are mutually exclusive ) */
'only_names' => false,
];
/**
* This has to stay because we changed the parameters of the function and this is called from the other plugins ( as long as they're not updated ).
* This is also called from TTW, so it can't be deleted for now.
*
* @param bool $only_connected
* @param array $exclude_types
* @param bool $only_names
*
* @return array
* @deprecated
*/
public static function getAvailableAPIs( $only_connected = false, $exclude_types = [], $only_names = false ) {
/* map the old parameters to the new filter array */
$api_filter = [
'exclude_types' => $exclude_types,
'only_names' => $only_names,
];
return static::get_available_apis( $only_connected, $api_filter );
}
/**
* @param bool $only_connected
* @param array $api_filter
*
* @return array
*/
public static function get_available_apis( $only_connected = false, $api_filter = [] ) {
$lists = [];
$api_filter = array_merge( static::$default_api_filter, $api_filter );
foreach ( static::available() as $key => $api ) {
if ( ! class_exists( $api ) ) {
continue;
}
/** @var Thrive_Dash_List_Connection_Abstract $instance */
$instance = static::connection_instance( $key );
if (
$instance &&
static::should_include_api( $instance, $api_filter ) &&
( ! $only_connected || static::is_api_connected( $key, $instance ) )
) {
$lists[ $key ] = $api_filter['only_names'] ? $instance->get_title() : $instance;
}
}
return apply_filters( 'tvd_api_available_connections', $lists, $only_connected, $api_filter );
}
/**
* @param string $key
* @param Thrive_Dash_List_Connection_Abstract $instance
*
* @return bool
*/
public static function is_api_connected( $key, $instance ) {
return ! empty( static::credentials( $key ) ) && $instance->is_connected();
}
/**
* @param Thrive_Dash_List_Connection_Abstract $instance
* @param array $api_filter
*
* @return bool
*/
public static function should_include_api( $instance, $api_filter ) {
$type = $instance::get_type();
/* 'include_types' and 'exclude_types' are mutually exclusive, so if we want to include something, we no longer check exclusions */
if ( empty( $api_filter['include_types'] ) ) {
if ( is_array( $api_filter['exclude_types'] ) ) {
$should_include_api = ! in_array( $type, $api_filter['exclude_types'], true );
} else {
$should_include_api = ( $type !== $api_filter['exclude_types'] );
}
} else {
if ( is_array( $api_filter['include_types'] ) ) {
$should_include_api = in_array( $type, $api_filter['include_types'], true );
} else {
$should_include_api = ( $type === $api_filter['include_types'] );
}
}
return $should_include_api;
}
/**
* @param bool $get_localized_data
*
* @return array
*/
public static function get_third_party_autoresponders( $get_localized_data = true ) {
return apply_filters( 'tvd_third_party_autoresponders', [], $get_localized_data );
}
/**
* Build custom fields for all available connections
* Can be renamed to get_available_custom_fields in 2-3 releases
*
* @return array
*/
public static function getAvailableCustomFields() {
$custom_fields = [];
$apis = static::get_available_apis( true, [ 'exclude_types' => [ 'email', 'social' ] ] );
/**
* @var string $api_name
* @var Thrive_Dash_List_Connection_Abstract $api
*/
foreach ( $apis as $api_name => $api ) {
$custom_fields[ $api_name ] = $api->get_api_custom_fields( [], false, true );
}
return $custom_fields;
}
/**
* Get the hardcoded mapper from the first connected API
* Can be renamed to get_custom_fields_mapper in 2-3 releases
*
* @return array
*/
public static function getCustomFieldsMapper( $default = false ) {
$mapper = [];
$apis = static::get_available_apis( true, [ 'exclude_types' => [ 'email', 'social', 'collaboration' ] ] );
/**
* @var Thrive_Dash_List_Connection_Abstract $api
*/
foreach ( $apis as $api ) {
if ( $default ) {
if ( method_exists( $api, 'get_default_fields_mapper' ) ) {
$mapper[ $api->get_key() ] = $api->get_default_fields_mapper();
}
} else if ( method_exists( $api, 'get_custom_fields_mapping' ) ) {
$mapper[ $api->get_key() ] = $api->get_custom_fields_mapping();
}
}
return $mapper;
}
/**
* DEPRECATED
* get a list of all available APIs by type
* todo: this is deprecated ( moved to get_available_apis() ), get rid of it after 2-3 releases
*
* @param bool $onlyConnected if true, it will return only APIs that are already connected
* @param string|array $include_types exclude connection by their type
*
* @return array Thrive_Dash_List_Connection_Abstract[]
* @deprecated
*/
public static function getAvailableAPIsByType( $onlyConnected = false, $include_types = [] ) {
if ( ! is_array( $include_types ) ) {
$include_types = array( $include_types );
}
$lists = array();
$credentials = static::credentials();
foreach ( static::available() as $key => $api ) {
/** @var Thrive_Dash_List_Connection_Abstract $instance */
$instance = static::connectionInstance( $key, isset( $credentials[ $key ] ) ? $credentials[ $key ] : array() );
if ( ( $onlyConnected && empty( $credentials[ $key ] ) ) || ! in_array( $instance::get_type(), $include_types, true ) ) {
continue;
}
if ( $onlyConnected && ! $instance->is_connected() ) {
continue;
}
$lists[ $key ] = $instance;
}
return $lists;
}
/**
* Fetch the connection credentials for a specific connection (or fetch them all)
*
* @param string $key if empty, all the credentials will be returned
*
* @return array
*/
public static function credentials( $key = '' ) {
if ( empty( static::$all_credentials ) ) {
$all_credentials = get_option( 'thrive_mail_list_api', [] );
/* make sure that the email connection is always available */
if ( empty( $all_credentials['email'] ) ) {
$all_credentials['email'] = [ 'connected' => true ];
}
/* make sure the WP API Connection is always available */
if ( empty( $all_credentials['wordpress'] ) ) {
$all_credentials['wordpress'] = [ 'connected' => true ];
}
static::$all_credentials = apply_filters( 'tve_filter_all_api_credentials', $all_credentials );
}
if ( empty( $key ) ) {
$credentials = static::$all_credentials;
} else if ( ! isset( static::$all_credentials[ $key ] ) ) {
$credentials = [];
} else {
$credentials = static::$all_credentials[ $key ];
}
return $credentials;
}
/**
* Save the credentials for an instance
*
* @param Thrive_Dash_List_Connection_Abstract $instance
*/
public static function save( $instance ) {
//put the credentials in this global array
//so that for the next save call this array contains the previous credentials
static::$all_credentials[ $instance->get_key() ] = $instance->getCredentials();
/**
* Invalidate cache for Email Connection
* - so that Email connection get to know the new email provider
*/
if ( $instance::get_type() === 'email' ) {
delete_transient( 'tve_api_data_email' );
}
update_option( 'thrive_mail_list_api', static::$all_credentials );
}
/**
* Used in TTW, do not delete.
*
* @param string $key
*
* @return Thrive_Dash_List_Connection_Abstract
* @deprecated
*/
public static function connectionInstance( $key ) {
return static::connection_instance( $key );
}
/**
* Factory method for a connection instance
*
* @param string $key
*
* @return Thrive_Dash_List_Connection_Abstract
*/
public static function connection_instance( $key ) {
$apis = array_merge( static::available(), static::get_third_party_autoresponders( false ) );
if ( ! isset( $apis[ $key ] ) ) {
return null;
}
if ( is_subclass_of( $apis[ $key ], 'Thrive_Dash_List_Connection_Abstract', true ) ) {
if ( empty( static::$api_instances[ $key ] ) ) {
/** @var Thrive_Dash_List_Connection_Abstract $instance */
$instance = new $apis[ $key ]( $key );
$instance->set_credentials( static::credentials( $key ) );
static::$api_instances[ $key ] = $instance;
}
$instance = static::$api_instances[ $key ];
} else {
/* if the API class does not extend abstract, we assume that it's a third party API. In this case, the instance should be found in the list */
$instance = $apis[ $key ];
}
return $instance;
}
/**
* saves a message to be displayed on the next request
*
* @param string $type
* @param string $message
*/
public static function message( $type, $message ) {
if ( $type === 'error' ) {
static::$ADMIN_HAS_ERROR = true;
}
$messages = get_option( 'tve_api_admin_notices', [] );
$messages[ $type ] = $message;
update_option( 'tve_api_admin_notices', $messages );
}
/**
* reads out all messages (success / error from the options table)
*/
public static function flash_messages() {
$GLOBALS['thrive_list_api_message'] = get_option( 'tve_api_admin_notices', [] );
delete_option( 'tve_api_admin_notices' );
}
/**
* transform the $string into an array of connections
*
* @param string $string
*
* @return array
*/
public static function decode_connections_string( $string ) {
if ( empty( $string ) ) {
return [];
}
$string = @base64_decode( $string );
if ( empty( $string ) ) {
return [];
}
$data = thrive_safe_unserialize( $string );
return empty( $data ) || ! is_array( $data ) ? [] : tve_sanitize_data_recursive( $data, 'sanitize_textarea_field' );
}
/**
* @param array $APIs
*
* @return false|string
*/
public static function to_json( $APIs = [] ) {
if ( ! is_array( $APIs ) || empty( $APIs ) ) {
return json_encode( [] );
}
$list = [];
foreach ( $APIs as $key => $instance ) {
/** @var $instance Thrive_Dash_List_Connection_Abstract */
if ( ! $instance instanceof Thrive_Dash_List_Connection_Abstract ) {
continue;
}
$list[] = $instance->prepare_json();
}
return json_encode( $list );
}
/**
* @return array|mixed|void
*/
public static function available() {
if ( ! self::$_available ) {
self::$_available = apply_filters( 'tve_filter_available_connection', self::$AVAILABLE );
}
return self::$_available;
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,429 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
/**
* Contains:
* - autoloaders for the main library files
* - wrappers over WordPress wp_remote_* functions
* - helper functions
*/
/**
* Get the timout, in seconds that should be set for an external api request
*
* @param string $request_method current request method
*
* @return int
*/
function tve_dash_request_timeout( $request_method = 'get' ) {
/* SUPP-14901 - we couldn't find the root cause of the long download time, so we increased the timeout */
$default_timeout = defined('THRIVE_REQ_TIMEOUT') ? THRIVE_REQ_TIMEOUT : 30;
/* SUPP-988, SUPP-3317, SUPP-8988 increased timeout to 30, it seems some hosts have some issues, not being able to resolve API URLs in 5 seconds */
/**
* Filter the default request timeout used throughout Thrive products.
* 30 seconds is a "hard-earned" value, it started from 10, and got increased each time a new server could not download something in that time.
* The filter offers a workaround for 3rd party code to increase this timeout if they have further issues.
* Ideally we could provide them with a mini-plugin that does this
*
* @param int $timeout timeout in seconds
* @param string $request_method allows finer control
*
* @return int
*
*/
return apply_filters( 'thrive_request_timeout', $default_timeout, $request_method );
}
/**
* Wrapper over the WP wp_remote_get function
*
* @param string $url Site URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
*
* @return WP_Error|array The response or WP_Error on failure.
* @see wp_remote_get
*
*/
function tve_dash_api_remote_get( $url, $args = array() ) {
$args['sslverify'] = false;
/* SUPP-988 increased timeout to 15, it seems some hosts have some issues, not being able to resolve API URLs in 5 seconds */
$args['timeout'] = tve_dash_request_timeout( 'get' );
/* makes sure this is NEVER used to download files */
unset( $args['stream'], $args['filename'] );
return wp_remote_get( $url, $args );
}
/**
* SUPP-1146 strange issue on user's host - ssl requests timed out - seems this was the way to fix it
* this is currently not used, but I'm leaving it here so that we have it for future references
*
* this is how it was used:
*
* add_action('http_api_curl', 'tve_dash_api_curl_ssl_version');
*
* @param resource $handle
*/
function tve_dash_api_curl_ssl_version( &$handle ) {
curl_setopt( $handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT );
}
/**
* Wrapper over the WP wp_remote_post function - all API POST requests pass through this function
*
* @param string $url Site URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
*
* @return WP_Error|array The response or WP_Error on failure.
* @see wp_remote_post
*
*/
function tve_dash_api_remote_post( $url, $args = array() ) {
$args['sslverify'] = false;
$args['timeout'] = tve_dash_request_timeout( 'post' );
/* makes sure this is NEVER used to download files */
unset( $args['stream'], $args['filename'] );
return wp_remote_post( $url, $args );
}
/**
*
* Wrapper over the WP wp_remote_request function - API external calls pass through this function
* sets some default parameters
*
* @param string $url Site URL to retrieve.
* @param array $args Optional. Request arguments. Default empty array.
*
* @return WP_Error|array The response or WP_Error on failure.
* @see wp_remote_request
*
*/
function tve_dash_api_remote_request( $url, $args = array() ) {
$args['sslverify'] = false;
/* makes sure this is NEVER used to download files */
unset( $args['stream'], $args['filename'] );
return wp_remote_request( $url, $args );
}
/**
* Retrieve versioning saved data
*
* @param string $api_name
*
* @return array
*/
function tve_saved_api_version( $api_name = '' ) {
if ( empty( $api_name ) ) {
return array();
}
$version = empty( $_REQUEST['connection']['version'] ) ? '' : sanitize_text_field( $_REQUEST['connection']['version'] );
$versioning = empty( $_REQUEST['connection']['versioning'] ) ? '' : sanitize_text_field( $_REQUEST['connection']['versioning'] );
if ( empty( $version ) && empty( $versioning ) ) {
$saved = get_option( 'thrive_mail_list_api', array() );
$version = ! empty( $saved[ $api_name ]['version'] ) ? $saved[ $api_name ]['version'] : $version;
$versioning = ! empty( $saved[ $api_name ]['versioning'] ) ? $saved[ $api_name ]['versioning'] : $versioning;
}
$data['version'] = $version;
$data['versioning'] = $versioning;
return $data;
}
/**
* handle the actual autoload (require_once)
*
* @param $basepath
* @param $className
* @param array $v [versioning flag and API version]
*
* @return bool
*/
function _tve_dash_api__autoload( $basepath, $className, $v = array() ) {
$parts = explode( '_', $className );
if ( empty( $parts ) ) {
return false;
}
$filename = array_pop( $parts );
$path = $basepath;
foreach ( $parts as $part ) {
$path .= $part . '/';
}
/**
* Added folder namespacing by API version [used in /auto-responder/classes/Connection/v and /auto-responder/lib/vendor/]
* Load the class from the version folder if exists based on template [versioning and version] params [for new implementations]
* Versioned class will be instantiated in Thrive_Dash_List_Manager::connection_instance()
*/
if ( ! empty( $v['version'] ) && ( ! empty( $v['versioning'] ) && (int) $v['versioning'] === 1 ) ) {
$api_version = $v['version'];
$versioned_file = $path . "v{$api_version}/" . $filename . '.php';
if ( file_exists( $versioned_file ) ) {
require_once $versioned_file;
return true;
}
}
$path .= $filename . '.php';
if ( ! file_exists( $path ) ) {
return false;
}
require_once $path;
return true;
}
/**
* autoload any class from the lib/vendor folder
*
* @param string $className
*
* @return bool|void
*/
function tve_dash_api_vendor_loader( $className ) {
$namespace = 'Thrive_Dash_Api_'; // = thrive
if ( strpos( $className, $namespace ) !== 0 ) {
return false;
}
$basedir = rtrim( __DIR__, '/\\' ) . '/lib/vendor/';
/**
* Get the API version info
*/
$parts = explode( '_', $className );
$connection_name = strtolower( array_pop( $parts ) );
$api_versioning = tve_saved_api_version( $connection_name );
return _tve_dash_api__autoload( $basedir, str_replace( $namespace, '', $className ), $api_versioning );
}
/**
*
* autoload "internal" auto-responder component classes (located in inc/auto-responder/classes folder)
*
* @param string $className
*
* @return bool
*/
function tve_dash_api_classes_loader( $className ) {
$namespace = 'Thrive_Dash_List_';
if ( strpos( $className, $namespace ) !== 0 ) {
return false;
}
$parts = explode( '_', $className );
$connection_name = strtolower( array_pop( $parts ) );
$api_versioning = tve_saved_api_version( $connection_name );
$basedir = rtrim( __DIR__, '/\\' ) . '/classes/';
return _tve_dash_api__autoload( $basedir, str_replace( $namespace, '', $className ), $api_versioning );
}
spl_autoload_register( 'tve_dash_api_vendor_loader' );
spl_autoload_register( 'tve_dash_api_classes_loader' );
do_action( 'thrive_dashboard_autoresponders_loaded' );
/**
* AJAX call handler for API logs that are being retried
* If the subscription is made with success the log is deleted from db
*/
function tve_dash_api_form_retry() {
check_ajax_referer( 'tve-dash' );
if ( ! current_user_can( TVE_DASH_CAPABILITY ) ) {
wp_die( '' );
}
$connection_name = ! empty( $_POST['connection_name'] ) ? sanitize_text_field( $_POST['connection_name'] ) : null;
$list_id = ! empty( $_POST['list_id'] ) ? sanitize_text_field( $_POST['list_id'] ) : null;
$email = ! empty( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : null;
$name = ! empty( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : '';
$phone = ! empty( $_POST['phone'] ) ? sanitize_text_field( $_POST['phone'] ) : '';
$log_id = ! empty( $_POST['log_id'] ) ? absint( $_POST['log_id'] ) : null;
$url = ! empty( $_POST['url'] ) ? sanitize_text_field( $_POST['url'] ) : null;
if ( empty( $connection_name ) ) {
exit( json_encode( array(
'status' => 'error',
'message' => __( 'Connection is not specified !', 'thrive-dash' ),
) ) );
}
if ( empty( $list_id ) ) {
exit( json_encode( array(
'status' => 'error',
'message' => __( 'Where should I subscribe this user? List is not specified !', 'thrive-dash' ),
) ) );
}
if ( empty( $email ) ) {
exit( json_encode( array(
'status' => 'error',
'message' => __( 'Email is not specified !', 'thrive-dash' ),
) ) );
}
$data = array(
'email' => $email,
'name' => $name,
'phone' => $phone,
'url' => $url,
);
if ( $list_id == "asset" ) {
$api = Thrive_Dash_List_Manager::connection_instance( $connection_name );
if ( ! $api ) {
$response = __( 'Cannot establish API connection', 'thrive-dash' );
} else {
$post_data['_asset_group'] = ! empty( $_POST['_asset_group'] ) ? sanitize_text_field( $_POST['_asset_group'] ) : '';
$post_data['email'] = sanitize_email( $_POST['email'] );
if ( isset( $_POST['name'] ) ) {
$post_data['name'] = sanitize_text_field( $_POST['name'] );
}
$response = true;
try {
$api->sendEmail( $post_data );
} catch ( Exception $e ) {
$response = $e->getMessage();
}
}
} else {
$response = tve_api_add_subscriber( $connection_name, $list_id, $data, false );
}
if ( $response !== true ) {
exit( json_encode( array(
'status' => 'error',
'message' => $response,
) ) );
}
if ( ! empty( $log_id ) ) {
global $wpdb;
$delete_result = $wpdb->delete( $wpdb->prefix . 'tcb_api_error_log', array( 'id' => $log_id ), array( '%d' ) );
if ( $delete_result === false ) {
exit( json_encode( array(
'status' => 'error',
'message' => __( "Subscription was made with success but we could not delete the log from database !", 'thrive-dash' ),
) ) );
}
}
exit( json_encode( array(
'status' => 'success',
'message' => __( 'Subscription was made with success !', 'thrive-dash' ),
) ) );
}
/**
* AJAX call handler to delete API's logs
*/
function tve_dash_api_delete_log() {
check_ajax_referer( 'tve-dash' );
if ( ! current_user_can( TVE_DASH_CAPABILITY ) ) {
wp_die( '' );
}
$log_id = ! empty( $_POST['log_id'] ) ? intval( $_POST['log_id'] ) : null;
if ( empty( $log_id ) ) {
exit( json_encode( array(
'status' => 'error',
'message' => __( "Log ID is not valid !", 'thrive-dash' ),
) ) );
}
global $wpdb;
$delete_result = $wpdb->delete( $wpdb->prefix . 'tcb_api_error_log', array( 'id' => $log_id ), array( '%d' ) );
if ( $delete_result === false ) {
exit( json_encode( array(
'status' => 'error',
'message' => sprintf( __( "An error occurred: %s", 'thrive-dash' ), $wpdb->last_error ),
) ) );
}
if ( $delete_result === 0 ) {
exit( json_encode( array(
'status' => 'error',
'message' => sprintf( __( "The log with ID: %s could not be found !", 'thrive-dash' ), $log_id ),
) ) );
}
exit( json_encode( array(
'status' => 'success',
'message' => sprintf( __( "API Log with ID: %s has been deleted with success !", 'thrive-dash' ), $log_id ),
) ) );
}
if ( ! class_exists( 'Thrive_List_Manager' ) ) {
class Thrive_List_Manager extends Thrive_Dash_List_Manager {
}
}
if ( ! class_exists( 'Thrive_List_Connection_Mandrill' ) ) {
class Thrive_List_Connection_Mandrill extends Thrive_Dash_List_Connection_Mandrill {
}
}
if ( ! class_exists( 'Thrive_List_Connection_Postmark' ) ) {
class Thrive_List_Connection_Postmark extends Thrive_Dash_List_Connection_Postmark {
}
}
if ( ! class_exists( 'Thrive_List_Connection_SparkPost' ) ) {
class Thrive_List_Connection_SparkPost extends Thrive_Dash_List_Connection_SparkPost {
}
}
if ( ! class_exists( 'Thrive_List_Connection_Mailgun' ) ) {
class Thrive_List_Connection_Mailgun extends Thrive_Dash_List_Connection_Mailgun {
}
}
if ( ! class_exists( 'Thrive_List_Connection_Awsses' ) ) {
class Thrive_List_Connection_Awsses extends Thrive_Dash_List_Connection_Awsses {
}
}
if ( ! class_exists( 'Thrive_List_Connection_SendinblueEmail' ) ) {
class Thrive_List_Connection_SendinblueEmail extends Thrive_Dash_List_Connection_SendinblueEmail {
}
}

View File

@@ -0,0 +1,109 @@
<div class="tvd-error-log-table">
<div class="tvd-row tvd-collapse">
<div class="tvd-col tvd-s6">
<h3 class="tvd-title"><?php echo esc_html__( "Thrive API Connections - error logs", 'thrive-dash' ) ?></h3>
</div>
<div class="tvd-col tvd-s6">
<h5 class="tvd-right-align">
<span class="tvd-error-log-item-number"></span>
<span><?php echo esc_html__( "items", 'thrive-dash' ) ?></span>
</h5>
</div>
</div>
<table class="tvd-collection tvd-with-header tvd-not-fixed-table">
<thead>
<tr class="tvd-collection-header">
<td>
<h5>
<?php echo esc_html__( 'Form data', 'thrive-dash' ) ?>
</h5>
</td>
<td class="tvd-error-log-connection tvd-col tvd-s1 tvd_filter_desc tvd-pointer"
data-val="connection">
<h5>
<?php echo esc_html__( 'Service', 'thrive-dash' ) ?>
<span class="tvd-icon-expanded tvd-orderby-icons"></span>
</h5>
</td>
<td class="tvd-error-log-date tvd-col tvd-s1 tvd-pointer tvd_filter_desc tvd-order-filter-active"
data-val="date">
<h5>
<?php echo esc_html__( 'Date', 'thrive-dash' ) ?>
<span class="tvd-icon-expanded tvd-orderby-icons"></span>
</h5>
</td>
<td>
<h5>
<?php echo esc_html__( 'Error Message', 'thrive-dash' ) ?>
</h5>
</td>
<td class="tvd-center-align">
<h5>
<?php echo esc_html__( 'Actions', 'thrive-dash' ) ?>
</h5>
</td>
</tr>
</thead>
<tbody class="tvd-error-log-table-content">
</tbody>
<tfoot>
<tr class="tvd-collection-item">
<td colspan="4">
<div class="tvd-right">
<p class="tvd-inline-block tvd-small-text tvd-no-margin">
<strong>
<?php echo esc_html__( 'Rows per page', 'thrive-dash' ) ?>
</strong>
</p>
<div class="tvd-input-field tvd-inline-block tvd-input-field-small tvd-no-margin">
<select class="" id="tvd-row-nr-per-page" tabindex="-1"
aria-hidden="true">
<option value="5">5</option>
<option value="10" selected>10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
</div>
<span class="tvd-inline-block tvd-margin-left"></span>
<p class="tvd-inline-block tvd-small-text tvd-no-margin">
<strong>
<?php echo esc_html__( 'Jump to page', 'thrive-dash' ) ?>
</strong>
</p>
<div class="tvd-input-field tvd-inline-block">
<input class="tvd-jump-to-page tvd-no-margin tvd-input-field-small" type="text" name="current_page"
data-error="<?php echo esc_html__( 'Page doesn\'t exist', 'thrive-dash' ) ?>"
id="current-page-input" value="">
</div>
<a class="tvd-jump-to-page-button tvd-waves-effect tvd-waves-light tvd-btn tvd-btn-blue tvd-btn-small tvd-margin-left-small"
href="javascript:void(0)" tabindex="1"><?php echo esc_html__( 'Go', 'thrive-dash' ) ?></a>
</div>
</td>
<td>
<div class="tvd-pagination-container">
<p class="tvd-inline-block tvd-small-text">
<strong>
<?php echo esc_html__( 'Page', 'thrive-dash' ) ?>
<span class="tvd-error-log-current-page"></span>&nbsp;
<?php echo esc_html__( 'of', 'thrive-dash' ) ?>&nbsp;
<span class="tvd-error-log-total-pages"></span>
</strong>
</p>
<a class="tvd-previous-page tvd-text-gray tvd-margin-left" href="javascript:void(0)"><span
class="tvd-icon-chevron-left"></span></a>
<a class="tvd-next-page tvd-text-gray tvd-margin-left" href="javascript:void(0)"><span
class="tvd-icon-chevron-right2"></span></a>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
<a class="tvd-waves-effect tvd-waves-light tvd-btn-small tvd-btn-gray"
href="<?php echo esc_url( admin_url( "admin.php?page=tve_dash_api_connect" ) ); ?>"><?php echo esc_html__( "Back to API Connections", 'thrive-dash' ) ?></a>
<script type="text/template" id="tvd-error-log-entry-template">
<?php include plugin_dir_path( __FILE__ ) . 'error-log-entry.php'; ?>
</script>

View File

@@ -0,0 +1,309 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
unset( $available_apis['zoom'] );
?>
<script type="text/javascript">
TVE_Dash.API.ConnectedAPIs = new TVE_Dash.API.collections.Connections(<?php echo Thrive_Dash_List_Manager::to_json( $connected_apis ); ?>);
TVE_Dash.API.AvailableAPIs = new TVE_Dash.API.collections.Connections(<?php echo Thrive_Dash_List_Manager::to_json( $available_apis ); ?>);
TVE_Dash.API.ToBeConnected = new TVE_Dash.API.models.ToBeConnected();
TVE_Dash.API.ThirdPartyAPIs = new Backbone.Collection(<?php echo json_encode( Thrive_Dash_List_Manager::get_third_party_autoresponders() ); ?>);
TVE_Dash.API.APITypes = new TVE_Dash.API.collections.APITypes(<?php echo json_encode( $types ); ?>);
</script>
<?php include dirname( __FILE__ ) . '/admin-messages.php' ?>
<?php include TVE_DASH_PATH . '/templates/header.phtml'; ?>
<div class="tvd-v-spacer"></div>
<div class="tvd-container tvd-hide tvd-show-onload">
<h3 class="tvd-section-title"><?php echo esc_html__( "Active Connections", 'thrive-dash' ) ?></h3>
<div class="tvd-row tvd-api-list"></div>
<?php if ( ! empty( Thrive_Dash_List_Manager::get_third_party_autoresponders() ) ) : ?>
<h3 class="tvd-section-title"><?php echo esc_html__( 'Third Party Connections', 'thrive-dash' ) ?></h3>
<div class="tvd-row tvd-third-party-api-list"></div>
<?php endif; ?>
<div class="tvd-row">
<div class="tvd-col tvd-s12">
<div style="height: 100px"></div>
</div>
</div>
<div class="tvd-row tvd-connections-footer">
<div class="tvd-col tvd-s12 tvd-m6">
<a href="<?php echo esc_url( admin_url( 'admin.php?page=tve_dash_section' ) ); ?>"
class="tvd-waves-effect tvd-waves-light tvd-btn-small tvd-btn-gray">
<?php echo esc_html__( "Back To Dashboard", 'thrive-dash' ); ?>
</a>
</div>
<div class="tvd-col tvd-s12 tvd-m6">
<a href="<?php echo esc_url( admin_url( 'admin.php?page=tve_dash_api_error_log' ) ); ?>"
class="tvd-btn-flat tvd-btn-flat-primary tvd-btn-flat-dark tvd-waves-effect tvd-right tvd-btn-small">
<?php echo esc_html__( "View Error Logs", 'thrive-dash' ); ?>
</a>
</div>
</div>
</div>
<script type="text/template" id="tvd-api-connected">
<div class="tvd-card tvd-white tvd-small">
<div class="tvd-card-image" style="background-image: url('<#= item.get('logoUrl') #>');">
<img src="<#= item.get('logoUrl') #>" alt="<#= item.get('title')#>">
</div>
<div class="tvd-card-action">
<div class="tvd-row">
<div class="tvd-col tvd-s12 tvd-m6">
<h4>
<#= item.get('title') === 'Brevo' ? 'Brevo (SendinBlue)' : item.get('title') #>
</h4>
</div>
<div class="tvd-col tvd-s12 tvd-m6">
<div class="tvd-right tvd-flex-mid">
<# if ( item.get('can_test') ) { #>
<a class="tvd-api-test tvd-btn tvd-btn-green tvd-btn-toggle">
<i class="tvd-icon-exchange tvd-left"></i>
<span class="tvd-btn-text"><?php echo esc_html__( "Test", 'thrive-dash' ) ?></span>
</a>
<# } #>
<# if ( item.get('can_edit') ) { #>
<a class="tvd-api-edit tvd-btn tvd-btn-blue tvd-btn-toggle">
<i class="tvd-icon-pencil tvd-left"></i>
<span class="tvd-btn-text"><?php echo esc_html__( "Edit", 'thrive-dash' ) ?></span>
</a>
<# } #>
<# if ( item.get('can_delete') ) { #>
<a class="tvd-api-delete tvd-btn tvd-btn-red tvd-btn-toggle">
<i class="tvd-icon-trash-o tvd-left"></i>
<span class="tvd-btn-text"><?php echo esc_html__( "Delete", 'thrive-dash' ) ?></span>
</a>
<# } #>
<#= item.get('status_icon') || '' #>
</div>
</div>
</div>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-state-new">
<div class="tvd-card tvd-small tvd-card-new tvd-valign-wrapper" id="tvd-add-new-api">
<div class="tvd-card-content tvd-valign tvd-center-align tvd-pointer">
<i class="tvd-icon-plus tvd-icon-rounded tvd-icon-medium"></i>
<h4><?php echo esc_html__( "Add new Connection", 'thrive-dash' ) ?></h4>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-state-select">
<div class="tvd-card tvd-small tvd-card-new tvd-valign-wrapper">
<div class="tvd-card-content tvd-valign tvd-center-align">
<div class="tvd-row">
<div class="tvd-col tvd-s10 tvd-offset-s1">
<div class="input-field2">
<select id="selected-api">
<optgroup label="" class="tvd-hide">
<option
value="none"><?php echo esc_html__( "- Select an app -", 'thrive-dash' ) ?></option>
</optgroup>
</select>
</div>
</div>
</div>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-state-form">
<div class="tvd-card tvd-white">
<div class="tvd-card-content tvd-card-content-wfooter"></div>
</div>
</script>
<script type="text/template" id="tvd-api-state-error">
<div class="tvd-card tvd-orange">
<div class="tvd-card-content tvd-card-content-wfooter">
<div class="tvd-center-align">
<i class="tvd-icon-close tvd-icon-big tvd-icon-border tvd-icon-rounded"></i>
</div>
<h3 class="tvd-card-title"><?php echo esc_html__( "The connection didn't work.", 'thrive-dash' ) ?></h3>
<p class="tvd-center tvd-card-spacer">
<?php echo esc_html__( "Error message:", 'thrive-dash' ) ?>
<#= item.get('response').message#>
</p>
<br><br>
<div class="tvd-card-action">
<div class="tvd-row tvd-no-margin">
<div class="tvd-col tvd-s12 tvd-m6">
<a class="tvd-api-cancel tvd-btn-flat tvd-btn-flat-secondary tvd-btn-flat-light tvd-waves-effect"><?php echo esc_html__( "Cancel", 'thrive-dash' ) ?></a>
</div>
<div class="tvd-col tvd-s12 tvd-m6">
<a class="tvd-api-retry tvd-btn-flat tvd-btn-flat-primary tvd-btn-flat-light tvd-waves-effect"><?php echo esc_html__( "Retry", 'thrive-dash' ) ?></a>
</div>
</div>
</div>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-state-success">
<div class="tvd-card tvd-green">
<div class="tvd-card-content tvd-center-align">
<i class="tvd-icon-check tvd-icon-big tvd-icon-border tvd-icon-rounded"></i>
<h3 class="tvd-modal-title">
<#= item.get('title') #><br/><?php echo esc_html__( "Connection Ready!", 'thrive-dash' ) ?></h3>
<p class="tvd-open-video" data-source="KuZcvyv-Tvs">
<# if(typeof item.get('success_message') !== 'undefined' && item.get('success_message') != '') { #>
<#= item.get('success_message') #>
<# } else { #>
<# if(item.get('key') === 'sendowl') { #>
<?php echo esc_html__( "You can now connect Thrive Apprentice to ", 'thrive-dash' ) ?>
<#= item.get('title') #>.
<a href="<?php echo esc_url( get_admin_url() . 'admin.php?page=thrive_apprentice#settings/sendowl/quick-start' ) ?>"><?php echo esc_html__( "Click here to discover the Quick Start Guide.", 'thrive-dash' ) ?></a>
<# } else { #>
<?php echo esc_html__( "You can now connect your opt-in forms to ", 'thrive-dash' ) ?>
<#= item.get('title') #>.
<# if ( item.get('type') !== 'storage' ) { #>
<a>
<?php echo esc_html__( "See how it's done.", 'thrive-dash' ) ?>
</a>
<# } #>
<# } #>
<# } #>
</p>
<div class="tvd-row">
<div class="tvd-col tvd-s12 tvd-m6 tvd-offset-m3">
<a href="javascript:void(0)"
class="tvd-api-done tvd-btn-flat tvd-btn-flat-primary tvd-btn-flat-light tvd-full-btn tvd-btn-margin-top tvd-waves-effect"><?php echo esc_html__( "Done", 'thrive-dash' ) ?></a>
</div>
</div>
</div>
</div>
</script>
<?php foreach ( $connected_apis as $key => $api ) : ?>
<?php /** @var $api Thrive_Dash_List_Connection_Abstract */ ?>
<script type="text/template" id="tvd-api-form-<?php echo esc_attr( $key ) ?>">
<?php echo $api->output_setup_form() //phpcs:ignore ?>
</script>
<?php endforeach; ?>
<?php foreach ( $available_apis as $key => $api ) : ?>
<?php /** @var $api Thrive_Dash_List_Connection_Abstract */ ?>
<script type="text/template" id="tvd-api-form-<?php echo esc_attr( $key ) ?>">
<?php echo $api->output_setup_form() //phpcs:ignore ?>
</script>
<?php endforeach; ?>
<script type="text/template" id="tvd-api-form-preloader">
<div class="tvd-card-preloader">
<div class="tvd-preloader-wrapper tvd-big tvd-active">
<div class="tvd-spinner-layer tvd-spinner-blue-only">
<div class="tvd-circle-clipper tvd-left">
<div class="tvd-circle"></div>
</div>
<div class="tvd-gap-patch">
<div class="tvd-circle"></div>
</div>
<div class="tvd-circle-clipper tvd-right">
<div class="tvd-circle"></div>
</div>
</div>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-connection-error">
<div class="tvd-card tvd-orange tvd-valign-wrapper">
<div class="tvd-card-content tvd-valign tvd-center-align">
<a href="javascript:void(0)" class="tvd-close-card">
<i class="tvd-icon-close2"></i>
</a>
<i class="tvd-icon-exclamation tvd-icon-rounded tvd-icon-medium"></i>
<h4><?php echo esc_html__( "The connection failed.", 'thrive-dash' ) ?></h4>
<p>
<#= item.get('response').message #>
</p>
<a class="tvd-btn-flat tvd-btn-flat-primary tvd-btn-flat-light tvd-api-edit tvd-waves-effect">
<?php echo esc_html__( "Edit settings", 'thrive-dash' ) ?>
</a>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-confirm-delete">
<div class="tvd-card tvd-small tvd-red">
<div class="tvd-card-content tvd-center-align">
<h4 class="tvd-margin-top">
<?php echo esc_html__( "Are you sure you want to delete this connection?", 'thrive-dash' ) ?>
</h4>
</div>
<div class="tvd-card-action">
<div class="tvd-row">
<div class="tvd-col tvd-s12 tvd-m6">
<a class="tvd-api-delete-yes tvd-btn-flat tvd-btn-flat-secondary tvd-btn-flat-light tvd-left tvd-waves-effect"
href="javascript:void(0)">
<?php echo esc_html__( "Yes, delete", 'thrive-dash' ) ?>
</a>
</div>
<div class="tvd-col tvd-s12 tvd-m6">
<a class="tvd-api-delete-no tvd-btn-flat tvd-btn-flat-primary tvd-btn-flat-light tvd-right tvd-waves-effect">
<?php echo esc_html__( "No, keep it", 'thrive-dash' ) ?>
</a>
</div>
</div>
</div>
</div>
</script>
<script type="text/template" id="tvd-api-connection-hover">
<div class="tvd-card tvd-small <#= color #> tvd-valign-wrapper">
<div class="tvd-card-content tvd-valign tvd-center-align">
<a href="javascript:void(0)" class="tvd-close-card">
<i class="tvd-icon-close2"></i>
</a>
<i class="<#= icon #> tvd-icon-medium"></i>
<h4 class="tvd-dark-text">
<#= text ? text : 'Testing...' #>
</h4>
</div>
</div>
</script>
<script type="text/template" id="tvd-third-party-api">
<div class="tvd-col tvd-s12 tvd-m4 tvd-l3">
<div class="tvd-card tvd-white tvd-small">
<div class="tvd-card-image" style="background-image: url('<#= item.get('thumbnail') #>');">
<img src="<#= item.get('thumbnail') #>">
</div>
<div class="tvd-card-action">
<div class="tvd-row">
<div class="tvd-col tvd-s12 tvd-m6 tvd-third-party-label">
<h4>
<#= item.get( 'title' ) #>
</h4>
</div>
<div class="tvd-col tvd-s12 tvd-m6">
<div class="tvd-right tvd-flex-mid">
<a href="<#= item.get( 'controls_link' ) #>" class="tvd-api-link" target="_blank">
<i class="tvd-icon-pencil tvd-left"></i>
</a>
<span class="tvd-api-status-icon status-<#= item.get( 'is_connected' ) ? 'green' : 'red' #>"</span>
</div>
</div>
</div>
</div>
</div>
</div>
</script>

View File

@@ -0,0 +1,17 @@
<div class="iconmanager-messages">
<?php if ( ! empty( $GLOBALS['thrive_list_api_message']['error'] ) ) : ?>
<div class="clear" style="height: 10px"></div>
<div class="error below-h2" style="margin-left: 0;">
<p><?php echo strip_tags( $GLOBALS['thrive_list_api_message']['error'], '<a>' ); ?></p>
</div>
<?php endif ?>
<?php if ( ! empty( $GLOBALS['thrive_list_api_message']['success'] ) ) : ?>
<div class="clear" style="height: 10px"></div>
<div class="updated below-h2" style="margin-left: 0;">
<p><?php echo esc_html( $GLOBALS['thrive_list_api_message']['success'] ); ?></p>
<?php if ( ! empty( $GLOBALS['thrive_list_api_message']['redirect'] ) ) : ?>
<input type="hidden" id="tve-redirect-to" value="<?php echo esc_attr( $GLOBALS['thrive_list_api_message']['redirect'] ); ?>">
<?php endif ?>
</div>
<?php endif ?>
</div>

View File

@@ -0,0 +1,21 @@
<h4><?php echo esc_html__( "Step 2: Choose your API Connection", 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<?php
include dirname( __FILE__ ) . '/partials/api-select.php';
include dirname( __FILE__ ) . '/partials/api-lists.php'; ?>
<?php if ( ! empty( $connected_apis ) ) : ?>
<div class="tve-sp"></div>
<div class="tve-sp"></div>
<div id="tve-save-api tve_clearfix">
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_default tve_button_margin tve_right" data-ctrl="function:auto_responder.dashboard"
data-edit="<?php echo esc_attr( $edit_api_key ); ?>">
<?php echo esc_html__( "Cancel", 'thrive-dash' ) ?>
</a>
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_success tve_right" data-ctrl="function:auto_responder.api.save"
data-edit="<?php echo esc_attr( $edit_api_key ); ?>">
<?php echo esc_html__( "Save", 'thrive-dash' ) ?>
</a>
</div>
<?php endif ?>

View File

@@ -0,0 +1,10 @@
<h4><?php echo esc_html__( "Step 2: Insert HTML code", 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<p><?php echo esc_html__( "Step 2: Now insert your full HTML autoresponder code. You can find more information about what code is required", 'thrive-dash' ) ?>
<a class="tve_lightbox_link tve_lightbox_link_info" target="_blank" href="https://thrivethemes.com/tkb_item/add-autoresponder-code-form/"><?php echo esc_html__( "in our knowledge base", 'thrive-dash' ) ?></a>
</p>
<?php $show_textarea = true;
$show_reCaptcha = false;
include dirname( __FILE__ ) . '/autoresponder-code-fields.php' ?>

View File

@@ -0,0 +1,17 @@
<h4><?php echo esc_html__( "Step 1: Choose Connection Type", 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<p><?php echo esc_html__( "Choose whether you would like to connect using HTML form code or through an established API connection ?", 'thrive-dash' ) ?></p>
<div class="tve_lightbox_select_holder">
<select class="" id="connection-type">
<?php foreach ( $connection_types as $connection_key => $connection_name ) : ?>
<option value="<?php echo esc_attr( $connection_key ); ?>"><?php echo esc_html( $connection_name ); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="tve-sp"></div>
<div class="tve_clearfix">
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_success tve_right"
data-ctrl="function:auto_responder.connection_form" data-step2="1">
<?php echo esc_html__( "Go to the next step", 'thrive-dash' ) ?>
</a>
</div>

View File

@@ -0,0 +1,51 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
if ( isset( $show_textarea ) ) : ?>
<textarea name="tve_lead_generation_code" placeholder="<?php echo esc_html__( "Insert your code here", 'thrive-dash' ) ?>"
class="tve_lightbox_textarea"></textarea>
<div class="tve_clearfix">
<a href="javascript:void(0)" class="tve_editor_button tve_editor_button_default tve_right tve_button_margin tve_click "
data-ctrl="function:auto_responder.dashboard"><?php echo esc_html__( "Cancel", 'thrive-dash' ) ?></a>
<a href="javascript:void(0)"
class="tve_editor_button tve_editor_button_success tve_right tve_lead_generate_fields tve_click"
data-ctrl="function:auto_responder.generate_fields"><?php echo esc_html__( "Generate Fields", 'thrive-dash' ) ?></a>
</div>
<?php endif ?>
<div class="tve_large_lightbox tve_lead_gen_lightbox_small">
<?php unset( $show_textarea ) ?>
<div id="generated_inputs_container"
class="tve_clearfix">
<?php echo isset( $fields_table ) ? $fields_table : '' ?>
</div>
<div id="tve_lg_icon_list" style="display: none">
<table>
<tfoot>
<tr>
<td style="width: 10%;"><?php echo esc_html__( 'Choose an icon', 'thrive-dash' ) ?></td>
<td>
<?php $icon_click = 'function:auto_responder.choose_icon';
$icon_hide_header = true;
if ( function_exists( 'tve_editor_path' ) ) {
include_once tve_editor_path( 'editor/lb_icon.php' );
}
?>
</td>
</tr>
</tfoot>
</table>
</div>
<?php if ( ! empty( $show_reCaptcha ) ): ?>
<?php include dirname( __FILE__ ) . '/captcha-settings.php'; ?>
<?php endif; ?>
<?php do_action( 'tve_tcb_delivery_connection' ); ?>
<?php do_action( 'tve_tcb_add_form_options', $data ); ?>
</div>

View File

@@ -0,0 +1,61 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
$captcha_api = Thrive_Dash_List_Manager::credentials( 'recaptcha' );
$captcha_available = ! empty( $captcha_api['site_key'] );
?>
<div class="tve_lead_captcha_settings">
<div class="tve_lightbox_input_holder">
<input class="tve_lg_validation_options tve_change"
type="checkbox"
name="tve_api_use_captcha"
data-ctrl="function:auto_responder.use_captcha_changed" id="tve-captcha"
<?php echo $captcha_available ? '' : ' disabled'; ?>
>
<label for="tve-captcha">
<?php echo esc_html__( 'Add Captcha to Prevent Spam Signups', 'thrive-dash' );
if ( ! $captcha_available ) {
echo '(<a href="' . esc_url(admin_url( 'admin.php?page=tve_dash_api_connect' )) . '">' . esc_html__( 'Requires integration with Google ReCaptcha', 'thrive-dash' ) . ')</a>';
}
?>
</label>
</div>
<div class="tve_captcha_options" style="display:none;">
<label><?php echo esc_html__( 'Theme', 'thrive-dash' ); ?>:</label>
<div class="tve_lightbox_select_holder tve_captcha_option">
<select class="tve_captcha_theme tve_change" data-option="captcha_theme" data-ctrl="function:auto_responder.captcha_option_changed">
<option value="light"><?php echo esc_html__( 'Light', 'thrive-dash' ); ?></option>
<option value="dark"><?php echo esc_html__( 'Dark', 'thrive-dash' ); ?></option>
</select>
</div>
<label><?php echo esc_html__( 'Type', 'thrive-dash' ); ?>:</label>
<div class="tve_lightbox_select_holder tve_captcha_option">
<select class="tve_captcha_type tve_change" data-option="captcha_type" data-ctrl="function:auto_responder.captcha_option_changed">
<option value="image"><?php echo esc_html__( 'Image', 'thrive-dash' ); ?></option>
<option value="audio"><?php echo esc_html__( 'Audio', 'thrive-dash' ); ?></option>
</select>
</div>
<label><?php echo esc_html__( 'Size', 'thrive-dash' ); ?>:</label>
<div class="tve_lightbox_select_holder tve_captcha_option">
<select class="tve_captcha_size tve_change" data-option="captcha_size" data-ctrl="function:auto_responder.captcha_option_changed">
<option value="normal"><?php echo esc_html__( 'Normal', 'thrive-dash' ); ?></option>
<option value="compact"><?php echo esc_html__( 'Compact', 'thrive-dash' ); ?></option>
</select>
</div>
</div>
</div>

View File

@@ -0,0 +1,202 @@
<h4><?php echo esc_html__( "Connect with Service", 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<?php
$connection_config = $data['connection_config'];
$klicktipp_option = count( $connection_config ) == 1 && isset( $connection_config['klicktipp'] );
$custom_messages = is_array( $data['custom_messages'] ) ? $data['custom_messages'] : array();
$custom_messages['error'] = empty( $custom_messages['error'] ) ? '' : $custom_messages['error'];
$custom_messages['success'] = empty( $custom_messages['success'] ) ? '' : $custom_messages['success'];
$create_account = $data['create_account'];
/**
* at this stage, we have a list of existing connections that are to be displayed in a list
*/
$available = Thrive_Dash_List_Manager::get_available_apis( true );
$helper = new Thrive_Dash_Api_CustomHtml();
$form_type = $helper->getFormType();
$form_type !== 'lead_generation' ? $variations = $helper->getFormVariations() : $variations = array();
if ( function_exists( 'tve_leads_get_form_variation' ) ) {
if ( ! empty( $_POST['_key'] ) ) {
$this_variation = tve_leads_get_form_variation( null, sanitize_text_field( $_POST['_key'] ) );
if ( $form_type != 'lightbox' && $this_variation['form_state'] == 'lightbox' ) {
foreach ( $variations as $key => $variation ) {
if ( $variation['form_state'] == 'lightbox' ) {
unset( $variations[ $key ] );
}
}
}
}
}
?>
<div class="tve_large_lightbox tve_lead_gen_lightbox_small">
<p><?php echo esc_html__( 'Your sign up form is connected to service(s) using the following API connections:', 'thrive-dash' ) ?></p>
<table>
<caption><?php echo esc_html__( 'API connections', 'thrive-dash' ) ?></caption>
<thead>
<tr>
<th scope="col" colspan="2">
<?php echo esc_html__( "Service Name", 'thrive-dash' ) ?>
</th>
</tr>
</thead>
<tbody>
<?php foreach ( $connection_config as $key => $list_id ) : if ( ! isset( $available[ $key ] ) ) {
continue;
} ?>
<tr>
<td width="90%">
<?php echo esc_html( $available[ $key ]->get_title() ); ?>
</td>
<td width="10%">
<a href="javascript:void(0)" class="tve_click" data-ctrl="function:auto_responder.connection_form"
data-connection-type="api" data-key="<?php echo esc_attr( $key ); ?>" title="<?php echo esc_html__( "Settings", 'thrive-dash' ) ?>">
<span class="tve_icm tve-ic-cog tve_ic_small tve_lightbox_icon_small"></span>
</a>
&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0)" class="tve_click" data-ctrl="function:auto_responder.api.remove"
data-key="<?php echo esc_attr( $key ); ?>" title="<?php echo esc_html__( "Remove", 'thrive-dash' ) ?>">
<span class="tve_icm tve-ic-close tve_ic_small tve_lightbox_icon_small"></span>
</a>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<div class="tve-sp"></div>
<?php if ( count( $available ) != count( $connection_config ) ) : ?>
<div class="clearfix">
<a href="javascript:void(0)" class="tve_click tve_right tve_editor_button tve_editor_button_success"
data-ctrl="function:auto_responder.connection_form" data-connection-type="api">
<?php echo esc_html__( "Add New Connection", 'thrive-dash' ) ?>
</a>
</div>
<?php endif ?>
<div class="tve_clear" style="height:30px;"></div>
<p><?php echo esc_html__( 'Select which fields to display and their properties (you can reorder them by dragging the "move" icon from the left):', 'thrive-dash' ) ?></p>
<?php
$fields_table = isset( $data['fields_table'] ) ? $data['fields_table'] : '';
$show_thank_you_url = true;
$show_reCaptcha = true;
include dirname( __FILE__ ) . '/autoresponder-code-fields.php';
?>
<div class="tve-sp"></div>
<?php if ( ! empty( $data['show_submit_options'] ) ) : ?>
<div class="tve_gray_box tve_ps_container">
<h4><?php echo esc_html__( "Action After Signup", 'thrive-dash' ) ?></h4>
<?php $submit = ! empty( $_POST['submit_option'] ) ? sanitize_text_field( $_POST['submit_option'] ) : 'reload' ?>
<?php if ( $submit == 'page' ) {
$thank_you_url = ! empty( $_POST['thank_you_url'] ) ? esc_url_raw( $_POST['thank_you_url'] ) : 0;
$post = get_post( $thank_you_url );
} ?>
<?php $state = ! empty( $_POST['state'] ) ? sanitize_text_field( $_POST['state'] ) : '' ?>
<label><?php echo esc_html__( "After the form is submitted:", 'thrive-dash' ) ?>&nbsp;</label>
<div class="tve_lightbox_select_holder tve_lightbox_select_holder_submit tve_lightbox_input_inline tve_lightbox_select_inline">
<select class="tve_lg_validation_options tve_change tve-api-submit-filters" id="tve-api-submit-option"
data-ctrl="function:auto_responder.api.submit_option_changed">
<option <?php echo ! empty( $create_account ) ? 'style="display:none"' : '' ?>
value="reload"<?php echo $submit == 'reload' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "Reload current page", 'thrive-dash' ) ?>
</option>
<option <?php echo ! empty( $create_account ) ? 'style="display:none"' : '' ?>
value="redirect"<?php echo $submit == 'redirect' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "Redirect to URL", 'thrive-dash' ) ?>
</option>
<option <?php echo ! empty( $create_account ) ? 'style="display:none"' : '' ?>
value="message" <?php echo $submit == 'message' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "Display message without reload", 'thrive-dash' ) ?>
</option>
<option
value="page" <?php echo $submit == 'page' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "Redirect to Page", 'thrive-dash' ) ?>
</option>
<?php if ( $form_type !== 'lead_generation' && ! empty( $variations ) ) : ?>
<option <?php echo ! empty( $create_account ) ? 'style="display:none"' : '' ?>
value="state" <?php echo $submit == 'state' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "Switch State", 'thrive-dash' ) ?>
</option>
<?php endif; ?>
<?php if ( $klicktipp_option ) : ?>
<option <?php echo ! empty( $create_account ) ? 'style="display:none"' : '' ?>
value="klicktipp-redirect" <?php echo $submit == 'klicktipp-redirect' ? ' selected="selected"' : '' ?>><?php echo esc_html__( "KlickTipp Thank You URL", 'thrive-dash' ) ?>
</option>
<?php endif; ?>
</select>
</div>
<input <?php echo $submit !== 'redirect' ? ' style="display: none"' : '' ?> size="70"
class="tve_change tve_text tve_lightbox_input tve_lightbox_input_inline tve_lightbox_input_inline_redirect"
data-ctrl="function:auto_responder.api.thank_you_url"
value="<?php echo ! empty( $_POST['thank_you_url'] ) ? sanitize_text_field( esc_attr( $_POST['thank_you_url'] ) ) : '' ?>"
placeholder="http://"/>
<input <?php echo $submit !== 'page' ? ' style="display: none"' : '' ?> size="70"
class="tve_change tve_text tve_lightbox_input tve_lightbox_input_inline tve-api-pages"
data-ctrl="function:auto_responder.api.set_page_search"
value="<?php echo isset( $post ) ? esc_attr( $post->post_title ) : '' ?>"
placeholder="Search for pages or posts"/>
<div class="tve_message_settings" <?php echo $submit !== 'message' ? ' style="display: none"' : '' ?>>
<p><?php echo esc_html__( "The following message will be displayed in a small popup after signup, without reloading the page.", 'thrive-dash' ) ?></p>
<div class="tve_dashboard_tab_success tve_dashboard_tab tve_dashboard_tab_selected">
<?php wp_editor( $custom_messages['success'], 'tve_success_wp_editor', $settings = array(
'quicktags' => false,
'media_buttons' => false
) ); ?>
</div>
</div>
<?php if ( $form_type !== 'lead_generation' ) : ?>
<div class="tve_state_settings" <?php echo $submit !== 'state' ? ' style="display: none"' : '' ?>>
<?php if ( ! empty( $variations ) ) : ?>
<label><?php echo esc_html__( "Choose the state to switch :", 'thrive-dash' ) ?>&nbsp;</label>
<div class="tve_lightbox_select_holder tve_lightbox_input_inline tve_lightbox_select_inline">
<select class="tve_change_states tve_change" data-ctrl="function:auto_responder.api.state_changed">
<?php foreach ( $variations as $variation ) : ?>
<option data-state="<?php echo esc_attr( $variation['form_state'] ); ?>"
value="<?php echo esc_attr( $variation['key'] ); ?>" <?php echo $state == $variation['key'] ? ' selected="selected"' : '' ?>><?php echo esc_html( $variation['state_name'] ); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<div
class="tve-shortcodes-wrapper tve-shortcodes-message" <?php echo $submit == 'message' && ! empty( $_POST['error_message_option'] ) && sanitize_text_field( $_POST['error_message_option'] ) != 1 ? '' : 'style="display:none"' ?>>
<?php include dirname( __FILE__ ) . '/partials/api-shortcodes.php'; ?>
</div>
<div class="tve-sp"></div>
<div class="tve-error-message-option tve_lightbox_input_holder">
<input type="checkbox" <?php echo ! empty( $_POST['error_message_option'] ) && absint( $_POST['error_message_option'] ) == 1 ? 'checked' : '' ?> class="tve_change" id="tve-error-message-option"
data-ctrl="function:auto_responder.error_message_option_changed"/>
<label for="tve-error-message-option"><?php echo esc_html__( "Add Error Message", 'thrive-dash' ) ?></label>
</div>
<div class="tve_gray_box tve-error-message-wrapper" <?php echo ! empty( $_POST['error_message_option'] ) && absint( $_POST['error_message_option'] ) != 1 ? 'style="display:none"' : '' ?>>
<h4><?php echo esc_html__( "Edit your error message", 'thrive-dash' ) ?></h4>
<p><?php echo esc_html__( "This error message is shown in the rare case that the signup fails. This can happen when your connected email marketing service can't be reached.", 'thrive-dash' ) ?>
</p>
<div class="tve_dashboard_tab_error">
<?php wp_editor( $custom_messages['error'], 'tve_error_wp_editor', $settings = array(
'quicktags' => false,
'media_buttons' => false
) ); ?>
</div>
</div>
<div class="tve-shortcodes-wrapper tve-shortcodes-error" <?php echo ! empty( $_POST['error_message_option'] ) && absint( $_POST['error_message_option'] ) != 1 ? 'style="display:none"' : '' ?>>
<?php include dirname( __FILE__ ) . '/partials/api-shortcodes.php'; ?>
</div>
<?php endif ?>
<div class="tve-sp"></div>
<div class="tve_clearfix">
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_default tve_right tve_button_margin"
data-ctrl="function:controls.lb_close">
<?php echo esc_html__( "Cancel", 'thrive-dash' ) ?>
</a>
&nbsp;
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_success tve_right"
data-ctrl="function:auto_responder.save_api_connection" data-edit-custom="1">
<?php echo esc_html__( "Save", 'thrive-dash' ) ?>
</a>
</div>
</div>

View File

@@ -0,0 +1,31 @@
<?php
/**
* Thrive Themes - https://thrivethemes.com
*
* @package thrive-dashboard
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Silence is golden!
}
if ( empty( $_POST['edit_custom_html'] ) ) : ?>
<h4><?php echo esc_html__( "Connect with Service", 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<p><?php echo esc_html__( "Your sign up form is connected to a service using custom HTML form code.", 'thrive-dash' ) ?></p>
<div class="tve-sp"></div>
<div class="tve_clearfix">
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_cancel tve_right tve_button_margin"
data-ctrl="function:auto_responder.remove_custom_html">
<span><?php echo esc_html__( "Delete Connection", 'thrive-dash' ) ?></span>
</a>
&nbsp;
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_success tve_right"
data-ctrl="function:auto_responder.dashboard" data-edit-custom="1">
<span><?php echo esc_html__( "Edit HTML form code", 'thrive-dash' ) ?></span>
</a>
</div>
<?php else : ?>
<?php $show_textarea = true;
$show_reCaptcha = false;
include dirname( __FILE__ ) . '/autoresponder-code-fields.php'; ?>
<?php endif; ?>

View File

@@ -0,0 +1,11 @@
<h4><?php echo esc_html__( 'Connect with Service', 'thrive-dash' ) ?></h4>
<hr class="tve_lightbox_line"/>
<p><?php echo esc_html__( 'This setting allows you to connect your sign up form with various web services, such as autoresponder accounts.', 'thrive-dash' ) ?>
<br/>
<?php echo esc_html__( 'You currently have no connections set up with this sign up form', 'thrive-dash' ) ?></p>
<div class="tve_clearfix">
<a href="javascript:void(0)" class="tve_click tve_editor_button tve_editor_button_success tve_right"
data-ctrl="function:auto_responder.connection_form">
<?php echo esc_html__( "Create a new Connection", 'thrive-dash' ) ?>
</a>
</div>

View File

@@ -0,0 +1,37 @@
<div id="thrive-api-list">
<div class="tve-sp"></div>
<?php if ( ! empty( $selected_api ) ) : ?>
<?php $list_subtitle = $selected_api->get_list_sub_title() ?>
<?php $api_key = $selected_api->get_key(); ?>
<?php $selected_api->render_before_lists_settings( empty( $extra_settings[ $api_key ] ) ? array() : $extra_settings[ $api_key ] ) ?>
<div class="tve-list-container tve-api-option-group tve-api-option-group-list" <?php echo $api_key == 'drip' && isset( $extra_settings[ $api_key ]['type'] ) && $extra_settings[ $api_key ]['type'] == 'automation' ? 'style="display:none"' : ''; ?>>
<?php if ( false === $lists ) : /** this means there's been an error while connecting / communicating to the API */ ?>
<p class="error-message" style="color: red">
<?php echo esc_html__( 'Error while communicating with the service:', 'thrive-dash' ) ?><?php echo esc_html( $selected_api->get_api_error() ) ?>
</p>
<?php else : ?>
<h6><?php echo empty( $list_subtitle ) ? 'Choose your mailing list:' : esc_html( $list_subtitle ) ?></h6>
<div class="tve_lightbox_select_holder tve_lightbox_input_inline tve_lightbox_select_inline">
<select id="thrive-api-list-select"<?php echo ( empty( $lists ) ) ? ' disabled' : ' data-api="' . esc_attr( $api_key ) . '"' ?> <?php echo ( ! empty( $lists ) && $api_key == 'mailchimp' ) ? 'class="tve_change" data-ctrl="function:auto_responder.api.api_get_groups"' : '' ?> >
<?php if ( empty( $lists ) ) : ?>
<option value=""><?php echo esc_html__( 'No list available', 'thrive-dash' ) ?></option>
<?php endif ?>
<?php foreach ( $lists as $list ) : ?>
<option value="<?php echo esc_attr( $list['id'] ) ?>"<?php echo ! empty( $selected_list ) && $selected_list == $list['id'] ? ' selected="selected"' : '' ?>><?php echo esc_html( $list['name'] ) ?></option>
<?php endforeach ?>
</select>
</div>
&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0)" class="tve_click tve_lightbox_link tve_lightbox_link_refresh" data-ctrl="function:auto_responder.api.reload_lists" data-force-fetch="1"" data-api="<?php echo esc_attr( $api_key ) ?>"><?php echo esc_html__( 'Reload', 'thrive-dash' ) ?></a>
<?php
if ( ! empty( $selected_list ) ) {
$extra_settings[ $api_key ]['list_id'] = $selected_list;
}
?>
<?php if ( ! empty( $lists ) || $api_key == 'drip' ) : ?>
<?php echo $selected_api->render_extra_editor_settings( empty( $extra_settings[ $api_key ] ) ? array() : $extra_settings[ $api_key ] ); // phpcs:ignore ?>
<?php endif ?>
<?php endif; /* false === $lists */ ?>
</div>
<?php endif; /* !empty ($selected_api) */ ?>
</div>

View File

@@ -0,0 +1,24 @@
<div id="thrive-api-connections">
<?php if ( empty( $connected_apis ) ) : ?>
<h6><?php echo esc_html__( "You currently don't have any API integrations set up.", 'thrive-dash' ) ?></h6>
<a href="<?php echo esc_url( admin_url( 'admin.php?page=tve_dash_api_connect' ) ); ?>" target="_blank"
class="tve_lightbox_link tve_lightbox_link_create"><?php echo esc_html__( "Click here to set up a new API connection", 'thrive-dash' ) ?></a>
<?php else : ?>
<h6><?php echo esc_html__( "Choose from your list of existing API connections or", 'thrive-dash' ) ?>
<a href="<?php echo esc_url( admin_url( 'admin.php?page=tve_dash_api_connect' ) ); ?>" target="_blank" class="tve_lightbox_link tve_lightbox_link_create">
<?php echo esc_html__( 'add a new integration', 'thrive-dash' ) ?>
</a>
</h6>
<div class="tve_lightbox_select_holder tve_lightbox_input_inline tve_lightbox_select_inline">
<select id="thrive-api-connections-select" class="tve_change"
data-ctrl="function:auto_responder.api.api_get_lists" autocomplete="off">
<?php foreach ( $connected_apis as $key => $api ) : ?>
<option
value="<?php echo esc_attr( $key ) ?>"<?php echo $edit_api_key == $key ? ' selected="selected"' : '' ?>><?php echo esc_html( $api->get_title() ); ?></option>
<?php endforeach ?>
</select>
</div>
&nbsp;&nbsp;&nbsp;
<a href="javascript:void(0)" data-ctrl="function:auto_responder.api.reload_apis" class="tve_click tve_lightbox_link tve_lightbox_link_refresh"><?php echo esc_html__( "Reload", 'thrive-dash' ) ?></a>
<?php endif ?>
</div>

View File

@@ -0,0 +1,45 @@
<h4 class="tl-clickable tl-toggle-tab-display collapsed tvd-pointer" data-target="#tve-shortcode-list">
<?php echo esc_html__( 'Available Shortcodes', 'thrive-dash' ) ?>
</h4>
<div class="tvd-relative">
<ul class="tvd-collection tvd-not-visible" id="tve-shortcode-list">
<li class="tvd-collection-item">
<div class="tve-copy-row">
<div class="tve-shortcode-input">
<div class="tvd-input-field">
<input readonly="readonly" type="text" value="[lead_email]" class="tve-copy tve_lightbox_input"/>
</div>
</div>
<div class="tve-shortcode-copy">
<a class="tve-copy-to-clipboard tve_editor_button tve_editor_button_blue" href="javascript:void(0)">
<span class="tve-copy-text"><?php echo esc_html__( 'Copy', 'thrive-dash' ) ?></span>
</a>
</div>
<div class="tvd-col tvd-s6">
<div class="tve-align-stupid-text">
<?php echo esc_html__( 'Displays the email of the person who opted in.', 'thrive-dash' ) ?>
</div>
</div>
</div>
</li>
<li class="tvd-collection-item">
<div class="tve-copy-row tvd-row tvd-collapse tvd-no-mb">
<div class="tve-shortcode-input">
<div class="tvd-input-field">
<input readonly="readonly" type="text" value="[lead_name]" class="tve-copy tve_lightbox_input"/>
</div>
</div>
<div class="tve-shortcode-copy">
<a class="tve-copy-to-clipboard tve_editor_button tve_editor_button_blue" href="javascript:void(0)">
<span class="tve-copy-text"><?php echo esc_html__( 'Copy', 'thrive-dash' ) ?></span>
</a>
</div>
<div class="tvd-col tvd-s6">
<div class="tve-align-stupid-text">
<?php echo esc_html__( 'Displays the name of the person who opted in.', 'thrive-dash' ) ?>
</div>
</div>
</div>
</li>
</ul>
</div>

View File

@@ -0,0 +1,36 @@
<td class="tvd-error-entry-api_data">
<span class="tvd-normal">
<#= item.get( 'fields_html' ) #>
</span>
</td>
<td class="tvd-error-entry-connection">
<span class="tvd-normal">
<#- item.get( 'connection_explicit' ) #>
</span>
</td>
<td class="tvd-error-entry-date">
<span class="tvd-normal">
<#- item.get( 'date' ) #>
</span>
</td>
<td class="tvd-error-entry-error_message">
<span class="tvd-normal">
<#- item.get( 'error_message' ) #>
</span>
</td>
<td class="tvd-error-entry-actions" data-log-id="<#= item.get( 'id' ) #>">
<div class="row-actions visible tvd-center-align">
<# if ( item.get( 'connection_type' ) !== 'storage' ) { #>
<span class="retry">
<span class="tvd-icon-loop2 tvd-tooltipped tvd-logs-icon tvd-logs-icon-repeat"
data-position="bottom"
data-tooltip="<?php echo esc_html__( 'Retry', 'thrive-dash' ) ?>"></span>
</span>
<# } #>
<span class="delete">
<span class="tvd-icon-trash-o tvd-tooltipped tvd-logs-icon tvd-logs-icon-delete"
data-position="bottom"
data-tooltip="<?php echo esc_html__( 'Delete', 'thrive-dash' ) ?>"></span>
</span>
</div>
</td>

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Some files were not shown because too many files have changed in this diff Show More