Server Migration results in eNews signup failure

MarthaW
Regular Participant

Server Migration results in eNews signup failure

Hi,

 

I've got a problem I'm hoping someone can help me with. Two weeks ago, my web site with a customized Constant Contact sign up form was migrated to a new server. Both the old server and the new server are Linux. But the enews sign-up now fails.

 

The code is the same, so I am assuming this is a server setting that could be easily tweaked if I had the slightest idea where to look for it. I read in another thread that it might a curl setting, also. Any thoughts would be most appreciated!  This is the form that is failing: http://www.wmf.org/e-newsletter

Instead of getting a 'thank you' message and the contact being inserted into the Constant Contact list, I get a Page Could Not Be Found 500 error on the client side (Drupal error log) and on the server side, they are seeing a rather generic error message: Premature end of script headers: index.php, referer: http://www.wmf.org/e-newsletter

 

Many thanks in advance for helping me out here!

 

Best,

Lissa

21 REPLIES 21
Ryan_D
Employee

Hey Lisa,

 

In order for me to be able to see what could be causing the error I would need to see the code in order to troubleshoot it.  Please provide it on the forum or in a private message.

 

 

Ryan Davis
Quality Engineer
MarthaW
Regular Participant

Hey Ryan,

 

Thanks for your reply. I need to amend my initial statement. The contact's email address actually IS inserting into the Constant Contact list; so the only problem is that the "Thank you" page after signing up is not being returned. It is the same page that should refresh with the message: Thank you for signing up for our newsletter. You should receive a confirmation email shortly.,

 

The code for doing that, below,  worked fine on the old server, but is not working on the new.  Instead it is returning a 500 /Page Not Found error.

 

 

<?php

function newsletter_menu(){
    $items['e-newsletter/thank-you'] = array(
        'title' => t("Thank You"),
        'page callback' => "newsletter_thankyou_page",
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );   
    $items['e-newsletter'] = array(
        'title' => t("E-Newsletter"),
        'page callback' => "newsletter_signup_page",
        'access arguments' => array('access content'),
                'type' => MENU_CALLBACK,
    );
    $items['admin/settings/newsletter'] = array(
        'title' => 'Constant Contact Email List Settings',
        'description' => 'Configure the Constant Contact and email  list settings',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('newsletter_admin'),
        'access arguments' => array('administer newsletter'),
        'type' => MENU_NORMAL_ITEM,
    );
    $items['e-newsletter/tests'] = array(
        'title' => 'Constant Contact Email Tests',
        'page callback' => 'newsletter_tests',
        'page arguments' => array('newsletter_admin'),
        'access arguments' => array('administer newsletter'),
        'type' => MENU_CALLBACK,
    );   
    return $items;
}


function newsletter_theme(){
    return array(
            'newsletter_signup' => array(
            'arguments' => array('form' => NULL),
            'template' => 'theme/newsletter_signup'
        ),
            'newsletter_thankyou' => array(
            'arguments' => array('form' => NULL),
            'template' => 'theme/newsletter_thankyou'
        ),
            'test_results' => array(
            'arguments' => array('form' => NULL),
            'template' => 'theme/test_results'
        )       
    );
}

function newsletter_thankyou_page(){
    return theme('newsletter_thankyou');   
}

function newsletter_tests(){
    return theme('test_results');
}


function newsletter_signup_page(){
    if(!variable_get("cc_toggle_newsletter", 1)){
        return drupal_goto("contact/request-enews/");
    }
    require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
    if(user_is_logged_in()){
        $cc = get_constant_contact();
        global $user;
        $email = $user->mail;
        $status = get_reg_status_from_cc($cc, urlencode($email));
       
        if($status['newsletter']){
            //$form = '<h2 class="title">You are signed up for the WMF e-newsletter.</h2><br/><p>You can unsubscribe by editing your profile, or by clicking unsubscribe from any e-newsletter you have received.</p>';
            $form = variable_get('cc_enews_already_signed_up_text',"");
            return theme('newsletter_signup', $form);
        }
    }
   
    $enews_headline_text = variable_get('cc_enews_headline_text',"");
   
    $form = t("<h2 class='title'>$enews_headline_text</h2>");
    $form .= drupal_get_form('newsletter_form');
    return theme('newsletter_signup', $form);
}

function newsletter_form(){

    $form['firstname'] = array(
     '#type' => 'textfield',
     '#title' => 'First Name',
        '#required' => true
    );
    $form['lastname'] = array(
     '#type' => 'textfield',
     '#title' => 'Last Name',
     '#required' => true
    );
    $form['email'] = array(
     '#type' => 'textfield',
     '#title' => 'Email',
     '#required' => true
    );
    $form['emailconf'] = array(
     '#type' => 'textfield',
     '#title' => 'Confirm Email',
     '#required' => true
    );
    $form['campaign'] = array(
     '#type' => 'checkbox',
     '#title' => variable_get('cc_enews_additional_signup_text',"") //'Also sign me up for emails about Special Campaigns and Announcements'
     );
     $form['submit'] = array(
     '#type' => 'submit',
     '#value' => 'Submit'
     );
     
     return $form;
}

function newsletter_form_validate($form, &$form_state){
    if($form_state['values']['email']
    != $form_state['values']['emailconf']){
        form_set_error('email', t('Your email addresses must match.'));
    }
}

function newsletter_form_submit($form, &$form_state){

    require_once("sites/all/modules/custom/constantcontact/wmfcc.php");

    $cc = get_constant_contact();

    //print_r($form_state);
    $newsletter_uri = variable_get('cc_newsletter_list_uri',"");
    $lists = array($newsletter_uri);
    if($form_state['values']['campaign'] == 1){
        $emaillist_uri = variable_get('cc_email_list_uri',"");
        $lists[] = $emaillist_uri;       
    }

    $email = urlencode($form_state['values']['email']);
    //$status = get_reg_status_from_cc($cc, $email);
    //$overview = get_contact_overview_xml($cc, $email);
    //$id = get_user_id_from_contact_overview($overview);
   
    $response = add_user_or_create_and_add_to_cc_list($cc,
            $form_state['values']['firstname'],
            $form_state['values']['lastname'],
            $email,
            $lists);

    if($response == FALSE){
        drupal_set_message("The email service is currently offline so we could not update your status.  Please try again later or email us for your status.");
    } else {
        drupal_goto('e-newsletter/thank-you');
    }

}

function newsletter_perm(){
    return array('administer newsletter');
}

function newsletter_admin() {
    $form = array();
    $form['cc_toggle_newsletter'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Constant Contact'),
    '#default_value' => variable_get('cc_toggle_newsletter', TRUE),
    '#description' => t("Use Constant Contact."),
    );

    $form['cc_user_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Constant Contact User Name'),
    '#default_value' => variable_get('cc_user_name',""),
    '#size' => 60,
    '#maxlength' => 60,
    '#description' => t("User name for Constant Contact account."),
    '#required' => TRUE,
    );
    $form['cc_password'] = array(
    '#type' => 'textfield',
    '#title' => t('Constant Contact password'),
    '#default_value' => variable_get('cc_password',""),
    '#size' => 60,
    '#maxlength' => 60,
    '#description' => t("Password for Constant Contact account."),
    '#required' => TRUE,
    );
    $form['cc_api_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Constant Contact API key'),
    '#default_value' => variable_get('cc_api_key',""),
    '#size' => 60,
    '#maxlength' => 60,
    '#description' => t("API Key for Constant Contact account."),
    '#required' => TRUE,
    );
    $form['cc_newsletter_list_uri'] = array(
    '#type' => 'textfield',
    '#title' => t('Constant Contact Newsletter URI'),
    '#default_value' => variable_get('cc_newsletter_list_uri',""),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t("URI for Constant Contact Newsletter"),
    '#required' => TRUE,
    );
    $form['cc_email_list_uri'] = array(
    '#type' => 'textfield',
    '#title' => t('Constant Contact Email URI'),
    '#default_value' => variable_get('cc_email_list_uri',""),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t("URI for Constant Contact Email List"),
    '#required' => TRUE,
    );
   
    $form['cc_enews_headline_text'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Newsletter Signup Page Headline'),
    '#default_value' => variable_get('cc_enews_headline_text',""),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t(""),
    '#required' => TRUE,
    );
   
    $form['cc_enews_already_signed_up_text'] = array(
    '#type' => 'textarea',
    '#title' => t('E-Newsletter Signup Page - Already Signed Up For E-News Message'),
    '#default_value' => variable_get('cc_enews_already_signed_up_text',""),
    '#description' => t("Enter some text for a user to see if they are already signed up for the e-newsletter."),
    '#required' => TRUE,
    );
   
    $form['cc_enews_additional_signup_text'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Newsletter Signup Page - Additional Checkbox Text'),
    '#default_value' => variable_get('cc_enews_additional_signup_text',""),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t(""),
    '#required' => TRUE,
    );
   
    return system_settings_form($form);
}



?>

 

 

The base code is pasted below, though there are several supporting files, too:

 

<?php
/**
 * An easy to use Constant Contact PHP Interface
 *
 * @name      ConstantContact PHP Interface
 * @author    Jared De Blander <jared@iofast.com>
 * @copyright (c) 2008 Jared De Blander
 * @link      http://www.iofast.com
 * @link      http://www.jareddeblander.com
 * @license   MIT
 * @version   $Rev$
 * @internal  $Id$
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * NOTICE:
 * Further alteration of this software were made by ESI design.
 *
 */
class constant_contact{

  //Debugging state
  private $debug;

  private $user;
  private $pass;
  private $api_key;

  /**
   * The ConstantContact contructor
   *
   * @param String $user - Your username
   * @param String $pass - Your password
   * @param String $api_key - Your API Key
   */
  public function __construct($user='', $pass='', $api_key=''){
    $this->debug=false;

    $this->set_user($user);
    $this->set_pass($pass);
    $this->set_api_key($api_key);
  }
 
  /**
   * Get a contact
   * @param int $contact_id - ID of the contact
   */
 
  public function get_contact($url){
        $post = "";
         $response = $this->fetch($url, $post);
          return $response;
  }
 
  public function get_contact_from_id($id){
          $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts/'.$id;
        return get_contact_from_url($url);
  }
 
  public function get_contact_from_url($url){
        $post = "";
         $response = $this->fetch($url, $post);
          return $response;
  }
 
  public function update_contact($contact){
     
          $tmpfile = tmpfile();
          fwrite($tmpfile, $contact);
          fseek($tmpfile, 0);
     
            $contact_arr = $this->xml_to_array($contact);
          $url = $contact_arr['entry']['id']['value'];
        $url = str_replace('http://', 'https://', $url);
       
          $session = curl_init($url);
         
        $usrpsw = $this->api_key. '%' .$this->user .':'.$this->pass;
        curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($session, CURLOPT_USERPWD, $usrpsw);
        curl_setopt($session, CURLOPT_INFILE, $tmpfile);
        fclose($tmpfile);
       
        curl_setopt($session, CURLOPT_PUT, 1);
        curl_setopt($session, CURLOPT_INFILESIZE, strlen($contact));

        curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
        curl_setopt($session, CURLOPT_HEADER, 0);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, 0);
        $response = curl_exec($session);
   
        $this->debug_print("HTTP Response Code '".curl_getinfo($session, CURLINFO_HTTP_CODE)."'");
        $this->debug_print("Received:<pre>\n\n---START---\n". htmlspecialchars($response) ."\n---END---\n\n</pre>");
   
        curl_close($session);
        return $response;
     
  }
 
  /**
   * Add a contact
   *
   * @param String $first_name - First name
   * @param String $last_name - Last name
   * @param String $email - Email address
   * @param Array of Strings $lists - The lists to subscribe to. This should be the entire id of the list
   */
  public function add_contact($first_name, $last_name, $email, $lists){
     
    $post ='<entry xmlns="http://www.w3.org/2005/Atom">';
    $post.='<title type="text"> </title>';
    $post.='<updated>'.date('Y-m-d\TH:i:s\Z') .'Z</updated>';
    $post.='<author></author>';
    $post.='<id>data:,none</id>';
    $post.='<summary type="text">Contact</summary>';
    $post.='<content type="application/vnd.ctct+xml">';
    $post.='<Contact xmlns="http://ws.constantcontact.com/ns/1.0/">';
    $post.='<EmailAddress>'.urldecode($email).'</EmailAddress>';
    $post.='<FirstName>'.$first_name.'</FirstName>';
    $post.='<LastName>'.$last_name.'</LastName>';
    $post.='<OptInSource>ACTION_BY_CONTACT</OptInSource>';
    $post.='<ContactLists>';
    foreach($lists as $list){
        $post.='<ContactList id="' . $list . '" />';         
    }
    $post.='</ContactLists>';
    $post.='</Contact>';
    $post.='</content>';
    $post.='</entry>';
     
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts';
    $credentials = $this->api_key. '%' .$this->user .':'.$this->pass;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS , $post);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
   
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
  }

  /**
   * Turn debugging output off.
   *
   */
  public function debug_off(){
    $this->debug=false;
  }

  /**
   * Turn debugging output on.
   *
   */
  public function debug_on(){
    $this->debug=true;
  }
 
  public function ping(){
      $url = "https://api.constantcontact.com/ws/customers/".$this->user."/";
    $credentials=$this->api_key.'%'.$this->user.':'.$this->pass;
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, 0);
      curl_setopt($ch, CURLOPT_HEADER, False);
      return curl_exec($ch);
  }

  /**
   * Print debugging output
   *
   * @param String $string - String to print
   */
  private function debug_print($string){
    if($this->debug) echo "ConstantContact Debug: $string<br>\n";
  }

  /**
   * Fetch a URI from ConstantContact
   *
   * @param String $url - URL to connect to
   * @param String $post - POST data to include
   * @return Respose
   */
  private function fetch($url, $post){
    $credentials=$this->api_key.'%'.$this->user.':'.$this->pass;
    $ch=curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(strlen(trim($post))>0){
      $this->debug_print("And Posting:<pre>\n\n---START---\n". htmlspecialchars($post) ."\n---END---\n\n</pre>");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/atom+xml'));
    }else{
      $this->debug_print("Not posting");
      curl_setopt($ch, CURLOPT_POST, 0);
    }
    if($this->debug){
      curl_setopt($ch, CURLOPT_HEADER, True);
    }else{
      curl_setopt($ch, CURLOPT_HEADER, False);
    }

    $response = curl_exec($ch);
    $this->debug_print("HTTP Response Code '".curl_getinfo($ch, CURLINFO_HTTP_CODE)."'");
    $this->debug_print("Received:<pre>\n\n---START---\n". htmlspecialchars($response) ."\n---END---\n\n</pre>");
   
    curl_close($ch);
    return $response;
  }


  public function get_activities_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/activities';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Return your list of campaigns
   *
   * @return XML document containing your campaigns
   */
  public function get_campaigns_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/campaigns';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Return your list of contacts. Paths can be specified to show
   * information about a specific contact. Path data can be found
   * in the master contact list by specifying no path.
   *
   * @param String $path - Optionally specify a path
   * @return XML document containing your contacts.
   */
  public function get_contacts_xml($path=''){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts'.$path;
    $post='';
    $response = $this->fetch($url, $post);
    return $response;
  }


  /**
   * Used to retrieve your list information. Paths can be specified
   * to show information about a specific list. Path data can be
   * found in the master list retrieved by specifying no path.
   *
   * @param String $path - Optionally specify a path.
   * @return XML document containing list information
   */
  public function get_lists_xml($path=''){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/lists'.$path;
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }


  /**
   * Retrieves the XML service document
   *
   * @return XML service document
   */
  public function get_service_doc_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Sets your API key
   *
   * @param String $api_key - Your API Key
   */
  public function set_api_key($api_key){
    $this->api_key=$api_key;
  }

  /**
   * Set your ConstantContact Password
   *
   * @param String $pass - Your Password
   */
  public function set_pass($pass){
    $this->pass=$pass;
  }

  /**
   * Set your ConstantContact Username
   *
   * @param String $user - Your Username
   */
  public function set_user($user){
    $this->user=$user;
  }

  /**
   * Converts XML data into a nested array
   *
   * @param String $contents - XML string
   * @param Integers $get_attributes - Include attributes (default 1)
   * @return Nested associative array
   */
  public function xml_to_array($contents, $get_attributes=1) {

    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
      return array();
    }

    $parser = xml_parser_create();
    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, $contents, $xml_values );
    xml_parser_free( $parser );

    if(!$xml_values) return;

    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array;


    foreach($xml_values as $data) {
      unset($attributes,$value);
      extract($data);

      $result = '';
      if($get_attributes) {
        $result = array();
        if(isset($value)) $result['value'] = $value;
        if(isset($attributes)) {
          foreach($attributes as $attr => $val) {
            if($get_attributes == 1) $result['attr'][$attr] = $val;
          }
        }
      } elseif(isset($value)) {
        $result = $value;
      }

      if($type == "open") {
        $parent[$level-1] = &$current;
        if(!is_array($current) or (!in_array($tag, array_keys($current)))) {
          $current[$tag] = $result;
          $current = &$current[$tag];
        } else {
          if(isset($current[$tag][0])) {
            array_push($current[$tag], $result);
          } else {
            $current[$tag] = array($current[$tag],$result);
          }
          $last = count($current[$tag]) - 1;
          $current = &$current[$tag][$last];
        }
      } elseif($type == "complete") {

        if(!isset($current[$tag])) {
          $current[$tag] = $result;
        } else {
          if((is_array($current[$tag]) and $get_attributes == 0)
          or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
            array_push($current[$tag],$result);
          } else {
            $current[$tag] = array($current[$tag],$result);
          }
        }
      } elseif($type == 'close') {
        $current = &$parent[$level-1];
      }
    }
    return($xml_array);
  }
 
}


?>

MarthaW
Regular Participant

Ok, so another update. This is ONLY happening when a user who has previously signed up, and been removed, tries to sign up again.

 

Best,

Lissa

Hey Martha,

 

Have any of the permissions changed since you did the server migration?  I have looked through your code and it appears to be fine.  If you step through it, where does the error occur?

 

Ryan Davis
Quality Engineer

Hey Martha,

 

After a second look at your error I think you are getting the wrong error. It looks like you are getting a 409 and which would happen if you try to create a contact that already exists.  Upon getting the 409  and when the error is handled it navigates to a page that does not exist.  Thus you would get a 500 error because its internal and the Page not exist error as well, the page does not exist. 

Ryan Davis
Quality Engineer
MarthaW
Regular Participant

I see...but if the contact has been previously removed, should that happen?

 

Many thanks!

 

Hey Martha,

 

Yes, as each contact is given a unique ID to your account.  If this an email address already has an ID, it would conflict.  Thus the 409.  You would want to do a search, if it exists then you would do a PUT.  Here is an example i made using our new wrapper.

 

<?php 
/****************************************************************************************
 * 
 * 		Please note that this is just an example, please change the credentials to
 * 		your own constant contact login credentials.  The following code is an example of:
 * 
 * 		Search for contact by email address
 * 		Creating a new contact if it doesen't already exist
 * 		If Contact exists, then update the contact by adding it to a new list
 * 		
 ****************************************************************************************/

// this application uses our new wrapper that can be found on github
// https://github.com/ctctsupport/ctct_php_library

include ('wrapper/ConstantContact.php');
	// Connecting to your account
	$ConstantContact = new ConstantContact("basic", "apikey", "Username", "Password");

	// Get potential contact lists
	$lists = $ConstantContact->getLists();
	// Lists are returned in multidimentional arrays 0 being the list, and 1 being the next50
	
	// Email address here is used for testing purposes
	// NOTE:  This email address will be added to your account if you execute this script,
	//		  you should send this to do-not-mail after your testing
	$emailAddress = "test@test.com";
	
	// Search for our new Email address
	$search = $ConstantContact->searchContactsByEmail($emailAddress);
	
	// If the search didnt return a contact object
	if($search == false)
	{
		// Create a new Contact Object to store data into
		$contactObj = new Contact();
		// Adding multiple lists to this new Contact Object
		$contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
		// Set the email address
		$contactObj->emailAddress = $emailAddress;
		// Create the Contact and DONE
		$Contact = $ConstantContact->addContact($contactObj);
		
	} // Otherwise we update our existing
	else 
	{
		
		// Gather data from our previous search and store it into a data type
		$contactObj = $ConstantContact->getContactDetails($search[0]);
		// We need to get the old list and add a new list to it as
		// this request requires a PUT and will remove the lists
		// as they are stored in an array
		array_push($contactObj->lists, $lists['lists'][3]->id );
		
		// Update the contact and DONE
		$UpdateContact = $ConstantContact->updateContact($contactObj);
	}
		

?>

 You can get this new wrapper here if you wish to implement this.

Ryan Davis
Quality Engineer
MarthaW
Regular Participant

Thanks, Ryan, very helfpul.

 

I have another problem seemingly related to the Constant Contact API.

 

On tne website's registration page, (http://www.wmf.org/user/register), I can optionally include checkboxes that sign the user up for two e-newsletters at the same time that they register for the website 'community'.

 

With those checkboxes checked, however, the registration process (for the web site) now fails. Again, this is a new bug that began happening with a recent server migration.

 

So on this page:

http://www.wmf.org/user/register

 

Once the user clicks "Create New Account", they should get redirected to a thank you page (http://www.wmf.org/content/thank-you), and an email should be sent out allowing them to click on a link to complete their registration.  Niether of these two things happen, on the new server, when the Constant Contact checkboxes are checked. If they are unchecked, then the registration process completes.

 

Again, the user is being inserted into the Constant Contact list, but those checkboxes being checked are somehow causing the WEBSITE registration process to fail.

 

Thanks for any thoughts on this you might have! I've had 6 server technicans at the host company scratching their heads over this for two weeks:)

 

Best,

Lissa

 

 

If you would like to post your code or PM it to me, I would be happy to take a look. 

Ryan Davis
Quality Engineer

I dont see anywhere in your code that would have them register to your site. 

Ryan Davis
Quality Engineer
MarthaW
Regular Participant

Thank you, Ryan. Of course, here is the code:

<?php

/*
See also: page-user.tpl.php in Themes folder
*/

function wmf_registration_theme(){
    return array(
        'upload-re' => array(
            'arguments' => array('form' => NULL),
            'template' => 'theme/upload-re',
        ),
        'export-userinfo' => array(
        	'arguments' => array('form'=>NULL),
        	'template' => 'theme/export',
        ),
    );
}

function wmf_registration_menu(){
		
		//--parent menu item
		$items['re-synch'] = array(
        'title' => "RE Synch",
        'page callback' => "export_userinfo_page",
        'access arguments' => array('access content'),
				'type' => MENU_NORMAL_ITEM,
    );
    
    //--tabs
    $items['re-synch/export'] = array(
        'title' => "Export",
        'page callback' => "export_userinfo_page",
        'access arguments' => array('access content'),
				'type' => MENU_DEFAULT_LOCAL_TASK,
				'weight' => 1,
    );
    
    $items['re-synch/import'] = array(
        'title' => "Import",
        'page callback' => "upload_drupal_to_re_file_page",
        'access arguments' => array('access content'),
				'type' => MENU_LOCAL_TASK,
				'weight' => 5,
    );
    
	$items['admin/settings/registration'] = array(
	    'title' => 'Registration / Profile Email List Settings',
	    'description' => 'Configure the Registration / Profile newsletter and email list settings',
	    'page callback' => 'drupal_get_form',
	    'page arguments' => array('wmf_registration_admin'),
	    'access arguments' => array('access administration pages'),
	    'type' => MENU_NORMAL_ITEM,
	   );        

    return $items;
}

function export_userinfo_page(){
  	// If the user has permission to, render the page.
    if(user_access('administer registration')){
    	
	$datepicker = "
		$('#edit-end').datepicker();
		$('#edit-start').datepicker();     
	";
	drupal_add_js($datepicker, $type="inline", 'footer');	
	drupal_add_js($data="sites/all/modules/contrib/date/date_popup/lib/ui.datepicker.js", $type="core");
	drupal_add_js($data="sites/all/modules/contrib/date/date_popup/date_popup.js", $type="core");
	drupal_add_js($data="sites/all/modules/contrib/date/date_popup/lib/jquery.timeentry.pack.js", $type="core");
    
    	
    	$form = drupal_get_form('user_export_form');
		return theme('export-userinfo', $form);
     } else {
        // Other wise, they're denied.
        drupal_access_denied();       
     }
}

function user_export_form(){
		drupal_add_js('function toggledate_div()
			{
			  $("div.daterange").slideToggle("slow");
			}','inline'
		);  	
		$opts = array('all' => 'Export all users', 'new' => 'Export only users who have not been synched to Raisers Edge');
		$form['newusers']  = array(
          '#type' => 'select',
		  '#title' => 'Select new users or all.',
          '#options' => $opts,
        );
		$form['filterbydate'] = array(
		    '#type' => 'checkbox',
	    	'#title' => t('Filter using date ranges.'),
			'#attributes' => array('onClick' => "toggledate_div()")
		);
        $form['start'] = array(
			'#prefix' => '<div class="daterange" style="display:none">',        
          '#type' => 'textfield',
          '#title' => 'Start Date'
        );
        $form['end'] = array(
          '#type' => 'textfield',
          '#title' => 'End Date',
          '#suffix' => '</div>'
        );
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => 'Download file',
          '#submit' => array('user_export_form_submit')
        );
        return $form;
}

function clean_data($row){
	foreach($row as $key=>$value){
		$value = addslashes($value);
		if(strstr($value, ",")){
			$value = '"'.$value.'"';
		}
		$row[$key] = $value;
	}
	return $row;
}

function get_account_object_for_uid($uid){
	$sql = "SELECT * FROM user_information JOIN users ON users.uid = user_information.uid WHERE user_information.uid = %d";
	$result = db_query($sql, $uid);
	return db_fetch_object($result);
}

function user_export_form_submit($form, &$form_state){
	
	$sql = "SELECT * FROM user_information INNER JOIN users WHERE 1 AND";
	
	if($form_state['values']['newusers'] == 'new'){
		$sql .= " synched_to_raisers_edge = 0 AND";
	}
	
	if($form_state['values']['filterbydate'] == 1){
		$start = strtotime($form_state['values']['start']);			
		$end = strtotime($form_state['values']['end']) + (86400);					
		$sql .=  sprintf(" users.created > %d AND users.created < %d AND", $start, $end);
	}
	
	//--added Mar 6th 2011 bby smw - function: do not report non-validated users
	$sql .=  " users.access != 0 AND";
		
	$sql .=  " users.uid = user_information.uid";	
	$result = db_query($sql);
	
	/*
	Many ways to get clever down here... but until we hear get finalized, lets keep it simple
 	*/
	
	$row = array();
	
	while($data = db_fetch_object($result)){

		$row['constituent_id'] = $data->raisers_edge_id;
		$row['firstname'] = $data->firstname;
		$row['middlename'] = "";	// We don't capture this
		$row['lastname'] = $data->lastname;
		$row['constituent_code'] = ""; // We don't capture this
		$row['constituent_date_from'] = "";
		$row['requests_no_email'] = "";
		$row['preferred_address1'] = $data->address1;
		$row['preferred_address2'] = $data->address2;
		$row['preferred_address3'] = "";
		$row['preferred_address4'] = "";
		$row['preferred_city'] = $data->city;
		$row['preferred_state'] = $data->state;
		$row['preferred_country'] = $countries[$data->country];
		$row['preferred_zip'] = $data->postalcode;		
		$row['preferred_email'] = $data->mail;
		$row['constituent_specific_attributes_source_of_name_date'] = ""; // We don't capture this yet
		$row['constituent_specific_attributes_source_of_name_description '] = ""; // We don't capture this yet
		$row['constituent_specific_attributes_receive_e-newsletter_date'] = ""; // We don't capture this yet
		$row['constituent_spe_attributes_receive_e-newsletter_description '] = ""; // We don't capture this yet
		$row['gift_specific_attributes_web_donation_date'] = ""; // We don't capture this yet
		$row['gift_specific_attributes_web_donation_description'] = ""; // We don't capture this yet
		
        require('wmf_registration_shared_data.php');
		$row['web_id'] = $data->uid;
		$row['web_user_from'] = date("m/d/y",$data->created);
		$row['selfdescription'] = $wmf_registration_self_description_options[$data->selfdescription];
		$row['selfdescription_other'] = $data->selfdescription_other;
		$row['reg_email_prefs'] = $data->emaillist;
		$row['reg_newsletter_prefs'] = $data->newsletter;	
		$row['user_name'] = $data->name;	
		
		$row = clean_data($row);
		$output .= implode($row, ",");
		$output .= "\n";
	}
	
	$column_names = array_keys($row);
	$output = implode($column_names, ',') . "\n" . $output;
	
	header("Content-type: text/csv");
	header("Content-disposition: attachment; filename=" . date('Y-m-d\TH-i-s') . "-webusers.csv");
	echo $output;
	flush();
	exit();
}

function upload_drupal_to_re_file_page(){
        // If the user has permission to, render the page.
        if(user_access('administer registration')){
           $form = drupal_get_form('drupal_to_re_upload_form');
           return theme('upload-re', $form);
        } else {
           // Otherwise, they're denied.
           drupal_access_denied();       
        }
}


function wmf_registration_perm(){
        return array('administer registration');
}

function drupal_to_re_upload_form(){
        $form['#attributes'] = array('enctype' => "multipart/form-data");
        $form['file_upload'] = array(
          '#type' => 'file',
          '#title' => 'Filename'
        );
        
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => 'Upload file',
          '#submit' => array('drupal_to_re_form_submit')
        );
        return $form;
}

function check_incoming_csv_file($file, $limits){
        
        /*
         Check that you have a header First row is non-numeric
         Check that you have two columns (in the first row at least)
        */
	
		ini_set('auto_detect_line_endings', 1);

        $errors = array();
        
        $f = fopen($file->filepath, 'r');
        // Assume header is first line.
        
        $header = true;
        $allowed_cols = $limits;
        
        // Grab the first row
        
        $data = fgetcsv($f, ",");
        if(count($data) != $allowed_cols){
                $errors[] = t("There should be ". $allowed_cols . " columns. Found " . count($data));        
        }
        
        foreach($data as $column){
                if(is_numeric($column)){
                        $header = false;
                }
        }
        
        if(!$header){
             $errors[] = "There is no header row at the beginning of the file.";   
        }

        return $errors;

}

function drupal_to_re_form_submit($form, &$form_state){
	
    /*
    Remove update in Constant Contact

	require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
	require_once("sites/all/modules/custom/newsletter/newsletter_shared_data.php");
	$cc = get_constant_contact();
	
	*/	
  
  $limits = array("columns"=> 2);
  $validators = array('check_incoming_csv_file' => $limits);

  if($file = file_save_upload('file_upload', $validators, file_directory_path() . "/wmf-data-uploads", FALSE)) {
  	
    $first_line = true;
    $f = fopen($file->filepath, 'r');
    
    $synched_total = 0;
    $rejected_lines = array();
    
    while($data = fgetcsv($f, ",")){
				
        if($first_line){
                // The first line is the header line, so reject it.
                
                $rejected_lines[] = implode($data, ",");
                $first_line = false;
                continue;
                
        } else if (count($data) != $limits['columns']){
                // If a line doesn't have the right number of columns, reject it
                
                $rejected_lines[] = implode($data, ",");                
                continue;
        
        } else {
                // Attempt to add the data to the database
                $re_id = $data[0];
                $web_id = (int)$data[1];

                // If the line is empty (often a last line) reject it.
                if($re_id == false && $web_id == false){
                        $rejected_lines[] = implode($data, ",");
                        continue;
                }
                
                /*
                Note: you could just check for synched to raisers edge in the select statement, but the spec defines the operation as
                its done below. There might be a reason.
                */
                                
                $userinfo = db_query("SELECT firstname, synched_to_raisers_edge, raisers_edge_id, mail FROM user_information INNER JOIN users WHERE user_information.uid = %d AND users.uid = user_information.uid", $web_id);
                
                $userinfo = db_fetch_object($userinfo);
                
                //drupal_set_message("userinfo: " . $userinfo . " " . $userinfo->raisers_edge_id . " " . $userinfo->synched_to_raisers_edge);
                
                if($userinfo->raisers_edge_id == NULL && $userinfo->synched_to_raisers_edge == 0){                	        
                        // If a web user doesn't have an REID and synched to RE is false, add it to the user info table then set synched to RE to true
                       
                        db_query("UPDATE {user_information} SET raisers_edge_id = '%s', synched_to_raisers_edge = 1 WHERE uid = %d", $re_id, $web_id);
                        $affected_rows = db_affected_rows();
                        $synched_total += $affected_rows;           

                        /*
                        Remove update in Constant Contact

                        
                        $ids = array(get_field_for_raisersedge_id() => $re_id,
                        			get_field_for_web_id() => $web_id);                        
                        
              			if($affected_rows > 0){
                        	add_data_to_custom_field($cc, urlencode($userinfo->mail), $ids);	
                        }
						*/			
                        			                        
                } else if ($userinfo->synched_to_raisers_edge == 0){
                        
                        // IF a web user has an REID and synched to re is false then set synched to re to true
                        //drupal_set_mesage(sprintf("UPDATE {user_information} SET synched_to_raisers_edge = 1 WHERE uid = %d", $web_id)); 
                        db_query("UPDATE {user_information} SET synched_to_raisers_edge = 1 WHERE uid = %d", $web_id);
                        $affected_rows = db_affected_rows();
                        $synched_total += $affected_rows;

                        /*
                        Remove update in Constant Contact

                        $ids = array(get_field_for_raisersedge_id() => $re_id,
                        			get_field_for_web_id() => $web_id);
                        
              			if($affected_rows > 0){
                        	add_data_to_custom_field($cc, urlencode($userinfo->mail), $ids);	
                        }
						*/			
                        
                } else {
                        // If neither of the above conditions are true, something is wrong. Reject the line.
                        $rejected_lines[] = implode($data, ",");
                }
        }
    
    }
  	drupal_set_message("The file has been uploaded. " . $synched_total . " record(s) have been changed.");  	  
  	file_delete($file->filepath);
  }


}

function wmf_registration_user($op, &$edit, &$account, $category = NULL){

	//

	switch($op){
		case 'delete':
			$sql = "DELETE FROM user_information WHERE uid = %d";
			db_query($sql, $account->uid);
			break;
		case 'validate':
		  require('wmf_registration_shared_data.php');

			if((isset($edit['selfdescription']))
			   && ($edit['selfdescription'] == (count($wmf_registration_self_description_options)-1))
			   && ($edit['selfdescription_other'] == "")){
				form_set_error('selfdescription_other', t('Please enter a description in the other field.'));
			}
			if(isset($edit['read_terms'])
			   && $edit['read_terms'] == 0){
				form_set_error('read_terms', t('You must read the terms of service.'));
			}
			break;
		case 'login':
			if(isset($_SESSION['redirect_on_login'])){
				$redirect = $_SESSION['redirect_on_login'];
				unset($_SESSION['redirect_on_login']);
				drupal_goto($redirect);
			}
			break;
		case 'insert':
			$result = db_query("INSERT INTO {user_information} (uid, firstname, lastname, emaillist, newsletter, selfdescription, selfdescription_other, terms_read) VALUES (%d, '%s', '%s', %d, %d, '%s', '%s', %d)",
					   $edit['uid'], $edit['fname'], $edit['lname'], $edit['emaillist'], $edit['newsletter'], $edit['selfdescription'], $edit['selfdescription_other'], 1);
			if(!$result){
				drupal_set_message("There was an error. Your data may not have been stored.");
			}
						
			/*
			 * CONSTANT CONTACT
			 * 
			 * if emaillist or newsletter chosen:
			 * 	check to see if the user is in constant contact.
			 *  if they are, update the lists and add the web id as a custom field
			 *  if they are not, add them with the appriate lists and the web id
			 * 
			 */
			
			if($edit['newsletter'] == 1 || $edit['emaillist'] == 1){
				require("sites/all/modules/custom/constantcontact/constant-contact.php");
				require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
				
				$lists = array();
					
				if($edit['newsletter'] == 1){
					$lists[] = variable_get('cc_newsletter_list_uri',"");
				}
				
				if($edit['emaillist'] == 1){
					$lists[] = variable_get('cc_email_list_uri',"");
				}
				
				// data is a dictionary of field name => values
				$data = array(get_field_for_web_id() => $edit['uid']);

								
				$cc = get_constant_contact();
				$email = urlencode($edit['mail']);				
				$add_resp = add_user_or_create_and_add_to_cc_list($cc, 
					$edit['fname'], $edit['lname'], $email, $lists
				);
				$data_resp = add_data_to_custom_field($cc, $email, $data);				
			}			
			break;
	}
}

function preexisting_user_form(){	
	/*
		This is the form the user is presented with if we find a match in Raiser's Edge
	*/	
	$options = array(
		'no' => t('No'),
		'yes' => t('Yes'),
	);
	$form['preexisting'] = array(
		'#type' => 'radios',
		'#options' => $options,
		'#required' => 1,
		'#title' => t("Welcome. Your information matches information in our database. Is this you?"),
		'#weight' => 60
	);
	$form['submit'] = array(
		'#type' => 'submit',
		'#value' => t("Submit"),
		'#weight' => 100
	);
	
	return $form;
}

function preexisting_user_form_validate($form, &$form_state){
	/* The user must choose 'yes' or 'no' */
	$val = $form_state['values']['preexisting'];
	if($val != "no" && $val !== "yes"){
		form_set_error('preexisting', t('You have entered an invalid value. Please select Yes or No.'));
	}
}

function preexisting_user_form_submit($form, &$form_state){ 
	
	$val = $form_state['values']['preexisting'];
	global $user;
	
	// Let's just get the result again. If we stick it in the form, we don't know who's had their hands on it.
	
	$account = get_account_object_for_uid(arg(1));
	
	
	$result = check_raisers_edge($account); 
	$data = db_fetch_object($result);
	
	// mark that they've answered the question.
	db_query("UPDATE {user_information} SET answered_preexisting = %d WHERE uid = %d", 1, $account->uid);

	if($val == 'no'){
		// Let the user know you got the answer. They can carry on...
		// make a record in an audit table
		db_query("INSERT INTO {wmf_registration_re_audit (time, uid, re_id, answer) VALUES (%d, %d, '%s', %d)}", time(), $account->uid, $data->constituent_id, 0);
	} else if ($val == 'yes'){
		// make the link
		db_query("UPDATE {user_information} SET raisers_edge_id = '%s' WHERE uid = %d", $data->constituent_id, $account->uid);
		// make a record in an audit table
		db_query("INSERT INTO {wmf_registration_re_audit (time, uid, re_id, answer) VALUES (%d, %d, '%s', %d)}", time(), $account->uid, $data->constituent_id, 1);
		//redirect to edit page and populate form
		// we set this value so the form on the next page knows 
		// it should be grabbing its data from raisers edge
		$array = array('prepopulate' => '1');
		
		/*This is left over. Techinically, it would be nice to move this away from the user, because
		its possible the user and the account are different, but since this is a special part of the  user
		creation process, it doesn't really matter. */				
		user_save($user, $array);

		if(variable_get('cc_toggle_registration', 1)){
			if($account->newsletter == 1 || $account->emaillist ==  1){
				require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
				require_once("sites/all/modules/custom/newsletter/newsletter_shared_data.php");
				$cc = get_constant_contact();
				$email = urlencode($account->mail);
				$customdata = array(get_field_for_raisersedge_id() => $data->constituent_id);			
				$response = add_data_to_custom_field($cc, $email, $customdata);
				if($response == FALSE){
					$warning = sprintf("I was not able to add the raisers edge id (%s) to constant contact for %s", $data->constituent_id, $account->mail);
					watchdog("wmf_registration", $warning);
				}
			}
		}		
	}
}

function check_raisers_edge($account){
	$found = NULL;
	
	$mail = trim($account->mail);
	$fname = trim($account->firstname);
	$lname = trim($account->lastname);
	
	$found = db_query("SELECT * FROM {raisersedge_data} WHERE preferred_email LIKE '%s' AND firstname LIKE '%s' AND lastname LIKE '%s' LIMIT 1", $mail, $fname, $lname);
	return $found;
}

function wmf_registration_form_alter(&$form, $form_state, $form_id){
	
	switch($form_id){
		case 'user_register':
			return wmf_registration_preprocess_registration($form, $form_state, $form_id);
		break;
		case 'user_profile_form': 
			$extended_from = wmf_registration_extended_profile_form($form, $form_state, $form_id);
			return $extended_form; // wmf_registration_extended_profile_form($form, $form_state, $form_id);
		break;
	}

}

function wmf_registration_user_profile_submit($form, &$form_state){	

	// Not the best place to put this, but...
	if($form_state['clicked_button']['#post']['selfdescription'] != 4){
		$form_state['clicked_button']['#post']['selfdescription_other'] = "";
	}
	
	global $user;
	
	$account = get_account_object_for_uid(arg(1));
	
	$sql = "UPDATE (user_information) SET
			firstname = '%s',
			lastname = '%s',
			selfdescription = %d,
			selfdescription_other = '%s',
			address1 = '%s',
			address2 = '%s',
			city = '%s',
			state = '%s',
			country = '%s',
			postalcode = '%s'
			WHERE
			uid = %d";
	
	$vals = array(
			$form_state['clicked_button']['#post']['fname'],
			$form_state['clicked_button']['#post']['lname'],
			$form_state['clicked_button']['#post']['selfdescription'],
			$form_state['clicked_button']['#post']['selfdescription_other'],
			$form_state['clicked_button']['#post']['address1'],
			$form_state['clicked_button']['#post']['address2'],
			$form_state['clicked_button']['#post']['city'],
			$form_state['clicked_button']['#post']['state'],
			$form_state['clicked_button']['#post']['country'],
			$form_state['clicked_button']['#post']['postalcode'],
			$account->uid
	);
	db_query($sql, $vals);
		
	/*
	 * CONSTANT CONTACT
	 * If user has signed up for lists
	 *    check if user is in constant contact
	 *       if she is,
	 *           add the lists she's signed up for
	 *           and update her re id and web id
	 *       if she isn't
	 *           make a contact for her
	 *           with the lists she's chosen
	 *           and add the re id and web id. 
	 *
	 */	
	
	if(variable_get('cc_toggle_registration', 1)){
		require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
		require_once("sites/all/modules/custom/newsletter/newsletter_shared_data.php");
		
		//$emaillist = $form_state['clicked_button']['#post']['emaillist'];
		//$newsletter = $form_state['clicked_button']['#post']['newsletter'];
		
		$emaillist = isset($form_state['clicked_button']['#post']['emaillist']) ? 1: 0;
		$newsletter = isset($form_state['clicked_button']['#post']['newsletter']) ? 1: 0;
		
		$email = urlencode($account->mail);
		$fname = $form_state['clicked_button']['#post']['fname'];
		$lname = $form_state['clicked_button']['#post']['lname'];
		$data = array(get_field_for_web_id() => $account->uid);
		$data[get_field_for_raisersedge_id()]  = $account->raisers_edge_id;
		
		$cc = get_constant_contact();	
		$status = get_reg_status_from_cc($cc, $email);
				
		$add = array();
		$remove = array();
		
		// If user has is not on CC at all
		if(is_null($status)){
			if($emaillist == 1){
				$add[] = variable_get('cc_email_list_uri',"");
			}
			if($newsletter == 1){
				$add[] = variable_get('cc_newsletter_list_uri',"");				
			}
			
			if(count($add) > 0){
				$response = add_user_or_create_and_add_to_cc_list($cc, $fname, $lname, $email, $add);
				$data_resp = add_data_to_custom_field($cc, $email, $data);
				
				if($response == FALSE){
					drupal_set_message("We could not update your mailing preferences at this time. Please try again or contact an administrator.");
				}
				if($data_resp == FALSE){
					$warning = sprintf("I was not able to update the Web ID or Raiser's Edge Constituent ID for %s", $account->mail);
					watchdog("wmf_registration", $warning);
				}
							
			}
		}
		elseif($status !== FALSE) {
			// otherwise, we update a user that's already in CC
			
			// determine if the user is adding or removing lists by 
			// comparing the form choices with their status
			
			if($status['emaillist'] != $emaillist){
				if($emaillist == 0){
					$remove[] = variable_get('cc_email_list_uri',"");
				} else {
					$add[] = variable_get('cc_email_list_uri',"");
				}
			}
			
			if($status['newsletter'] != $newsletter){
				if($newsletter == 0){
					$remove[] = variable_get('cc_newsletter_list_uri',"");
				} else {
					$add[] = variable_get('cc_newsletter_list_uri',"");
				}
			}
			
			if(count($add) > 0){
				$add_resp = add_user_to_cc_list($cc, $email, $add);
				if($add_resp == FALSE){
					drupal_set_message("We could not update your mailing preferences at this time. Please try again or contact an administrator.");
				}
			}
			
			if(count($remove) > 0){
				$rem_resp = remove_user_from_cc_list($cc, $email, $remove);
				if($rem_resp == FALSE){
					drupal_set_message("We could not update your mailing preferences at this time. Please try again or contact an administrator. You can also unsubscribe by following the instructions in the email.");
				}	
			}
			
			if(count($add) > 0 || count($remove) > 0){
				$data_resp = add_data_to_custom_field($cc, $email, $data);
				
				if($data_resp == FALSE){
					$warning = sprintf("I was not able to update the Web ID or Raiser's Edge Constituent ID for %s", $account->mail);
					watchdog("wmf_registration", $warning);
				}
				
			}			
		} 
		else {
			// BAD response from CC
			drupal_set_message("We could not update your mailing preferences at this time. Please try again or contact an administrator.");
		}
	}

}

function check_tags($data){
	return ($data == filter_xss($data)) ? true : false; 
}

function wmf_registration_extended_profile_form(&$form, $form_state, $form_id){
	
		
	$form['account']['pass']['#attributes'] = array('autocomplete'=>'off');
	
	global $user;
	$account = get_account_object_for_uid(arg(1));
	
	// Remove the change password form if the user is the admin,
	// and she's editing a different user's profile
	if($user->uid == 1 && $account->uid != 1){
		unset($form['account']['pass']);
	}
	
	// Grab the base for, first stick on the extra fields from the init reg process
	$form = wmf_registration_preprocess_registration($form, $form_state, $form_id);
	// Remove the redirect to the thank you page
	$form['#redirect'] = NULL;
	
	// Then stick on the rest of the fields
	$form = wmf_registration_get_full_profile_form($form, $form_state, $form_id);
	// Remove the terms and conditions checkbox
	$form['account']['read_terms'] = NULL;
	// Add our own submission function to handle all the additional fields.
	$form['#submit'][] = 'wmf_registration_user_profile_submit';
	
	// Now we populate the form with user data. It's either going to come
	// from the raisers edge data table, or the information they've previously added
	// Up here, get the stuff out of user information...
	$result = db_query("SELECT users.*, user_information.* FROM users, user_information WHERE users.uid = user_information.uid && users.uid = %d LIMIT 1", $account->uid);
		
	if($user->prepopulate == "1"){
		$raisers_result = db_query("SELECT raisersedge_data.* FROM raisersedge_data, user_information WHERE user_information.raisers_edge_id = raisersedge_data.constituent_id && user_information.uid = %d", $account->uid);
		wmf_registration_populate_from_re($form, $result, $raisers_result);
		// Set prepopulate to zero so it doesn't happen next time.
		$array = array('prepopulate' => '0');
		user_save($user, $array); // REFACTOR WHAT DO I DO HERE
	} else {
		wmf_registration_populate_form_from_user_results($form, $result);
	}
	
	/*
	 * I think this is where it makes most sense to add the live constant contact info
	 */
	
	if(variable_get("cc_toggle_registration", 1)){
		require("sites/all/modules/custom/constantcontact/constant-contact.php");
		require_once("sites/all/modules/custom/constantcontact/wmfcc.php");
		$cc = get_constant_contact();
		$status = get_reg_status_from_cc($cc, urlencode($account->mail));
		if($status){
			$form['account']['newsletter']['#value'] = $status['newsletter'];
			$form['account']['emaillist']['#value'] = $status['emaillist'];
		} elseif (is_null($status)) {
			$form['account']['newsletter']['#value'] = 0;		
			$form['account']['emaillist']['#value'] = 0;		
		} else {
			drupal_set_message("The email service is currently offline so we could not check or update your status.  Please try again later or email us for your status.");
		}
		
	}
}

function wmf_registration_populate_from_re(&$form, $result, $raisers_result){
	
		$user_info = db_fetch_object($result);
		$re_info = db_fetch_object($raisers_result);
		$form['account']['title']['#value'] = filter_xss($re_info->title);		
		$form['account']['fname']['#value'] = filter_xss($user_info->firstname);
		$form['account']['lname']['#value'] = filter_xss($user_info->lastname);
		$form['account']['address1']['#value'] = filter_xss($re_info->preferred_address1);
		$form['account']['address2']['#value'] = filter_xss($re_info->preferred_address2);
		$form['account']['city']['#value'] = filter_xss($re_info->preferred_city);
		$form['account']['state']['#value'] = filter_xss($re_info->preferred_state);
		
		/* Raisers edge contains country info, but we need it in a special format. It may
			not match what we have in our database. So we lowercase it, then check the
			array with lowercased keys 
		*/
		
		$country = strtolower($re_info->preferred_country);
		require("wmf_registration_shared_data.php");
		
		$flipped_countries_array = array_flip($countries);
		$lower_flipped_countries_array = array();
		
		foreach($flipped_countries_array as $key=> $value){
			$lower_flipped_countries_array[strtolower($key)] = $value;
		}
		
		if(isset($lower_flipped_countries_array[$country])){
			$country = $lower_flipped_countries_array[$country];
		} else {
			drupal_set_message("We could not confirm your Country. Please correct it in the form below.");
		}
		
		$form['account']['country']['#value'] = filter_xss($country);
		$form['account']['postalcode']['#value'] = filter_xss($re_info->preferred_zip);

		if(variable_get('cc_toggle_registration',1)){
			$form['account']['newsletter']['#value'] = filter_xss($user_info->newsletter);
			$form['account']['emaillist']['#value'] = filter_xss($user_info->emaillist);
		}
		
		if($user_info->selfdescription_other != ''){
			$form['account']['selfdescription']['#default_value'] = filter_xss($user_info->selfdescription);
			$form['account']['selfdescription_other']['#value'] = filter_xss($user_info->selfdescription_other);
		} else {
			$form['account']['selfdescription']['#default_value'] = filter_xss($user_info->selfdescription);
		}
}

function wmf_registration_populate_form_from_user_results(&$form, $result){
	
		$user_info = db_fetch_object($result);		
		$form['account']['title']['#value'] = filter_xss($user_info->title);	
		$form['account']['fname']['#value'] = filter_xss($user_info->firstname);
		$form['account']['lname']['#value'] = filter_xss($user_info->lastname);
		$form['account']['address1']['#value'] = filter_xss($user_info->address1);
		$form['account']['address2']['#value'] = filter_xss($user_info->address2);
		$form['account']['city']['#value'] = filter_xss($user_info->city);
		$form['account']['state']['#value'] = filter_xss($user_info->state);
		$form['account']['country']['#value'] = filter_xss($user_info->country);
		$form['account']['postalcode']['#value'] = filter_xss($user_info->postalcode);
		
		if(variable_get('cc_toggle_registration', 1)){
			$form['account']['newsletter']['#value'] = $user_info->newsletter;
			$form['account']['emaillist']['#value'] = $user_info->emaillist;
		}
		
		if($user_info->selfdescription_other != ''){
			$form['account']['selfdescription']['#default_value'] = filter_xss($user_info->selfdescription);
			$form['account']['selfdescription_other']['#value'] = filter_xss($user_info->selfdescription_other);
		} else {
			$form['account']['selfdescription']['#default_value'] = filter_xss($user_info->selfdescription);
		}

}

function wmf_registration_get_full_profile_form(&$form, $form_state, $form_id){
	$form['account']['address1'] = array(
		'#type' => 'textfield',
	    '#title' => t('Address'),
	    '#default_value' => NULL,
	    '#maxlength' => 60,
	    '#description' => NULL,
	    '#required' => 0,
		'#attributes' => array("autocomplete" => "off"),
		'#weight' => 1
	);
	$form['account']['address2'] = array(
		'#type' => 'textfield',
	    '#title' => t('Address (continued)'),
	    '#default_value' => NULL,
	    '#maxlength' => 30,
	    '#description' => NULL,
	    '#required' => 0,
		'#attributes' => array("autocomplete" => "off"),	
		'#weight' => 2
	);
	$form['account']['city'] = array(
		'#type' => 'textfield',
	    '#title' => t('City'),
	    '#default_value' => NULL,
	    '#maxlength' => 60,
	    '#description' => NULL,
	    '#required' => 0,
		'#attributes' => array("autocomplete" => "off"),	
		'#weight' => 3
	);
	$form['account']['state'] = array(
		'#type' => 'textfield',
	    '#title' => t('State/Province'),
	    '#default_value' => NULL,
	    '#maxlength' => 5,
	    '#description' => "(2 digit code. e.g. NY)",
	    '#required' => 0,
		'#attributes' => array("autocomplete" => "off"),
		'#weight' => 4
	);
	
	$form['account']['postalcode'] = array(
		'#type' => 'textfield',
	    '#title' => t('Postal Code'),
	    '#default_value' => NULL,
	    '#maxlength' => 12,
	    '#description' => NULL,
	    '#required' => 0,
		'#attributes' => array("autocomplete" => "off"),	
		'#weight' => 6
	);
  require('wmf_registration_shared_data.php');
	$form['account']['country'] = array(
		'#type' => 'select',
		'#options' => $countries,
    	'#required' => 0,
		'#title' => t("Country"),	
		'#weight' => 5
	);
	$form['#redirect'] = 'user/' . $user->name;	
	
	return $form;
}

/*
 
This adds the extra fields to the initial registration form.
 
*/

function wmf_registration_preprocess_registration(&$form, $form_state, $form_id){
	$form['account']['fname'] = array(
		'#type' => 'textfield',
        '#title' => t('First Name'),
        '#default_value' => NULL,
        '#maxlength' => 60,
        '#description' => NULL,
        '#required' => 1,
		'#attributes' => array("autocomplete" => "off"),
		'#weight' => -10
		);
	$form['account']['lname'] = array(
		'#type' => 'textfield',
        '#title' => t('Last Name'),
        '#default_value' => NULL,
        '#maxlength' => 60,
        '#description' => NULL,
        '#required' => 1,
		'#attributes' => array("autocomplete" => "off"),	
		'#weight' => -9
		);
		
	if(variable_get("cc_toggle_registration", 1)){
		$form['account']['newsletter'] = array(
			'#type' => 'checkbox',
		               '#maxlength' => 60,
		               '#title' => t("Sign Up for WMF's free e-newsletter, including updates on the 2010 Watch"),
		               '#required' => 0,
						'#default_value' => 1,
			'#weight' => 50
			);
		$form['account']['emaillist'] = array(
			'#type' => 'checkbox',
            '#maxlength' => 60,
            '#title' => t("Email me about WMF campaigns, events and trips"),
            '#required' => 0,		
			'#default_value' => 1,		
			'#weight' => 55
			);		
		}

    // Import the self description options (used here and by the export to raisers edge script)
    require_once('wmf_registration_shared_data.php');

	$form['account']['selfdescription'] = array(
		'#type' => 'radios',
		'#options' => $wmf_registration_self_description_options,
                '#required' => 1,
		'#title' => t("Which best describes you?"),
		'#weight' => 60,
		'#prefix' => "<div class='self-desc'>",
		'#suffix' => "</div>"
		);
	$form['account']['selfdescription_other'] = array(
		'#type' => 'textfield',
		'#title' => NULL,
		'#required' => 0,
		'#description' => NULL,
		'#size' => 30,
		'#weight' => 65,
		'#attributes' => array("autocomplete" => "off")		
		);
	$form['account']['read_terms'] = array(
		'#type' => 'checkbox',
		'#title' => t("I have read the <a href='" . base_path() . "privacy-terms-use' target='_blank'>terms and conditions</a>"),
		'#required' => 1,
		'#description' => NULL,
		'#weight' => 70
		);
	$form['#redirect'] = 'content/thank-you';	
	$form['account']['pass']['#weight'] = 75;
	return $form;
}

function wmf_registration_admin() {
	
  $form = array();
  $form['cc_toggle_registration'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use Constant Contact in registration process.'),
    '#default_value' => variable_get('cc_toggle_registration', TRUE),
    '#description' => t("Use Constant Contact in registration process. If this box is unchecked, users will not be given the option of signing up for the newsletter and emaillist in the registration process or in their profiles."),
  );

  return system_settings_form($form);
}






?>

 Best,

L

MarthaW
Regular Participant

P.S.

 

Someone who worked on this code thinks the error is occuring in the function call:

 

$data_resp = add_data_to_custom_field($cc, $email, $data);
The function calls back to the constact contact api and it somewhere in this function add_data_to_custom_field

Hey Martha,

 

Looked over your code and from as far as I can see everything seems to be ok.  So if the contact gets put into constant contact but not into the database, I would have to assume it is where the contact is created into the DB where the issue occurs. 

Ryan Davis
Quality Engineer
MarthaW
Regular Participant

Thanks - the issue is really just that the 'thank you' page is not returned and the activation email does not get sent. I think this is a server setting or mod security rule issue.

MarthaW
Regular Participant

Also, the error log shows that each time a user attempts to register, the site is trying to access:

http://dev.wmf.org/crossdomain.xml

 

which does not exist. Does CC require a cross domain file to be in place?

The crossdomain.xml files are used only by Adobe Flash family of languages (Flash and Flex) to get around XSS vulnerabilities.  Constant Contact is not involved in this requirement as our API features are webservices and thus are not language specific.  If the Contact is being added to your account and the failure is sending an email from your server, than the problem is likely due to server configuration and/or differences from the previous server you were hosted on. 

 

If you are failing on a crossdomain.xml file, than you are likely trying to access a file on another server (possibly by including a reference directly to that server) through a Flash/Flex script and thus the error is being thrown that you do not have access to that server via scripting.  This would not have anything to do with the Constant Contact API or your integration with us. 

 

At this point, it sounds like the problems are likely with the new configuration of the server you migrated to.  My recommendation would be to work with the technical support for your new hosting company and/or vendor for the hosting software.  Since the problem is not with the API features of Constant Contact, we are not going to be able to provide any assistance with these problems.

Dave Berard
Senior Product Manager, Constant Contact
MarthaW
Regular Participant

Thanks, Dave. Yes, I've been working with the host for two weeks - 7 different sysadmins have not been able to solve the problem, so I'm looking at all angles.

 

Thanks so much!

Lissa

MarthaW
Regular Participant

Hello Dave & Ryan,

 

As you recommended, I went back to the host (LiquidWeb) and asked one more technican to look at this. Since the code works on the old server, but not on the new, I also think this could be solved by a server configuration.

 

However, the new sysadmin seems to think he tracked down the issue to one line of code. I paste the code below - and his comment that the problem occurs in Line 109 or  $response = curl_exec($session);

and I hope that perhaps you could recommend exactly WHAT could be changed on the server to fix it, since he (and a dozen other sysadmins at a reputable hosting company) do not seem to know, and it's certainly beyond me.

 

Thanks again,

Lissa

 

HIS COMMENT:

 

I've been working on this all day, tracing the source of the error through
your application, and I finally found it. This error is unequivocally coming
from constant contact, in the file:
prodenv/sites/all/modules/custom/constantcontact/constant-contact.php

on line 109. The problem appears to be with the way they're using curl, but I
can't be sure. I attempted to connect to their API using the same information
as this script, but I couldn't authenticate for some reason.

In any case, curl is indeed working in other places, which strongly suggests
that this function is at fault somehow.

 

There could be something on the server that needs to change for it work properly, but I'm unable to say what that is.
You need a developer to look at why that particular call is failing, since the application itself is not telling us.

 

THE CODE (WITH HIS COMMENT ON LINE 110 POINTING TO THE LINE HE TRACED THE ERROR TO):

 

<?php
/**
 * An easy to use Constant Contact PHP Interface
 *
 * @name      ConstantContact PHP Interface
 * @author    Jared De Blander <jared@iofast.com>
 * @copyright (c) 2008 Jared De Blander
 * @link      http://www.iofast.com
 * @link      http://www.jareddeblander.com
 * @license   MIT
 * @version   $Rev$
 * @internal  $Id$
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * NOTICE:
 * Further alteration of this software were made by ESI design.
 *
 */
class constant_contact{

  //Debugging state
  private $debug;

  private $user;
  private $pass;
  private $api_key;

  /**
   * The ConstantContact contructor
   *
   * @param String $user - Your username
   * @param String $pass - Your password
   * @param String $api_key - Your API Key
   */
  public function __construct($user='', $pass='', $api_key=''){
    $this->debug=false;

    $this->set_user($user);
    $this->set_pass($pass);
    $this->set_api_key($api_key);
  }
 
  /**
   * Get a contact
   * @param int $contact_id - ID of the contact
   */
 
  public function get_contact($url){
        $post = "";
         $response = $this->fetch($url, $post);
          return $response;
  }
 
  public function get_contact_from_id($id){
          $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts/'.$id;
        return get_contact_from_url($url);
  }
 
  public function get_contact_from_url($url){
        $post = "";
         $response = $this->fetch($url, $post);
          return $response;
  }
 
  public function update_contact($contact){
     
          $tmpfile = tmpfile();
          fwrite($tmpfile, $contact);
          fseek($tmpfile, 0);
     
            $contact_arr = $this->xml_to_array($contact);
          $url = $contact_arr['entry']['id']['value'];
        $url = str_replace('http://', 'https://', $url);
       
          $session = curl_init($url);
         
        $usrpsw = $this->api_key. '%' .$this->user .':'.$this->pass;
        curl_setopt($session, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($session, CURLOPT_USERPWD, $usrpsw);
        curl_setopt($session, CURLOPT_INFILE, $tmpfile);
        fclose($tmpfile);
       
        curl_setopt($session, CURLOPT_PUT, 1);
        curl_setopt($session, CURLOPT_INFILESIZE, strlen($contact));

        curl_setopt($session, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
        curl_setopt($session, CURLOPT_HEADER, 0);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, 0);

        $response = curl_exec($session);
        // ^ this line is where the app is choking on that form submission

        $this->debug_print("HTTP Response Code '".curl_getinfo($session, CURLINFO_HTTP_CODE)."'");
        $this->debug_print("Received:<pre>\n\n---START---\n". htmlspecialchars($response) ."\n---END---\n\n</pre>");
   
        curl_close($session);
        return $response;
     
  }
 
  /**
   * Add a contact
   *
   * @param String $first_name - First name
   * @param String $last_name - Last name
   * @param String $email - Email address
   * @param Array of Strings $lists - The lists to subscribe to. This should be the entire id of the list
   */
  public function add_contact($first_name, $last_name, $email, $lists){
     
    $post ='<entry xmlns="http://www.w3.org/2005/Atom">';
    $post.='<title type="text"> </title>';
    $post.='<updated>'.date('Y-m-d\TH:i:s\Z') .'Z</updated>';
    $post.='<author></author>';
    $post.='<id>data:,none</id>';
    $post.='<summary type="text">Contact</summary>';
    $post.='<content type="application/vnd.ctct+xml">';
    $post.='<Contact xmlns="http://ws.constantcontact.com/ns/1.0/">';
    $post.='<EmailAddress>'.urldecode($email).'</EmailAddress>';
    $post.='<FirstName>'.$first_name.'</FirstName>';
    $post.='<LastName>'.$last_name.'</LastName>';
    $post.='<OptInSource>ACTION_BY_CONTACT</OptInSource>';
    $post.='<ContactLists>';
    foreach($lists as $list){
        $post.='<ContactList id="' . $list . '" />';         
    }
    $post.='</ContactLists>';
    $post.='</Contact>';
    $post.='</content>';
    $post.='</entry>';
     
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts';
    $credentials = $this->api_key. '%' .$this->user .':'.$this->pass;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS , $post);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
   
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
  }

  /**
   * Turn debugging output off.
   *
   */
  public function debug_off(){
    $this->debug=false;
  }

  /**
   * Turn debugging output on.
   *
   */
  public function debug_on(){
    $this->debug=true;
  }
 
  public function ping(){
      $url = "https://api.constantcontact.com/ws/customers/".$this->user."/";
    $credentials=$this->api_key.'%'.$this->user.':'.$this->pass;
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, 0);
      curl_setopt($ch, CURLOPT_HEADER, False);
      return curl_exec($ch);
  }

  /**
   * Print debugging output
   *
   * @param String $string - String to print
   */
  private function debug_print($string){
    if($this->debug) echo "ConstantContact Debug: $string<br>\n";
  }

  /**
   * Fetch a URI from ConstantContact
   *
   * @param String $url - URL to connect to
   * @param String $post - POST data to include
   * @return Respose
   */
  private function fetch($url, $post){
    $credentials=$this->api_key.'%'.$this->user.':'.$this->pass;
    $ch=curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD,  $credentials);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(strlen(trim($post))>0){
      $this->debug_print("And Posting:<pre>\n\n---START---\n". htmlspecialchars($post) ."\n---END---\n\n</pre>");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/atom+xml'));
    }else{
      $this->debug_print("Not posting");
      curl_setopt($ch, CURLOPT_POST, 0);
    }
    if($this->debug){
      curl_setopt($ch, CURLOPT_HEADER, True);
    }else{
      curl_setopt($ch, CURLOPT_HEADER, False);
    }

    $response = curl_exec($ch);
    $this->debug_print("HTTP Response Code '".curl_getinfo($ch, CURLINFO_HTTP_CODE)."'");
    $this->debug_print("Received:<pre>\n\n---START---\n". htmlspecialchars($response) ."\n---END---\n\n</pre>");
   
    curl_close($ch);
    return $response;
  }


  public function get_activities_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/activities';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Return your list of campaigns
   *
   * @return XML document containing your campaigns
   */
  public function get_campaigns_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/campaigns';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Return your list of contacts. Paths can be specified to show
   * information about a specific contact. Path data can be found
   * in the master contact list by specifying no path.
   *
   * @param String $path - Optionally specify a path
   * @return XML document containing your contacts.
   */
  public function get_contacts_xml($path=''){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/contacts'.$path;
    $post='';
    $response = $this->fetch($url, $post);
    return $response;
  }


  /**
   * Used to retrieve your list information. Paths can be specified
   * to show information about a specific list. Path data can be
   * found in the master list retrieved by specifying no path.
   *
   * @param String $path - Optionally specify a path.
   * @return XML document containing list information
   */
  public function get_lists_xml($path=''){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/lists'.$path;
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }


  /**
   * Retrieves the XML service document
   *
   * @return XML service document
   */
  public function get_service_doc_xml(){
    $url='https://api.constantcontact.com/ws/customers/'.$this->user.'/';
    $post='';

    $response=$this->fetch($url, $post);
    return $response;
  }

  /**
   * Sets your API key
   *
   * @param String $api_key - Your API Key
   */
  public function set_api_key($api_key){
    $this->api_key=$api_key;
  }

  /**
   * Set your ConstantContact Password
   *
   * @param String $pass - Your Password
   */
  public function set_pass($pass){
    $this->pass=$pass;
  }

  /**
   * Set your ConstantContact Username
   *
   * @param String $user - Your Username
   */
  public function set_user($user){
    $this->user=$user;
  }

  /**
   * Converts XML data into a nested array
   *
   * @param String $contents - XML string
   * @param Integers $get_attributes - Include attributes (default 1)
   * @return Nested associative array
   */
  public function xml_to_array($contents, $get_attributes=1) {

    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
      return array();
    }

    $parser = xml_parser_create();
    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, $contents, $xml_values );
    xml_parser_free( $parser );

    if(!$xml_values) return;

    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array;


    foreach($xml_values as $data) {
      unset($attributes,$value);
      extract($data);

      $result = '';
      if($get_attributes) {
        $result = array();
        if(isset($value)) $result['value'] = $value;
        if(isset($attributes)) {
          foreach($attributes as $attr => $val) {
            if($get_attributes == 1) $result['attr'][$attr] = $val;
          }
        }
      } elseif(isset($value)) {
        $result = $value;
      }

      if($type == "open") {
        $parent[$level-1] = &$current;
        if(!is_array($current) or (!in_array($tag, array_keys($current)))) {
          $current[$tag] = $result;
          $current = &$current[$tag];
        } else {
          if(isset($current[$tag][0])) {
            array_push($current[$tag], $result);
          } else {
            $current[$tag] = array($current[$tag],$result);
          }
          $last = count($current[$tag]) - 1;
          $current = &$current[$tag][$last];
        }
      } elseif($type == "complete") {

        if(!isset($current[$tag])) {
          $current[$tag] = $result;
        } else {
          if((is_array($current[$tag]) and $get_attributes == 0)
          or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
            array_push($current[$tag],$result);
          } else {
            $current[$tag] = array($current[$tag],$result);
          }
        }
      } elseif($type == 'close') {
        $current = &$parent[$level-1];
      }
    }
    return($xml_array);
  }
 
}


?>

I'm sorry that this is causing problems for you, however this is not a library that is provided by Constant Contact or supported by Constant Contact.  If you notice the top of the code you posted, it is provided by a 3rd party who did this development work on his own (see below quoted text).

 

There is definitely a lot of confusion here on my part from what you've earlier posted and what you're now posting from your hosting provider.  Earlier you told us that the Contact is being added to your account and the problem is simply with a confirmation email being sent and the error page not being found when the error occurs.  If this is the case, there is no conflict both from this library and Constant Contact API features. 

 

The follow up here is now that there is an error in the curl_exec() method that is causing a problem.  This could indicate many things, depending on what the actual error that is being thrown is.  For example, if the curl request is being sent but an error message is being returned from our API (such as a 409 Conflict or a 400 Bad Request), this would indicate that the library you are using is not creating the request correctly and that would indicate a library error.  If curl is just throwing a generic curl error, this would indicate something is different with the version/setup of curl you previously had installed on your old server and the current one, something that is beyond the scope of this forum to support.

 

Is there any chance you can provide additional information into the exact error message that is happening with Curl?  At this point, there isn't any information to indicate what is actually happening and with the different symptoms previously reported, there is no way to provide you with any detailed direction.

 

Library information (note this is not a Constant Contact wrapper library and therefor is not maintained or supported by Constant Contact):

 

/**
* An easy to use Constant Contact PHP Interface
*
* @name      ConstantContact PHP Interface
* @author Jared De Blander <jared@iofast.com>
* @copyright (c) 2008 Jared De Blander
* @link      http://www.iofast.com
* @link      http://www.jareddeblander.com
* @license   MIT
* @version   $Rev$
* @internal  $Id$
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* NOTICE:
* Further alteration of this software were made by ESI design.
*
*/

 

Dave Berard
Senior Product Manager, Constant Contact
MarthaW
Regular Participant

Thanks, Dave! I will share your reply with the host and see if they can provide any additional information on the error and/or compare the curl version/setup on the new server to the old.

 

Best,

L

Developer Portal

View API documentation, code samples, get your API key.

Visit Page