Initial commit
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace FluentCrm\App\Services\CrmMigrator\Api;
|
||||
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class ActiveCampaign
|
||||
{
|
||||
protected $apiUrl = null;
|
||||
|
||||
protected $apiKey = null;
|
||||
|
||||
public function __construct($apiUrl, $apiKey = null)
|
||||
{
|
||||
$this->apiUrl = $apiUrl;
|
||||
$this->apiKey = $apiKey;
|
||||
}
|
||||
|
||||
public function default_options()
|
||||
{
|
||||
return array(
|
||||
'api_key' => $this->apiKey,
|
||||
'api_output' => 'json'
|
||||
);
|
||||
}
|
||||
|
||||
public function make_request($action, $options = array(), $method = 'GET')
|
||||
{
|
||||
/* Build request options string. */
|
||||
$request_options = $this->default_options();
|
||||
$request_options['api_action'] = $action;
|
||||
|
||||
if ($request_options['api_action'] == 'contact_edit')
|
||||
$request_options['overwrite'] = '0';
|
||||
|
||||
$request_options = http_build_query($request_options);
|
||||
$request_options .= ($method == 'GET') ? '&' . http_build_query($options) : null;
|
||||
|
||||
/* Build request URL. */
|
||||
$request_url = untrailingslashit($this->apiUrl) . '/admin/api.php?' . $request_options;
|
||||
$response = null;
|
||||
/* Execute request based on method. */
|
||||
switch ($method) {
|
||||
|
||||
case 'POST':
|
||||
$args = array(
|
||||
'body' => $options,
|
||||
'timeout' => 30
|
||||
);
|
||||
$response = wp_remote_post($request_url, $args);
|
||||
break;
|
||||
|
||||
case 'GET':
|
||||
$response = wp_remote_get($request_url, [
|
||||
'timeout' => 30
|
||||
]);
|
||||
break;
|
||||
}
|
||||
|
||||
$error = $this->maybeError($response);
|
||||
if ($error) {
|
||||
return $error;
|
||||
}
|
||||
return json_decode($response['body'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the provided API credentials.
|
||||
*
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function auth_test()
|
||||
{
|
||||
/* Build options string. */
|
||||
$request_options = $this->default_options();
|
||||
$request_options['api_action'] = 'list_paginator';
|
||||
$request_options = http_build_query($request_options);
|
||||
|
||||
/* Setup request URL. */
|
||||
$request_url = untrailingslashit($this->apiUrl) . '/admin/api.php?' . $request_options;
|
||||
|
||||
/* Execute request. */
|
||||
$response = wp_remote_get($request_url);
|
||||
|
||||
$error = $this->maybeError($response);
|
||||
if ($error) {
|
||||
return $error;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all custom list fields.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function get_custom_fields()
|
||||
{
|
||||
return $this->make_request('list_field_view', array('ids' => 'all'));
|
||||
}
|
||||
|
||||
public function getContacts($args = ['offset' => 0, 'status' => -1])
|
||||
{
|
||||
|
||||
$args = wp_parse_args(
|
||||
$args,
|
||||
array(
|
||||
'offset' => 0,
|
||||
'status' => $args['status'],
|
||||
'include' => 'contactTags,contactLists,fieldValues',
|
||||
'limit' => 100,
|
||||
'api_key' => $this->apiKey,
|
||||
)
|
||||
);
|
||||
|
||||
$subscribers = array();
|
||||
|
||||
$request = add_query_arg( $args, untrailingslashit( $this->apiUrl ) . '/api/3/contacts' );
|
||||
$response = wp_safe_remote_get( $request );
|
||||
|
||||
$error = $this->maybeError( $response );
|
||||
if ( $error ) {
|
||||
return $error;
|
||||
}
|
||||
|
||||
$response = json_decode( wp_remote_retrieve_body( $response ) );
|
||||
|
||||
if ( ! empty( $response->contacts ) ) {
|
||||
|
||||
// Base subscriber data.
|
||||
|
||||
foreach ( $response->contacts as $contact ) {
|
||||
|
||||
$subscribers[ $contact->id ] = array(
|
||||
'first_name' => $contact->{'firstName'},
|
||||
'last_name' => $contact->{'lastName'},
|
||||
'email' => $contact->{'email'},
|
||||
'phone' => $contact->{'phone'},
|
||||
'cdate' => $contact->{'cdate'},
|
||||
'ip' => $contact->{'ip'},
|
||||
'status' => 1, // @todo this should be checked based on the list membership.
|
||||
'tags' => array(),
|
||||
'lists' => array(),
|
||||
'fields' => array(),
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
// Fields.
|
||||
|
||||
if ( ! empty( $response->{'fieldValues'} ) ) {
|
||||
|
||||
foreach ( $response->{'fieldValues'} as $field ) {
|
||||
|
||||
if ( false !== strpos( $field->value, '||' ) ) {
|
||||
$type = 'checkbox';
|
||||
} else {
|
||||
$type = 'text';
|
||||
}
|
||||
|
||||
$subscribers[ $field->contact ]['fields'][] = array(
|
||||
'val' => $field->value,
|
||||
'perstag' => $field->field,
|
||||
'type' => $type,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Tags.
|
||||
|
||||
if ( ! empty( $response->{'contactTags'} ) ) {
|
||||
|
||||
foreach ( $response->{'contactTags'} as $tag ) {
|
||||
$subscribers[ $tag->contact ]['tags'][] = $tag->tag;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Lists.
|
||||
|
||||
if ( ! empty( $response->{'contactLists'} ) ) {
|
||||
|
||||
foreach ( $response->{'contactLists'} as $list ) {
|
||||
$subscribers[ $list->contact ]['lists'][] = array( 'listid' => $list->list );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $subscribers;
|
||||
|
||||
}
|
||||
|
||||
public function contactPaginator($args = ['limit' => 20, 'public' => 0])
|
||||
{
|
||||
return $this->make_request('contact_paginator', $args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all lists in the system.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function get_lists()
|
||||
{
|
||||
return $this->make_request('list_list', array('ids' => 'all'));
|
||||
}
|
||||
|
||||
public function getTags()
|
||||
{
|
||||
return $this->make_request('tags_list', array('ids' => 'all'));
|
||||
}
|
||||
|
||||
public function maybeError($response)
|
||||
{
|
||||
/* If invalid content type, API URL is invalid. */
|
||||
if (is_wp_error($response))
|
||||
return $response;
|
||||
$contentType = isset($response['headers']['content-type']) ? (string) $response['headers']['content-type'] : '';
|
||||
if (strpos($contentType, 'application/json') === false) {
|
||||
return new \WP_Error('error', 'Invalid API URL');
|
||||
}
|
||||
|
||||
if ($response['response']['code'] > 300) {
|
||||
return new \WP_Error('API_Error', $response['response']['message'], $response);
|
||||
}
|
||||
|
||||
$body = json_decode($response['body'], true);
|
||||
if (isset($body['result_code']) && $body['result_code'] == 0) {
|
||||
$message = 'Invalid API';
|
||||
return new \WP_Error('API_Error', $message, $response);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace FluentCrm\App\Services\CrmMigrator\Api;
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class ConvertKit
|
||||
{
|
||||
protected $apiUrl = 'https://api.convertkit.com/v3/';
|
||||
|
||||
protected $apiKey = null;
|
||||
|
||||
protected $apiSecret = null;
|
||||
|
||||
public function __construct( $apiKey = null, $apiSecret = null )
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
$this->apiSecret = $apiSecret;
|
||||
}
|
||||
|
||||
public function default_options()
|
||||
{
|
||||
return array(
|
||||
'api_key' => $this->apiKey
|
||||
);
|
||||
}
|
||||
|
||||
public function make_request( $action, $options = array(), $method = 'GET' )
|
||||
{
|
||||
/* Build request options string. */
|
||||
$request_options = $this->default_options();
|
||||
|
||||
$request_options = wp_parse_args($options, $request_options);
|
||||
$options_string = http_build_query( $request_options );
|
||||
|
||||
/* Execute request based on method. */
|
||||
switch ( $method ) {
|
||||
case 'POST':
|
||||
$args = array(
|
||||
'body' => json_encode($options),
|
||||
'headers' => [
|
||||
'Accept' => 'application/json',
|
||||
'Content-Type' => 'application/json'
|
||||
]
|
||||
);
|
||||
$response = wp_remote_post( $this->apiUrl.$action.'?api_key='.$this->apiKey, $args );
|
||||
break;
|
||||
|
||||
case 'GET':
|
||||
/* Build request URL. */
|
||||
$request_url = $this->apiUrl . $action.'?' . $options_string;
|
||||
$response = wp_remote_get( $request_url );
|
||||
break;
|
||||
}
|
||||
|
||||
/* If WP_Error, die. Otherwise, return decoded JSON. */
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return [
|
||||
'error' => __('API_Error', 'fluent-crm'),
|
||||
'message' => $response->get_error_message()
|
||||
];
|
||||
} else {
|
||||
return json_decode( $response['body'], true );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the provided API credentials.
|
||||
*
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function auth_test()
|
||||
{
|
||||
return $this->make_request('forms', [], 'GET');
|
||||
}
|
||||
|
||||
|
||||
public function subscribe($formId, $data)
|
||||
{
|
||||
$response = $this->make_request('forms/'.$formId.'/subscribe', $data, 'POST');
|
||||
if(!empty($response['error'])) {
|
||||
return new \WP_Error('api_error', $response['message']);
|
||||
}
|
||||
|
||||
return $response['subscription'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all Forms in the system.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getLists()
|
||||
{
|
||||
$response = $this->make_request( 'forms', array(), 'GET' );
|
||||
if(empty($response['error'])) {
|
||||
return $response['forms'];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all Tags in the system.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getTags()
|
||||
{
|
||||
$response = $this->make_request( 'tags', array(), 'GET' );
|
||||
if(empty($response['error'])) {
|
||||
return $response['tags'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getCustomFields()
|
||||
{
|
||||
$response = $this->make_request( 'custom_fields', array(), 'GET' );
|
||||
if(empty($response['error'])) {
|
||||
return $response['custom_fields'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getSubscribers($args = [])
|
||||
{
|
||||
$args['api_secret'] = $this->apiSecret;
|
||||
$response = $this->make_request( 'subscribers', $args, 'GET' );
|
||||
|
||||
if(empty($response['error'])) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
new \WP_Error('api_error', $response['message']);
|
||||
}
|
||||
|
||||
public function getTagSubscribers($tagId, $args = [])
|
||||
{
|
||||
$args['api_secret'] = $this->apiSecret;
|
||||
$response = $this->make_request( 'tags/'.$tagId.'/subscriptions', $args, 'GET' );
|
||||
|
||||
if(empty($response['error'])) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
new \WP_Error('api_error', $response['message']);
|
||||
}
|
||||
|
||||
public function getSubscriberTags($contactId)
|
||||
{
|
||||
$args['api_secret'] = $this->apiSecret;
|
||||
$response = $this->make_request( 'subscribers/'.$contactId.'/tags', $args, 'GET' );
|
||||
|
||||
if(empty($response['error'])) {
|
||||
return $response['tags'];
|
||||
}
|
||||
|
||||
new \WP_Error('api_error', $response['message']);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace FluentCrm\App\Services\CrmMigrator\Api;
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class Drip
|
||||
{
|
||||
protected $apiKey = null;
|
||||
protected $accountId = null;
|
||||
|
||||
private $apiUrl = "https://api.getdrip.com/v2/";
|
||||
|
||||
public function __construct($apiKey = null, $accountId = null)
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
$this->accountId = $accountId;
|
||||
}
|
||||
|
||||
public function make_request($endpoint = '', $data = array(), $method = 'POST')
|
||||
{
|
||||
$data['api_key'] = $this->apiKey;
|
||||
|
||||
$args = array(
|
||||
'method' => $method,
|
||||
'headers' => array(
|
||||
'content-type' => 'application/vnd.api+json',
|
||||
'Authorization' => 'Basic ' . base64_encode($this->apiKey)
|
||||
),
|
||||
'body' => ($method == 'POST') ? wp_json_encode($data) : $data
|
||||
);
|
||||
|
||||
if ($method == 'POST') {
|
||||
$response = wp_remote_post($this->apiUrl . $endpoint, $args);
|
||||
} else {
|
||||
$response = wp_remote_get($this->apiUrl . $endpoint, $args);
|
||||
}
|
||||
/* If WP_Error, die. Otherwise, return decoded JSON. */
|
||||
if (is_wp_error($response)) {
|
||||
return $response;
|
||||
}
|
||||
return json_decode($response['body'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the provided API credentials.
|
||||
*
|
||||
* @access public
|
||||
* @return array|\WP_Error
|
||||
*/
|
||||
public function auth_test()
|
||||
{
|
||||
return $this->make_request('accounts', [], 'GET');
|
||||
}
|
||||
|
||||
public function sendAccountItems($endpoint, $args = [])
|
||||
{
|
||||
return $this->make_request($this->accountId . '/'.$endpoint, $args, 'GET');
|
||||
}
|
||||
|
||||
public function addContact($contact)
|
||||
{
|
||||
$accountId = $this->accountId;
|
||||
$contactObj = [
|
||||
'subscribers' => [$contact]
|
||||
];
|
||||
$response = $this->make_request($accountId . '/subscribers', $contactObj, 'POST');
|
||||
|
||||
if (!empty($response['subscribers'])) {
|
||||
return $response;
|
||||
}
|
||||
$message = 'API Eroror';
|
||||
|
||||
if (is_wp_error($response)) {
|
||||
$message = $response->get_error_message();
|
||||
}
|
||||
|
||||
return new \WP_Error('error', $message);
|
||||
}
|
||||
|
||||
public function add_note($contact_id, $email, $note)
|
||||
{
|
||||
return $this->make_request([
|
||||
'action' => 'contact_add_note',
|
||||
'value' => (object)[
|
||||
'contact_id' => $contact_id,
|
||||
'email' => $email,
|
||||
'note' => $note
|
||||
],
|
||||
], 'POST');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
<?php
|
||||
|
||||
namespace FluentCrm\App\Services\CrmMigrator\Api;
|
||||
|
||||
/**
|
||||
* Super-simple, minimum abstraction MailChimp API v3 wrapper
|
||||
* MailChimp API v3: http://developer.mailchimp.com
|
||||
* This wrapper: https://github.com/drewm/mailchimp-api
|
||||
*
|
||||
* @author Drew McLellan <drew.mclellan@gmail.com>
|
||||
* @version 2.4
|
||||
*/
|
||||
class MailChimp
|
||||
{
|
||||
private $api_key;
|
||||
private $api_endpoint = 'https://<dc>.api.mailchimp.com/3.0';
|
||||
|
||||
const TIMEOUT = 10;
|
||||
|
||||
/* SSL Verification
|
||||
Read before disabling:
|
||||
http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
|
||||
*/
|
||||
public $verify_ssl = true;
|
||||
|
||||
private $request_successful = false;
|
||||
private $last_error = '';
|
||||
private $last_response = array();
|
||||
private $last_request = array();
|
||||
|
||||
/**
|
||||
* Create a new instance
|
||||
* @param string $api_key Your MailChimp API key
|
||||
* @param string $api_endpoint Optional custom API endpoint
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function __construct($api_key, $api_endpoint = null)
|
||||
{
|
||||
$this->api_key = $api_key;
|
||||
|
||||
if ($api_endpoint === null) {
|
||||
if (strpos($this->api_key, '-') === false) {
|
||||
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
|
||||
throw new \Exception("Invalid MailChimp API key `{$api_key}` supplied.");
|
||||
}
|
||||
list(, $data_center) = explode('-', $this->api_key);
|
||||
$this->api_endpoint = str_replace('<dc>', $data_center, $this->api_endpoint);
|
||||
} else {
|
||||
$this->api_endpoint = $api_endpoint;
|
||||
}
|
||||
|
||||
$this->last_response = array('headers' => null, 'body' => null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string The url to the API endpoint
|
||||
*/
|
||||
public function getApiEndpoint()
|
||||
{
|
||||
return $this->api_endpoint;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert an email address into a 'subscriber hash' for identifying the subscriber in a method URL
|
||||
* @param string $email The subscriber's email address
|
||||
* @return string Hashed version of the input
|
||||
*/
|
||||
public function subscriberHash($email)
|
||||
{
|
||||
return md5(strtolower($email));
|
||||
}
|
||||
|
||||
/**
|
||||
* Was the last request successful?
|
||||
* @return bool True for success, false for failure
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
return $this->request_successful;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last error returned by either the network transport, or by the API.
|
||||
* If something didn't work, this should contain the string describing the problem.
|
||||
* @return string|false describing the error
|
||||
*/
|
||||
public function getLastError()
|
||||
{
|
||||
return $this->last_error ?: false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array containing the HTTP headers and the body of the API response.
|
||||
* @return array Assoc array with keys 'headers' and 'body'
|
||||
*/
|
||||
public function getLastResponse()
|
||||
{
|
||||
return $this->last_response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an array containing the HTTP headers and the body of the API request.
|
||||
* @return array Assoc array
|
||||
*/
|
||||
public function getLastRequest()
|
||||
{
|
||||
return $this->last_request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an HTTP DELETE request - for deleting data
|
||||
* @param string $method URL of the API request method
|
||||
* @param array $args Assoc array of arguments (if any)
|
||||
* @param int $timeout Timeout limit for request in seconds
|
||||
* @return array|false Assoc array of API response, decoded from JSON
|
||||
*/
|
||||
public function delete($method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
return $this->makeRequest('delete', $method, $args, $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an HTTP GET request - for retrieving data
|
||||
* @param string $method URL of the API request method
|
||||
* @param array $args Assoc array of arguments (usually your data)
|
||||
* @param int $timeout Timeout limit for request in seconds
|
||||
* @return array|false Assoc array of API response, decoded from JSON
|
||||
*/
|
||||
public function get($method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
return $this->makeRequest('get', $method, $args, $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an HTTP PATCH request - for performing partial updates
|
||||
* @param string $method URL of the API request method
|
||||
* @param array $args Assoc array of arguments (usually your data)
|
||||
* @param int $timeout Timeout limit for request in seconds
|
||||
* @return array|false Assoc array of API response, decoded from JSON
|
||||
*/
|
||||
public function patch($method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
return $this->makeRequest('patch', $method, $args, $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an HTTP POST request - for creating and updating items
|
||||
* @param string $method URL of the API request method
|
||||
* @param array $args Assoc array of arguments (usually your data)
|
||||
* @param int $timeout Timeout limit for request in seconds
|
||||
* @return array|false Assoc array of API response, decoded from JSON
|
||||
*/
|
||||
public function post($method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
return $this->makeRequest('post', $method, $args, $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make an HTTP PUT request - for creating new items
|
||||
* @param string $method URL of the API request method
|
||||
* @param array $args Assoc array of arguments (usually your data)
|
||||
* @param int $timeout Timeout limit for request in seconds
|
||||
* @return array|false Assoc array of API response, decoded from JSON
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function put($method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
return $this->makeRequest('put', $method, $args, $timeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the underlying HTTP request. Not very exciting.
|
||||
* @param string $http_verb The HTTP verb to use: get, post, put, patch, delete
|
||||
* @param string $method The API method to be called
|
||||
* @param array $args Assoc array of parameters to be passed
|
||||
* @param int $timeout
|
||||
* @return array|false Assoc array of decoded result
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function makeRequest($http_verb, $method, $args = array(), $timeout = self::TIMEOUT)
|
||||
{
|
||||
if (!function_exists('curl_init') || !function_exists('curl_setopt')) {
|
||||
throw new \Exception("cURL support is required, but can't be found.");
|
||||
}
|
||||
|
||||
$url = $this->api_endpoint . '/' . $method;
|
||||
|
||||
$response = $this->prepareStateForRequest($http_verb, $method, $url, $timeout);
|
||||
|
||||
$httpHeader = array(
|
||||
'Accept: application/vnd.api+json',
|
||||
'Content-Type: application/vnd.api+json',
|
||||
'Authorization: apikey ' . $this->api_key
|
||||
);
|
||||
|
||||
if (isset($args["language"])) {
|
||||
$httpHeader[] = "Accept-Language: " . $args["language"];
|
||||
}
|
||||
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_init
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_exec
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_close
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_getinfo
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_error
|
||||
// PluginCheck:ignoreFile
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
|
||||
curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)');
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_VERBOSE, true);
|
||||
curl_setopt($ch, CURLOPT_HEADER, true);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
|
||||
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
|
||||
curl_setopt($ch, CURLOPT_ENCODING, '');
|
||||
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
|
||||
|
||||
switch ($http_verb) {
|
||||
case 'post':
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
$this->attachRequestPayload($ch, $args);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
$query = http_build_query($args, '', '&');
|
||||
curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
|
||||
break;
|
||||
|
||||
case 'patch':
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
|
||||
$this->attachRequestPayload($ch, $args);
|
||||
break;
|
||||
|
||||
case 'put':
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
|
||||
$this->attachRequestPayload($ch, $args);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
$responseContent = curl_exec($ch);
|
||||
$response['headers'] = curl_getinfo($ch);
|
||||
$response = $this->setResponseState($response, $responseContent, $ch);
|
||||
$formattedResponse = $this->formatResponse($response);
|
||||
|
||||
curl_close($ch);
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_init
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_exec
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_close
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_getinfo
|
||||
// phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_error
|
||||
|
||||
$this->determineSuccess($response, $formattedResponse, $timeout);
|
||||
|
||||
return $formattedResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $http_verb
|
||||
* @param string $method
|
||||
* @param string $url
|
||||
* @param integer $timeout
|
||||
*/
|
||||
private function prepareStateForRequest($http_verb, $method, $url, $timeout)
|
||||
{
|
||||
$this->last_error = '';
|
||||
|
||||
$this->request_successful = false;
|
||||
|
||||
$this->last_response = array(
|
||||
'headers' => null, // array of details from curl_getinfo()
|
||||
'httpHeaders' => null, // array of HTTP headers
|
||||
'body' => null // content of the response
|
||||
);
|
||||
|
||||
$this->last_request = array(
|
||||
'method' => $http_verb,
|
||||
'path' => $method,
|
||||
'url' => $url,
|
||||
'body' => '',
|
||||
'timeout' => $timeout,
|
||||
);
|
||||
|
||||
return $this->last_response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP headers as an array of header-name => header-value pairs.
|
||||
*
|
||||
* The "Link" header is parsed into an associative array based on the
|
||||
* rel names it contains. The original value is available under
|
||||
* the "_raw" key.
|
||||
*
|
||||
* @param string $headersAsString
|
||||
* @return array
|
||||
*/
|
||||
private function getHeadersAsArray($headersAsString)
|
||||
{
|
||||
$headers = array();
|
||||
|
||||
foreach (explode("\r\n", $headersAsString) as $i => $line) {
|
||||
if ($i === 0) { // HTTP code
|
||||
continue;
|
||||
}
|
||||
|
||||
$line = trim($line);
|
||||
if (empty($line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
list($key, $value) = explode(': ', $line);
|
||||
|
||||
if ($key == 'Link') {
|
||||
$value = array_merge(
|
||||
array('_raw' => $value),
|
||||
$this->getLinkHeaderAsArray($value)
|
||||
);
|
||||
}
|
||||
|
||||
$headers[$key] = $value;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all rel => URL pairs from the provided Link header value
|
||||
*
|
||||
* Mailchimp only implements the URI reference and relation type from
|
||||
* RFC 5988, so the value of the header is something like this:
|
||||
*
|
||||
* 'https://us13.api.mailchimp.com/schema/3.0/Lists/Instance.json; rel="describedBy", <https://us13.admin.mailchimp.com/lists/members/?id=XXXX>; rel="dashboard"'
|
||||
*
|
||||
* @param string $linkHeaderAsString
|
||||
* @return array
|
||||
*/
|
||||
private function getLinkHeaderAsArray($linkHeaderAsString)
|
||||
{
|
||||
$urls = array();
|
||||
|
||||
if (preg_match_all('/<(.*?)>\s*;\s*rel="(.*?)"\s*/', $linkHeaderAsString, $matches)) {
|
||||
foreach ($matches[2] as $i => $relName) {
|
||||
$urls[$relName] = $matches[1][$i];
|
||||
}
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the data and attach it to the request
|
||||
* @param resource $ch cURL session handle, used by reference
|
||||
* @param array $data Assoc array of data to attach
|
||||
*/
|
||||
private function attachRequestPayload(&$ch, $data)
|
||||
{
|
||||
$encoded = json_encode($data);
|
||||
$this->last_request['body'] = $encoded;
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the response and format any error messages for debugging
|
||||
* @param array $response The response from the curl request
|
||||
* @return array|false The JSON decoded into an array
|
||||
*/
|
||||
private function formatResponse($response)
|
||||
{
|
||||
$this->last_response = $response;
|
||||
|
||||
if (!empty($response['body'])) {
|
||||
return json_decode($response['body'], true);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do post-request formatting and setting state from the response
|
||||
* @param array $response The response from the curl request
|
||||
* @param string $responseContent The body of the response from the curl request
|
||||
* * @return array The modified response
|
||||
*/
|
||||
private function setResponseState($response, $responseContent, $ch)
|
||||
{
|
||||
if ($responseContent === false) {
|
||||
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_error
|
||||
$this->last_error = curl_error($ch);
|
||||
} else {
|
||||
|
||||
$headerSize = $response['headers']['header_size'];
|
||||
|
||||
$response['httpHeaders'] = $this->getHeadersAsArray(substr($responseContent, 0, $headerSize));
|
||||
$response['body'] = substr($responseContent, $headerSize);
|
||||
|
||||
if (isset($response['headers']['request_header'])) {
|
||||
$this->last_request['headers'] = $response['headers']['request_header'];
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the response was successful or a failure. If it failed, store the error.
|
||||
* @param array $response The response from the curl request
|
||||
* @param array|false $formattedResponse The response body payload from the curl request
|
||||
* @param int $timeout The timeout supplied to the curl request.
|
||||
* @return bool If the request was successful
|
||||
*/
|
||||
private function determineSuccess($response, $formattedResponse, $timeout)
|
||||
{
|
||||
$status = $this->findHTTPStatus($response, $formattedResponse);
|
||||
|
||||
if ($status >= 200 && $status <= 299) {
|
||||
$this->request_successful = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset($formattedResponse['detail'])) {
|
||||
$this->last_error = sprintf('%d: %s', $formattedResponse['status'], $formattedResponse['detail']);
|
||||
return false;
|
||||
}
|
||||
|
||||
if( $timeout > 0 && $response['headers'] && $response['headers']['total_time'] >= $timeout ) {
|
||||
$this->last_error = sprintf('Request timed out after %f seconds.', $response['headers']['total_time'] );
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the HTTP status code from the headers or API response body
|
||||
* @param array $response The response from the curl request
|
||||
* @param array|false $formattedResponse The response body payload from the curl request
|
||||
* @return int HTTP status code
|
||||
*/
|
||||
private function findHTTPStatus($response, $formattedResponse)
|
||||
{
|
||||
if (!empty($response['headers']) && isset($response['headers']['http_code'])) {
|
||||
return (int) $response['headers']['http_code'];
|
||||
}
|
||||
|
||||
if (!empty($response['body']) && isset($formattedResponse['status'])) {
|
||||
return (int) $formattedResponse['status'];
|
||||
}
|
||||
|
||||
return 418;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace FluentCrm\App\Services\CrmMigrator\Api;
|
||||
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit; // Exit if accessed directly.
|
||||
}
|
||||
|
||||
class MailerLite
|
||||
{
|
||||
protected $apiUrl = 'https://api.mailerlite.com/api/v2/';
|
||||
|
||||
protected $apiKey = null;
|
||||
|
||||
protected $apiSecret = null;
|
||||
|
||||
public function __construct($apiKey = null)
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
}
|
||||
|
||||
public function default_options()
|
||||
{
|
||||
return [
|
||||
'User-Agent' => 'MailerLite PHP SDK/2.0',
|
||||
'X-MailerLite-ApiKey' => $this->apiKey,
|
||||
'Content-Type' => 'application/json'
|
||||
];
|
||||
}
|
||||
|
||||
public function make_request($action, $options = array(), $method = 'GET')
|
||||
{
|
||||
|
||||
$headers = $this->default_options();
|
||||
$endpointUrl = $this->apiUrl . $action;
|
||||
$args = [
|
||||
'headers' => $headers
|
||||
];
|
||||
|
||||
if ($options && $method == 'POST') {
|
||||
$args['body'] = \json_encode($options);
|
||||
} else if($method == 'GET' && $options) {
|
||||
$endpointUrl = add_query_arg($options, $endpointUrl);
|
||||
}
|
||||
|
||||
/* Execute request based on method. */
|
||||
switch ($method) {
|
||||
case 'POST':
|
||||
$response = wp_remote_post($endpointUrl, $args);
|
||||
break;
|
||||
|
||||
case 'GET':
|
||||
$response = wp_remote_get($endpointUrl, $args);
|
||||
break;
|
||||
}
|
||||
|
||||
/* If WP_Error, die. Otherwise, return decoded JSON. */
|
||||
if (is_wp_error($response)) {
|
||||
return new \WP_Error('API_Error', $response->get_error_message());
|
||||
} else if ($response && $response['response']['code'] >= 300) {
|
||||
return new \WP_Error('API_Error', $response['response']['message']);
|
||||
}
|
||||
return json_decode($response['body'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the provided API credentials.
|
||||
*
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function auth_test()
|
||||
{
|
||||
return $this->make_request('groups', [], 'GET');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all Forms in the system.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function getGroups()
|
||||
{
|
||||
return $this->make_request('groups', array(), 'GET');
|
||||
}
|
||||
|
||||
public function getGroupSubscribers($groupId, $args = [])
|
||||
{
|
||||
return $this->make_request('groups/' . $groupId . '/subscribers', $args, 'GET');
|
||||
}
|
||||
|
||||
public function getContactCountByGroup($groupId)
|
||||
{
|
||||
$result = $this->make_request('groups/' . $groupId . '/subscribers/count', array(), 'GET');
|
||||
|
||||
if (is_wp_error($result)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $result['count'];
|
||||
}
|
||||
|
||||
public function getCustomFields()
|
||||
{
|
||||
return $this->make_request('fields', array(), 'GET');
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user