/**
  * Process the feed, subscribe the user to the list.
  *
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  *
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If API instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->log_error(__METHOD__ . '(): Failed to set up the API.');
         return;
     }
     /* Setup member array. */
     $member = array('email' => $this->get_field_value($form, $entry, $feed['meta']['email_address']), 'fields' => array(), 'group_ids' => array());
     /* If email address is empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($member['email'])) {
         $this->log_error(__METHOD__ . '(): Aborting. Email address invalid.');
         return;
     }
     /* If a group is set, add it to the member array. */
     if ($feed['meta']['group'] !== 'none') {
         $member['group_ids'][] = $feed['meta']['group'];
     }
     /* Add custom fields (if exist) to the member array. */
     if (!empty($feed['meta']['custom_fields'])) {
         foreach ($feed['meta']['custom_fields'] as $custom_field) {
             $member['fields'][$custom_field['key']] = $this->get_field_value($form, $entry, $custom_field['value']);
         }
     }
     /* If no custom fields were added to the member array, remove it. */
     if (empty($member['fields'])) {
         unset($member['fields']);
     }
     /* Add member to group. */
     $this->log_debug(__METHOD__ . '(): Member to be added => ' . print_r($member, true));
     try {
         /* If double optin, use membersSignup function. Otherwise, use addSingle function. */
         if ($feed['meta']['double_optin'] == true) {
             $add_member = json_decode($this->api->membersSignup($member));
         } else {
             $add_member = json_decode($this->api->membersAddSingle($member));
         }
         if ($add_member->status == true) {
             $this->log_debug(__METHOD__ . "(): Member {$member['email']} added.");
         } else {
             $this->log_debug(__METHOD__ . "(): Member {$member['email']} already existed and has been updated.");
         }
     } catch (Exception $e) {
         $this->log_error(__METHOD__ . "(): Unable to add member {$member['email']}; {$e->getMessage()}");
     }
 }
Beispiel #2
0
 private static function is_valid_notification_email($text)
 {
     if (empty($text)) {
         return false;
     }
     $emails = explode(",", $text);
     foreach ($emails as $email) {
         $email = trim($email);
         $invalid_email = GFCommon::is_invalid_or_empty_email($email);
         $invalid_variable = !preg_match('/^({[^{]*?:(\\d+(\\.\\d+)?)(:(.*?))?},? *)+$/', $email);
         if ($invalid_email && $invalid_variable) {
             return false;
         }
     }
     return true;
 }
 public static function resend_notifications()
 {
     check_admin_referer('gf_resend_notifications', 'gf_resend_notifications');
     $leads = rgpost('leadIds');
     // may be a single ID or an array of IDs
     $leads = !is_array($leads) ? array($leads) : $leads;
     $form = RGFormsModel::get_form_meta(rgpost('formId'));
     if (empty($leads) || empty($form)) {
         _e("There was an error while resending the notifications.", "gravityforms");
         die;
     }
     $send_admin = rgpost('sendAdmin');
     $send_user = rgpost('sendUser');
     $override_options = array();
     $validation_errors = array();
     if (rgpost('sendTo')) {
         if (rgpost('sendTo') && GFCommon::is_invalid_or_empty_email(rgpost('sendTo'))) {
             $validation_errors[] = __("The <strong>Send To</strong> email address provided is not valid.", "gravityforms");
         }
         if (!empty($validation_errors)) {
             echo count($validation_errors) > 1 ? '<ul><li>' . implode('</li><li>', $validation_errors) . '</li></ul>' : $validation_errors[0];
             die;
         }
         $override_options['to'] = rgpost('sendTo');
         $override_options['bcc'] = '';
         // overwrite bcc settings
     }
     foreach ($leads as $lead_id) {
         $lead = RGFormsModel::get_lead($lead_id);
         if ($send_admin) {
             GFCommon::send_admin_notification($form, $lead, $override_options);
         }
         if ($send_user) {
             GFCommon::send_user_notification($form, $lead, $override_options);
         }
     }
     die;
 }
 private static function is_valid_notification_email($text)
 {
     if (empty($text)) {
         return false;
     }
     $emails = explode(',', $text);
     foreach ($emails as $email) {
         $email = trim($email);
         $invalid_email = GFCommon::is_invalid_or_empty_email($email);
         // this used to be more strict; updated to match any merge-tag-like string
         $invalid_variable = !preg_match('/^{.+}$/', $email);
         if ($invalid_email && $invalid_variable) {
             return false;
         }
     }
     return true;
 }
Beispiel #5
0
 public static function resend_notifications()
 {
     check_admin_referer('gf_resend_notifications', 'gf_resend_notifications');
     $form_id = rgpost('formId');
     $leads = rgpost('leadIds');
     // may be a single ID or an array of IDs
     if (0 == $leads) {
         // get all the lead ids for the current filter / search
         $filter = rgpost("filter");
         $search = rgpost("search");
         $star = $filter == "star" ? 1 : null;
         $read = $filter == "unread" ? 0 : null;
         $status = in_array($filter, array("trash", "spam")) ? $filter : "active";
         $search_criteria["status"] = $status;
         if ($star) {
             $search_criteria["field_filters"][] = array("key" => "is_starred", "value" => (bool) $star);
         }
         if (!is_null($read)) {
             $search_criteria["field_filters"][] = array("key" => "is_read", "value" => (bool) $read);
         }
         $search_field_id = rgpost("fieldId");
         if (isset($_POST["fieldId"]) && $_POST["fieldId"] !== '') {
             $key = $search_field_id;
             $val = $search;
             $strpos_row_key = strpos($search_field_id, "|");
             if ($strpos_row_key !== false) {
                 //multi-row
                 $key_array = explode("|", $search_field_id);
                 $key = $key_array[0];
                 $val = $key_array[1] . ":" . $val;
             }
             $search_criteria["field_filters"][] = array("key" => $key, "operator" => rgempty("operator", $_POST) ? "is" : rgpost("operator"), "value" => $val);
         }
         $leads = GFFormsModel::search_lead_ids($form_id, $search_criteria);
     } else {
         $leads = !is_array($leads) ? array($leads) : $leads;
     }
     $form = apply_filters("gform_before_resend_notifications_{$form_id}", apply_filters('gform_before_resend_notifications', RGFormsModel::get_form_meta($form_id), $leads), $leads);
     if (empty($leads) || empty($form)) {
         _e("There was an error while resending the notifications.", "gravityforms");
         die;
     }
     $notifications = json_decode(rgpost('notifications'));
     if (!is_array($notifications)) {
         die(__("No notifications have been selected. Please select a notification to be sent.", "gravityforms"));
     }
     if (rgpost('sendTo') && GFCommon::is_invalid_or_empty_email(rgpost('sendTo'))) {
         die(__("The <strong>Send To</strong> email address provided is not valid.", "gravityforms"));
     }
     foreach ($leads as $lead_id) {
         $lead = RGFormsModel::get_lead($lead_id);
         foreach ($notifications as $notification_id) {
             $notification = $form["notifications"][$notification_id];
             if (!$notification) {
                 continue;
             }
             //overriding To email if one was specified
             if (rgpost('sendTo')) {
                 $notification["to"] = rgpost('sendTo');
                 $notification["toType"] = "email";
             }
             GFCommon::send_notification($notification, $form, $lead);
         }
     }
     die;
 }
 /**
  * Processes the feed, subscribes the user to the list.
  * 
  * @access public
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  * @return array|null
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If Mad Mimi instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         return $entry;
     }
     /* Prepare audience member import array. */
     $audience_member = array();
     /* If a list is chosen for this feed, add it to the audience member array. */
     $audience_member['add_list'] = $feed['meta']['list'];
     /* Find all fields mapped and push them to the audience member array. */
     foreach ($this->get_field_map_fields($feed, 'fields') as $field_name => $field_id) {
         $field_value = $this->get_field_value($form, $entry, $field_id);
         if (!rgblank($field_value)) {
             $audience_member[$field_name] = $field_value;
         }
     }
     /* If email address is empty, return. */
     if (GFCommon::is_invalid_or_empty_email($audience_member['email'])) {
         $this->log_error(__METHOD__ . '(): Email address not provided.');
         return;
     }
     /* Push any custom fields to the audience member array. */
     if (!empty($feed['meta']['custom_fields'])) {
         foreach ($feed['meta']['custom_fields'] as $custom_field) {
             /* If field map field is not paired to a form field, skip. */
             if (rgblank($custom_field['value'])) {
                 continue;
             }
             $field_value = $this->get_field_value($form, $entry, $custom_field['value']);
             if (!rgblank($field_value)) {
                 $field_name = $custom_field['key'] == 'gf_custom' ? $custom_field['custom_key'] : $custom_field['key'];
                 $audience_member[$field_name] = $field_value;
             }
         }
     }
     /* Check if audience member already exists. */
     $this->log_debug(__METHOD__ . "(): Checking to see if {$audience_member['email']} is already on the list.");
     $member_search = $this->api->search($audience_member['email']);
     $member_exists = $member_search['success'] && $member_search['result']['count'] > 0;
     /* If the audience member exists, add them to the list and update information. If the audience member does not exist, add audience member.  */
     if ($member_exists) {
         /* Fork audience member array to remove email and list information. */
         $updated_info = $audience_member;
         $updated_info['first_name'] = $updated_info['firstname'];
         $updated_info['last_name'] = $updated_info['lastname'];
         unset($updated_info['add_list']);
         unset($updated_info['email']);
         unset($updated_info['firstname']);
         unset($updated_info['lastname']);
         /* If a list is chosen, check if they exist on list. */
         if (isset($audience_member['add_list'])) {
             $is_member_on_list = $this->is_member_on_list($audience_member['email'], $audience_member['add_list'], $member_search);
             if (!$is_member_on_list) {
                 $this->log_debug(__METHOD__ . "(): {$audience_member['email']} exists, but is not on list; adding audience member to list.");
                 $this->api->add_membership($audience_member['add_list'], $audience_member['email'], $updated_info);
             } else {
                 $this->log_debug(__METHOD__ . "(): {$audience_member['email']} exists on list; updating info.");
                 $this->api->update_member($audience_member['email'], $updated_info);
             }
         } else {
             $this->log_debug(__METHOD__ . "(): {$audience_member['email']} exists; updating info.");
             $this->api->update_member($audience_member['email'], $updated_info);
         }
     } else {
         $this->log_debug(__METHOD__ . "(): {$audience_member['email']} does not exist; adding audience member to list.");
         $this->api->add_member($audience_member);
     }
     return $entry;
 }
 public static function resend_notifications()
 {
     check_admin_referer('gf_resend_notifications', 'gf_resend_notifications');
     $form_id = rgpost('formId');
     $leads = rgpost('leadIds');
     // may be a single ID or an array of IDs
     if (0 == $leads) {
         // get all the lead ids for the current filter / search
         $filter = rgpost("filter");
         $search = rgpost("search");
         $star = $filter == "star" ? 1 : null;
         $read = $filter == "unread" ? 0 : null;
         $status = in_array($filter, array("trash", "spam")) ? $filter : "active";
         $leads = GFFormsModel::get_lead_ids($form_id, $search, $star, $read, null, null, $status);
     } else {
         $leads = !is_array($leads) ? array($leads) : $leads;
     }
     $form = apply_filters("gform_before_resend_notifications_{$form_id}", apply_filters('gform_before_resend_notifications', RGFormsModel::get_form_meta($form_id), $leads), $leads);
     if (empty($leads) || empty($form)) {
         _e("There was an error while resending the notifications.", "gravityforms");
         die;
     }
     $notifications = json_decode(rgpost('notifications'));
     if (!is_array($notifications)) {
         die(__("No notifications have been selected. Please select a notification to be sent.", "gravityforms"));
     }
     if (rgpost('sendTo') && GFCommon::is_invalid_or_empty_email(rgpost('sendTo'))) {
         die(__("The <strong>Send To</strong> email address provided is not valid.", "gravityforms"));
     }
     foreach ($leads as $lead_id) {
         $lead = RGFormsModel::get_lead($lead_id);
         foreach ($notifications as $notification_id) {
             $notification = $form["notifications"][$notification_id];
             if (!$notification) {
                 continue;
             }
             //overriding To email if one was specified
             if (rgpost('sendTo')) {
                 $notification["to"] = rgpost('sendTo');
                 $notification["toType"] = "email";
             }
             GFCommon::send_notification($notification, $form, $lead);
         }
     }
     die;
 }
 public static function resend_notifications()
 {
     check_admin_referer('gf_resend_notifications', 'gf_resend_notifications');
     $leads = rgpost('leadIds');
     // may be a single ID or an array of IDs
     $leads = !is_array($leads) ? array($leads) : $leads;
     $form_id = rgpost('formId');
     $form = apply_filters("gform_before_resend_notifications_{$form_id}", apply_filters('gform_before_resend_notifications', RGFormsModel::get_form_meta($form_id), $leads), $leads);
     if (empty($leads) || empty($form)) {
         _e("There was an error while resending the notifications.", "gravityforms");
         die;
     }
     $notifications = json_decode(rgpost('notifications'));
     if (!is_array($notifications)) {
         die(__("No notifications have been selected. Please select a notification to be sent.", "gravityforms"));
     }
     if (rgpost('sendTo') && GFCommon::is_invalid_or_empty_email(rgpost('sendTo'))) {
         die(__("The <strong>Send To</strong> email address provided is not valid.", "gravityforms"));
     }
     foreach ($leads as $lead_id) {
         $lead = RGFormsModel::get_lead($lead_id);
         foreach ($notifications as $notification_id) {
             $notification = $form["notifications"][$notification_id];
             if (!$notification) {
                 continue;
             }
             //overriding To email if one was specified
             if (rgpost('sendTo')) {
                 $notification["to"] = rgpost('sendTo');
                 $notification["toType"] = "email";
             }
             GFCommon::send_notification($notification, $form, $lead);
         }
     }
     die;
 }
 /**
  * Process the feed, subscribe the user to the list.
  *
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  *
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If GetResponse instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->log_debug(__METHOD__ . '(): Failed to set up the API.');
         return;
     }
     /* Prepare new contact array */
     $contact = array('name' => $this->get_field_value($form, $entry, $feed['meta']['fields_name']), 'email' => $this->get_field_value($form, $entry, $feed['meta']['fields_email']), 'custom_fields' => array());
     /* If email address is empty or invalid, exit. */
     if (GFCommon::is_invalid_or_empty_email($contact['email'])) {
         $this->log_error(__METHOD__ . '(): Aborting. Email address invalid.');
         return;
     }
     /* Find any custom fields mapped and push them to the new contact array. */
     if (!empty($feed['meta']['custom_fields'])) {
         foreach ($feed['meta']['custom_fields'] as $custom_field) {
             /* If no field is paired to this key, skip field. */
             if (rgblank($custom_field['value'])) {
                 continue;
             }
             /* Get the field value. */
             $field_value = $this->get_field_value($form, $entry, $custom_field['value']);
             /* If this field is empty, skip field. */
             if (rgblank($field_value)) {
                 continue;
             }
             /* Get the custom field name */
             if ($custom_field['key'] == 'gf_custom') {
                 $custom_field_name = trim($custom_field['custom_key']);
                 // Set shortcut name to custom key
                 $custom_field_name = str_replace(' ', '_', $custom_field_name);
                 // Remove all spaces
                 $custom_field_name = preg_replace('([^\\w\\d])', '', $custom_field_name);
                 // Strip all custom characters
                 $custom_field_name = strtolower($custom_field_name);
                 // Set to lowercase
                 $custom_field_name = substr($custom_field_name, 0, 32);
             } else {
                 $custom_field_name = $custom_field['key'];
             }
             /* Trim field value to max length. */
             $field_value = substr($field_value, 0, 255);
             $contact['custom_fields'][$custom_field_name] = $field_value;
         }
     }
     $this->log_debug(__METHOD__ . '(): Contact to be added => ' . print_r($contact, true));
     /* Check if email address is already on this campaign list. */
     $this->log_debug(__METHOD__ . "(): Checking to see if {$contact['email']} is already on the list.");
     $email_in_campaign = get_object_vars($this->api->getContactsByEmail($contact['email'], array($feed['meta']['campaign']), 'CONTAINS'));
     /* If email address is not in campaign, add. Otherwise, update. */
     if (empty($email_in_campaign)) {
         $add_contact_response = $this->api->addContact($feed['meta']['campaign'], $contact['name'], $contact['email'], 'standard', 0, $contact['custom_fields']);
         if (is_null($add_contact_response)) {
             $this->log_debug(__METHOD__ . "(): {$contact['email']} is on campaign list, but unconfirmed.");
             return;
         } else {
             $this->log_debug(__METHOD__ . "(): {$contact['email']} is not on campaign list; added info.");
             return;
         }
     } else {
         $this->log_debug(__METHOD__ . "(): {$contact['email']} is already on campaign list; updating info.");
         $contact_id = key($email_in_campaign);
         if (!empty($contact['name'])) {
             $contact_name_response = $this->api->setContactName($contact_id, $contact['name']);
             if (isset($contact_name_response->updated)) {
                 $this->log_debug(__METHOD__ . "(): Name for {$contact['email']} have been updated.");
             }
         }
         if (!empty($contact['custom_fields'])) {
             $contact_customs_response = $this->api->setContactCustoms($contact_id, $contact['custom_fields']);
             if (isset($contact_customs_response->updated)) {
                 $this->log_debug(__METHOD__ . "(): Custom fields for {$contact['email']} have been updated.");
             }
         }
     }
 }
 /**
  * Process the feed, subscribe the user to the list.
  *
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  *
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     // login to MailChimp
     $api = $this->get_api();
     if (!is_object($api)) {
         $this->log_error(__METHOD__ . '(): Failed to set up the API.');
         return;
     }
     $feed_meta = $feed['meta'];
     // retrieve name => value pairs for all fields mapped in the 'mappedFields' field map
     $field_map = $this->get_field_map_fields($feed, 'mappedFields');
     $this->merge_var_name = 'EMAIL';
     $email = $this->get_field_value($form, $entry, $field_map['EMAIL']);
     // abort if email is invalid
     if (GFCommon::is_invalid_or_empty_email($email)) {
         $this->log_error(__METHOD__ . "(): A valid Email address must be provided.");
         return;
     }
     $override_empty_fields = gf_apply_filters('gform_mailchimp_override_empty_fields', $form['id'], true, $form, $entry, $feed);
     if (!$override_empty_fields) {
         $this->log_debug(__METHOD__ . '(): Empty fields will not be overridden.');
     }
     $merge_vars = array();
     foreach ($field_map as $name => $field_id) {
         if ($name == 'EMAIL') {
             continue;
         }
         $this->merge_var_name = $name;
         $field_value = $this->get_field_value($form, $entry, $field_id);
         if (empty($field_value) && !$override_empty_fields) {
             continue;
         } else {
             $merge_vars[$name] = $field_value;
         }
     }
     $mc_groupings = $this->get_mailchimp_groups($feed_meta['mailchimpList']);
     if (!empty($mc_groupings)) {
         $groupings = array();
         foreach ($mc_groupings as $grouping) {
             if (!is_array($grouping['groups'])) {
                 continue;
             }
             $groups = array();
             foreach ($grouping['groups'] as $group) {
                 $this->log_debug(__METHOD__ . '(): Evaluating condition for group: ' . rgar($group, 'name'));
                 $group_settings = $this->get_group_settings($group, $grouping['id'], $feed);
                 if (!$this->is_group_condition_met($group_settings, $form, $entry)) {
                     continue;
                 }
                 $groups[] = $group['name'];
             }
             if (!empty($groups)) {
                 $groupings[] = array('name' => $grouping['name'], 'groups' => $groups);
             }
         }
         if (!empty($groupings)) {
             $merge_vars['GROUPINGS'] = $groupings;
         }
     }
     $this->log_debug(__METHOD__ . "(): Checking to see if {$email} is already on the list.");
     $list_id = $feed_meta['mailchimpList'];
     try {
         $params = array('id' => $list_id, 'emails' => array(array('email' => $email)));
         $member_info = $api->call('lists/member-info', $params);
     } catch (Exception $e) {
         $this->log_error(__METHOD__ . '(): ' . $e->getCode() . ' - ' . $e->getMessage());
     }
     if (empty($member_info)) {
         $this->log_error(__METHOD__ . '(): There was an error while trying to retrieve member information. Unable to process feed.');
         return;
     }
     $subscribe_or_update = false;
     $member_not_found = absint(rgar($member_info, 'error_count')) > 0;
     $member_status = rgars($member_info, 'data/0/status');
     if ($member_not_found || $member_status != 'subscribed') {
         $allow_resubscription = gf_apply_filters('gform_mailchimp_allow_resubscription', $form['id'], true, $form, $entry, $feed);
         if ($member_status == 'unsubscribed' && !$allow_resubscription) {
             $this->log_debug(__METHOD__ . '(): User is unsubscribed and resubscription is not allowed.');
             return;
         }
         // adding member to list
         // $member_status != 'subscribed', 'pending', 'cleaned' need to be 're-subscribed' to send out confirmation email
         $this->log_debug(__METHOD__ . "(): {$email} is either not on the list or on the list but the status is not subscribed - status: " . $member_status . '; adding to list.');
         $transaction = 'Subscribe';
         try {
             $params = array('id' => $list_id, 'email' => array('email' => $email), 'merge_vars' => $merge_vars, 'email_type' => 'html', 'double_optin' => $feed_meta['double_optin'] == true, 'update_existing' => false, 'replace_interests' => true, 'send_welcome' => $feed_meta['sendWelcomeEmail'] == true);
             $params = gf_apply_filters('gform_mailchimp_args_pre_subscribe', $form['id'], $params, $form, $entry, $feed, $transaction);
             $this->log_debug(__METHOD__ . '(): Calling - subscribe, Parameters ' . print_r($params, true));
             $subscribe_or_update = $api->call('lists/subscribe', $params);
         } catch (Exception $e) {
             $this->log_error(__METHOD__ . '(): ' . $e->getCode() . ' - ' . $e->getMessage());
         }
     } else {
         // updating member
         $this->log_debug(__METHOD__ . "(): {$email} is already on the list; updating info.");
         $keep_existing_groups = gf_apply_filters('gform_mailchimp_keep_existing_groups', $form['id'], true, $form, $entry, $feed);
         $transaction = 'Update';
         /**
          * Switching to setting the replace_interests parameter instead of using append_groups()
          * MailChimp now handles merging the new group selections with any existing groups at their end
          */
         //			// retrieve existing groups for subscribers
         //			$current_groups = rgar( $member_info['data'][0]['merges'], 'GROUPINGS' );
         //			if ( is_array( $current_groups ) && $keep_existing_groups ) {
         //				// add existing groups to selected groups from form so that existing groups are maintained for that subscriber
         //				$merge_vars = $this->append_groups( $merge_vars, $current_groups );
         //			}
         try {
             $params = array('id' => $list_id, 'email' => array('email' => $email), 'merge_vars' => $merge_vars, 'email_type' => 'html', 'replace_interests' => !$keep_existing_groups);
             $params = gf_apply_filters('gform_mailchimp_args_pre_subscribe', $form['id'], $params, $form, $entry, $feed, $transaction);
             $this->log_debug(__METHOD__ . '(): Calling - update-member, Parameters ' . print_r($params, true));
             $subscribe_or_update = $api->call('lists/update-member', $params);
         } catch (Exception $e) {
             $this->log_error(__METHOD__ . '(): ' . $e->getCode() . ' - ' . $e->getMessage());
         }
     }
     if (rgar($subscribe_or_update, 'email')) {
         //email will be returned if successful
         $this->log_debug(__METHOD__ . "(): {$transaction} successful.");
     } else {
         $this->log_error(__METHOD__ . "(): {$transaction} failed.");
     }
 }
 /**
  * Update contact.
  * 
  * @access public
  * @param array $contact
  * @param array $feed
  * @param array $entry
  * @param array $form
  * @return array $contact
  */
 public function update_contact($contact, $feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Updating existing contact.');
     /* Setup mapped fields array. */
     $contact_standard_fields = $this->get_field_map_fields($feed, 'contactStandardFields');
     $contact_custom_fields = $this->get_dynamic_field_map_fields($feed, 'contactCustomFields');
     /* Setup base fields. */
     $first_name = $this->get_field_value($form, $entry, $contact_standard_fields['first_name']);
     $last_name = $this->get_field_value($form, $entry, $contact_standard_fields['last_name']);
     $default_email = $this->get_field_value($form, $entry, $contact_standard_fields['email_address']);
     /* If the name is empty, exit. */
     if (rgblank($first_name) || rgblank($last_name)) {
         $this->add_feed_error(esc_html__('Contact could not be created as first and/or last name were not provided.', 'gravityformsagilecrm'), $feed, $entry, $form);
         return null;
     }
     /* If the email address is empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($default_email)) {
         $this->add_feed_error(esc_html__('Contact could not be created as email address was not provided.', 'gravityformsagilecrm'), $feed, $entry, $form);
         return null;
     }
     /* Clear out unneeded data. */
     foreach ($contact as $key => $value) {
         if (!in_array($key, array('tags', 'properties', 'id', 'type'))) {
             unset($contact[$key]);
         }
     }
     /* If we're replacing all data, clear out the properties and add the base properties. */
     if (rgars($feed, 'meta/updateContactAction') == 'replace') {
         $contact['tags'] = array();
         $contact['properties'] = array(array('type' => 'SYSTEM', 'name' => 'first_name', 'value' => $first_name), array('type' => 'SYSTEM', 'name' => 'last_name', 'value' => $last_name), array('type' => 'SYSTEM', 'name' => 'email', 'value' => $default_email));
     }
     /* Add custom field data. */
     foreach ($contact_custom_fields as $field_key => $field_id) {
         /* Get the field value. */
         $this->custom_field_key = $field_key;
         $field_value = $this->get_field_value($form, $entry, $field_id);
         /* If the field value is empty, skip this field. */
         if (rgblank($field_value)) {
             continue;
         }
         $contact = $this->add_contact_property($contact, $field_key, $field_value, rgars($feed, 'meta/updateContactAction') == 'replace');
     }
     /* Prepare tags. */
     if (rgars($feed, 'meta/contactTags')) {
         $tags = GFCommon::replace_variables($feed['meta']['contactTags'], $form, $entry, false, false, false, 'text');
         $tags = array_map('trim', explode(',', $tags));
         $tags = array_merge($contact['tags'], $tags);
         $contact['tags'] = gf_apply_filters('gform_agilecrm_tags', $form['id'], $tags, $feed, $entry, $form);
     }
     $this->log_debug(__METHOD__ . '(): Updating contact: ' . print_r($contact, true));
     try {
         /* Update contact. */
         $this->api->update_contact($contact);
         /* Save contact ID to entry. */
         gform_update_meta($entry['id'], 'agilecrm_contact_id', $contact['id']);
         /* Log that contact was updated. */
         $this->log_debug(__METHOD__ . '(): Contact #' . $contact['id'] . ' updated.');
     } catch (Exception $e) {
         $this->add_feed_error(sprintf(esc_html__('Contact could not be updated. %s', 'gravityformsagilecrm'), $e->getMessage()), $feed, $entry, $form);
         return null;
     }
     return $contact;
 }
 /**
  * Create a new person.
  * 
  * @access public
  * @param array $feed
  * @param array $entry
  * @param array $form
  * @return null|array $person
  */
 public function create_person($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Creating person.');
     /* Setup mapped fields array. */
     $person_standard_fields = $this->get_field_map_fields($feed, 'person_standard_fields');
     $person_custom_fields = $this->get_dynamic_field_map_fields($feed, 'person_custom_fields');
     /* Prepare task object */
     $person = array('firstName' => $this->get_field_value($form, $entry, $person_standard_fields['first_name']), 'lastName' => $this->get_field_value($form, $entry, $person_standard_fields['last_name']), 'jobTitle' => isset($person_custom_fields['title']) ? $this->get_field_value($form, $entry, $person_custom_fields['title']) : '', 'organisationName' => isset($person_custom_fields['organization']) ? $this->get_field_value($form, $entry, $person_custom_fields['organization']) : '', 'about' => GFCommon::replace_variables($feed['meta']['person_about'], $form, $entry, false, false, false, 'text'), 'contacts' => array('address' => array(), 'email' => array(array('emailAddress' => $this->get_field_value($form, $entry, $person_standard_fields['email_address']))), 'phone' => array(), 'website' => array()));
     /* If the name is empty, exit. */
     if (rgblank($person['firstName']) || rgblank($person['lastName'])) {
         $this->add_feed_error(esc_html__('Person could not be created as first and/or last name were not provided.', 'gravityformscapsulecrm'), $feed, $entry, $form);
         return null;
     }
     /* If the email address is empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($person['contacts']['email'][0]['emailAddress'])) {
         $this->add_feed_error(esc_html__('Person could not be created as email address was not provided.', 'gravityformscapsulecrm'), $feed, $entry, $form);
         return null;
     }
     /* Add any mapped addresses. */
     $person = $this->add_person_address_data($person, $feed, $entry, $form);
     /* Add any mapped email addresses. */
     $person = $this->add_person_email_data($person, $feed, $entry, $form);
     /* Add any mapped phone numbers. */
     $person = $this->add_person_phone_data($person, $feed, $entry, $form);
     /* Add any mapped websites. */
     $person = $this->add_person_website_data($person, $feed, $entry, $form);
     /* Create person. */
     $this->log_debug(__METHOD__ . '(): Creating person: ' . print_r($person, true));
     try {
         $person['id'] = $this->api->create_person($person);
         gform_update_meta($entry['id'], 'capsulecrm_person_id', $person['id']);
         $this->log_debug(__METHOD__ . '(): Person #' . $person['id'] . ' created.');
     } catch (Exception $e) {
         $this->add_feed_error(sprintf(esc_html__('Person could not be created. %s', 'gravityformscapsulecrm'), $e->getMessage()), $feed, $entry, $form);
         return null;
     }
     return $person;
 }
 /**
  * Process feed, create conversation.
  * 
  * @access public
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     /* If Help Scout instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->log_error(__METHOD__ . '(): Failed to set up the API.');
         return;
     }
     /* If this entry already has a Help Scout conversation, exit. */
     if (gform_get_meta($entry['id'], 'helpscout_conversation_id')) {
         $this->log_debug(__METHOD__ . '(): Entry already has a Help Scout conversation associated to it. Skipping processing.');
         return;
     }
     /* Prepare needed information. */
     $data = array('email' => $this->get_field_value($form, $entry, $feed['meta']['customer_email']), 'first_name' => $this->get_field_value($form, $entry, $feed['meta']['customer_first_name']), 'last_name' => $this->get_field_value($form, $entry, $feed['meta']['customer_last_name']), 'subject' => GFCommon::replace_variables($feed['meta']['subject'], $form, $entry, false, false, false, 'text'), 'body' => GFCommon::replace_variables($feed['meta']['body'], $form, $entry), 'attachments' => array(), 'tags' => GFCommon::replace_variables($feed['meta']['tags'], $form, $entry));
     /* If the email address is empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($data['email'])) {
         $this->log_error(__METHOD__ . "(): Email address must be provided.");
         return false;
     }
     /* Setup the mailbox for this conversation */
     $mailbox = new \HelpScout\model\ref\MailboxRef();
     $mailbox->setId($feed['meta']['mailbox']);
     /* Create the customer object */
     $customer = $this->api->getCustomerRefProxy(null, $data['email']);
     $customer->setFirstName($data['first_name']);
     $customer->setLastName($data['last_name']);
     /* Create the conversation object */
     $conversation = new \HelpScout\model\Conversation();
     $conversation->setSubject($data['subject']);
     $conversation->setMailbox($mailbox);
     $conversation->setCustomer($customer);
     $conversation->setCreatedBy($customer);
     $conversation->setType($feed['meta']['type']);
     /* Create the message thread */
     if (gf_apply_filters('gform_helpscout_process_body_shortcodes', $form['id'], false, $form, $feed)) {
         $data['body'] = do_shortcode($data['body']);
     }
     $thread = new \HelpScout\model\thread\Customer();
     $thread->setCreatedBy($customer);
     $thread->setBody($data['body']);
     $thread->setStatus($feed['meta']['status']);
     /* Assign this conversation to user if set */
     if (!rgempty('user', $feed['meta'])) {
         $user = new \HelpScout\model\ref\PersonRef();
         $user->setId($feed['meta']['user']);
         $user->setType('user');
         $thread->setAssignedTo($user);
     }
     /* If feed has an attachments field assign, process the attachments. */
     if (!empty($feed['meta']['attachments'])) {
         $attachment_fields = array_keys($feed['meta']['attachments']);
         $attachment_files = array();
         foreach ($attachment_fields as $attachment_field) {
             $field_value = $this->get_field_value($form, $entry, $attachment_field);
             $field_value = $this->is_json($field_value) ? json_decode($field_value, true) : $field_value;
             $field_value = strpos($field_value, ' , ') !== FALSE ? explode(' , ', $field_value) : $field_value;
             if (empty($field_value)) {
                 continue;
             }
             if (is_array($field_value)) {
                 $attachment_files = array_merge($attachment_files, $field_value);
             } else {
                 $attachment_files[] = $field_value;
             }
         }
         if (!empty($attachment_files)) {
             $attachments = $this->process_feed_attachments($attachment_files);
             $thread->setAttachments($attachments);
         }
     }
     /* Add tags to conversation */
     $tags = !empty($data['tags']) ? array_map('trim', explode(',', $data['tags'])) : array();
     $tags = gf_apply_filters('gform_helpscout_tags', $form['id'], $tags, $feed, $entry, $form);
     if (!empty($tags)) {
         $conversation->setTags($tags);
     }
     /* Add CC and BCC support if set. */
     if (isset($feed['meta']['cc'])) {
         $data['cc'] = GFCommon::replace_variables($feed['meta']['cc'], $form, $entry);
         $data['cc'] = is_array($data['cc']) ? $data['cc'] : explode(',', $data['cc']);
         if (!empty($data['cc'])) {
             $thread->setCcList($data['cc']);
         }
     }
     if (isset($feed['meta']['bcc'])) {
         $data['bcc'] = GFCommon::replace_variables($feed['meta']['bcc'], $form, $entry);
         $data['bcc'] = is_array($data['bcc']) ? $data['bcc'] : explode(',', $data['bcc']);
         if (!empty($data['bcc'])) {
             $thread->setCcList($data['bcc']);
         }
     }
     /* Assign the message thread to the conversation */
     $conversation->setThreads(array($thread));
     /* Set thread count to 1 so Help Scout will include the conversation in the mailbox folder count */
     $conversation->setThreadCount(1);
     $this->log_debug(__METHOD__ . "(): Conversation to be created => " . print_r($conversation, true));
     try {
         $auto_reply = rgars($feed, 'meta/auto_reply') == '1';
         /* Create the conversation. */
         $this->api->createConversation($conversation, false, $auto_reply, true);
         gform_update_meta($entry['id'], 'helpscout_conversation_id', $conversation->getId());
         /* Log that conversation was created. */
         $this->log_debug(__METHOD__ . "(): Conversation has been created.");
     } catch (Exception $e) {
         /* Log that conversation was not created. */
         $this->log_error(__METHOD__ . "(): Conversation was not created; {$e->getMessage()}");
         return;
     }
     /* Add conversation note if set. */
     if (rgars($feed, 'meta/note')) {
         /* Replace variables for note. */
         $note_text = GFCommon::replace_variables($feed['meta']['note'], $form, $entry);
         /* Get API user. */
         $api_user = $this->api->getUserMe();
         /* Create note object. */
         $note = new \HelpScout\model\thread\Message();
         $note->setCreatedBy($this->api->getUserRefProxy($api_user->getId()));
         $note->setBody($note_text);
         $note->setType('note');
         try {
             /* Post note to conversation. */
             $this->api->createThread($conversation->getId(), $note);
             /* Log that note was added. */
             $this->log_debug(__METHOD__ . '(): Note was successfully added to conversation.');
         } catch (Exception $e) {
             /* Log that note was not added. */
             $this->log_error(__METHOD__ . '(): Note was not added to conversation; ' . $e->getMessage());
             return;
         }
     }
 }
 /**
  * Process feed.
  * 
  * @access public
  * @param array $feed
  * @param array $entry
  * @param array $form
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If API instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->add_feed_error(esc_html__('Feed was not processed because API was not initialized.', 'gravityformsbatchbook'), $feed, $entry, $form);
         return;
     }
     /* Either update or create a new person. */
     if (rgars($feed, 'meta/person_update_enable') == '1') {
         $email_address = $this->get_field_value($form, $entry, $feed['meta']['person_standard_fields_email_address']);
         /* If the email address is empty, exit. */
         if (GFCommon::is_invalid_or_empty_email($email_address)) {
             /* Add feed error. */
             $this->add_feed_error(esc_html__('Person was not created because email address was not provided.', 'gravityformsbatchbook'), $feed, $entry, $form);
             return false;
         }
         $existing_people = $this->api->get_people_by_email($email_address);
         if (empty($existing_people)) {
             $person = $this->create_person($feed, $entry, $form);
         } else {
             $person = $this->update_person($existing_people[0], $feed, $entry, $form);
         }
     } else {
         $person = $this->create_person($feed, $entry, $form);
     }
 }
 /**
  * Process feed.
  * 
  * @access public
  * @param array $feed
  * @param array $entry
  * @param array $form
  * @return void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If API instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->add_feed_error(esc_html__('Feed was not processed because API was not initialized.', 'gravityformsicontact'), $feed, $entry, $form);
         return;
     }
     /* Setup mapped fields array. */
     $mapped_fields = $this->get_field_map_fields($feed, 'fields');
     /* Setup contact array. */
     $contact = array('email' => $this->get_field_value($form, $entry, $mapped_fields['email']), 'prefix' => $this->get_field_value($form, $entry, $mapped_fields['prefix']), 'firstName' => $this->get_field_value($form, $entry, $mapped_fields['first_name']), 'lastName' => $this->get_field_value($form, $entry, $mapped_fields['last_name']), 'suffix' => $this->get_field_value($form, $entry, $mapped_fields['suffix']), 'street' => $this->get_field_value($form, $entry, $mapped_fields['street']), 'street2' => $this->get_field_value($form, $entry, $mapped_fields['street2']), 'city' => $this->get_field_value($form, $entry, $mapped_fields['city']), 'state' => $this->get_field_value($form, $entry, $mapped_fields['state']), 'postalCode' => $this->get_field_value($form, $entry, $mapped_fields['postal_code']), 'phone' => $this->get_field_value($form, $entry, $mapped_fields['phone']), 'fax' => $this->get_field_value($form, $entry, $mapped_fields['fax']), 'business' => $this->get_field_value($form, $entry, $mapped_fields['business']));
     /* If the email address is empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($contact['email'])) {
         $this->add_feed_error(esc_html__('Contact could not be created as email address was not provided.', 'gravityformsicontact'), $feed, $entry, $form);
         return;
     }
     /* Add custom fields to contact array. */
     if (rgars($feed, 'meta/custom_fields')) {
         foreach ($feed['meta']['custom_fields'] as $custom_field) {
             if (rgblank($custom_field['key']) || $custom_field['key'] == 'gf_custom' || rgblank($custom_field['value'])) {
                 continue;
             }
             $field_value = $this->get_field_value($form, $entry, $custom_field['value']);
             if (rgblank($field_value)) {
                 continue;
             }
             $contact[$custom_field['key']] = $field_value;
         }
     }
     /* Check to see if we're adding a new contact. */
     $find_contact = $this->api->get_contact_by_email($contact['email']);
     $is_new_contact = empty($find_contact);
     if ($is_new_contact) {
         /* Log that we're creating a new contact. */
         $this->log_debug(__METHOD__ . "(): {$contact['email']} does not exist and will be created.");
         /* Log the contact object we're creating. */
         $this->log_debug(__METHOD__ . '(): Creating contact: ' . print_r($contact, true));
         try {
             /* Add the contact. */
             $new_contact = $this->api->add_contact($contact);
             /* Log that contact was created. */
             $this->log_debug(__METHOD__ . "(): {$contact['email']} has been created; contact ID: {$new_contact['contactId']}.");
         } catch (Exception $e) {
             /* Log error. */
             $this->add_feed_error(sprintf(esc_html__('Contact could not be created. %s', 'gravityformsicontact'), $e->getMessage()), $feed, $entry, $form);
             /* Stop processing feed. */
             return false;
         }
         $contact['id'] = $new_contact['contactId'];
         $this->add_subscription($contact, $feed, $entry, $form);
     } else {
         /* Log that we're updating an existing contact. */
         $this->log_debug(__METHOD__ . "(): {$contact['email']} already exists and will be updated.");
         /* Log the contact object we're updating. */
         $this->log_debug(__METHOD__ . '(): Updating contact: ' . print_r($contact, true));
         $contact_id = $find_contact[0]['contactId'];
         try {
             /* Update the contact. */
             $update_contact = $this->api->update_contact($contact_id, $contact);
             /* Log that contact was created. */
             $this->log_debug(__METHOD__ . "(): {$contact['email']} has been updated; contact ID: {$contact_id}.");
         } catch (Exception $e) {
             /* Log error. */
             $this->add_feed_error(sprintf(esc_html__('Contact could not be updated. %s', 'gravityformsicontact'), $e->getMessage()), $feed, $entry, $form);
             /* Stop processing feed. */
             return false;
         }
         $contact['id'] = $contact_id;
         $this->add_subscription($contact, $feed, $entry, $form);
     }
 }
 /**
  * Process the feed, subscribe the user to the list.
  *
  * @param array $feed The feed object to be processed.
  * @param array $entry The entry object currently being processed.
  * @param array $form The form object currently being processed.
  *
  * @return bool|void
  */
 public function process_feed($feed, $entry, $form)
 {
     $this->log_debug(__METHOD__ . '(): Processing feed.');
     /* If API instance is not initialized, exit. */
     if (!$this->initialize_api()) {
         $this->log_error(__METHOD__ . '(): Failed to set up the API.');
         return;
     }
     /* Setup mapped fields array. */
     $mapped_fields = $this->get_field_map_fields($feed, 'fields');
     /* Setup contact array. */
     $contact = array('email' => $this->get_field_value($form, $entry, rgar($mapped_fields, 'email')), 'first_name' => $this->get_field_value($form, $entry, rgar($mapped_fields, 'first_name')), 'last_name' => $this->get_field_value($form, $entry, rgar($mapped_fields, 'last_name')), 'phone' => $this->get_field_value($form, $entry, rgar($mapped_fields, 'phone')), 'orgname' => $this->get_field_value($form, $entry, rgar($mapped_fields, 'orgname')));
     /* If the email address is invalid or empty, exit. */
     if (GFCommon::is_invalid_or_empty_email($contact['email'])) {
         $this->log_error(__METHOD__ . '(): Aborting. Invalid email address: ' . rgar($contact, 'email'));
         return;
     }
     /* Prepare tags. */
     if (rgars($feed, 'meta/tags')) {
         $tags = GFCommon::replace_variables($feed['meta']['tags'], $form, $entry, false, false, false, 'text');
         $tags = array_map('trim', explode(',', $tags));
         $contact['tags'] = gf_apply_filters('gform_activecampaign_tags', $form['id'], $tags, $feed, $entry, $form);
     }
     /* Add list to contact array. */
     $list_id = $feed['meta']['list'];
     $contact['p[' . $list_id . ']'] = $list_id;
     $contact['status[' . $list_id . ']'] = '1';
     /* Add custom fields to contact array. */
     $custom_fields = rgars($feed, 'meta/custom_fields');
     if (is_array($custom_fields)) {
         foreach ($feed['meta']['custom_fields'] as $custom_field) {
             if (rgblank($custom_field['key']) || $custom_field['key'] == 'gf_custom' || rgblank($custom_field['value'])) {
                 continue;
             }
             $field_value = $this->get_field_value($form, $entry, $custom_field['value']);
             if (rgblank($field_value)) {
                 continue;
             }
             $contact['field[' . $custom_field['key'] . ',0]'] = $field_value;
         }
     }
     /* Set instant responders flag if needed. */
     if ($feed['meta']['instant_responders'] == 1) {
         $contact['instantresponders[' . $list_id . ']'] = $feed['meta']['instant_responders'];
     }
     /* Set last message flag. */
     $contact['lastmessage[' . $list_id . ']'] = $feed['meta']['last_message'];
     /* Add opt-in form if set. */
     if (isset($feed['meta']['double_optin_form'])) {
         $contact['form'] = $feed['meta']['double_optin_form'];
     }
     /**
      * Allows the contact properties to be overridden before the contact_sync request is sent to the API.
      *
      * @param array $contact The contact properties.
      * @param array $entry The entry currently being processed.
      * @param array $form The form object the current entry was created from.
      * @param array $feed The feed which is currently being processed.
      *
      * @since 1.3.5
      */
     $contact = apply_filters('gform_activecampaign_contact_pre_sync', $contact, $entry, $form, $feed);
     $contact = apply_filters('gform_activecampaign_contact_pre_sync_' . $form['id'], $contact, $entry, $form, $feed);
     /* Sync the contact. */
     $this->log_debug(__METHOD__ . '(): Contact to be added => ' . print_r($contact, true));
     $sync_contact = $this->api->sync_contact($contact);
     if ($sync_contact['result_code'] == 1) {
         $this->log_debug(__METHOD__ . "(): {$contact['email']} has been added; {$sync_contact['result_message']}.");
         return true;
     } else {
         $this->log_error(__METHOD__ . "(): {$contact['email']} was not added; {$sync_contact['result_message']}");
         return false;
     }
 }