View source
<?php
class cc {
var $http_user_agent = 'CC-Drupal 2.0';
var $api_key = '';
var $api_username = '';
var $api_password = '';
var $api_url = 'https://api.constantcontact.com';
var $api_uri = '';
var $last_error = '';
var $action_type = 'ACTION_BY_CUSTOMER';
var $list_meta_data;
var $member_meta_data;
var $http_host;
var $http_port;
var $http_url_bits;
var $http_request_timeout = 30;
var $http_user;
var $http_pass;
var $http_content_type;
var $http_default_content_type = 'text/html';
var $http_response_code;
var $http_response;
var $http_response_body;
var $http_request;
var $http_method;
var $http_linebreak = "\r\n";
var $http_request_headers = array();
var $http_response_headers = array();
var $xml_known_encodings = array(
'UTF-8',
'US-ASCII',
'ISO-8859-1',
);
function cc($api_username, $api_password, $api_key) {
$this->api_username = $api_username;
$this->api_password = $api_password;
$this->api_key = $api_key;
$this->api_url .= '/ws/customers/' . rawurlencode($api_username) . '/';
$this->api_uri .= '/ws/customers/' . urlencode($api_username) . '/';
$this->http_user = $api_key . "%" . $api_username;
$this->http_pass = $api_password;
$this
->http_set_content_type($this->http_default_content_type);
}
function set_action_type($action_type = 'customer') {
$this->action_type = strtolower($action_type) == 'customer' ? 'ACTION_BY_CUSTOMER' : 'ACTION_BY_CONTACT';
}
function load_url($action = '', $method = 'get', $params = array(), $expected_http_code = 200) {
$method = "http_{$method}";
if (!method_exists($this, $method)) {
$this->last_error = "{$method} method does not exist";
return false;
}
$this
->{$method}($this->api_url . $action, $params);
if (intval($expected_http_code) === $this->http_response_code) {
if ($this->http_content_type) {
return $this
->xml_to_array($this->http_response_body);
}
else {
return $this->http_response_body;
}
}
else {
$this->last_error = "Invalid status code {$this->http_response_code}";
return false;
}
}
function output($content) {
print_r($content);
}
function get_service_description() {
$res = $this
->load_url();
return $res;
}
function get_lists($action = 'lists', $exclude = 3) {
$xml = $this
->load_url($action);
if (!$xml) {
return false;
}
$lists = array();
$_lists = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'first') {
$this->list_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->list_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->list_meta_data->next_page = '';
}
elseif (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'next') {
$this->list_meta_data->next_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->list_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->list_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['4_attr']['href']);
}
if (is_array($_lists) && count($_lists) > 3) {
if ($exclude) {
$_lists = array_slice($_lists, $exclude);
}
if (isset($_lists[0]['link_attr']['href'])) {
foreach ($_lists as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$list = array(
'id' => $id,
'Name' => $v['content']['ContactList']['Name'],
'ShortName' => $v['content']['ContactList']['ShortName'],
);
if (isset($v['content']['ContactList']['OptInDefault'])) {
$list['OptInDefault'] = $v['content']['ContactList']['OptInDefault'];
}
if (isset($v['content']['ContactList']['SortOrder'])) {
$list['SortOrder'] = $v['content']['ContactList']['SortOrder'];
}
$lists[] = $list;
}
}
else {
$id = $this
->get_id_from_link($_lists['link_attr']['href']);
$list = array(
'id' => $id,
'Name' => $_lists['content']['ContactList']['Name'],
'ShortName' => $_lists['content']['ContactList']['ShortName'],
);
if (isset($_lists['content']['ContactList']['OptInDefault'])) {
$list['OptInDefault'] = $_lists['content']['ContactList']['OptInDefault'];
}
if (isset($_lists['content']['ContactList']['SortOrder'])) {
$list['SortOrder'] = $_lists['content']['ContactList']['SortOrder'];
}
$lists[] = $list;
}
}
return $lists;
}
function get_list($listid) {
$xml = $this
->load_url("lists/{$listid}");
if (!$xml) {
return false;
}
$list = false;
$_list = isset($xml['entry']) ? $xml['entry'] : false;
if (is_array($_list)) {
$id = $this
->get_id_from_link($_list['link_attr']['href']);
$list = array(
'id' => $id,
'Name' => $_list['content']['ContactList']['Name'],
'ShortName' => $v['content']['ContactList']['ShortName'],
'OptInDefault' => $_list['content']['ContactList']['OptInDefault'],
'SortOrder' => $_list['content']['ContactList']['SortOrder'],
);
}
return $list;
}
function delete_list($listid) {
$this
->http_set_content_type('text/html');
$this
->load_url("lists/{$listid}", 'delete', array(), 204);
if (intval($this->http_response_code) === 204) {
return true;
}
return false;
}
function update_list($id, $name, $default = "false") {
$url = $this
->get_list_url($id);
$xml_data = '
<entry xmlns="http://www.w3.org/2005/Atom">
<id>' . $url . '</id>
<title type="text">' . $name . '</title>
<author />
<updated>2008-04-16T18:39:35.710Z</updated>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/"
id="' . $url . '">
<OptInDefault>' . $default . '</OptInDefault>
<Name>' . $name . '</Name>
<ShortName>' . $name . '</ShortName>
</ContactList>
</content>
<link href="/ws/customers/' . $this->api_username . '/lists/' . $id . '" rel="update" />
</entry>
';
$this
->http_set_content_type('application/atom+xml');
$xml = $this
->load_url("lists/{$id}", 'put', $xml_data, 204);
if (intval($this->http_response_code) === 204) {
return true;
}
return false;
}
function create_list($name, $default = "false", $sort_order = 99) {
$xml_post = '<entry xmlns="http://www.w3.org/2005/Atom">
<id>data:,</id>
<title/>
<author/>
<updated>2008-04-16</updated>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/">
<OptInDefault>' . $default . '</OptInDefault>
<Name>' . $name . '</Name>
<SortOrder>' . $sort_order . '</SortOrder>
</ContactList>
</content>
</entry>';
$this
->http_set_content_type('application/atom+xml');
$xml = $this
->load_url("lists", 'post', $xml_post, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function get_list_url($id, $full_address = true) {
if ($full_address) {
$_url = str_replace('https:', 'http:', $this->api_url . "lists");
}
else {
$_url = $this->api_uri . "lists";
}
return "{$_url}/{$id}";
}
function get_http_api_url() {
return str_replace('https:', 'http:', $this->api_url);
}
function get_list_members($listid, $action = 'members') {
$xml = $this
->load_url("lists/{$listid}/{$action}");
if (!$xml) {
return false;
}
$contacts = array();
$_members = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'first') {
$this->member_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->member_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->member_meta_data->next_page = '';
}
elseif (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'next') {
$this->member_meta_data->next_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->member_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->member_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['4_attr']['href']);
}
if (is_array($_members)) {
if (isset($_members[0]['link_attr']['href'])) {
foreach ($_members as $k => $v) {
$EmailAddress = $v['content']['ContactListMember']['EmailAddress'];
$Name = $v['content']['ContactListMember']['Name'];
$id = $this
->get_id_from_link($v['link_attr']['href']);
$contact = array(
'id' => $id,
'EmailAddress' => $EmailAddress,
'Name' => $Name,
);
$contacts[] = $contact;
}
}
else {
$EmailAddress = $_members['content']['ContactListMember']['EmailAddress'];
$Name = $_members['content']['ContactListMember']['Name'];
$id = $this
->get_id_from_link($_members['link_attr']['href']);
$contact = array(
'id' => $id,
'EmailAddress' => $EmailAddress,
'Name' => $Name,
);
$contacts[] = $contact;
}
}
return $contacts;
}
function create_contact($email, $lists = array(), $additional_fields = array()) {
$lists_url = str_replace('https:', 'http:', $this->api_url . "lists");
$xml_post = '
<entry xmlns="http://www.w3.org/2005/Atom">
<title type="text"> </title>
<updated>2008-07-23T14:21:06.407Z</updated>
<author></author>
<id>data:,none</id>
<summary type="text">Contact</summary>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/">
<EmailAddress>' . $email . '</EmailAddress>
<OptInSource>' . $this->action_type . '</OptInSource>
';
if ($additional_fields) {
foreach ($additional_fields as $field => $value) {
$xml_post .= "<{$field}>{$value}</{$field}>\n";
}
}
$xml_post .= '<ContactLists>';
if ($lists) {
if (is_array($lists)) {
foreach ($lists as $k => $id) {
$xml_post .= '<ContactList id="' . $lists_url . '/' . $id . '" />';
}
}
else {
$xml_post .= '<ContactList id="' . $lists_url . '/' . $lists . '" />';
}
}
$xml_post .= '</ContactLists>';
$xml_post .= '
</Contact>
</content>
</entry>';
$this
->http_set_content_type('application/atom+xml');
$xml = $this
->load_url("contacts", 'post', $xml_post, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function update_contact($id, $email, $lists = array(), $additional_fields = array()) {
$_url = str_replace('https:', 'http:', $this->api_url . "contacts");
$url = "{$_url}/{$id}";
$xml_data = '<entry xmlns="http://www.w3.org/2005/Atom">
<id>' . $url . '</id>
<title type="text">Contact: ' . $email . '</title>
<updated>2008-04-25T19:29:06.096Z</updated>
<author></author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="' . $url . '">
<EmailAddress>' . $email . '</EmailAddress>
<OptInSource>' . $this->action_type . '</OptInSource>
';
if ($additional_fields) {
foreach ($additional_fields as $field => $value) {
$xml_data .= "<{$field}>{$value}</{$field}>\n";
}
}
$xml_data .= "<ContactLists>\n";
if ($lists) {
if (is_array($lists)) {
foreach ($lists as $k => $list_id) {
$xml_data .= '<ContactList id="' . $this
->get_list_url($list_id) . '"></ContactList>';
}
}
else {
$xml_data .= '<ContactList id="' . $this
->get_list_url($list_id) . '"></ContactList>';
}
}
$xml_data .= "</ContactLists>\n";
$xml_data .= '
</Contact>
</content>
</entry>
';
$this
->http_set_content_type('application/atom+xml');
$this
->load_url("contacts/{$id}", 'put', $xml_data, 204);
if (intval($this->http_response_code) === 204) {
return true;
}
return false;
}
function get_contacts($action = 'contacts') {
$xml = $this
->load_url($action);
if (!$xml) {
return false;
}
$contacts = array();
$_contacts = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'first') {
$this->contact_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->contact_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->contact_meta_data->next_page = '';
}
elseif (isset($xml['feed']['link']['2_attr']['rel']) && $xml['feed']['link']['2_attr']['rel'] == 'next') {
$this->contact_meta_data->next_page = $this
->get_id_from_link($xml['feed']['link']['2_attr']['href']);
$this->contact_meta_data->current_page = $this
->get_id_from_link($xml['feed']['link']['3_attr']['href']);
$this->contact_meta_data->first_page = $this
->get_id_from_link($xml['feed']['link']['4_attr']['href']);
}
if (is_array($_contacts)) {
if (isset($_contacts[0]['link_attr']['href'])) {
foreach ($_contacts as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$contact = $v['content']['Contact'];
$contact['id'] = $id;
$contacts[] = $contact;
}
}
else {
$id = $this
->get_id_from_link($_contacts['link_attr']['href']);
$contact = $_contacts['content']['Contact'];
$contact['id'] = $id;
$contacts[] = $contact;
}
}
return $contacts;
}
function get_contact($id) {
$xml = $this
->load_url("contacts/{$id}");
if (!$xml) {
return false;
}
$contact = false;
$_contact = isset($xml['entry']) ? $xml['entry'] : false;
if (is_array($_contact)) {
$id = $this
->get_id_from_link($_contact['link_attr']['href']);
$contact = $_contact['content']['Contact'];
if (isset($_contact['content']['Contact']['ContactLists']['ContactList'])) {
$_lists = $_contact['content']['Contact']['ContactLists']['ContactList'];
unset($_lists['0_attr']);
unset($_lists['ContactList_attr']);
}
else {
$_lists = false;
}
$lists = array();
if (is_array($_lists) && count($_lists) > 0) {
unset($_lists['id']);
if (isset($_lists['link_attr']['href'])) {
$list_id = $this
->get_id_from_link($_lists['link_attr']['href']);
$lists[$list_id] = $list_id;
}
else {
foreach ($_lists as $k => $v) {
if (isset($v['link_attr']['href'])) {
$list_id = $this
->get_id_from_link($v['link_attr']['href']);
$lists[$list_id] = $list_id;
}
}
}
unset($contact['ContactLists']);
}
$contact['lists'] = $lists;
$contact['id'] = $id;
}
return $contact;
}
function query_contacts($email) {
$xml = $this
->load_url('contacts?email=' . strtolower(urlencode($email)));
if (!$xml) {
return false;
}
$contact = false;
$_contact = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (is_array($_contact)) {
$id = $this
->get_id_from_link($_contact['link_attr']['href']);
$contact = $_contact['content']['Contact'];
$contact['id'] = $id;
}
return $contact;
}
function delete_contact($id) {
$this
->http_set_content_type('text/html');
$this
->load_url("contacts/{$id}", 'delete', array(), 204);
if (intval($this->http_response_code) === 204) {
return true;
}
return false;
}
function download_activity_file($filename) {
$this
->http_set_content_type(NULL);
$this
->load_url("activities/{$filename}", 'get');
return $this->http_response_body;
}
function get_activity($id) {
$xml = $this
->load_url("activities/{$id}");
if (!$xml) {
return false;
}
$_activity = isset($xml['entry']) ? $xml['entry'] : false;
$activity = $_activity['content']['Activity'];
$activity['id'] = $id;
$activity['FileName'] = $this
->get_id_from_link($activity['FileName']);
return $activity;
}
function get_activities($action = 'activities') {
$xml = $this
->load_url($action);
if (!$xml) {
return false;
}
$activities = array();
$_activities = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (is_array($_activities)) {
if (isset($_activities[0]['link_attr']['href'])) {
foreach ($_activities as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$activity = $v['content']['Activity'];
$activity['id'] = $id;
$activities[] = $activity;
}
}
else {
$id = $this
->get_id_from_link($_activities['link_attr']['href']);
$activity = $_activities['content']['Activity'];
$activity['id'] = $id;
$activities[] = $activity;
}
}
return $activities;
}
function clear_contacts($lists) {
$params['activityType'] = 'CLEAR_CONTACTS_FROM_LISTS';
$lists_string = '';
if (is_array($lists)) {
foreach ($lists as $id) {
$params['lists'][] = $this
->get_list_url($id);
}
}
$this
->http_set_content_type('application/x-www-form-urlencoded');
$this
->load_url("activities", 'post', $params, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function export_contacts($list_id, $export_type = 'CSV', $columns = array()) {
if (!is_array($columns) || !count($columns)) {
$columns = array(
'FIRST NAME',
'MIDDLE NAME',
'LAST NAME',
'JOB TITLE',
'COMPANY NAME',
'WORK PHONE',
'HOME PHONE',
'ADDRESS LINE 1',
'ADDRESS LINE 2',
'ADDRESS LINE 3',
'CITY, STATE',
'STATE/PROVINCE (US/CANADA)',
'COUNTRY',
'POSTAL CODE',
'SUB POSTAL CODE',
);
}
$params['activityType'] = 'EXPORT_CONTACTS';
$params['fileType'] = 'CSV';
$params['exportOptDate'] = 'true';
$params['exportOptSource'] = 'true';
$params['exportListName'] = 'false';
$params['sortBy'] = 'DATE_DESC';
$params['columns'] = $columns;
$params['listId'] = $this
->get_list_url($list_id);
$this
->http_set_content_type('application/x-www-form-urlencoded');
$this
->load_url("activities", 'post', $params, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function create_contacts($contacts, $lists) {
$params['activityType'] = 'SV_ADD';
if (is_array($contacts) && count($contacts) > 0) {
$fieldnames = array_keys($contacts[0]);
$contacts = array_values($contacts);
$contacts_string = '';
foreach ($contacts as $k => $contact) {
foreach ($fieldnames as $k => $fieldname) {
if (isset($contact[$fieldname]) || is_null($contact[$fieldname])) {
$contacts_string .= $contact[$fieldname] . "{$this->http_linebreak}";
}
else {
$this->last_error = 'contacts array is not formatted correctly, please ensure all contact entries have the same fields and values';
return false;
}
}
}
$params['data'] = implode(',', $fieldnames) . "{$this->http_linebreak}" . $contacts_string;
$lists_string = '';
if (is_array($lists)) {
foreach ($lists as $id) {
$params['lists'][] = $this
->get_list_url($id);
}
}
}
elseif (file_exists($contacts) && is_readable($contacts)) {
$params['data'] = file_get_contents($contacts);
}
$this
->http_set_content_type('application/x-www-form-urlencoded');
$this
->load_url("activities", 'post', $params, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function get_campaigns($action = 'campaigns') {
$xml = $this
->load_url($action);
if (!$xml) {
return false;
}
$campaigns = array();
$_campaigns = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (is_array($_campaigns)) {
if (isset($_campaigns[0]['link_attr']['href'])) {
foreach ($_campaigns as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$campaign = $v['content']['Campaign'];
$campaign['id'] = $id;
$campaigns[] = $campaign;
}
}
else {
$id = $this
->get_id_from_link($_campaigns['link_attr']['href']);
$campaign = $_campaigns['content']['Campaign'];
$campaign['id'] = $id;
$campaigns[] = $campaign;
}
}
return $campaigns;
}
function get_campaign($id) {
$xml = $this
->load_url("campaigns/{$id}");
if (!$xml) {
return false;
}
$campaign = false;
$_campaign = isset($xml['entry']) ? $xml['entry'] : false;
if (is_array($_campaign)) {
$id = $this
->get_id_from_link($_campaign['link_attr']['href']);
$campaign = $_campaign['content']['Campaign'];
$campaign['id'] = $id;
}
return $campaign;
}
function delete_campaign($id) {
$this
->http_set_content_type('text/html');
$this
->load_url("campaigns/{$id}", 'delete', array(), 204);
if (intval($this->http_response_code) === 204) {
return true;
}
return false;
}
function create_campaign($title, $email_subject, $email_html, $email_text, $contact_lists = array(), $options = array(), $content_type = 'HTML') {
$dynamic_fields = array(
'GreetingSalutation',
'GreetingName',
'GreetingString',
'OrganizationName',
'OrganizationAddress1',
'OrganizationAddress2',
'OrganizationAddress3',
'OrganizationCity',
'OrganizationInternationalState',
'OrganizationCountry',
'OrganizationPostalCode',
'StyleSheet',
);
$xml_post = '
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_username . '/campaigns" />
<id>' . $this
->get_http_api_url() . 'campaigns</id>
<title type="text">' . $title . '</title>
<updated>2009-10-28T14:11:40.881Z</updated>
<author/>
<content type="application/vnd.ctct+xml">
<Campaign xmlns="http://ws.constantcontact.com/ns/1.0/" id="' . $this
->get_http_api_url() . 'campaigns">
<Name>' . $title . '</Name>
<Status>Draft</Status>
<Date>2009-10-28T14:11:40.881Z</Date>
<Subject>' . $email_subject . '</Subject>
';
if (isset($options['ViewAsWebpage'])) {
$xml_post .= '
<ViewAsWebpage>YES</ViewAsWebpage>
<ViewAsWebpageLinkText>' . $options['ViewAsWebpageLinkText'] . '</ViewAsWebpageLinkText>
<ViewAsWebpageText>' . $options['ViewAsWebpageLinkText'] . '</ViewAsWebpageText>
';
}
if (isset($options['PermissionReminder'])) {
$xml_post .= '
<PermissionReminder>YES</PermissionReminder>
<PermissionReminderText>' . $options['PermissionReminderText'] . '</PermissionReminderText>
';
}
if (isset($options['IncludeForwardEmail'])) {
$xml_post .= '
<IncludeForwardEmail>YES</IncludeForwardEmail>
<ForwardEmailLinkText>' . $options['ForwardEmailLinkText'] . '</ForwardEmailLinkText>
';
}
if (isset($options['IncludeSubscribeLink'])) {
$xml_post .= '
<IncludeSubscribeLink>YES</IncludeSubscribeLink>
<SubscribeLinkText>' . $options['SubscribeLinkText'] . '</SubscribeLinkText>
';
}
foreach ($dynamic_fields as $field) {
if (isset($options[$field])) {
$xml_post .= "<{$field}>{$options[$field]}</{$field}>";
}
}
$xml_post .= '
<EmailContentFormat>' . $content_type . '</EmailContentFormat>
<EmailContent>' . htmlentities($email_html) . '</EmailContent>
<EmailTextContent>' . htmlentities($email_text) . '</EmailTextContent>
';
if (is_array($contact_lists)) {
$xml_post .= '<ContactLists>';
foreach ($contact_lists as $id) {
$xml_post .= '
<ContactList id="' . $this
->get_list_url($id) . '">
<link xmlns="http://www.w3.org/2005/Atom" href="' . $this
->get_list_url($id, 0) . '" rel="self" />
</ContactList>
';
}
$xml_post .= '</ContactLists>';
}
if (isset($options['FromName'])) {
$xml_post .= '<FromName>' . $options['FromName'] . '</FromName>';
}
if (isset($options['EmailAddress'], $options['EmailID'])) {
$xml_post .= '
<FromEmail>
<Email id="' . $this
->get_http_api_url() . 'settings/emailaddresses/' . $options['EmailID'] . '">
<link xmlns="http://www.w3.org/2005/Atom" href="' . $this->api_uri . 'settings/emailaddresses/' . $options['EmailID'] . '" rel="self" />
</Email>
<EmailAddress>' . $options['EmailAddress'] . '</EmailAddress>
</FromEmail>
<ReplyToEmail>
<Email id="' . $this
->get_http_api_url() . 'settings/emailaddresses/' . $options['EmailID'] . '">
<link xmlns="http://www.w3.org/2005/Atom" href="' . $this->api_uri . 'settings/emailaddresses/' . $options['EmailID'] . '" rel="self" />
</Email>
<EmailAddress>' . $options['EmailAddress'] . '</EmailAddress>
</ReplyToEmail>
';
}
$xml_post .= '</Campaign></content></entry>';
$this
->http_set_content_type('application/atom+xml');
$xml = $this
->load_url("campaigns", 'post', $xml_post, 201);
if (isset($this->http_response_headers['Location']) && trim($this->http_response_headers['Location']) != '') {
return $this
->get_id_from_link($this->http_response_headers['Location']);
}
return false;
}
function query_campaigns($status = 'SENT') {
$xml = $this
->load_url('campaigns?status=' . urlencode($status));
if (!$xml) {
return false;
}
$campaigns = array();
$_campaigns = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (is_array($_campaigns)) {
if (isset($_campaigns[0]['link_attr']['href'])) {
foreach ($_campaigns as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$campaign = $v['content']['Campaign'];
$campaign['id'] = $id;
$campaigns[] = $campaign;
}
}
else {
$id = $this
->get_id_from_link($_campaigns['link_attr']['href']);
$campaign = $_campaigns['content']['Campaign'];
$campaign['id'] = $id;
$campaigns[] = $campaign;
}
}
return $campaigns;
}
function get_emails() {
$xml = $this
->load_url("settings/emailaddresses");
if (!$xml) {
return false;
}
$emails = array();
$_emails = isset($xml['feed']['entry']) ? $xml['feed']['entry'] : false;
if (is_array($_emails)) {
if (isset($_emails[0]['link_attr']['href'])) {
foreach ($_emails as $k => $v) {
$id = $this
->get_id_from_link($v['link_attr']['href']);
$email = $v['content']['Email'];
$email['id'] = $id;
$emails[] = $email;
}
}
else {
$id = $this
->get_id_from_link($_emails['link_attr']['href']);
$email = $_emails['content']['Email'];
$email['id'] = $id;
$emails[] = $email;
}
}
return $emails;
}
function convert_timestamp($timestamp) {
$timestamp_bits = explode('T', $timestamp);
if (isset($timestamp_bits[0], $timestamp_bits[0])) {
$date_bits = explode('-', $timestamp_bits[0]);
$time_bits = explode(':', $timestamp_bits[1]);
$year = $date_bits[0];
$month = $date_bits[1];
$day = $date_bits[2];
$hour = $time_bits[0];
$minute = $time_bits[1];
return mktime($hour, $minute, 0, $month, $day, $year);
}
return false;
}
function get_id_from_link($link) {
$link_bits = explode('/', $link);
return $link_bits[count($link_bits) - 1];
}
function xml_to_array($contents, $get_attributes = 1, $priority = 'tag') {
if (!$contents) {
return array();
}
if (!function_exists('xml_parser_create')) {
$this->last_error = 'XML not supported';
return array();
}
$output_encoding = 'ISO-8859-1';
$input_encoding = NULL;
$detect_encoding = true;
list($parser, $source) = $this
->xml_create_parser($contents, $output_encoding, $input_encoding, $detect_encoding);
if (!is_resource($parser)) {
exit("Failed to create an instance of PHP's XML parser. " . "http://www.php.net/manual/en/ref.xml.php");
}
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values) {
return;
}
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current =& $xml_array;
$repeated_tag_index = array();
foreach ($xml_values as $data) {
unset($attributes, $value);
extract($data);
$result = array();
$attributes_data = array();
if (isset($value)) {
if ($priority == 'tag') {
$result = $value;
}
else {
$result['value'] = $value;
}
}
if (isset($attributes) and $get_attributes) {
foreach ($attributes as $attr => $val) {
if ($priority == 'tag') {
$attributes_data[$attr] = $val;
}
else {
$result['attr'][$attr] = $val;
}
}
}
if ($type == "open") {
$parent[$level - 1] =& $current;
if (!is_array($current) or !in_array($tag, array_keys($current))) {
$current[$tag] = $result;
if ($attributes_data) {
$current[$tag . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level] = 1;
$current =& $current[$tag];
}
else {
if (isset($current[$tag][0])) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
}
else {
$current[$tag] = array(
$current[$tag],
$result,
);
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset($current[$tag . '_attr'])) {
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current =& $current[$tag][$last_item_index];
}
}
elseif ($type == "complete") {
if (!isset($current[$tag])) {
$current[$tag] = $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $attributes_data) {
$current[$tag . '_attr'] = $attributes_data;
}
}
else {
if (isset($current[$tag][0]) and is_array($current[$tag])) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
}
else {
$current[$tag] = array(
$current[$tag],
$result,
);
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $get_attributes) {
if (isset($current[$tag . '_attr'])) {
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
if ($attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++;
}
}
}
elseif ($type == 'close') {
$current =& $parent[$level - 1];
}
}
return $xml_array;
}
function xml_create_parser($source, $out_enc, $in_enc, $detect) {
if (substr(phpversion(), 0, 1) == 5) {
$parser = $this
->xml_php5_create_parser($in_enc, $detect);
}
else {
list($parser, $source) = $this
->xml_php4_create_parser($source, $in_enc, $detect);
}
if ($out_enc) {
$this->xml_encoding = $out_enc;
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $out_enc);
}
return array(
$parser,
$source,
);
}
function xml_php5_create_parser($in_enc, $detect) {
if (!$detect && $in_enc) {
return xml_parser_create($in_enc);
}
else {
return xml_parser_create('');
}
}
function xml_php4_create_parser($source, $in_enc, $detect) {
if (!$detect) {
return array(
xml_parser_create($in_enc),
$source,
);
}
if (!$in_enc) {
if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m', $source, $m)) {
$in_enc = strtoupper($m[1]);
$this->xml_source_encoding = $in_enc;
}
else {
$in_enc = 'UTF-8';
}
}
if ($this
->xml_known_encoding($in_enc)) {
return array(
xml_parser_create($in_enc),
$source,
);
}
if (function_exists('iconv')) {
$encoded_source = iconv($in_enc, 'UTF-8', $source);
if ($encoded_source) {
return array(
xml_parser_create('UTF-8'),
$encoded_source,
);
}
}
if (function_exists('mb_convert_encoding')) {
$encoded_source = mb_convert_encoding($source, 'UTF-8', $in_enc);
if ($encoded_source) {
return array(
xml_parser_create('UTF-8'),
$encoded_source,
);
}
}
exit("Feed is in an unsupported character encoding. ({$in_enc}) " . "You may see strange artifacts, and mangled characters.");
return array(
xml_parser_create(),
$source,
);
}
function xml_known_encoding($enc) {
$enc = strtoupper($enc);
if (in_array($enc, $this->xml_known_encodings)) {
return $enc;
}
else {
return false;
}
}
function http_set_content_type($content_type) {
$this->http_content_type = $content_type;
}
function http_parse_request_url($url) {
$this->http_url_bits = parse_url($url);
}
function http_get($path, $params = array(), $headers = array()) {
$this
->http_send($path, 'get', $params, $headers);
}
function http_post($path, $params = array(), $headers = array()) {
$this
->http_send($path, 'post', $params, $headers);
}
function http_put($path, $params = array(), $headers = array()) {
$this
->http_send($path, 'put', $params, $headers);
}
function http_delete($path, $params = array(), $headers = array()) {
$this
->http_send($path, 'delete', $params, $headers);
}
function http_auth_headers() {
if ($this->http_user || $this->http_pass) {
$this
->http_headers_add('Authorization', " Basic " . base64_encode($this->http_user . ":" . $this->http_pass));
}
}
function http_serialize_params($params) {
$query_string = array();
if (is_array($params)) {
foreach ($params as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $fieldvalue) {
$query_string[] = urlencode($key) . '=' . urlencode($fieldvalue);
}
}
else {
$query_string[] = urlencode($key) . '=' . urlencode($value);
}
}
}
else {
return $params;
}
return implode('&', $query_string);
}
function http_send($path, $method, $params = array(), $headers = array()) {
$this->http_response = '';
$this->http_response_code = '';
$this->http_method = $method;
$this
->http_parse_request_url($path);
$this
->http_headers_merge($headers);
if (is_array($params)) {
$params = $this
->http_serialize_params($params);
}
$method = strtoupper($method);
$the_host = $this->http_url_bits['host'];
$the_path = isset($this->http_url_bits['path']) && trim($this->http_url_bits['path']) != '' ? $this->http_url_bits['path'] : '';
$the_path .= isset($this->http_url_bits['query']) && trim($this->http_url_bits['query']) != '' ? '?' . $this->http_url_bits['query'] : '';
$this
->http_headers_add('', "{$method} {$the_path} HTTP/1.1");
$this
->http_headers_add('Host', $the_host);
if ($this->http_content_type) {
$this
->http_headers_add('Content-Type', $this->http_content_type);
}
$this
->http_headers_add('User-Agent', $this->http_user_agent);
$this
->http_headers_add('Content-Length', strlen($params));
$request = $this
->http_build_request_headers();
if (trim($params) != '') {
$request .= "{$params}{$this->http_linebreak}";
}
$this->http_request = $request;
if ($this->http_url_bits['scheme'] == 'https') {
$port = 443;
$fsockurl = "ssl://{$the_host}";
}
else {
$port = 80;
$fsockurl = $the_host;
}
if ($fp = fsockopen($fsockurl, $port, $errno, $errstr, $this->http_request_timeout)) {
if (fwrite($fp, $request)) {
while (!feof($fp)) {
$this->http_response .= fread($fp, 4096);
}
}
fclose($fp);
}
else {
return false;
}
$this
->http_parse_response();
}
function http_build_request_headers() {
$this
->http_auth_headers();
$this
->http_headers_add('Connection', "Close{$this->http_linebreak}");
$request = $this
->http_headers_to_s($this->http_request_headers);
$this->http_request_headers = array();
return $request;
}
function http_parse_response() {
$this->http_response = str_replace("\r\n", "\n", $this->http_response);
list($headers, $body) = explode("\n\n", $this->http_response, 2);
$body_pos = strpos($body, "\n");
if (!is_null($this->http_content_type)) {
$body = $body_pos !== false ? substr($body, $body_pos) : $body;
}
$this->http_response_body = $body;
$this
->http_parse_headers($headers);
$this
->http_set_content_type($this->http_default_content_type);
}
function http_headers_to_s($headers) {
$string = '';
if (is_array($headers)) {
foreach ($headers as $header => $value) {
if (trim($header) != '' && !is_numeric($header)) {
$string .= "{$header}: {$value}{$this->http_linebreak}";
}
else {
$string .= "{$value}{$this->http_linebreak}";
}
}
}
return $string;
}
function http_headers_add($header, $value) {
if (trim($header) != '' && !is_numeric($header)) {
$this->http_request_headers[$header] = $value;
}
else {
$this->http_request_headers[] = $value;
}
}
function http_headers_merge($headers) {
$this->http_request_headers = array_merge($this->http_request_headers, $headers);
}
function http_headers_get($header) {
return $this->http_request_headers[$header];
}
function http_headers_get_response_code() {
return $this->http_response_code;
}
function http_parse_headers($headers) {
$replace = $this->http_linebreak == "\n" ? "\r\n" : "\n";
$headers = str_replace($replace, $this->http_linebreak, trim($headers));
$headers = explode($this->http_linebreak, $headers);
$this->http_response_headers = array();
if (preg_match('/^HTTP\\/\\d\\.\\d (\\d{3})/', $headers[0], $matches)) {
$this->http_response_code = intval($matches[1]);
array_shift($headers);
}
if ($headers) {
foreach ($headers as $string) {
list($header, $value) = explode(': ', $string, 2);
$this->http_response_headers[$header] = $value;
}
}
}
function http_get_response_code_error($code) {
$errors = array(
200 => 'Success - The request was successful',
201 => 'Created (Success) - The request was successful. The requested object/resource was created.',
400 => 'Invalid Request - There are many possible causes for this error, but most commonly there is a problem with the structure or content of XML your application provided. Carefully review your XML. One simple test approach is to perform a GET on a URI and use the GET response as an input to a PUT for the same resource. With minor modifications, the input can be used for a POST as well.',
401 => 'Unauthorized - This is an authentication problem. Primary reason is that the API call has either not provided a valid API Key, Account Owner Name and Associated Password or the API call attempted to access a resource (URI) which does not match the same as the Account Owner provided in the login credientials.',
404 => 'URL Not Found - The URI which was provided was incorrect. Compare the URI you provided with the documented URIs. Start here.',
409 => 'Conflict - There is a problem with the action you are trying to perform. Commonly, you are trying to "Create" (POST) a resource which already exists such as a Contact List or Email Address that already exists. In general, if a resource already exists, an application can "Update" the resource with a "PUT" request for that resource.',
415 => 'Unsupported Media Type - The Media Type (Content Type) of the data you are sending does not match the expected Content Type for the specific action you are performing on the specific Resource you are acting on. Often this is due to an error in the content-type you define for your HTTP invocation (GET, PUT, POST). You will also get this error message if you are invoking a method (PUT, POST, DELETE) which is not supported for the Resource (URI) you are referencing.
To understand which methods are supported for each resource, and which content-type is expected, see the documentation for that Resource.',
500 => 'Server Error',
);
if (array_key_exists($error, $errors)) {
return $errors[$error];
}
return '';
}
}