<?php

# PLUGIN PREVIEW BY TEXTPATTERN.INFO

if (txpinterface === 'public') {
    
register_callback('zcr_mailchimp''zemcontact.deliver');
}

/**
 * Callback hook for zem_contact_reborn to handle delivery.
 */
function zcr_mailchimp($evt$stp, &$payload)
{
    
// If using copysender, it's the 2nd time the plugin has been called so no need
    // to do anything. ZCR will continue as normal and mail out the email.
    
if ($stp === 'copysender') {
        return 
'';
    }

    
$zcrConfig = array('return_action' => 'skip');
    
$chimpConfig = array('email' => array('email' => null), 'id' => null);
    
$chimpVars = array();
    
$apiKey null;
    
$action 'lists/subscribe';

    foreach (
$payload['fields'] as $key => $value) {
        if (
$key === 'mailchimp_api_key') {
           
$apiKey $value;
        } elseif (
$key === 'mailchimp_action') {
           
$action $value;
        } elseif (
strpos($key'mailchimp_') === 0) {
            
$rawKey substr($key10); // Strip off mailchimp_ prefix

            // Optional parameter type can be specified at end of key.
            // Default to string.
            // Todo: arrays?
            
$parts explode(':'$rawKey);
            
$param $parts[0];
            
$type = (isset($parts[1])) ? $parts[1] : 's';

            switch (
$type) {
                case 
'b':
                    
$chimpConfig[$param] = (bool)$value;
                    break;
                case 
'i':
                    
$chimpConfig[$param] = (int)$value;
                    break;
                case 
's':
                default:
                    
$chimpConfig[$param] = $value;
                    break;
            }
        } elseif (
strpos($key'zcr_') === 0) {
            
$param substr($key4); // Strip off zcr_ prefix
            
$zcrConfig[$param] = $value;
        } elseif (
$key === 'list_id') {
            
$chimpConfig['id'] = $value;
        } elseif (
$key === 'email') {
            
// Don't ask. It's their spec!
            
$chimpConfig['email']['email'] = $value;
        } else {
            
$chimpVars[$key] = $value;
        }
    }

    if (
$apiKey) {
        
$chimpConfig['merge_vars'] = $chimpVars;

        
$mc = new zcr_Mailchimp($apiKey);
        
$result $mc->call($action$chimpConfig);

        
// Todo: what to do with the result?

        
if ($zcrConfig['return_action']) {
            return 
'zemcontact.' $zcrConfig['return_action'];
        }
    } else {
        
// Not for us.
        
return '';
    }
}

/**
 * Super-simple, minimum abstraction MailChimp API v2 wrapper
 *
 * Uses curl if available, falls back to file_get_contents and HTTP stream.
 * This probably has more comments than code.
 *
 * Contributors:
 * Michael Minor <me@pixelbacon.com>
 * Lorna Jane Mitchell, github.com/lornajane
 *
 * @author Drew McLellan <drew.mclellan@gmail.com>
 * @version 1.1.1
 */
class zcr_MailChimp
{
    private 
$api_key;
    private 
$api_endpoint 'https://<dc>.api.mailchimp.com/2.0';
    private 
$verify_ssl   false;

    
/**
     * Create a new instance
     * @param string $api_key Your MailChimp API key
     */
    
function __construct($api_key)
    {
        
$this->api_key $api_key;
        list(, 
$datacentre) = explode('-'$this->api_key);
        
$this->api_endpoint str_replace('<dc>'$datacentre$this->api_endpoint);
    }

    
/**
     * Call an API method. Every request needs the API key, so that is added automatically -- you don't need to pass it in.
     * @param  string $method The API method to call, e.g. 'lists/list'
     * @param  array  $args   An array of arguments to pass to the method. Will be json-encoded for you.
     * @return array          Associative array of json decoded API response.
     */
    
public function call($method$args=array(), $timeout 10)
    {
        return 
$this->makeRequest($method$args$timeout);
    }

    
/**
     * Performs the underlying HTTP request. Not very exciting
     * @param  string $method The API method to be called
     * @param  array  $args   Assoc array of parameters to be passed
     * @return array          Assoc array of decoded result
     */
    
private function makeRequest($method$args=array(), $timeout 10)
    {
        
$args['apikey'] = $this->api_key;

        
$url $this->api_endpoint.'/'.$method.'.json';

        if (
function_exists('curl_init') && function_exists('curl_setopt')){
            
$ch curl_init();
            
curl_setopt($chCURLOPT_URL$url);
            
curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            
curl_setopt($chCURLOPT_USERAGENT'PHP-MCAPI/2.0');
            
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
            
curl_setopt($chCURLOPT_TIMEOUT$timeout);
            
curl_setopt($chCURLOPT_POSTtrue);
            
curl_setopt($chCURLOPT_SSL_VERIFYPEER$this->verify_ssl);
            
curl_setopt($chCURLOPT_POSTFIELDSjson_encode($args));
            
$result curl_exec($ch);
            
curl_close($ch);
        } else {
            
$json_data json_encode($args);
            
$result    file_get_contents($urlnullstream_context_create(array(
                
'http' => array(
                    
'protocol_version' => 1.1,
                    
'user_agent'       => 'PHP-MCAPI/2.0',
                    
'method'           => 'POST',
                    
'header'           => "Content-type: application/json\r\n".
                                          
"Connection: close\r\n" .
                                          
"Content-length: " strlen($json_data) . "\r\n",
                    
'content'          => $json_data,
                ),
            )));
        }

        return 
$result json_decode($resulttrue) : false;
    }
}