View source
<?php
module_load_include('inc', 'webform_civicrm', 'includes/wf_crm_webform_base');
class wf_crm_webform_postprocess extends wf_crm_webform_base {
private $form;
private $form_state;
private $crmValues;
private $rawValues;
private $multiPageDataLoaded;
private $billing_params = array();
private $totalContribution = 0;
private $contributionIsIncomplete = FALSE;
private $contributionIsPayLater = FALSE;
private $existing_contacts = array();
private $submission;
private $update = array();
private $all_fields;
private $all_sets;
private $shared_address = array();
static $singleton;
const BILLING_MODE_LIVE = 1, BILLING_MODE_MIXED = 3;
function __construct($node) {
civicrm_initialize();
$this->node = $node;
$this->settings = $node->webform_civicrm;
$this->data = $this->settings['data'];
$this->enabled = wf_crm_enabled_fields($node);
$this->all_fields = wf_crm_get_fields();
$this->all_sets = wf_crm_get_fields('sets');
}
public static function singleton($node) {
if (!self::$singleton) {
self::$singleton = new wf_crm_webform_postprocess($node);
}
return self::$singleton;
}
public function validate($form, &$form_state) {
$this->form = $form;
$this->form_state =& $form_state;
$this->rawValues = _webform_client_form_submit_flatten($this->node, wf_crm_aval($this->form_state, 'values:submitted'));
$this->crmValues = wf_crm_enabled_fields($this->node, $this->rawValues);
$this->ent = wf_crm_aval($form_state, 'civicrm:ent', array());
$this
->hiddenFieldValidation();
$this
->validateThisPage($this->form['submitted']);
if (!empty($this->data['participant']) && !empty($this->data['participant_reg_type'])) {
$this
->loadMultiPageData();
$this
->validateParticipants();
}
if ($this->contribution_page) {
$this
->addPaymentJs();
$this
->loadMultiPageData();
if ($this
->tallyLineItems()) {
if ($this
->isLivePaymentProcessor() && $this
->isPaymentPage() && !form_get_errors()) {
if ($this
->validateBillingFields()) {
if ($this
->createBillingContact()) {
$this
->submitLivePayment();
}
}
}
}
}
$form_state['civicrm']['ent'] = $this->ent;
$form_state['civicrm']['line_items'] = $this->line_items;
}
public function preSave(&$submission) {
$this->submission =& $submission;
$this->data = $this->settings['data'];
$this
->setUpdateParam();
$this
->getExistingContactIds();
if (!empty($this->submission->is_draft)) {
return;
}
$this
->fillDataFromSubmission();
foreach ($this->data['contact'] as $c => $contact) {
if (empty($this->ent['contact'][$c]['id'])) {
if ($this
->isContactEmpty($contact)) {
$this->ent['contact'][$c]['id'] = 0;
continue;
}
$this->ent['contact'][$c]['id'] = $this
->findDuplicateContact($contact);
}
unset($contact['contact'][1]['employer_id']);
$newContact = empty($this->ent['contact'][$c]['id']);
if ($newContact) {
$this->ent['contact'][$c]['id'] = $this
->createContact($contact);
}
if ($c == 1) {
$this
->setLoggingContact();
}
if (!$newContact) {
$this
->updateContact($contact, $c);
}
}
ksort($this->ent['contact']);
$this
->fillContactRefs();
if (empty($this->ent['contribution'][1]['id']) && $this->totalContribution) {
$this
->createDeferredPayment();
}
foreach ($this->data['contact'] as $c => $contact) {
$cid = $this->ent['contact'][$c]['id'];
if (!$cid) {
continue;
}
$this
->saveCurrentEmployer($contact, $cid);
$this
->saveCustomData($contact, $cid, 'Contact', !empty($this->existing_contacts[$c]), $c);
$this
->fillHiddenContactFields($cid, $c);
$this
->saveContactLocation($contact, $cid, $c);
$this
->saveGroupsAndTags($contact, $cid, $c);
foreach (wf_crm_aval($contact, 'relationship', array()) as $n => $params) {
$relationship_type_id = wf_crm_aval($params, 'relationship_type_id');
if ($relationship_type_id) {
foreach ((array) $relationship_type_id as $params['relationship_type_id']) {
$this
->processRelationship($params, $cid, $this->ent['contact'][$n]['id']);
}
}
}
if (isset($this->all_sets['participant']) && !empty($this->data['participant_reg_type'])) {
$this
->processParticipants($c, $cid);
}
}
$this
->processSharedAddresses();
foreach ($this->ent['contact'] as $c => $contact) {
if ($contact['id'] && isset($this->all_sets['membership']) && !empty($this->data['membership'][$c]['number_of_membership'])) {
$this
->processMemberships($c, $contact['id']);
}
}
}
public function postSave($submission) {
$this->submission = $submission;
if (empty($this->submission->is_draft)) {
if (!empty($this->data['case']['number_of_case'])) {
$this
->processCases();
}
if (!empty($this->data['activity']['number_of_activity'])) {
$this
->processActivities();
}
if (isset($this->data['grant']['number_of_grant'])) {
$this
->processGrants();
}
if (!empty($this->ent['contribution'][1]['id'])) {
$this
->processContribution();
}
}
$record = $this
->formatSubmission();
drupal_write_record('webform_civicrm_submissions', $record, $this->update);
if (empty($this->submission->is_draft) && !empty($this->ent['contribution'][1]['id']) && $this->contributionIsIncomplete && !$this->contributionIsPayLater) {
webform_submission_send_mail($this->node, $this->submission);
$this
->submitIPNPayment();
}
if (empty($this->submission->is_draft) && !empty($this->ent['contribution'][1]['id']) && !empty($this->contribution_page['is_email_receipt']) && (!$this->contributionIsIncomplete || $this->contributionIsPayLater)) {
$this
->sendReceipt();
}
}
private function sendReceipt() {
if (!is_null($this->tax_rate)) {
$template = CRM_Core_Smarty::singleton();
$template
->assign('dataArray', array(
"{$this->tax_rate}" => $this->tax_rate / 100,
));
}
if ($this->contributionIsIncomplete) {
$template = CRM_Core_Smarty::singleton();
$template
->assign('is_pay_later', 1);
}
$params = array_merge($this->contribution_page, array(
'id' => $this->ent['contribution'][1]['id'],
));
$params['payment_processor_id'] = $this->data['contribution'][1]['contribution'][1]['payment_processor_id'];
unset($params['payment_processor']);
wf_civicrm_api('contribution', 'sendconfirmation', $params);
}
private function formatSubmission() {
$data = $this->ent;
unset($data['contact']);
$record = array(
'sid' => $this->submission->sid,
'contact_id' => '-',
'civicrm_data' => $data,
);
foreach ($this->ent['contact'] as $contact) {
$record['contact_id'] .= $contact['id'] . '-';
}
return $record;
}
private function hiddenFieldValidation() {
$errors = form_get_errors();
foreach ((array) $errors as $key => $error) {
$pieces = wf_crm_explode_key(substr($key, strrpos($key, '][') + 2));
if ($pieces) {
list(, $c, $ent, $n, $table, $name) = $pieces;
if ($this
->isFieldHiddenByExistingContactSettings($ent, $c, $table, $n, $name)) {
$this
->unsetError($key);
}
elseif ($table == 'address' && !empty($this->crmValues["civicrm_{$c}_contact_{$n}_address_master_id"])) {
$master_id = $this->crmValues["civicrm_{$c}_contact_{$n}_address_master_id"];
if (!is_array($master_id) || array_filter($master_id)) {
$this
->unsetError($key);
}
}
}
}
}
private function validateThisPage($elements) {
foreach (element_children($elements) as $key) {
if (is_array($elements[$key]) && ($element = $elements[$key])) {
$this
->validateThisPage($elements[$key]);
if (!empty($element['#civicrm_data_type']) && substr(wf_crm_aval($element, '#type', ''), 0, 4) === 'text' && isset($element['#value']) && $element['#value'] !== '') {
$dt = $element['#civicrm_data_type'];
if ($dt == 'state_province_abbr') {
$ckey = str_replace('state_province', 'country', $key);
if (!empty($this->crmValues[$ckey]) && is_numeric($this->crmValues[$ckey])) {
$country_id = $this->crmValues[$ckey];
}
else {
$config = CRM_Core_Config::singleton();
$country_id = $config->defaultContactCountry;
}
$states = wf_crm_get_states($country_id);
if ($states && !array_key_exists(strtoupper($element['#value']), $states)) {
$countries = wf_crm_apivalues('address', 'getoptions', array(
'field' => 'country_id',
));
form_error($element, t('Mismatch: "@state" is not a state/province of %country. Please enter a valid state/province abbreviation for %field.', array(
'@state' => $element['#value'],
'%country' => $countries[$country_id],
'%field' => $element['#title'],
)));
}
}
elseif ($dt !== 'String' && $dt !== 'Memo' && $dt !== 'File' && CRM_Utils_Type::escape($element['#value'], $dt, FALSE) === NULL) {
switch ($dt) {
case 'Int':
$dt = t('an integer');
break;
case 'Float':
$dt = t('a number');
break;
case 'Link':
$dt = t('a web address starting with http://');
break;
case 'Money':
$dt = t('a currency value');
break;
}
form_error($element, t('Please enter @type for %field.', array(
'@type' => $dt,
'%field' => $element['#title'],
)));
}
}
}
}
}
private function validateParticipants() {
if (!$this->existing_contacts) {
return;
}
$count = $this->data['participant_reg_type'] == 'all' ? count($this->existing_contacts) : 1;
foreach ($this->data['participant'] as $c => $par) {
if ($this->data['participant_reg_type'] == 'all') {
$contacts = $this->existing_contacts;
}
elseif (isset($this->existing_contacts[$c])) {
$contacts = array(
$this->existing_contacts[$c],
);
}
else {
continue;
}
$participants = current(wf_crm_aval($this->data['contact'], "{$c}:contact", array()));
$firstName = CRM_Utils_Array::value('first_name', $participants);
$lastName = CRM_Utils_Array::value('last_name', $participants);
$participantName = "{$firstName} {$lastName}";
if (!trim($participantName)) {
$participantName = CRM_Utils_Array::value('webform_label', $participants);
if (!empty($this->existing_contacts[$c])) {
$participantName = CRM_Contact_BAO_Contact::displayName($this->existing_contacts[$c]);
}
}
foreach (wf_crm_aval($par, 'participant', array()) as $n => $p) {
foreach (array_filter(wf_crm_aval($p, 'event_id', array())) as $id_and_type) {
list($eid) = explode('-', $id_and_type);
if (is_numeric($eid)) {
$this->events[$eid]['ended'] = TRUE;
$this->events[$eid]['title'] = t('this event');
$this->events[$eid]['count'] = wf_crm_aval($this->events, "{$eid}:count", 0) + $count;
$this->line_items[] = array(
'qty' => $count,
'entity_table' => 'civicrm_participant',
'event_id' => $eid,
'contact_ids' => $contacts,
'unit_price' => $p['fee_amount'],
'element' => "civicrm_{$c}_participant_{$n}_participant_{$id_and_type}",
'contact_label' => $participantName,
);
}
}
}
}
$cids = array_filter($this->existing_contacts);
if ($this->events && $cids) {
$dao = CRM_Core_DAO::executeQuery("SELECT event_id, contact_id\n FROM civicrm_participant p, civicrm_participant_status_type s\n WHERE s.id = p.status_id AND s.is_counted = 1\n AND event_id IN (" . implode(',', array_keys($this->events)) . ")\n AND contact_id IN (" . implode(',', $cids) . ")\n AND is_test = 0");
while ($dao
->fetch()) {
if (isset($this->events[$dao->event_id])) {
if (!--$this->events[$dao->event_id]['count']) {
unset($this->events[$dao->event_id]);
}
}
foreach ($this->line_items as $k => &$item) {
if ($dao->event_id == $item['event_id'] && in_array($dao->contact_id, $item['contact_ids'])) {
unset($this->line_items[$k]['contact_ids'][array_search($dao->contact_id, $item['contact_ids'])]);
if (!--$item['qty']) {
unset($this->line_items[$k]);
}
}
}
}
$dao
->free();
}
$this
->loadEvents();
$format = wf_crm_aval($this->data['reg_options'], 'title_display', 'title');
foreach ($this->line_items as &$item) {
$label = empty($item['contact_label']) ? '' : "{$item['contact_label']} - ";
$item['label'] = $label . wf_crm_format_event($this->events[$item['event_id']], $format);
$item['financial_type_id'] = wf_crm_aval($this->events[$item['event_id']], 'financial_type_id', 'Event Fee');
}
if (!empty($this->data['reg_options']['validate'])) {
foreach ($this->events as $eid => $event) {
if ($event['ended']) {
form_set_error($eid, t('Sorry, you can no longer register for %event.', array(
'%event' => $event['title'],
)));
}
elseif ($event['max_participants'] && $event['count'] > $event['remaining']) {
if (!empty($event['full'])) {
form_set_error($eid, '<em>' . $event['title'] . '</em>: ' . $event['full_message']);
}
else {
form_set_error($eid, format_plural($event['remaining'], 'Sorry, you tried to register !count people for %event but there is only 1 space remaining.', 'Sorry, you tried to register !count people for %event but there are only @count spaces remaining.', array(
'%event' => $event['title'],
'!count' => $event['count'],
)));
}
}
}
}
}
private function loadMultiPageData() {
if (!$this->multiPageDataLoaded) {
$this->multiPageDataLoaded = TRUE;
if (!empty($this->form_state['storage']['submitted']) && wf_crm_aval($this->form_state, 'storage:page_num', 1) > 1) {
$this->rawValues += $this->form_state['storage']['submitted'];
$this->crmValues = wf_crm_enabled_fields($this->node, $this->rawValues);
}
foreach ($this->data['contact'] as $c => $contact) {
$fid = "civicrm_{$c}_contact_1_contact_existing";
if ($this
->verifyExistingContact(wf_crm_aval($this->crmValues, $fid), $fid)) {
$this->existing_contacts[$c] = $this->crmValues[$fid];
}
elseif (wf_crm_name_field_exists($this->crmValues, $c, $contact['contact'][1]['contact_type'])) {
$this->existing_contacts[$c] = 0;
}
}
$this
->fillDataFromSubmission();
}
}
private function setUpdateParam() {
if (!empty($this->submission->sid)) {
$submitted = array(
$this->submission->sid => new stdClass(),
);
webform_civicrm_webform_submission_load($submitted);
if (isset($submitted[$this->submission->sid]->civicrm)) {
$this->update = 'sid';
}
}
}
private function getExistingContactIds() {
foreach ($this->enabled as $field_key => $fid) {
if (substr($field_key, -8) == 'existing') {
list(, $c, ) = explode('_', $field_key, 3);
$cid = wf_crm_aval($this
->submissionValue($fid), 0);
$this->ent['contact'][$c]['id'] = $this
->verifyExistingContact($cid, $field_key);
if ($this->ent['contact'][$c]['id']) {
$this->existing_contacts[$c] = $cid;
}
}
}
}
private function verifyExistingContact($cid, $fid) {
if (wf_crm_is_positive($cid) && !empty($this->enabled[$fid])) {
module_load_include('inc', 'webform_civicrm', 'includes/contact_component');
$component = $this
->getComponent($fid);
$filters = wf_crm_search_filters($this->node, $component);
if (wf_crm_contact_access($component, $filters, $cid) !== FALSE) {
return $cid;
}
}
return 0;
}
private function isContactEmpty($contact) {
$contact_type = $contact['contact'][1]['contact_type'];
foreach (wf_crm_required_contact_fields($contact_type) as $f) {
if (!empty($contact[$f['table']][1][$f['name']])) {
return FALSE;
}
}
return TRUE;
}
private function findDuplicateContact($contact) {
$dupes = $rule_type = $rule_id = $params_custom = NULL;
$rule = wf_crm_aval($contact, 'matching_rule', 'Unsupervised', TRUE);
$contact_type = ucfirst($contact['contact'][1]['contact_type']);
if ($rule) {
$params = array(
'check_permission' => FALSE,
);
foreach ($contact as $table => $field) {
if (is_array($field) && !empty($field[1])) {
if (substr($table, 0, 2) == 'cg') {
foreach ($field[1] as $custom_key => $custom_value) {
if (!empty($custom_value)) {
$params_custom[$custom_key] = $custom_value;
}
}
}
elseif ($table == 'address' && !empty($field[1]['master_id'])) {
$m = $field[1]['master_id'];
if (!empty($contact[$m]['address'][1])) {
$params['civicrm_address'] = $contact[$m]['address'][1];
}
elseif (!empty($this->existing_contacts[$m])) {
$masters = wf_civicrm_api('address', 'get', array(
'contact_id' => $this->ent['contact'][$m]['id'],
'sort' => 'is_primary DESC',
));
if (!empty($masters['values'])) {
$params['civicrm_address'] = array_shift($masters['values']);
}
}
}
elseif (in_array($table, array(
'contact',
'address',
'email',
'phone',
'website',
))) {
$params['civicrm_' . $table] = $field[1];
}
}
}
if (is_numeric($rule)) {
$rule_id = $rule;
}
else {
$rule_type = $rule;
}
if ($params_custom) {
$params_custom = CRM_Dedupe_Finder::formatParams($params_custom, $contact_type);
$params = array_merge($params, $params_custom);
}
$dupes = CRM_Dedupe_Finder::dupesByParams($params, $contact_type, $rule_type, array(), $rule_id);
}
if ($dupes) {
return $dupes[0];
}
return 0;
}
private function createContact($contact) {
$params = $contact['contact'][1];
$params['contact_type'] = ucfirst($params['contact_type']);
unset($params['contact_id'], $params['id']);
if (!isset($params['source'])) {
$params['source'] = $this->settings['new_contact_source'];
}
if ($params['contact_type'] == 'Individual' && empty($params['first_name']) && empty($params['last_name'])) {
$params['display_name'] = $params['sort_name'] = empty($params['nick_name']) ? $contact['email'][1]['email'] : $params['nick_name'];
}
$result = wf_civicrm_api('contact', 'create', $params);
return wf_crm_aval($result, 'id', 0);
}
private function updateContact($contact, $c) {
$params = $contact['contact'][1];
unset($params['contact_type'], $params['contact_id']);
$fetch = $multi = array();
foreach ($this->all_fields as $fid => $field) {
if (!empty($field['extra']['multiple']) && substr($fid, 0, 7) == 'contact') {
list(, $name) = explode('_', $fid, 2);
if ($name != 'privacy' && isset($params[$name])) {
$fetch["return.{$name}"] = 1;
$multi[] = $name;
}
}
}
if ($multi) {
$existing = wf_civicrm_api('contact', 'get', array(
'id' => $this->ent['contact'][$c]['id'],
) + $fetch);
$existing = wf_crm_aval($existing, 'values:' . $this->ent['contact'][$c]['id'], array());
foreach ($multi as $name) {
$exist = array_filter(drupal_map_assoc((array) wf_crm_aval($existing, $name, array())));
if (!empty($this->existing_contacts[$c])) {
foreach ($this
->getExposedOptions("civicrm_{$c}_contact_1_contact_{$name}") as $k => $v) {
unset($exist[$k]);
}
}
$params[$name] = array_unique(array_merge($params[$name], $exist));
}
}
$params['id'] = $this->ent['contact'][$c]['id'];
wf_civicrm_api('contact', 'create', $params);
}
function saveCurrentEmployer($contact, $cid) {
if ($contact['contact'][1]['contact_type'] == 'individual' && !empty($contact['contact'][1]['employer_id'])) {
wf_civicrm_api('contact', 'create', array(
'id' => $cid,
'employer_id' => $contact['contact'][1]['employer_id'],
));
}
}
private function fillHiddenContactFields($cid, $c) {
$fid = 'civicrm_' . $c . '_contact_1_contact_';
if (!empty($this->enabled[$fid . 'contact_id'])) {
$this
->submissionValue($this->enabled[$fid . 'contact_id'], $cid);
}
if (!empty($this->enabled[$fid . 'user_id'])) {
$user_id = wf_crm_user_cid($cid, 'contact');
$user_id = $user_id ? $user_id : '';
$this
->submissionValue($this->enabled[$fid . 'user_id'], $user_id);
}
if (!empty($this->enabled[$fid . 'existing'])) {
$this
->submissionValue($this->enabled[$fid . 'existing'], $cid);
}
if (!empty($this->enabled[$fid . 'external_identifier']) && !empty($this->existing_contacts[$c])) {
$exid = wf_civicrm_api('contact', 'get', array(
'contact_id' => $cid,
'return.external_identifier' => 1,
));
$this
->submissionValue($this->enabled[$fid . 'external_identifier'], wf_crm_aval($exid, "values:{$cid}:external_identifier"));
}
if (!empty($this->enabled[$fid . 'cs'])) {
$cs = $this
->submissionValue($this->enabled[$fid . 'cs']);
$life = !empty($cs[0]) ? intval(24 * $cs[0]) : 'inf';
$cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($cid, NULL, $life);
$this
->submissionValue($this->enabled[$fid . 'cs'], $cs);
}
}
private function saveContactLocation($contact, $cid, $c) {
$is_primary_address_location_type = wf_crm_aval($contact, 'address:1:location_type_id');
$is_primary_email_location_type = wf_crm_aval($contact, 'email:1:location_type_id');
if (!empty($contact['address'])) {
foreach ($contact['address'] as &$address) {
if (!empty($address['state_province_id'])) {
$config = CRM_Core_Config::singleton();
if (!($address['state_province_id'] = wf_crm_state_abbr($address['state_province_id'], 'id', wf_crm_aval($address, 'country_id', $config->defaultContactCountry)))) {
$address['state_province_id'] = '';
}
}
if (isset($address['county_id']) && $address['county_id'] === '-') {
$address['county_id'] = '';
}
}
}
foreach (wf_crm_location_fields() as $location) {
if (!empty($contact[$location])) {
$existing = array();
$params = array(
'contact_id' => $cid,
);
if ($location != 'website') {
$params['options'] = array(
'sort' => 'is_primary DESC',
);
}
$result = wf_civicrm_api($location, 'get', $params);
if (!empty($result['values'])) {
$contact[$location] = self::reorderLocationValues($contact[$location], $result['values'], $location);
$existing = array_merge(array(
array(),
), $result['values']);
}
foreach ($contact[$location] as $i => $params) {
if ($location == 'email' && !empty($params['email']) && $i == 1) {
$uid = wf_crm_user_cid($cid, 'contact');
if ($uid) {
$user = user_load($uid);
if ($params['email'] != $user->mail) {
$args = array(
':mail' => $params['email'],
);
if (!db_query("SELECT count(uid) FROM {users} WHERE mail = :mail", $args)
->fetchField()) {
user_save($user, array(
'mail' => $params['email'],
));
}
}
}
}
if (!empty($existing[$i])) {
$same = TRUE;
foreach ($params as $param => $val) {
if ($val != (string) wf_crm_aval($existing[$i], $param, '')) {
$same = FALSE;
}
}
if ($same) {
continue;
}
}
if ($location == 'address') {
if (!empty($params['master_id'])) {
$this->shared_address[$cid][$i] = array(
'id' => wf_crm_aval($existing, "{$i}:id"),
'mc' => $params['master_id'],
'loc' => $params['location_type_id'],
);
continue;
}
$params['master_id'] = $params['geo_code_1'] = $params['geo_code_2'] = 'null';
}
$params['contact_id'] = $cid;
if (!empty($existing[$i])) {
$params['id'] = $existing[$i]['id'];
}
if ($this
->locationIsEmpty($location, $params)) {
if (!empty($this->existing_contacts[$c]) && !empty($params['id'])) {
wf_civicrm_api($location, 'delete', $params);
}
continue;
}
if ($location != 'website') {
if (empty($params['location_type_id'])) {
$params['location_type_id'] = wf_crm_aval($existing, "{$i}:location_type_id", 1);
}
$params['is_primary'] = $i == 1 ? 1 : 0;
if ($location == 'address' && $params['location_type_id'] == $is_primary_address_location_type) {
$params['is_primary'] = 1;
}
if ($location == 'email' && $params['location_type_id'] == $is_primary_email_location_type) {
$params['is_primary'] = 1;
}
}
wf_civicrm_api($location, 'create', $params);
}
}
}
}
private function saveGroupsAndTags($contact, $cid, $c) {
foreach ($this->all_fields as $fid => $field) {
list($set, $type) = explode('_', $fid, 2);
if ($set == 'other') {
$field_name = 'civicrm_' . $c . '_contact_1_' . $fid;
if (!empty($contact['other'][1][$type]) || isset($this->enabled[$field_name])) {
$add = wf_crm_aval($contact, "other:1:{$type}", array());
$remove = empty($this->existing_contacts[$c]) ? array() : $this
->getExposedOptions($field_name, $add);
$this
->addOrRemoveMultivaluedData($field['table'], 'contact', $cid, $add, $remove);
}
}
}
}
private function addOrRemoveMultivaluedData($data_type, $entity_type, $id, $add, $remove = array()) {
$confirmations_sent = $existing = $params = array();
$add = drupal_map_assoc($add);
static $mailing_lists = array();
switch ($data_type) {
case 'group':
$api = 'group_contact';
$params['method'] = 'Webform';
break;
case 'tag':
$api = 'entity_tag';
break;
default:
$api = $data_type;
}
if (!empty($add) || !empty($remove)) {
if ($entity_type == 'contact') {
$params['contact_id'] = $id;
}
else {
$params['entity_id'] = $id;
$params['entity_type'] = 'civicrm_' . $entity_type;
}
$fetch = wf_civicrm_api($api, 'get', $params);
foreach (wf_crm_aval($fetch, 'values', array()) as $i) {
$existing[] = $i[$data_type . '_id'];
unset($add[$i[$data_type . '_id']]);
}
foreach ($remove as $i => $name) {
if (!in_array($i, $existing)) {
unset($remove[$i]);
}
}
}
if (!empty($add)) {
if ($data_type == 'group' && !empty($this->settings['confirm_subscription'])) {
$result = wf_civicrm_api('email', 'get', array(
'contact_id' => $id,
'options' => array(
'sort' => 'is_primary DESC',
),
));
if (!empty($result['values'])) {
foreach ($result['values'] as $value) {
if (($value['is_primary'] || empty($email)) && strpos($value['email'], '@')) {
$email = $value['email'];
}
}
$mailer_params = array(
'contact_id' => $id,
'email' => $email,
);
if (empty($mailing_lists)) {
$mailing_lists = wf_crm_apivalues('group', 'get', array(
'visibility' => 'Public Pages',
'group_type' => 2,
), 'title');
}
}
}
foreach ($add as $a) {
$params[$data_type . '_id'] = $mailer_params['group_id'] = $a;
if ($data_type == 'group' && isset($mailing_lists[$a]) && !empty($email)) {
$result = wf_civicrm_api('mailing_event_subscribe', 'create', $mailer_params);
if (empty($result['is_error'])) {
$confirmations_sent[] = check_plain($mailing_lists[$a]);
}
else {
wf_civicrm_api($api, 'create', $params);
}
}
else {
wf_civicrm_api($api, 'create', $params);
}
}
if ($confirmations_sent) {
drupal_set_message(t('A message has been sent to %email to confirm subscription to !group.', array(
'%email' => $email,
'!group' => '<em>' . implode('</em> ' . t('and') . ' <em>', $confirmations_sent) . '</em>',
)));
}
}
foreach ($remove as $a => $name) {
$params[$data_type . '_id'] = $a;
wf_civicrm_api($api, 'delete', $params);
}
if (!empty($remove) && $data_type == 'group') {
$display_name = wf_civicrm_api('contact', 'get', array(
'contact_id' => $id,
'return.display_name' => 1,
));
$display_name = wf_crm_aval($display_name, "values:{$id}:display_name", t('Contact'));
drupal_set_message(t('%contact has been removed from !group.', array(
'%contact' => $display_name,
'!group' => '<em>' . implode('</em> ' . t('and') . ' <em>', $remove) . '</em>',
)));
}
}
private function processRelationship($params, $cid1, $cid2) {
if (!empty($params['relationship_type_id']) && $cid2 && $cid1 != $cid2) {
list($type, $side) = explode('_', $params['relationship_type_id']);
$existing = $this
->getRelationship(array(
$params['relationship_type_id'],
), $cid1, $cid2);
$perm = wf_crm_aval($params, 'relationship_permission');
if ($side == 'b' || $existing && $existing['contact_id_a'] != $cid1) {
list($cid1, $cid2) = array(
$cid2,
$cid1,
);
if ($perm == 1 || $perm == 2) {
$perm = $perm == 1 ? 2 : 1;
}
}
if (empty($existing) && !array_key_exists('start_date', $params)) {
$params['start_date'] = 'now';
}
$params += $existing;
$params['contact_id_a'] = $cid1;
$params['contact_id_b'] = $cid2;
$params['relationship_type_id'] = $type;
if ($perm) {
$params['is_permission_a_b'] = $params['is_permission_b_a'] = $perm == 3 ? 1 : 0;
if ($perm == 1 || $perm == 2) {
$params['is_permission_' . ($perm == 1 ? 'a_b' : 'b_a')] = 1;
}
}
unset($params['relationship_permission']);
wf_civicrm_api('relationship', 'create', $params);
}
}
private function processParticipants($c, $cid) {
static $registered_by_id = array();
$n = $this->data['participant_reg_type'] == 'separate' ? $c : 1;
if ($p = wf_crm_aval($this->data, "participant:{$n}:participant")) {
$existing = array();
$dao = CRM_Core_DAO::executeQuery("SELECT id, event_id FROM civicrm_participant WHERE contact_id = {$cid} AND is_test = 0");
while ($dao
->fetch()) {
$existing[$dao->event_id] = $dao->id;
}
foreach ($p as $e => $params) {
$remove = array();
$fid = "civicrm_{$c}_participant_{$e}_participant_event_id";
if (empty($this->data['reg_options']['disable_unregister'])) {
if (empty($params['status_id'])) {
foreach ($this
->getExposedOptions($fid) as $eid => $title) {
list($eid) = explode('-', $eid);
if (isset($existing[$eid])) {
$remove[$eid] = $title;
}
}
}
}
if (!empty($params['event_id'])) {
$params['contact_id'] = $cid;
if (empty($params['campaign_id']) || empty($this->all_fields['participant_campaign_id'])) {
unset($params['campaign_id']);
}
$custom = array();
foreach ($this->data['participant'][$n] as $key => $vals) {
if (substr($key, 0, 2) == 'cg' && isset($vals[$e])) {
$custom[$key][1] = $vals[$e];
}
}
$this->events = (array) $params['event_id'];
foreach ($this->events as $i => $id_and_type) {
if (!empty($id_and_type)) {
list($eid) = explode('-', $id_and_type);
$params['event_id'] = $eid;
unset($remove[$eid], $params['registered_by_id'], $params['id'], $params['source']);
if (!empty($existing[$eid])) {
$params['id'] = $existing[$params['event_id']];
}
else {
if (isset($this->data['contact'][$c]['contact'][1]['source'])) {
$params['source'] = $this->data['contact'][$c]['contact'][1]['source'];
}
else {
$params['source'] = $this->settings['new_contact_source'];
}
if ($c > 1 && !empty($registered_by_id[$e][$i])) {
$params['registered_by_id'] = $registered_by_id[$e][$i];
}
}
if (empty($params['status_id']) && empty($params['id'])) {
$params['status_id'] = 'Registered';
if ($this->contributionIsIncomplete && !empty($params['fee_amount'])) {
$params['status_id'] = $this->contributionIsPayLater ? 'Pending from pay later' : 'Pending from incomplete transaction';
}
}
if (empty($params['status_id'])) {
unset($params['status_id']);
}
$result = wf_civicrm_api('participant', 'create', $params);
foreach ($this->line_items as &$item) {
if ($item['element'] == "civicrm_{$n}_participant_{$e}_participant_{$id_and_type}") {
if (empty($item['participant_id'])) {
$item['participant_id'] = $item['entity_id'] = $result['id'];
}
$item['participant_count'] = wf_crm_aval($item, 'participant_count', 0) + 1;
break;
}
}
if ($c == 1) {
$registered_by_id[$e][$i] = $result['id'];
}
if ($custom) {
$this
->saveCustomData($custom, $result['id'], 'Participant');
}
}
}
}
foreach ($remove as $eid => $title) {
wf_civicrm_api('participant', 'create', array(
'status_id' => "Cancelled",
'id' => $existing[$eid],
));
drupal_set_message(t('Registration cancelled for !event', array(
'!event' => $title,
)));
}
}
}
}
private function processMemberships($c, $cid) {
static $types;
if (!isset($types)) {
$types = wf_crm_apivalues('membership_type', 'get');
}
$existing = $this
->findMemberships($cid);
foreach (wf_crm_aval($this->data, "membership:{$c}:membership", array()) as $n => $params) {
$membershipStatus = "";
$membershipEndDate = "";
$is_active = FALSE;
if (empty($params['membership_type_id'])) {
continue;
}
if (empty($params['status_id'])) {
$params['status_override_end_date'] = '';
}
if (!empty($params['num_terms'])) {
$type = $types[$params['membership_type_id']];
foreach ($existing as $mem) {
$existing_type = $types[$mem['membership_type_id']];
if ($type['domain_id'] == $existing_type['domain_id'] && $type['member_of_contact_id'] == $existing_type['member_of_contact_id']) {
$params['id'] = $mem['id'];
if ($mem['membership_type_id'] == $params['membership_type_id']) {
$is_active = $mem['is_active'];
$membershipStatus = $mem['status'];
$membershipEndDate = $mem['end_date'];
break;
}
}
}
}
if (empty($params['id'])) {
if (isset($this->data['contact'][$c]['contact'][1]['source'])) {
$params['source'] = $this->data['contact'][$c]['contact'][1]['source'];
}
else {
$params['source'] = $this->settings['new_contact_source'];
}
}
if (empty($params['status_id'])) {
unset($params['status_id']);
if ($this->contributionIsIncomplete && $this
->getMembershipTypeField($params['membership_type_id'], 'minimum_fee')) {
if ($is_active == FALSE) {
$params['status_id'] = 'Pending';
}
else {
$params['status_id'] = $membershipStatus;
$params['end_date'] = $membershipEndDate;
}
}
}
else {
$params['is_override'] = 1;
}
$params['contact_id'] = $cid;
$params['skipStatusCal'] = !empty($params['status_id']);
if (isset($this->ent['contribution_recur'][1]['id'])) {
$params['contribution_recur_id'] = $this->ent['contribution_recur'][1]['id'];
}
$result = wf_civicrm_api('membership', 'create', $params);
if (!empty($result['id'])) {
if (!empty($params['id'])) {
$membership = $result['values'][$result['id']];
$actParams = array(
'source_record_id' => $result['id'],
'activity_type_id' => 'Membership Renewal',
'target_id' => $cid,
);
$memType = wf_civicrm_api('MembershipType', 'getsingle', array(
'id' => $membership['membership_type_id'],
));
$memStatus = wf_civicrm_api('MembershipStatus', 'getsingle', array(
'id' => $membership['status_id'],
));
$actParams['subject'] = ts("%1 - Status: %2", array(
1 => $memType['name'],
2 => $memStatus['label'],
));
wf_civicrm_api('Activity', 'create', $actParams);
}
foreach ($this->line_items as &$item) {
if ($item['element'] == "civicrm_{$c}_membership_{$n}") {
$item['membership_id'] = $result['id'];
break;
}
}
}
}
}
private function processSharedAddresses() {
foreach ($this->shared_address as $cid => $shared) {
foreach ($shared as $i => $addr) {
if (!empty($this->ent['contact'][$addr['mc']]['id'])) {
$masters = wf_civicrm_api('address', 'get', array(
'contact_id' => $this->ent['contact'][$addr['mc']]['id'],
'options' => array(
'sort' => 'is_primary DESC',
),
));
if (!empty($masters['values'])) {
$masters = array_values($masters['values']);
$params = $masters[0];
foreach ($masters as $m) {
if ($m['location_type_id'] == $addr['loc']) {
$params = $m;
break;
}
}
$params['master_id'] = $params['id'];
$params['id'] = $addr['id'];
$params['contact_id'] = $cid;
$params['is_primary'] = $i == 1;
wf_civicrm_api('address', 'create', $params);
}
}
}
}
}
private function processCases() {
foreach (wf_crm_aval($this->data, 'case', array()) as $n => $data) {
if (is_array($data) && !empty($data['case'][1]['client_id'])) {
$params = $data['case'][1];
if (empty($this->ent['case'][$n]['id'])) {
if (empty($params['case_type_id'])) {
continue;
}
if (empty($params['status_id'])) {
$options = wf_crm_apivalues('case', 'getoptions', array(
'field' => 'status_id',
));
$params['status_id'] = current(array_keys($options));
}
if (empty($params['subject'])) {
$params['subject'] = check_plain($this->node->title);
}
if (empty($data['case'][1]['creator_id'])) {
if (user_is_logged_in()) {
$params['creator_id'] = wf_crm_user_cid();
}
elseif (!empty($this->ent['contact'][1]['id'])) {
$params['creator_id'] = $this->ent['contact'][1]['id'];
}
else {
continue;
}
}
}
else {
$params['id'] = $this->ent['case'][$n]['id'];
unset($params['creator_id'], $params['case_type_id']);
}
if (empty($params['status_id'])) {
unset($params['status_id']);
}
$result = wf_civicrm_api('case', 'create', $params);
if (!empty($result['id'])) {
$this->ent['case'][$n]['id'] = $result['id'];
$this
->saveCustomData($data, $result['id'], 'Case', FALSE);
foreach ($params as $param => $val) {
if ($val && strpos($param, 'role_') === 0) {
foreach ((array) $params['client_id'] as $client) {
foreach ((array) $val as $contactB) {
wf_civicrm_api('relationship', 'create', array(
'relationship_type_id' => substr($param, 5),
'contact_id_a' => $client,
'contact_id_b' => $contactB,
'case_id' => $result['id'],
));
}
}
}
}
}
}
}
}
private function processActivities() {
foreach (wf_crm_aval($this->data, 'activity', array()) as $n => $data) {
if (is_array($data)) {
$params = $data['activity'][1];
if (empty($this->ent['activity'][$n]['id'])) {
if (empty($params['activity_type_id'])) {
continue;
}
if (empty($params['status_id'])) {
$params['status_id'] = strtotime(wf_crm_aval($params, 'activity_date_time', 'now')) > time() ? 'Scheduled' : 'Completed';
}
if (empty($data['activity'][1]['source_contact_id'])) {
if (user_is_logged_in()) {
$params['source_contact_id'] = wf_crm_user_cid();
}
elseif (!empty($this->ent['contact'][1]['id'])) {
$params['source_contact_id'] = $this->ent['contact'][1]['id'];
}
}
$this
->formatSubmissionDetails($params, $n);
}
else {
$params['id'] = $this->ent['activity'][$n]['id'];
if (!empty($data['details']['update_existing'])) {
$this
->formatSubmissionDetails($params, $n);
}
}
foreach ($params as $field => $value) {
if ((isset($this->all_fields["activity_{$field}"]['empty_option']) || isset($this->all_fields["activity_{$field}"]['exposed_empty_option'])) && !$value) {
unset($params[$field]);
}
}
if (!empty($params['survey_id'])) {
$params['source_record_id'] = $params['survey_id'];
if (empty($params['id']) && empty($params['subject'])) {
$survey = wf_civicrm_api('survey', 'getsingle', array(
'id' => $params['survey_id'],
'return' => 'title',
));
$params['subject'] = wf_crm_aval($survey, 'title', '');
}
}
if (!empty($data['case_type_id'])) {
if ($data['case_type_id'][0] === '#') {
$case_num = substr($data['case_type_id'], 1);
if (!empty($this->ent['case'][$case_num]['id'])) {
$params['case_id'] = $this->ent['case'][$case_num]['id'];
}
}
else {
$case_contact = $this->ent['contact'][$data['case_contact_id']]['id'];
if ($case_contact) {
if (empty($params['id']) || !wf_crm_apivalues('case', 'get', array(
'activity_id' => $params['id'],
))) {
$case = $this
->findCaseForContact($case_contact, array(
'status_id' => $data['case_status_id'],
'case_type_id' => $data['case_type_id'],
));
if ($case) {
$params['case_id'] = $case['id'];
}
}
}
}
}
$activity = wf_civicrm_api('activity', 'create', $params);
if (!empty($activity['id'])) {
$this->ent['activity'][$n]['id'] = $activity['id'];
$this
->saveCustomData($data, $activity['id'], 'Activity', FALSE);
if (isset($data['activityupload'])) {
$this
->processAttachments('activity', $n, $activity['id'], empty($params['id']));
}
if (!empty($params['assignee_contact_id'])) {
if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
$assignees = wf_crm_apivalues('contact', 'get', array(
'id' => array(
'IN' => (array) $params['assignee_contact_id'],
),
));
$mail = array();
foreach ($assignees as $assignee) {
if (!empty($assignee['email'])) {
$mail[$assignee['email']] = $assignee;
}
}
if ($mail) {
$caseId = isset($params['case_id']) ? $params['case_id'] : NULL;
$caseClientId = $caseId ? CRM_Utils_Array::first(CRM_Case_BAO_Case::getCaseClients($caseId)) : NULL;
$attachments = CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity['id']);
CRM_Case_BAO_Case::sendActivityCopy($caseClientId, $activity['id'], $mail, $attachments, $caseId);
}
}
}
}
}
}
}
private function formatSubmissionDetails(&$params, $activity_number) {
$params['details'] = nl2br(wf_crm_aval($params, 'details', ''));
if (!empty($this->data['activity'][$activity_number]['details']['entire_result'])) {
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_submission_render($this->node, $this->submission, NULL, 'html');
$params['details'] .= drupal_render($submission);
}
if (!empty($this->data['activity'][$activity_number]['details']['view_link'])) {
$params['details'] .= '<p>' . l(t('View Webform Submission'), "node/{$this->node->nid}/submission/{$this->submission->sid}", array(
'absolute' => TRUE,
'alias' => TRUE,
)) . '</p>';
}
if (!empty($this->data['activity'][$activity_number]['details']['edit_link'])) {
$params['details'] .= '<p>' . l(t('Edit Submission'), "node/{$this->node->nid}/submission/{$this->submission->sid}/edit", array(
'absolute' => TRUE,
'alias' => TRUE,
)) . '</p>';
}
}
private function processGrants() {
foreach (wf_crm_aval($this->data, 'grant', array()) as $n => $data) {
if (is_array($data) && !empty($data['grant'][1]['contact_id'])) {
$params = $data['grant'][1];
if (empty($this->ent['grant'][$n]['id'])) {
if (empty($params['status_id'])) {
$options = wf_crm_apivalues('grant', 'getoptions', array(
'field' => 'status_id',
));
$params['status_id'] = current(array_keys($options));
}
if (empty($params['application_received_date'])) {
$params['application_received_date'] = 'now';
}
if (empty($params['grant_report_received'])) {
$params['grant_report_received'] = '0';
}
}
else {
$params['id'] = $this->ent['grant'][$n]['id'];
}
if (empty($params['status_id'])) {
unset($params['status_id']);
}
$result = wf_civicrm_api('grant', 'create', $params);
if (!empty($result['id'])) {
$this->ent['grant'][$n]['id'] = $result['id'];
$this
->saveCustomData($data, $result['id'], 'Grant', FALSE);
if (isset($data['grantupload'])) {
$this
->processAttachments('grant', $n, $result['id'], empty($params['id']));
}
}
}
}
}
private function tallyLineItems() {
$fid = 'civicrm_1_contribution_1_contribution_total_amount';
if (isset($this->enabled[$fid]) || $this
->getData($fid) > 0) {
$this->line_items[] = array(
'qty' => 1,
'unit_price' => $this
->getData($fid),
'financial_type_id' => $this->contribution_page['financial_type_id'],
'label' => wf_crm_aval($this->node->webform['components'], $this->enabled[$fid] . ':name', t('Contribution')),
'element' => 'civicrm_1_contribution_1',
'entity_table' => 'civicrm_contribution',
);
}
$fid = "civicrm_1_lineitem_1_contribution_line_total";
if (isset($this->enabled[$fid])) {
foreach ($this->data['lineitem'][1]['contribution'] as $n => $lineitem) {
$fid = "civicrm_1_lineitem_{$n}_contribution_line_total";
if ($this
->getData($fid) != 0) {
$this->line_items[] = array(
'qty' => 1,
'unit_price' => $lineitem['line_total'],
'financial_type_id' => $lineitem['financial_type_id'],
'label' => wf_crm_aval($this->node->webform['components'], $this->enabled[$fid] . ':name', t('Line item')),
'element' => "civicrm_1_lineitem_{$n}",
'entity_table' => 'civicrm_contribution',
);
}
}
}
foreach (wf_crm_aval($this->data, 'membership', array()) as $c => $memberships) {
if (isset($this->existing_contacts[$c]) && !empty($memberships['number_of_membership'])) {
foreach ($memberships['membership'] as $n => $item) {
if (!empty($item['membership_type_id'])) {
$type = $item['membership_type_id'];
$price = $this
->getMembershipTypeField($type, 'minimum_fee');
if (isset($item['fee_amount'])) {
$price = $item['fee_amount'];
if (empty($item['num_terms'])) {
$item['num_terms'] = 1;
}
}
$membership_financialtype = $this
->getMembershipTypeField($type, 'financial_type_id');
if (isset($item['financial_type_id']) && $item['financial_type_id'] != 0) {
$membership_financialtype = $item['financial_type_id'];
}
if ($price) {
$this->line_items[] = array(
'qty' => $item['num_terms'],
'unit_price' => $price,
'financial_type_id' => $membership_financialtype,
'label' => $this
->getMembershipTypeField($type, 'name') . ": " . wf_crm_display_name($this->existing_contacts[$c]),
'element' => "civicrm_{$c}_membership_{$n}",
'entity_table' => 'civicrm_membership',
);
}
}
}
}
}
$this->totalContribution = 0;
$taxRates = CRM_Core_PseudoConstant::getTaxRates();
foreach ($this->line_items as &$item) {
if (!empty($item['financial_type_id'])) {
$itemTaxRate = isset($taxRates[$item['financial_type_id']]) ? $taxRates[$item['financial_type_id']] : NULL;
}
else {
$itemTaxRate = $this->tax_rate;
}
if (!is_null($itemTaxRate)) {
$item['line_total'] = $item['unit_price'] * (int) $item['qty'];
$item['tax_amount'] = $itemTaxRate / 100 * $item['line_total'];
$this->totalContribution += $item['unit_price'] * (int) $item['qty'] + $item['tax_amount'];
}
else {
$item['line_total'] = $item['unit_price'] * (int) $item['qty'];
$this->totalContribution += $item['line_total'];
}
}
return round($this->totalContribution, 2);
}
private function isPaymentPage() {
$page = wf_crm_aval($this->form_state, 'storage:page_num', 1);
$field = $this
->getComponent('civicrm_1_contribution_1_contribution_contribution_page_id');
return $page == $field['page_num'];
}
private function isLivePaymentProcessor() {
if ($this->payment_processor) {
if ($this->payment_processor['billing_mode'] == self::BILLING_MODE_LIVE) {
return TRUE;
}
if ($this->payment_processor['billing_mode'] == self::BILLING_MODE_MIXED && wf_crm_aval($_POST, 'credit_card_number') != 'express') {
return TRUE;
}
}
return FALSE;
}
private function validateBillingFields() {
$valid = TRUE;
$params = $card_errors = array();
$processor = Civi\Payment\System::singleton()
->getById(wf_crm_aval($this->data, 'contribution:1:contribution:1:payment_processor_id'));
$billingAddressFieldsMetadata = array();
if (method_exists($processor, 'getBillingAddressFieldsMetadata')) {
$billingAddressFieldsMetadata = $processor
->getBillingAddressFieldsMetadata();
}
$fields = CRM_Utils_Array::crmArrayMerge($processor
->getPaymentFormFieldsMetadata(), $billingAddressFieldsMetadata);
foreach ($_POST as $field => $value) {
if (empty($_POST[$field]) && isset($fields[$field]) && $fields[$field]['is_required'] !== FALSE) {
form_set_error($field, t('!name field is required.', array(
'!name' => check_plain($fields[$field]['title']),
)));
$valid = FALSE;
}
if (!empty($_POST[$field]) && array_key_exists($field, $fields)) {
$name = str_replace('billing_', '', str_replace('-5', '', $field));
$params[$name] = $params[$field] = $_POST[$field];
}
}
if (isset($params['credit_card_exp_date'])) {
$params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
$params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
}
CRM_Core_Payment_Form::validatePaymentInstrument(wf_crm_aval($this->data, 'contribution:1:contribution:1:payment_processor_id'), $params, $card_errors, NULL);
foreach ($card_errors as $field => $msg) {
form_set_error($field, $msg);
$valid = FALSE;
}
for ($i = 1; $i <= $this->data['contact'][1]['number_of_email']; ++$i) {
if (!empty($this->crmValues["civicrm_1_contact_{$i}_email_email"])) {
$params['email'] = $this->crmValues["civicrm_1_contact_{$i}_email_email"];
break;
}
}
if (empty($params['email'])) {
form_set_error('billing_email', ts('An email address is required to complete this transaction.'));
$valid = FALSE;
}
if ($valid) {
$this->billing_params = $params;
}
drupal_add_js(array(
'webform_civicrm' => array(
'billingSubmission' => $params,
),
), 'setting');
return $valid;
}
private function createBillingContact() {
$cid = wf_crm_aval($this->existing_contacts, 1);
if (!$cid) {
$contact = $this->data['contact'][1];
if (empty($contact['contact'][1]['first_name']) && !empty($this->billing_params['middle_name'])) {
$contact['contact'][1]['middle_name'] = $this->billing_params['middle_name'];
}
$contact['contact'][1] += array(
'first_name' => $this->billing_params['first_name'],
'last_name' => $this->billing_params['last_name'],
);
$cid = $this
->findDuplicateContact($contact);
}
$address = array(
'street_address' => $this->billing_params['street_address'],
'city' => $this->billing_params['city'],
'country_id' => $this->billing_params['country_id'],
'state_province_id' => wf_crm_aval($this->billing_params, 'state_province_id'),
'postal_code' => $this->billing_params['postal_code'],
'location_type_id' => 'Billing',
);
$email = array(
'email' => $this->billing_params['email'],
'location_type_id' => 'Billing',
);
if (!$cid) {
$cid = $this
->createContact($contact);
}
else {
foreach (array(
'address',
'email',
) as $loc) {
$result = wf_civicrm_api($loc, 'get', array(
'contact_id' => $cid,
'location_type_id' => 'Billing',
));
if (!empty($result['values'])) {
$ids = array_keys($result['values']);
${$loc}['id'] = $ids[0];
}
}
}
if ($cid) {
$address['contact_id'] = $email['contact_id'] = $this->ent['contact'][1]['id'] = $cid;
wf_civicrm_api('address', 'create', $address);
wf_civicrm_api('email', 'create', $email);
}
return $cid;
}
private function submitLivePayment() {
$contributionParams = $this
->contributionParams();
$numInstallments = wf_crm_aval($contributionParams, 'installments', NULL, TRUE);
$frequencyInterval = wf_crm_aval($contributionParams, 'frequency_unit');
if ($numInstallments != 1 && !empty($frequencyInterval)) {
$result = $this
->contributionRecur($contributionParams);
}
else {
$result = wf_civicrm_api('contribution', 'transact', $contributionParams);
}
if (empty($result['id'])) {
if (!empty($result['error_message'])) {
form_set_error('contribution', $result['error_message']);
}
else {
form_set_error('contribution', t('Transaction failed. Please verify all billing fields are correct.'));
}
return;
}
$this->ent['contribution'][1]['id'] = $result['id'];
}
private function contributionRecur($contributionParams, $paymentType = 'live') {
$numInstallments = wf_crm_aval($contributionParams, 'installments', NULL, TRUE);
$contributionFirstAmount = $contributionRecurAmount = $contributionParams['total_amount'];
$salesTaxFirstAmount = wf_crm_aval($contributionParams, 'tax_amount', NULL, TRUE);
if ($numInstallments > 0) {
$contributionRecurAmount = floor($contributionParams['total_amount'] / $numInstallments * 100) / 100;
$contributionFirstAmount = $contributionParams['total_amount'] - $contributionRecurAmount * ($numInstallments - 1);
$salesTaxFirstAmount = $salesTaxFirstAmount - floor($salesTaxFirstAmount / $numInstallments * 100) / 100 * ($numInstallments - 1);
foreach ($this->line_items as $key => $k) {
$this->line_items[$key]['unit_price'] = $k['unit_price'] / $numInstallments;
$this->line_items[$key]['line_total'] = $k['line_total'] / $numInstallments;
$this->line_items[$key]['tax_amount'] = $k['tax_amount'] / $numInstallments;
}
}
$contributionRecurParams = array(
'contact_id' => $contributionParams['contact_id'],
'frequency_interval' => wf_crm_aval($contributionParams, 'frequency_interval', 1),
'frequency_unit' => wf_crm_aval($contributionParams, 'frequency_unit', 'month'),
'installments' => $numInstallments,
'amount' => $contributionRecurAmount,
'contribution_status_id' => 'In Progress',
'currency' => $contributionParams['currency'],
'payment_processor_id' => $contributionParams['payment_processor_id'],
'financial_type_id' => $contributionParams['financial_type_id'],
);
if (empty($contributionParams['payment_processor_id'])) {
$contributionRecurParams['payment_processor_id'] = 'null';
}
$resultRecur = wf_civicrm_api('ContributionRecur', 'create', $contributionRecurParams);
$this->ent['contribution_recur'][1]['id'] = $resultRecur['id'];
$contributionParams['total_amount'] = $contributionFirstAmount;
$contributionParams['tax_amount'] = $salesTaxFirstAmount;
$additionalParams = array(
'contribution_recur_id' => $resultRecur['id'],
'contributionRecurID' => $resultRecur['id'],
'is_recur' => 1,
'contactID' => $contributionParams['contact_id'],
'frequency_interval' => wf_crm_aval($contributionParams, 'frequency_interval', 1),
'frequency_unit' => wf_crm_aval($contributionParams, 'frequency_unit', 'month'),
);
$APIAction = 'transact';
if ($paymentType === 'deferred') {
$APIAction = 'create';
}
$result = wf_civicrm_api('contribution', $APIAction, $contributionParams + $additionalParams);
if (empty($result['error_message'])) {
$resultUpdateRecur = wf_civicrm_api('ContributionRecur', 'create', array(
'id' => $resultRecur['id'],
'currency' => $contributionParams['currency'],
'next_sched_contribution_date' => date("Y-m-d H:i:s", strtotime('+' . $contributionRecurParams['frequency_interval'] . ' ' . $contributionRecurParams['frequency_unit'])),
'invoice_id' => $result['values'][$result['id']]['invoice_id'],
'payment_instrument_id' => $result['values'][$result['id']]['payment_instrument_id'],
));
}
return $result;
}
private function createDeferredPayment() {
$this->contributionIsIncomplete = TRUE;
$this->contributionIsPayLater = FALSE;
if (empty($this->data['contribution'][1]['contribution'][1]['payment_processor_id'])) {
$this->contributionIsPayLater = TRUE;
}
else {
$paymentProcessorID = $this->data['contribution'][1]['contribution'][1]['payment_processor_id'];
$paymentProcessorClassName = civicrm_api3('PaymentProcessor', 'getvalue', array(
'return' => 'class_name',
'id' => $paymentProcessorID,
));
if ($paymentProcessorClassName === 'Payment_Manual') {
$this->contributionIsPayLater = TRUE;
}
}
$params = $this
->contributionParams();
$params['contribution_status_id'] = 'Pending';
$params['is_pay_later'] = $this->contributionIsPayLater;
if (empty($params['payment_instrument_id'])) {
if (!empty($params['payment_processor_id']) && $this->contribution_page['is_monetary']) {
$defaultPaymentInstrument = CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1');
$params['payment_instrument_id'] = key($defaultPaymentInstrument);
}
}
$numInstallments = wf_crm_aval($params, 'installments', NULL, TRUE);
$frequencyInterval = wf_crm_aval($params, 'frequency_unit');
if ($numInstallments != 1 && !empty($frequencyInterval) && $this->contributionIsPayLater) {
$result = $this
->contributionRecur($params, 'deferred');
}
else {
$result = wf_civicrm_api('contribution', 'create', $params);
}
$this->ent['contribution'][1]['id'] = $result['id'];
}
private function submitIPNPayment() {
$params = $this->data['contribution'][1]['contribution'][1];
$processor_type = wf_civicrm_api('payment_processor', 'getsingle', array(
'id' => $params['payment_processor_id'],
));
if (version_compare($this->civicrm_version, 4.7, '<')) {
$mode = empty($params['is_test']) ? 'live' : 'test';
$paymentProcessor = CRM_Core_Payment::singleton($mode, $processor_type);
}
else {
$paymentProcessor = \Civi\Payment\System::singleton()
->getById($params['payment_processor_id']);
if (!empty($params['is_test'])) {
$paymentProcessor = \Civi\Payment\System::singleton()
->getByName($processor_type['name'], TRUE);
}
}
$contact = wf_civicrm_api('contact', 'getsingle', array(
'id' => $this->ent['contact'][1]['id'],
));
$params += $contact;
$params['contributionID'] = $params['id'] = $this->ent['contribution'][1]['id'];
$params['qfKey'] = $this
->getQfKey();
$params['contactID'] = $params['contact_id'];
$params['currency'] = $params['currencyID'] = $this->contribution_page['currency'];
$params['total_amount'] = round($this->totalContribution, 2);
$params['amount'] = $params['total_amount'];
$params['financial_type_id'] = $this->contribution_page['financial_type_id'];
$params['source'] = $this->settings['new_contact_source'];
$params['item_name'] = $params['description'] = t('Webform Payment: @title', array(
'@title' => $this->node->title,
));
foreach ($this->form_state['input'] as $formKey => $formValue) {
if (substr($formKey, 0, 8) === 'billing_') {
$params[$formKey] = $formValue;
}
}
if (method_exists($paymentProcessor, 'setSuccessUrl')) {
$paymentProcessor
->setSuccessUrl($this
->getIpnRedirectUrl('success'));
$paymentProcessor
->setCancelUrl($this
->getIpnRedirectUrl('cancel'));
}
$params['webform_redirect_cancel'] = $this
->getIpnRedirectUrl('cancel');
$params['webform_redirect_success'] = $this
->getIpnRedirectUrl('success');
if (method_exists($paymentProcessor, 'doTransferCheckout')) {
if (wf_crm_aval($_POST, 'credit_card_number') == 'express') {
try {
$params['button'] = 'express';
$params['component'] = 'contribute';
$result = $paymentProcessor
->doPreApproval($params);
if (empty($result)) {
return;
}
} catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
drupal_set_message(ts('Payment approval failed with message :') . $e
->getMessage(), 'error');
CRM_Utils_System::redirect($this
->getIpnRedirectUrl('cancel'));
}
$preApprovalParams = $paymentProcessor
->getPreApprovalDetails($result['pre_approval_parameters']);
$params = array_merge($params, $preApprovalParams);
if (!empty($result['redirect_url'])) {
CRM_Utils_System::redirect($result['redirect_url']);
}
}
$paymentProcessor
->doTransferCheckout($params, 'contribute');
}
else {
$paymentProcessor
->doPayment($params);
}
}
public function getIpnRedirectUrl($type) {
$url = trim($this->node->webform['redirect_url']);
if ($url == '<none>' || $type == 'cancel') {
$url = url('node/' . $this->node->nid, array(
'absolute' => TRUE,
));
}
elseif ($url == '<confirmation>') {
$query = array(
'sid' => $this->submission->sid,
);
if (user_is_anonymous()) {
$query['token'] = webform_get_submission_access_token($this->submission);
}
$url = url("node/{$this->node->nid}/done", array(
'query' => $query,
'absolute' => TRUE,
));
}
else {
$parsed = webform_replace_url_tokens($url, $this->node, $this->submission);
$parsed[1]['absolute'] = TRUE;
$url = url($parsed[0], $parsed[1]);
}
return $url;
}
private function contributionParams() {
$params = $this->billing_params + $this->data['contribution'][1]['contribution'][1];
$params['financial_type_id'] = $this->contribution_page['financial_type_id'];
$params['currency'] = $params['currencyID'] = $this->contribution_page['currency'];
$params['skipRecentView'] = $params['skipLineItem'] = 1;
$params['contact_id'] = $this->ent['contact'][1]['id'];
$params['total_amount'] = round($this->totalContribution, 2);
$params['contactID'] = $params['contact_id'];
if (!$this->contributionIsPayLater) {
$params['invoice_id'] = $this->data['contribution'][1]['contribution'][1]['invoiceID'] = md5(uniqid(rand(), TRUE));
}
$params['tax_amount'] = 0;
if (isset($this->form_state['civicrm']['line_items'])) {
foreach ($this->form_state['civicrm']['line_items'] as $lineItem) {
if (!empty($lineItem['tax_amount'])) {
$params['tax_amount'] += $lineItem['tax_amount'];
}
}
$params['tax_amount'] = round($params['tax_amount'], 2);
}
$params['description'] = t('Webform Payment: @title', array(
'@title' => $this->node->title,
));
if (!isset($params['source'])) {
$params['source'] = $this->settings['new_contact_source'];
}
$financialTypeId = $params['financial_type_id'];
$financialTypeDetails = wf_civicrm_api('FinancialType', 'get', array(
'return' => "is_deductible,name",
'id' => $financialTypeId,
));
$params['financialType_name'] = $financialTypeDetails['values'][$financialTypeId]['name'];
$params['financialTypeID'] = $financialTypeId;
if ($financialTypeDetails['values'][$financialTypeId]['is_deductible'] == 1) {
$params['non_deductible_amount'] = 0;
}
else {
$params['non_deductible_amount'] = $params['total_amount'];
}
foreach ($_POST as $key => $value) {
if (empty($params[$key])) {
$params[$key] = $value;
}
}
if ($params['is_test'] == 1) {
$liveProcessorName = wf_civicrm_api('payment_processor', 'getvalue', array(
'id' => $params['payment_processor_id'],
'return' => 'name',
));
static $domain = 0;
if (!$domain) {
$domain = wf_civicrm_api('domain', 'get', array(
'current_domain' => 1,
'return' => 'id',
));
$domain = wf_crm_aval($domain, 'id', 1);
}
$params['payment_processor_id'] = wf_civicrm_api('payment_processor', 'getvalue', array(
'return' => 'id',
'name' => $liveProcessorName,
'is_test' => 1,
'domain_id' => $domain,
));
}
if (version_compare($this->civicrm_version, '4.7', '>=')) {
$params['payment_processor'] = wf_crm_aval($params, 'payment_processor_id');
}
if (version_compare($this->civicrm_version, '4.7.17', '>=')) {
if (!empty($params['credit_card_number'])) {
if (!empty($params['credit_card_type'])) {
$result = wf_civicrm_api('OptionValue', 'get', array(
'return' => [
'value',
],
'option_group_id.name' => 'accept_creditcard',
'name' => ucfirst($params['credit_card_type']),
));
if (!empty($result['id'])) {
$params['card_type_id'] = $result['values'][$result['id']]['value'];
}
}
$params['pan_truncation'] = substr($params['credit_card_number'], -4);
}
}
unset($params['soft'], $params['honor_contact_id'], $params['honor_type_id']);
return $params;
}
private function processContribution() {
$contribution = $this->data['contribution'][1]['contribution'][1];
$id = $this->ent['contribution'][1]['id'];
$this
->saveCustomData($this->data['contribution'][1], $id, 'Contribution', FALSE);
if (!empty($contribution['soft'])) {
$amount = $this->totalContribution;
$default_soft_credit_type = wf_civicrm_api('OptionValue', 'getsingle', array(
'return' => "value",
'option_group_id' => "soft_credit_type",
'is_default' => 1,
));
foreach (array_filter($contribution['soft']) as $cid) {
wf_civicrm_api('contribution_soft', 'create', array(
'contact_id' => $cid,
'contribution_id' => $id,
'amount' => $amount,
'currency' => $this->contribution_page['currency'],
'soft_credit_type_id' => $default_soft_credit_type['value'],
));
}
}
if (!empty($contribution['honor_contact_id']) && !empty($contribution['honor_type_id'])) {
wf_civicrm_api('contribution', 'create', array(
'id' => $id,
'total_amount' => $contribution['total_amount'],
'honor_contact_id' => $contribution['honor_contact_id'],
'honor_type_id' => $contribution['honor_type_id'],
));
}
$contributionResult = CRM_Contribute_BAO_Contribution::getValues(array(
'id' => $id,
), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
foreach ($this->line_items as &$item) {
if (empty($item['line_total'])) {
continue;
}
if (empty($item['entity_id'])) {
$item['entity_id'] = $id;
}
if (empty($item['contribution_id'])) {
$item['contribution_id'] = $id;
}
if (!empty($item['membership_id'])) {
$item['entity_id'] = $item['membership_id'];
$lineItemArray = wf_civicrm_api('LineItem', 'get', array(
'entity_table' => "civicrm_membership",
'entity_id' => $item['entity_id'],
));
if ($lineItemArray['count'] != 0) {
$firstLineItem = array_shift($lineItemArray['values']);
if (!isset($firstLineItem['contribution_id'])) {
$item['id'] = $firstLineItem['id'];
}
}
}
isset($item['unit_price']) ? $item['unit_price'] = CRM_Utils_Money::format($item['unit_price'], NULL, NULL, TRUE) : NULL;
isset($item['line_total']) ? $item['line_total'] = CRM_Utils_Money::format($item['line_total'], NULL, NULL, TRUE) : NULL;
isset($item['tax_amount']) ? $item['tax_amount'] = CRM_Utils_Money::format($item['tax_amount'], NULL, NULL, TRUE) : NULL;
$line_result = wf_civicrm_api('line_item', 'create', $item);
$item['id'] = $line_result['id'];
$lineItemRecord = json_decode(json_encode($item), FALSE);
CRM_Financial_BAO_FinancialItem::add($lineItemRecord, $contributionResult);
if (!empty($lineItemRecord->tax_amount)) {
CRM_Financial_BAO_FinancialItem::add($lineItemRecord, $contributionResult, TRUE);
}
if (isset($item['membership_id']) || isset($item['participant_id'])) {
$type = isset($item['participant_id']) ? 'participant' : 'membership';
wf_civicrm_api("{$type}_payment", 'create', array(
"{$type}_id" => $item["{$type}_id"],
'contribution_id' => $id,
));
}
}
}
private function processAttachments($ent, $n, $id, $new = FALSE) {
$attachments = $new ? array() : $this
->getAttachments($ent, $id);
foreach ((array) wf_crm_aval($this->data[$ent], "{$n}:{$ent}upload:1") as $num => $file_id) {
if ($file_id) {
list(, $i) = explode('_', $num);
$dao = new CRM_Core_DAO_EntityFile();
if (!empty($attachments[$i])) {
$dao->id = $attachments[$i]['id'];
}
$dao->file_id = $file_id;
$dao->entity_id = $id;
$dao->entity_table = "civicrm_{$ent}";
$dao
->save();
}
}
}
private function fillContactRefs($values = NULL, $depth = 0) {
$order = array(
'ent',
'c',
'table',
'n',
'name',
);
static $ent = '';
static $c = '';
static $table = '';
static $n = '';
if ($values === NULL) {
$values = $this->data;
}
foreach ($values as $key => $val) {
${$order[$depth]} = $key;
if ($depth < 4 && is_array($val)) {
$this
->fillContactRefs($val, $depth + 1);
}
elseif ($depth == 4 && $val && wf_crm_aval($this->all_fields, "{$table}_{$name}:data_type") == 'ContactReference') {
if (is_array($val)) {
$this->data[$ent][$c][$table][$n][$name] = array();
foreach ($val as $v) {
if (is_numeric($v) && !empty($this->ent['contact'][$v]['id'])) {
$this->data[$ent][$c][$table][$n][$name][] = $this->ent['contact'][$v]['id'];
}
}
}
else {
unset($this->data[$ent][$c][$table][$n][$name]);
if (!empty($this->ent['contact'][$val]['id'])) {
$this->data[$ent][$c][$table][$n][$name] = $this->ent['contact'][$val]['id'];
}
}
}
}
}
private function fillDataFromSubmission() {
foreach ($this->enabled as $field_key => $fid) {
$val = $this
->submissionValue($fid);
if ($val !== NULL && $val !== array(
NULL,
)) {
list(, $c, $ent, $n, $table, $name) = explode('_', $field_key, 6);
if (in_array($name, array(
'existing',
'fieldset',
'createmode',
))) {
continue;
}
if ($this
->isFieldHiddenByExistingContactSettings($ent, $c, $table, $n, $name, TRUE)) {
$this
->submissionValue($fid, array(
NULL,
));
continue;
}
$field = $this->all_fields[$table . '_' . $name];
$component = $this->node->webform['components'][$this->enabled[$field_key]];
if ($field['type'] == 'hidden') {
continue;
}
if ($name === 'privacy') {
foreach (array_keys($this
->getExposedOptions($field_key)) as $key) {
$this->data[$ent][$c][$table][$n][$key] = in_array($key, $val);
}
continue;
}
$dataType = wf_crm_aval($field, 'data_type');
if (!empty($field['extra']['multiple'])) {
if ($val === array(
'',
)) {
$val = array();
}
if (!empty($this->data[$ent][$c][$table][$n][$name]) && is_array($this->data[$ent][$c][$table][$n][$name])) {
$val = array_unique(array_merge($val, $this->data[$ent][$c][$table][$n][$name]));
}
if ($table !== 'other' && $name !== 'event_id' && $name !== 'relationship_type_id' && $table !== 'contact' && $dataType != 'ContactReference') {
$val = CRM_Utils_Array::implodePadded($val);
}
}
elseif ($name === 'image_URL') {
if (empty($val[0]) || !($val = $this
->getDrupalFileUrl($val[0]))) {
continue;
}
}
elseif ($dataType == 'File') {
if (empty($val[0]) || !($val = $this
->saveDrupalFileToCivi($val[0]))) {
continue;
}
}
elseif ($field['type'] === 'date') {
$val = empty($val[0]) ? '' : str_replace('-', '', $val[0]);
$time = wf_crm_aval($this->data, "{$ent}:{$c}:{$table}:{$n}:{$name}", '');
if (strlen($time) == 14) {
$time = substr($time, -6);
}
$val .= $time;
}
elseif ($field['type'] === 'number') {
$sum = 0;
foreach ((array) $val as $k => $v) {
if ($component['type'] == 'grid' && is_numeric($k)) {
$v = $v * $k;
}
if (is_numeric($v)) {
$sum += $v;
}
}
$val = $sum;
}
else {
$val = isset($val[0]) ? $val[0] : '';
}
if ($component['type'] == 'autocomplete' && is_string($val) && strlen($val)) {
$options = wf_crm_field_options($component, '', $this->data);
$val = array_search($val, $options);
}
if ($field['type'] === 'time' && substr($name, -8) === 'timepart') {
$name = str_replace('_timepart', '', $name);
$date = wf_crm_aval($this->data, "{$ent}:{$c}:{$table}:{$n}:{$name}", date('Ymd'));
$val = $date . str_replace(':', '', $val);
}
if ($val !== '' && $val !== NULL && $val !== array() || !empty($this->existing_contacts[$c])) {
$this->data[$ent][$c][$table][$n][$name] = $val;
}
}
}
}
private function isFieldHiddenByExistingContactSettings($ent, $c, $table, $n, $name, $checkSubmitDisabledSetting = FALSE) {
if ($ent == 'contact' && isset($this->enabled["civicrm_{$c}_contact_1_contact_existing"])) {
$component = $this
->getComponent("civicrm_{$c}_contact_1_contact_existing");
$existing_contact_val = $this
->submissionValue($component['cid']);
if (!$existing_contact_val[0] || is_numeric($existing_contact_val[0])) {
$type = $table == 'contact' && strpos($name, 'name') ? 'name' : $table;
if (in_array($type, $component['extra']['hide_fields'])) {
if ($checkSubmitDisabledSetting && $component['extra']['submit_disabled']) {
return FALSE;
}
if (wf_crm_aval($component['extra'], 'no_hide_blank')) {
$value = wf_crm_aval($this
->loadContact($c), "{$table}:{$n}:{$name}");
return !(!$value && !is_numeric($value));
}
else {
return TRUE;
}
}
}
}
return FALSE;
}
private function locationIsEmpty($location, $params) {
switch ($location) {
case 'address':
return empty($params['street_address']) && empty($params['city']) && empty($params['state_province_id']) && empty($params['country_id']) && empty($params['postal_code']) && (empty($params['master_id']) || $params['master_id'] == 'null');
case 'website':
return empty($params['url']);
case 'im':
return empty($params['name']);
default:
return empty($params[$location]);
}
}
private function unsetError($name) {
$errors =& drupal_static('form_set_error', array());
$removed_messages = array();
if (isset($errors[$name])) {
$removed_messages[] = $errors[$name];
unset($errors[$name]);
}
$_SESSION['messages']['error'] = array_diff($_SESSION['messages']['error'], $removed_messages);
if (empty($_SESSION['messages']['error'])) {
unset($_SESSION['messages']['error']);
}
}
protected function submissionValue($fid, $value = NULL) {
if ($this->submission) {
if (!isset($this->submission->data[$fid])) {
return NULL;
}
$field =& $this->submission->data[$fid];
if ($value !== NULL) {
$field = (array) $value;
}
return $field;
}
else {
if (!isset($this->rawValues[$fid])) {
return NULL;
}
if (is_array($this->rawValues[$fid])) {
$val = array_filter($this->rawValues[$fid]);
return $val;
}
else {
return (array) $this->rawValues[$fid];
}
}
}
public function setLoggingContact() {
if (!empty($this->ent['contact'][1]['id']) && user_is_anonymous()) {
CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1', array(
1 => array(
$this->ent['contact'][1]['id'],
'Integer',
),
));
}
}
protected function reorderLocationValues($submittedLocationValues, $existingLocationValues, $entity) {
$reorderedArray = array();
$index = 1;
$entityTypeIdIndex = $entity . '_type_id';
$entity = $entity == 'website' ? 'url' : $entity;
foreach ($existingLocationValues as $eValue) {
$existingLocationTypeId = $entity != 'url' ? $eValue['location_type_id'] : NULL;
$existingEntityTypeId = isset($eValue[$entityTypeIdIndex]) ? $eValue[$entityTypeIdIndex] : NULL;
if (!empty($existingEntityTypeId)) {
$reorderedArray[$index][$entityTypeIdIndex] = $existingEntityTypeId;
}
elseif (!empty($existingLocationTypeId)) {
$reorderedArray[$index]['location_type_id'] = $existingLocationTypeId;
}
if (!empty($eValue[$entity])) {
$reorderedArray[$index][$entity] = $eValue[$entity];
}
if ($entity != 'address') {
$submittedLocationValues = self::unsetEmptyValueIndexes($submittedLocationValues, $entity);
$reorderedArray[$index][$entity] = wf_crm_aval($eValue, $entity);
}
else {
foreach (wf_crm_address_fields() as $field) {
if ($field != 'location_type_id') {
$reorderedArray[$index][$field] = isset($eValue[$field]) ? $eValue[$field] : '';
}
}
}
foreach ($submittedLocationValues as $key => $sValue) {
$sLocationTypeId = isset($sValue['location_type_id']) ? $sValue['location_type_id'] : NULL;
$sEntityTypeId = isset($sValue[$entityTypeIdIndex]) ? $sValue[$entityTypeIdIndex] : NULL;
if ($existingLocationTypeId == $sLocationTypeId && empty($sEntityTypeId) || $existingEntityTypeId == $sEntityTypeId && empty($sLocationTypeId) || $existingLocationTypeId == $sLocationTypeId && $existingEntityTypeId == $sEntityTypeId) {
if ($entity != 'address') {
$reorderedArray[$index] = $sValue;
unset($submittedLocationValues[$key]);
break;
}
else {
foreach (wf_crm_address_fields() as $field) {
if (isset($sValue[$field]) && $field != 'location_type_id') {
$reorderedArray[$index][$field] = $sValue[$field];
}
}
}
unset($submittedLocationValues[$key]);
}
}
$index++;
}
if (!empty($submittedLocationValues)) {
foreach ($submittedLocationValues as $sValue) {
$reorderedArray[] = $sValue;
}
}
return $reorderedArray;
}
private function unsetEmptyValueIndexes($values, $entity) {
foreach ($values as $k => $v) {
if (!isset($v[$entity])) {
unset($values[$k]);
}
}
return $values;
}
}